OSDN Git Service

2005-10-18 Paolo Bonzini <bonzini@gnu.org>
[pf3gnuchains/gcc-fork.git] / gcc / expmed.c
1 /* Medium-level subroutines: convert bit-field store and extract
2    and shifts, multiplies and divides to rtl instructions.
3    Copyright (C) 1987, 1988, 1989, 1992, 1993, 1994, 1995, 1996, 1997, 1998,
4    1999, 2000, 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
5
6 This file is part of GCC.
7
8 GCC is free software; you can redistribute it and/or modify it under
9 the terms of the GNU General Public License as published by the Free
10 Software Foundation; either version 2, or (at your option) any later
11 version.
12
13 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
14 WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
16 for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING.  If not, write to the Free
20 Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA
21 02110-1301, USA.  */
22
23
24 #include "config.h"
25 #include "system.h"
26 #include "coretypes.h"
27 #include "tm.h"
28 #include "toplev.h"
29 #include "rtl.h"
30 #include "tree.h"
31 #include "tm_p.h"
32 #include "flags.h"
33 #include "insn-config.h"
34 #include "expr.h"
35 #include "optabs.h"
36 #include "real.h"
37 #include "recog.h"
38 #include "langhooks.h"
39
40 static void store_fixed_bit_field (rtx, unsigned HOST_WIDE_INT,
41                                    unsigned HOST_WIDE_INT,
42                                    unsigned HOST_WIDE_INT, rtx);
43 static void store_split_bit_field (rtx, unsigned HOST_WIDE_INT,
44                                    unsigned HOST_WIDE_INT, rtx);
45 static rtx extract_fixed_bit_field (enum machine_mode, rtx,
46                                     unsigned HOST_WIDE_INT,
47                                     unsigned HOST_WIDE_INT,
48                                     unsigned HOST_WIDE_INT, rtx, int);
49 static rtx mask_rtx (enum machine_mode, int, int, int);
50 static rtx lshift_value (enum machine_mode, rtx, int, int);
51 static rtx extract_split_bit_field (rtx, unsigned HOST_WIDE_INT,
52                                     unsigned HOST_WIDE_INT, int);
53 static void do_cmp_and_jump (rtx, rtx, enum rtx_code, enum machine_mode, rtx);
54 static rtx expand_smod_pow2 (enum machine_mode, rtx, HOST_WIDE_INT);
55 static rtx expand_sdiv_pow2 (enum machine_mode, rtx, HOST_WIDE_INT);
56
57 /* Test whether a value is zero of a power of two.  */
58 #define EXACT_POWER_OF_2_OR_ZERO_P(x) (((x) & ((x) - 1)) == 0)
59
60 /* Nonzero means divides or modulus operations are relatively cheap for
61    powers of two, so don't use branches; emit the operation instead.
62    Usually, this will mean that the MD file will emit non-branch
63    sequences.  */
64
65 static bool sdiv_pow2_cheap[NUM_MACHINE_MODES];
66 static bool smod_pow2_cheap[NUM_MACHINE_MODES];
67
68 #ifndef SLOW_UNALIGNED_ACCESS
69 #define SLOW_UNALIGNED_ACCESS(MODE, ALIGN) STRICT_ALIGNMENT
70 #endif
71
72 /* For compilers that support multiple targets with different word sizes,
73    MAX_BITS_PER_WORD contains the biggest value of BITS_PER_WORD.  An example
74    is the H8/300(H) compiler.  */
75
76 #ifndef MAX_BITS_PER_WORD
77 #define MAX_BITS_PER_WORD BITS_PER_WORD
78 #endif
79
80 /* Reduce conditional compilation elsewhere.  */
81 #ifndef HAVE_insv
82 #define HAVE_insv       0
83 #define CODE_FOR_insv   CODE_FOR_nothing
84 #define gen_insv(a,b,c,d) NULL_RTX
85 #endif
86 #ifndef HAVE_extv
87 #define HAVE_extv       0
88 #define CODE_FOR_extv   CODE_FOR_nothing
89 #define gen_extv(a,b,c,d) NULL_RTX
90 #endif
91 #ifndef HAVE_extzv
92 #define HAVE_extzv      0
93 #define CODE_FOR_extzv  CODE_FOR_nothing
94 #define gen_extzv(a,b,c,d) NULL_RTX
95 #endif
96
97 /* Cost of various pieces of RTL.  Note that some of these are indexed by
98    shift count and some by mode.  */
99 static int zero_cost;
100 static int add_cost[NUM_MACHINE_MODES];
101 static int neg_cost[NUM_MACHINE_MODES];
102 static int shift_cost[NUM_MACHINE_MODES][MAX_BITS_PER_WORD];
103 static int shiftadd_cost[NUM_MACHINE_MODES][MAX_BITS_PER_WORD];
104 static int shiftsub_cost[NUM_MACHINE_MODES][MAX_BITS_PER_WORD];
105 static int mul_cost[NUM_MACHINE_MODES];
106 static int div_cost[NUM_MACHINE_MODES];
107 static int mul_widen_cost[NUM_MACHINE_MODES];
108 static int mul_highpart_cost[NUM_MACHINE_MODES];
109
110 void
111 init_expmed (void)
112 {
113   struct
114   {
115     struct rtx_def reg;         rtunion reg_fld[2];
116     struct rtx_def plus;        rtunion plus_fld1;
117     struct rtx_def neg;
118     struct rtx_def udiv;        rtunion udiv_fld1;
119     struct rtx_def mult;        rtunion mult_fld1;
120     struct rtx_def div;         rtunion div_fld1;
121     struct rtx_def mod;         rtunion mod_fld1;
122     struct rtx_def zext;
123     struct rtx_def wide_mult;   rtunion wide_mult_fld1;
124     struct rtx_def wide_lshr;   rtunion wide_lshr_fld1;
125     struct rtx_def wide_trunc;
126     struct rtx_def shift;       rtunion shift_fld1;
127     struct rtx_def shift_mult;  rtunion shift_mult_fld1;
128     struct rtx_def shift_add;   rtunion shift_add_fld1;
129     struct rtx_def shift_sub;   rtunion shift_sub_fld1;
130   } all;
131
132   rtx pow2[MAX_BITS_PER_WORD];
133   rtx cint[MAX_BITS_PER_WORD];
134   int m, n;
135   enum machine_mode mode, wider_mode;
136
137   zero_cost = rtx_cost (const0_rtx, 0);
138
139   for (m = 1; m < MAX_BITS_PER_WORD; m++)
140     {
141       pow2[m] = GEN_INT ((HOST_WIDE_INT) 1 << m);
142       cint[m] = GEN_INT (m);
143     }
144
145   memset (&all, 0, sizeof all);
146
147   PUT_CODE (&all.reg, REG);
148   /* Avoid using hard regs in ways which may be unsupported.  */
149   REGNO (&all.reg) = LAST_VIRTUAL_REGISTER + 1;
150
151   PUT_CODE (&all.plus, PLUS);
152   XEXP (&all.plus, 0) = &all.reg;
153   XEXP (&all.plus, 1) = &all.reg;
154
155   PUT_CODE (&all.neg, NEG);
156   XEXP (&all.neg, 0) = &all.reg;
157
158   PUT_CODE (&all.udiv, UDIV);
159   XEXP (&all.udiv, 0) = &all.reg;
160   XEXP (&all.udiv, 1) = &all.reg;
161
162   PUT_CODE (&all.mult, MULT);
163   XEXP (&all.mult, 0) = &all.reg;
164   XEXP (&all.mult, 1) = &all.reg;
165
166   PUT_CODE (&all.div, DIV);
167   XEXP (&all.div, 0) = &all.reg;
168   XEXP (&all.div, 1) = 32 < MAX_BITS_PER_WORD ? cint[32] : GEN_INT (32);
169
170   PUT_CODE (&all.mod, MOD);
171   XEXP (&all.mod, 0) = &all.reg;
172   XEXP (&all.mod, 1) = XEXP (&all.div, 1);
173
174   PUT_CODE (&all.zext, ZERO_EXTEND);
175   XEXP (&all.zext, 0) = &all.reg;
176
177   PUT_CODE (&all.wide_mult, MULT);
178   XEXP (&all.wide_mult, 0) = &all.zext;
179   XEXP (&all.wide_mult, 1) = &all.zext;
180
181   PUT_CODE (&all.wide_lshr, LSHIFTRT);
182   XEXP (&all.wide_lshr, 0) = &all.wide_mult;
183
184   PUT_CODE (&all.wide_trunc, TRUNCATE);
185   XEXP (&all.wide_trunc, 0) = &all.wide_lshr;
186
187   PUT_CODE (&all.shift, ASHIFT);
188   XEXP (&all.shift, 0) = &all.reg;
189
190   PUT_CODE (&all.shift_mult, MULT);
191   XEXP (&all.shift_mult, 0) = &all.reg;
192
193   PUT_CODE (&all.shift_add, PLUS);
194   XEXP (&all.shift_add, 0) = &all.shift_mult;
195   XEXP (&all.shift_add, 1) = &all.reg;
196
197   PUT_CODE (&all.shift_sub, MINUS);
198   XEXP (&all.shift_sub, 0) = &all.shift_mult;
199   XEXP (&all.shift_sub, 1) = &all.reg;
200
201   for (mode = GET_CLASS_NARROWEST_MODE (MODE_INT);
202        mode != VOIDmode;
203        mode = GET_MODE_WIDER_MODE (mode))
204     {
205       PUT_MODE (&all.reg, mode);
206       PUT_MODE (&all.plus, mode);
207       PUT_MODE (&all.neg, mode);
208       PUT_MODE (&all.udiv, mode);
209       PUT_MODE (&all.mult, mode);
210       PUT_MODE (&all.div, mode);
211       PUT_MODE (&all.mod, mode);
212       PUT_MODE (&all.wide_trunc, mode);
213       PUT_MODE (&all.shift, mode);
214       PUT_MODE (&all.shift_mult, mode);
215       PUT_MODE (&all.shift_add, mode);
216       PUT_MODE (&all.shift_sub, mode);
217
218       add_cost[mode] = rtx_cost (&all.plus, SET);
219       neg_cost[mode] = rtx_cost (&all.neg, SET);
220       div_cost[mode] = rtx_cost (&all.udiv, SET);
221       mul_cost[mode] = rtx_cost (&all.mult, SET);
222
223       sdiv_pow2_cheap[mode] = (rtx_cost (&all.div, SET) <= 2 * add_cost[mode]);
224       smod_pow2_cheap[mode] = (rtx_cost (&all.mod, SET) <= 4 * add_cost[mode]);
225
226       wider_mode = GET_MODE_WIDER_MODE (mode);
227       if (wider_mode != VOIDmode)
228         {
229           PUT_MODE (&all.zext, wider_mode);
230           PUT_MODE (&all.wide_mult, wider_mode);
231           PUT_MODE (&all.wide_lshr, wider_mode);
232           XEXP (&all.wide_lshr, 1) = GEN_INT (GET_MODE_BITSIZE (mode));
233
234           mul_widen_cost[wider_mode] = rtx_cost (&all.wide_mult, SET);
235           mul_highpart_cost[mode] = rtx_cost (&all.wide_trunc, SET);
236         }
237
238       shift_cost[mode][0] = 0;
239       shiftadd_cost[mode][0] = shiftsub_cost[mode][0] = add_cost[mode];
240
241       n = MIN (MAX_BITS_PER_WORD, GET_MODE_BITSIZE (mode));
242       for (m = 1; m < n; m++)
243         {
244           XEXP (&all.shift, 1) = cint[m];
245           XEXP (&all.shift_mult, 1) = pow2[m];
246
247           shift_cost[mode][m] = rtx_cost (&all.shift, SET);
248           shiftadd_cost[mode][m] = rtx_cost (&all.shift_add, SET);
249           shiftsub_cost[mode][m] = rtx_cost (&all.shift_sub, SET);
250         }
251     }
252 }
253
254 /* Return an rtx representing minus the value of X.
255    MODE is the intended mode of the result,
256    useful if X is a CONST_INT.  */
257
258 rtx
259 negate_rtx (enum machine_mode mode, rtx x)
260 {
261   rtx result = simplify_unary_operation (NEG, mode, x, mode);
262
263   if (result == 0)
264     result = expand_unop (mode, neg_optab, x, NULL_RTX, 0);
265
266   return result;
267 }
268
269 /* Report on the availability of insv/extv/extzv and the desired mode
270    of each of their operands.  Returns MAX_MACHINE_MODE if HAVE_foo
271    is false; else the mode of the specified operand.  If OPNO is -1,
272    all the caller cares about is whether the insn is available.  */
273 enum machine_mode
274 mode_for_extraction (enum extraction_pattern pattern, int opno)
275 {
276   const struct insn_data *data;
277
278   switch (pattern)
279     {
280     case EP_insv:
281       if (HAVE_insv)
282         {
283           data = &insn_data[CODE_FOR_insv];
284           break;
285         }
286       return MAX_MACHINE_MODE;
287
288     case EP_extv:
289       if (HAVE_extv)
290         {
291           data = &insn_data[CODE_FOR_extv];
292           break;
293         }
294       return MAX_MACHINE_MODE;
295
296     case EP_extzv:
297       if (HAVE_extzv)
298         {
299           data = &insn_data[CODE_FOR_extzv];
300           break;
301         }
302       return MAX_MACHINE_MODE;
303
304     default:
305       gcc_unreachable ();
306     }
307
308   if (opno == -1)
309     return VOIDmode;
310
311   /* Everyone who uses this function used to follow it with
312      if (result == VOIDmode) result = word_mode; */
313   if (data->operand[opno].mode == VOIDmode)
314     return word_mode;
315   return data->operand[opno].mode;
316 }
317
318 \f
319 /* Generate code to store value from rtx VALUE
320    into a bit-field within structure STR_RTX
321    containing BITSIZE bits starting at bit BITNUM.
322    FIELDMODE is the machine-mode of the FIELD_DECL node for this field.
323    ALIGN is the alignment that STR_RTX is known to have.
324    TOTAL_SIZE is the size of the structure in bytes, or -1 if varying.  */
325
326 /* ??? Note that there are two different ideas here for how
327    to determine the size to count bits within, for a register.
328    One is BITS_PER_WORD, and the other is the size of operand 3
329    of the insv pattern.
330
331    If operand 3 of the insv pattern is VOIDmode, then we will use BITS_PER_WORD
332    else, we use the mode of operand 3.  */
333
334 rtx
335 store_bit_field (rtx str_rtx, unsigned HOST_WIDE_INT bitsize,
336                  unsigned HOST_WIDE_INT bitnum, enum machine_mode fieldmode,
337                  rtx value)
338 {
339   unsigned int unit
340     = (MEM_P (str_rtx)) ? BITS_PER_UNIT : BITS_PER_WORD;
341   unsigned HOST_WIDE_INT offset, bitpos;
342   rtx op0 = str_rtx;
343   int byte_offset;
344   rtx orig_value;
345
346   enum machine_mode op_mode = mode_for_extraction (EP_insv, 3);
347
348   while (GET_CODE (op0) == SUBREG)
349     {
350       /* The following line once was done only if WORDS_BIG_ENDIAN,
351          but I think that is a mistake.  WORDS_BIG_ENDIAN is
352          meaningful at a much higher level; when structures are copied
353          between memory and regs, the higher-numbered regs
354          always get higher addresses.  */
355       bitnum += SUBREG_BYTE (op0) * BITS_PER_UNIT;
356       op0 = SUBREG_REG (op0);
357     }
358
359   /* No action is needed if the target is a register and if the field
360      lies completely outside that register.  This can occur if the source
361      code contains an out-of-bounds access to a small array.  */
362   if (REG_P (op0) && bitnum >= GET_MODE_BITSIZE (GET_MODE (op0)))
363     return value;
364
365   /* Use vec_set patterns for inserting parts of vectors whenever
366      available.  */
367   if (VECTOR_MODE_P (GET_MODE (op0))
368       && !MEM_P (op0)
369       && (vec_set_optab->handlers[GET_MODE (op0)].insn_code
370           != CODE_FOR_nothing)
371       && fieldmode == GET_MODE_INNER (GET_MODE (op0))
372       && bitsize == GET_MODE_BITSIZE (GET_MODE_INNER (GET_MODE (op0)))
373       && !(bitnum % GET_MODE_BITSIZE (GET_MODE_INNER (GET_MODE (op0)))))
374     {
375       enum machine_mode outermode = GET_MODE (op0);
376       enum machine_mode innermode = GET_MODE_INNER (outermode);
377       int icode = (int) vec_set_optab->handlers[outermode].insn_code;
378       int pos = bitnum / GET_MODE_BITSIZE (innermode);
379       rtx rtxpos = GEN_INT (pos);
380       rtx src = value;
381       rtx dest = op0;
382       rtx pat, seq;
383       enum machine_mode mode0 = insn_data[icode].operand[0].mode;
384       enum machine_mode mode1 = insn_data[icode].operand[1].mode;
385       enum machine_mode mode2 = insn_data[icode].operand[2].mode;
386
387       start_sequence ();
388
389       if (! (*insn_data[icode].operand[1].predicate) (src, mode1))
390         src = copy_to_mode_reg (mode1, src);
391
392       if (! (*insn_data[icode].operand[2].predicate) (rtxpos, mode2))
393         rtxpos = copy_to_mode_reg (mode1, rtxpos);
394
395       /* We could handle this, but we should always be called with a pseudo
396          for our targets and all insns should take them as outputs.  */
397       gcc_assert ((*insn_data[icode].operand[0].predicate) (dest, mode0)
398                   && (*insn_data[icode].operand[1].predicate) (src, mode1)
399                   && (*insn_data[icode].operand[2].predicate) (rtxpos, mode2));
400       pat = GEN_FCN (icode) (dest, src, rtxpos);
401       seq = get_insns ();
402       end_sequence ();
403       if (pat)
404         {
405           emit_insn (seq);
406           emit_insn (pat);
407           return dest;
408         }
409     }
410
411   /* If the target is a register, overwriting the entire object, or storing
412      a full-word or multi-word field can be done with just a SUBREG.
413
414      If the target is memory, storing any naturally aligned field can be
415      done with a simple store.  For targets that support fast unaligned
416      memory, any naturally sized, unit aligned field can be done directly.  */
417
418   offset = bitnum / unit;
419   bitpos = bitnum % unit;
420   byte_offset = (bitnum % BITS_PER_WORD) / BITS_PER_UNIT
421                 + (offset * UNITS_PER_WORD);
422
423   if (bitpos == 0
424       && bitsize == GET_MODE_BITSIZE (fieldmode)
425       && (!MEM_P (op0)
426           ? ((GET_MODE_SIZE (fieldmode) >= UNITS_PER_WORD
427              || GET_MODE_SIZE (GET_MODE (op0)) == GET_MODE_SIZE (fieldmode))
428              && byte_offset % GET_MODE_SIZE (fieldmode) == 0)
429           : (! SLOW_UNALIGNED_ACCESS (fieldmode, MEM_ALIGN (op0))
430              || (offset * BITS_PER_UNIT % bitsize == 0
431                  && MEM_ALIGN (op0) % GET_MODE_BITSIZE (fieldmode) == 0))))
432     {
433       if (GET_MODE (op0) != fieldmode)
434         {
435           if (MEM_P (op0))
436             op0 = adjust_address (op0, fieldmode, offset);
437           else
438             op0 = simplify_gen_subreg (fieldmode, op0, GET_MODE (op0),
439                                        byte_offset);
440         }
441       emit_move_insn (op0, value);
442       return value;
443     }
444
445   /* Make sure we are playing with integral modes.  Pun with subregs
446      if we aren't.  This must come after the entire register case above,
447      since that case is valid for any mode.  The following cases are only
448      valid for integral modes.  */
449   {
450     enum machine_mode imode = int_mode_for_mode (GET_MODE (op0));
451     if (imode != GET_MODE (op0))
452       {
453         if (MEM_P (op0))
454           op0 = adjust_address (op0, imode, 0);
455         else
456           {
457             gcc_assert (imode != BLKmode);
458             op0 = gen_lowpart (imode, op0);
459           }
460       }
461   }
462
463   /* We may be accessing data outside the field, which means
464      we can alias adjacent data.  */
465   if (MEM_P (op0))
466     {
467       op0 = shallow_copy_rtx (op0);
468       set_mem_alias_set (op0, 0);
469       set_mem_expr (op0, 0);
470     }
471
472   /* If OP0 is a register, BITPOS must count within a word.
473      But as we have it, it counts within whatever size OP0 now has.
474      On a bigendian machine, these are not the same, so convert.  */
475   if (BYTES_BIG_ENDIAN
476       && !MEM_P (op0)
477       && unit > GET_MODE_BITSIZE (GET_MODE (op0)))
478     bitpos += unit - GET_MODE_BITSIZE (GET_MODE (op0));
479
480   /* Storing an lsb-aligned field in a register
481      can be done with a movestrict instruction.  */
482
483   if (!MEM_P (op0)
484       && (BYTES_BIG_ENDIAN ? bitpos + bitsize == unit : bitpos == 0)
485       && bitsize == GET_MODE_BITSIZE (fieldmode)
486       && (movstrict_optab->handlers[fieldmode].insn_code
487           != CODE_FOR_nothing))
488     {
489       int icode = movstrict_optab->handlers[fieldmode].insn_code;
490
491       /* Get appropriate low part of the value being stored.  */
492       if (GET_CODE (value) == CONST_INT || REG_P (value))
493         value = gen_lowpart (fieldmode, value);
494       else if (!(GET_CODE (value) == SYMBOL_REF
495                  || GET_CODE (value) == LABEL_REF
496                  || GET_CODE (value) == CONST))
497         value = convert_to_mode (fieldmode, value, 0);
498
499       if (! (*insn_data[icode].operand[1].predicate) (value, fieldmode))
500         value = copy_to_mode_reg (fieldmode, value);
501
502       if (GET_CODE (op0) == SUBREG)
503         {
504           /* Else we've got some float mode source being extracted into
505              a different float mode destination -- this combination of
506              subregs results in Severe Tire Damage.  */
507           gcc_assert (GET_MODE (SUBREG_REG (op0)) == fieldmode
508                       || GET_MODE_CLASS (fieldmode) == MODE_INT
509                       || GET_MODE_CLASS (fieldmode) == MODE_PARTIAL_INT);
510           op0 = SUBREG_REG (op0);
511         }
512
513       emit_insn (GEN_FCN (icode)
514                  (gen_rtx_SUBREG (fieldmode, op0,
515                                   (bitnum % BITS_PER_WORD) / BITS_PER_UNIT
516                                   + (offset * UNITS_PER_WORD)),
517                                   value));
518
519       return value;
520     }
521
522   /* Handle fields bigger than a word.  */
523
524   if (bitsize > BITS_PER_WORD)
525     {
526       /* Here we transfer the words of the field
527          in the order least significant first.
528          This is because the most significant word is the one which may
529          be less than full.
530          However, only do that if the value is not BLKmode.  */
531
532       unsigned int backwards = WORDS_BIG_ENDIAN && fieldmode != BLKmode;
533       unsigned int nwords = (bitsize + (BITS_PER_WORD - 1)) / BITS_PER_WORD;
534       unsigned int i;
535
536       /* This is the mode we must force value to, so that there will be enough
537          subwords to extract.  Note that fieldmode will often (always?) be
538          VOIDmode, because that is what store_field uses to indicate that this
539          is a bit field, but passing VOIDmode to operand_subword_force
540          is not allowed.  */
541       fieldmode = GET_MODE (value);
542       if (fieldmode == VOIDmode)
543         fieldmode = smallest_mode_for_size (nwords * BITS_PER_WORD, MODE_INT);
544
545       for (i = 0; i < nwords; i++)
546         {
547           /* If I is 0, use the low-order word in both field and target;
548              if I is 1, use the next to lowest word; and so on.  */
549           unsigned int wordnum = (backwards ? nwords - i - 1 : i);
550           unsigned int bit_offset = (backwards
551                                      ? MAX ((int) bitsize - ((int) i + 1)
552                                             * BITS_PER_WORD,
553                                             0)
554                                      : (int) i * BITS_PER_WORD);
555
556           store_bit_field (op0, MIN (BITS_PER_WORD,
557                                      bitsize - i * BITS_PER_WORD),
558                            bitnum + bit_offset, word_mode,
559                            operand_subword_force (value, wordnum, fieldmode));
560         }
561       return value;
562     }
563
564   /* From here on we can assume that the field to be stored in is
565      a full-word (whatever type that is), since it is shorter than a word.  */
566
567   /* OFFSET is the number of words or bytes (UNIT says which)
568      from STR_RTX to the first word or byte containing part of the field.  */
569
570   if (!MEM_P (op0))
571     {
572       if (offset != 0
573           || GET_MODE_SIZE (GET_MODE (op0)) > UNITS_PER_WORD)
574         {
575           if (!REG_P (op0))
576             {
577               /* Since this is a destination (lvalue), we can't copy
578                  it to a pseudo.  We can remove a SUBREG that does not
579                  change the size of the operand.  Such a SUBREG may
580                  have been added above.  */
581               gcc_assert (GET_CODE (op0) == SUBREG
582                           && (GET_MODE_SIZE (GET_MODE (op0))
583                               == GET_MODE_SIZE (GET_MODE (SUBREG_REG (op0)))));
584               op0 = SUBREG_REG (op0);
585             }
586           op0 = gen_rtx_SUBREG (mode_for_size (BITS_PER_WORD, MODE_INT, 0),
587                                 op0, (offset * UNITS_PER_WORD));
588         }
589       offset = 0;
590     }
591
592   /* If VALUE has a floating-point or complex mode, access it as an
593      integer of the corresponding size.  This can occur on a machine
594      with 64 bit registers that uses SFmode for float.  It can also
595      occur for unaligned float or complex fields.  */
596   orig_value = value;
597   if (GET_MODE (value) != VOIDmode
598       && GET_MODE_CLASS (GET_MODE (value)) != MODE_INT
599       && GET_MODE_CLASS (GET_MODE (value)) != MODE_PARTIAL_INT)
600     {
601       value = gen_reg_rtx (int_mode_for_mode (GET_MODE (value)));
602       emit_move_insn (gen_lowpart (GET_MODE (orig_value), value), orig_value);
603     }
604
605   /* Now OFFSET is nonzero only if OP0 is memory
606      and is therefore always measured in bytes.  */
607
608   if (HAVE_insv
609       && GET_MODE (value) != BLKmode
610       && !(bitsize == 1 && GET_CODE (value) == CONST_INT)
611       /* Ensure insv's size is wide enough for this field.  */
612       && (GET_MODE_BITSIZE (op_mode) >= bitsize)
613       && ! ((REG_P (op0) || GET_CODE (op0) == SUBREG)
614             && (bitsize + bitpos > GET_MODE_BITSIZE (op_mode))))
615     {
616       int xbitpos = bitpos;
617       rtx value1;
618       rtx xop0 = op0;
619       rtx last = get_last_insn ();
620       rtx pat;
621       enum machine_mode maxmode = mode_for_extraction (EP_insv, 3);
622       int save_volatile_ok = volatile_ok;
623
624       volatile_ok = 1;
625
626       /* If this machine's insv can only insert into a register, copy OP0
627          into a register and save it back later.  */
628       if (MEM_P (op0)
629           && ! ((*insn_data[(int) CODE_FOR_insv].operand[0].predicate)
630                 (op0, VOIDmode)))
631         {
632           rtx tempreg;
633           enum machine_mode bestmode;
634
635           /* Get the mode to use for inserting into this field.  If OP0 is
636              BLKmode, get the smallest mode consistent with the alignment. If
637              OP0 is a non-BLKmode object that is no wider than MAXMODE, use its
638              mode. Otherwise, use the smallest mode containing the field.  */
639
640           if (GET_MODE (op0) == BLKmode
641               || GET_MODE_SIZE (GET_MODE (op0)) > GET_MODE_SIZE (maxmode))
642             bestmode
643               = get_best_mode (bitsize, bitnum, MEM_ALIGN (op0), maxmode,
644                                MEM_VOLATILE_P (op0));
645           else
646             bestmode = GET_MODE (op0);
647
648           if (bestmode == VOIDmode
649               || (SLOW_UNALIGNED_ACCESS (bestmode, MEM_ALIGN (op0))
650                   && GET_MODE_BITSIZE (bestmode) > MEM_ALIGN (op0)))
651             goto insv_loses;
652
653           /* Adjust address to point to the containing unit of that mode.
654              Compute offset as multiple of this unit, counting in bytes.  */
655           unit = GET_MODE_BITSIZE (bestmode);
656           offset = (bitnum / unit) * GET_MODE_SIZE (bestmode);
657           bitpos = bitnum % unit;
658           op0 = adjust_address (op0, bestmode,  offset);
659
660           /* Fetch that unit, store the bitfield in it, then store
661              the unit.  */
662           tempreg = copy_to_reg (op0);
663           store_bit_field (tempreg, bitsize, bitpos, fieldmode, orig_value);
664           emit_move_insn (op0, tempreg);
665           return value;
666         }
667       volatile_ok = save_volatile_ok;
668
669       /* Add OFFSET into OP0's address.  */
670       if (MEM_P (xop0))
671         xop0 = adjust_address (xop0, byte_mode, offset);
672
673       /* If xop0 is a register, we need it in MAXMODE
674          to make it acceptable to the format of insv.  */
675       if (GET_CODE (xop0) == SUBREG)
676         /* We can't just change the mode, because this might clobber op0,
677            and we will need the original value of op0 if insv fails.  */
678         xop0 = gen_rtx_SUBREG (maxmode, SUBREG_REG (xop0), SUBREG_BYTE (xop0));
679       if (REG_P (xop0) && GET_MODE (xop0) != maxmode)
680         xop0 = gen_rtx_SUBREG (maxmode, xop0, 0);
681
682       /* On big-endian machines, we count bits from the most significant.
683          If the bit field insn does not, we must invert.  */
684
685       if (BITS_BIG_ENDIAN != BYTES_BIG_ENDIAN)
686         xbitpos = unit - bitsize - xbitpos;
687
688       /* We have been counting XBITPOS within UNIT.
689          Count instead within the size of the register.  */
690       if (BITS_BIG_ENDIAN && !MEM_P (xop0))
691         xbitpos += GET_MODE_BITSIZE (maxmode) - unit;
692
693       unit = GET_MODE_BITSIZE (maxmode);
694
695       /* Convert VALUE to maxmode (which insv insn wants) in VALUE1.  */
696       value1 = value;
697       if (GET_MODE (value) != maxmode)
698         {
699           if (GET_MODE_BITSIZE (GET_MODE (value)) >= bitsize)
700             {
701               /* Optimization: Don't bother really extending VALUE
702                  if it has all the bits we will actually use.  However,
703                  if we must narrow it, be sure we do it correctly.  */
704
705               if (GET_MODE_SIZE (GET_MODE (value)) < GET_MODE_SIZE (maxmode))
706                 {
707                   rtx tmp;
708
709                   tmp = simplify_subreg (maxmode, value1, GET_MODE (value), 0);
710                   if (! tmp)
711                     tmp = simplify_gen_subreg (maxmode,
712                                                force_reg (GET_MODE (value),
713                                                           value1),
714                                                GET_MODE (value), 0);
715                   value1 = tmp;
716                 }
717               else
718                 value1 = gen_lowpart (maxmode, value1);
719             }
720           else if (GET_CODE (value) == CONST_INT)
721             value1 = gen_int_mode (INTVAL (value), maxmode);
722           else
723             /* Parse phase is supposed to make VALUE's data type
724                match that of the component reference, which is a type
725                at least as wide as the field; so VALUE should have
726                a mode that corresponds to that type.  */
727             gcc_assert (CONSTANT_P (value));
728         }
729
730       /* If this machine's insv insists on a register,
731          get VALUE1 into a register.  */
732       if (! ((*insn_data[(int) CODE_FOR_insv].operand[3].predicate)
733              (value1, maxmode)))
734         value1 = force_reg (maxmode, value1);
735
736       pat = gen_insv (xop0, GEN_INT (bitsize), GEN_INT (xbitpos), value1);
737       if (pat)
738         emit_insn (pat);
739       else
740         {
741           delete_insns_since (last);
742           store_fixed_bit_field (op0, offset, bitsize, bitpos, value);
743         }
744     }
745   else
746     insv_loses:
747     /* Insv is not available; store using shifts and boolean ops.  */
748     store_fixed_bit_field (op0, offset, bitsize, bitpos, value);
749   return value;
750 }
751 \f
752 /* Use shifts and boolean operations to store VALUE
753    into a bit field of width BITSIZE
754    in a memory location specified by OP0 except offset by OFFSET bytes.
755      (OFFSET must be 0 if OP0 is a register.)
756    The field starts at position BITPOS within the byte.
757     (If OP0 is a register, it may be a full word or a narrower mode,
758      but BITPOS still counts within a full word,
759      which is significant on bigendian machines.)  */
760
761 static void
762 store_fixed_bit_field (rtx op0, unsigned HOST_WIDE_INT offset,
763                        unsigned HOST_WIDE_INT bitsize,
764                        unsigned HOST_WIDE_INT bitpos, rtx value)
765 {
766   enum machine_mode mode;
767   unsigned int total_bits = BITS_PER_WORD;
768   rtx subtarget, temp;
769   int all_zero = 0;
770   int all_one = 0;
771
772   /* There is a case not handled here:
773      a structure with a known alignment of just a halfword
774      and a field split across two aligned halfwords within the structure.
775      Or likewise a structure with a known alignment of just a byte
776      and a field split across two bytes.
777      Such cases are not supposed to be able to occur.  */
778
779   if (REG_P (op0) || GET_CODE (op0) == SUBREG)
780     {
781       gcc_assert (!offset);
782       /* Special treatment for a bit field split across two registers.  */
783       if (bitsize + bitpos > BITS_PER_WORD)
784         {
785           store_split_bit_field (op0, bitsize, bitpos, value);
786           return;
787         }
788     }
789   else
790     {
791       /* Get the proper mode to use for this field.  We want a mode that
792          includes the entire field.  If such a mode would be larger than
793          a word, we won't be doing the extraction the normal way.
794          We don't want a mode bigger than the destination.  */
795
796       mode = GET_MODE (op0);
797       if (GET_MODE_BITSIZE (mode) == 0
798           || GET_MODE_BITSIZE (mode) > GET_MODE_BITSIZE (word_mode))
799         mode = word_mode;
800       mode = get_best_mode (bitsize, bitpos + offset * BITS_PER_UNIT,
801                             MEM_ALIGN (op0), mode, MEM_VOLATILE_P (op0));
802
803       if (mode == VOIDmode)
804         {
805           /* The only way this should occur is if the field spans word
806              boundaries.  */
807           store_split_bit_field (op0, bitsize, bitpos + offset * BITS_PER_UNIT,
808                                  value);
809           return;
810         }
811
812       total_bits = GET_MODE_BITSIZE (mode);
813
814       /* Make sure bitpos is valid for the chosen mode.  Adjust BITPOS to
815          be in the range 0 to total_bits-1, and put any excess bytes in
816          OFFSET.  */
817       if (bitpos >= total_bits)
818         {
819           offset += (bitpos / total_bits) * (total_bits / BITS_PER_UNIT);
820           bitpos -= ((bitpos / total_bits) * (total_bits / BITS_PER_UNIT)
821                      * BITS_PER_UNIT);
822         }
823
824       /* Get ref to an aligned byte, halfword, or word containing the field.
825          Adjust BITPOS to be position within a word,
826          and OFFSET to be the offset of that word.
827          Then alter OP0 to refer to that word.  */
828       bitpos += (offset % (total_bits / BITS_PER_UNIT)) * BITS_PER_UNIT;
829       offset -= (offset % (total_bits / BITS_PER_UNIT));
830       op0 = adjust_address (op0, mode, offset);
831     }
832
833   mode = GET_MODE (op0);
834
835   /* Now MODE is either some integral mode for a MEM as OP0,
836      or is a full-word for a REG as OP0.  TOTAL_BITS corresponds.
837      The bit field is contained entirely within OP0.
838      BITPOS is the starting bit number within OP0.
839      (OP0's mode may actually be narrower than MODE.)  */
840
841   if (BYTES_BIG_ENDIAN)
842       /* BITPOS is the distance between our msb
843          and that of the containing datum.
844          Convert it to the distance from the lsb.  */
845       bitpos = total_bits - bitsize - bitpos;
846
847   /* Now BITPOS is always the distance between our lsb
848      and that of OP0.  */
849
850   /* Shift VALUE left by BITPOS bits.  If VALUE is not constant,
851      we must first convert its mode to MODE.  */
852
853   if (GET_CODE (value) == CONST_INT)
854     {
855       HOST_WIDE_INT v = INTVAL (value);
856
857       if (bitsize < HOST_BITS_PER_WIDE_INT)
858         v &= ((HOST_WIDE_INT) 1 << bitsize) - 1;
859
860       if (v == 0)
861         all_zero = 1;
862       else if ((bitsize < HOST_BITS_PER_WIDE_INT
863                 && v == ((HOST_WIDE_INT) 1 << bitsize) - 1)
864                || (bitsize == HOST_BITS_PER_WIDE_INT && v == -1))
865         all_one = 1;
866
867       value = lshift_value (mode, value, bitpos, bitsize);
868     }
869   else
870     {
871       int must_and = (GET_MODE_BITSIZE (GET_MODE (value)) != bitsize
872                       && bitpos + bitsize != GET_MODE_BITSIZE (mode));
873
874       if (GET_MODE (value) != mode)
875         {
876           if ((REG_P (value) || GET_CODE (value) == SUBREG)
877               && GET_MODE_SIZE (mode) < GET_MODE_SIZE (GET_MODE (value)))
878             value = gen_lowpart (mode, value);
879           else
880             value = convert_to_mode (mode, value, 1);
881         }
882
883       if (must_and)
884         value = expand_binop (mode, and_optab, value,
885                               mask_rtx (mode, 0, bitsize, 0),
886                               NULL_RTX, 1, OPTAB_LIB_WIDEN);
887       if (bitpos > 0)
888         value = expand_shift (LSHIFT_EXPR, mode, value,
889                               build_int_cst (NULL_TREE, bitpos), NULL_RTX, 1);
890     }
891
892   /* Now clear the chosen bits in OP0,
893      except that if VALUE is -1 we need not bother.  */
894
895   subtarget = op0;
896
897   if (! all_one)
898     {
899       temp = expand_binop (mode, and_optab, op0,
900                            mask_rtx (mode, bitpos, bitsize, 1),
901                            subtarget, 1, OPTAB_LIB_WIDEN);
902       subtarget = temp;
903     }
904   else
905     temp = op0;
906
907   /* Now logical-or VALUE into OP0, unless it is zero.  */
908
909   if (! all_zero)
910     temp = expand_binop (mode, ior_optab, temp, value,
911                          subtarget, 1, OPTAB_LIB_WIDEN);
912   if (op0 != temp)
913     emit_move_insn (op0, temp);
914 }
915 \f
916 /* Store a bit field that is split across multiple accessible memory objects.
917
918    OP0 is the REG, SUBREG or MEM rtx for the first of the objects.
919    BITSIZE is the field width; BITPOS the position of its first bit
920    (within the word).
921    VALUE is the value to store.
922
923    This does not yet handle fields wider than BITS_PER_WORD.  */
924
925 static void
926 store_split_bit_field (rtx op0, unsigned HOST_WIDE_INT bitsize,
927                        unsigned HOST_WIDE_INT bitpos, rtx value)
928 {
929   unsigned int unit;
930   unsigned int bitsdone = 0;
931
932   /* Make sure UNIT isn't larger than BITS_PER_WORD, we can only handle that
933      much at a time.  */
934   if (REG_P (op0) || GET_CODE (op0) == SUBREG)
935     unit = BITS_PER_WORD;
936   else
937     unit = MIN (MEM_ALIGN (op0), BITS_PER_WORD);
938
939   /* If VALUE is a constant other than a CONST_INT, get it into a register in
940      WORD_MODE.  If we can do this using gen_lowpart_common, do so.  Note
941      that VALUE might be a floating-point constant.  */
942   if (CONSTANT_P (value) && GET_CODE (value) != CONST_INT)
943     {
944       rtx word = gen_lowpart_common (word_mode, value);
945
946       if (word && (value != word))
947         value = word;
948       else
949         value = gen_lowpart_common (word_mode,
950                                     force_reg (GET_MODE (value) != VOIDmode
951                                                ? GET_MODE (value)
952                                                : word_mode, value));
953     }
954
955   while (bitsdone < bitsize)
956     {
957       unsigned HOST_WIDE_INT thissize;
958       rtx part, word;
959       unsigned HOST_WIDE_INT thispos;
960       unsigned HOST_WIDE_INT offset;
961
962       offset = (bitpos + bitsdone) / unit;
963       thispos = (bitpos + bitsdone) % unit;
964
965       /* THISSIZE must not overrun a word boundary.  Otherwise,
966          store_fixed_bit_field will call us again, and we will mutually
967          recurse forever.  */
968       thissize = MIN (bitsize - bitsdone, BITS_PER_WORD);
969       thissize = MIN (thissize, unit - thispos);
970
971       if (BYTES_BIG_ENDIAN)
972         {
973           int total_bits;
974
975           /* We must do an endian conversion exactly the same way as it is
976              done in extract_bit_field, so that the two calls to
977              extract_fixed_bit_field will have comparable arguments.  */
978           if (!MEM_P (value) || GET_MODE (value) == BLKmode)
979             total_bits = BITS_PER_WORD;
980           else
981             total_bits = GET_MODE_BITSIZE (GET_MODE (value));
982
983           /* Fetch successively less significant portions.  */
984           if (GET_CODE (value) == CONST_INT)
985             part = GEN_INT (((unsigned HOST_WIDE_INT) (INTVAL (value))
986                              >> (bitsize - bitsdone - thissize))
987                             & (((HOST_WIDE_INT) 1 << thissize) - 1));
988           else
989             /* The args are chosen so that the last part includes the
990                lsb.  Give extract_bit_field the value it needs (with
991                endianness compensation) to fetch the piece we want.  */
992             part = extract_fixed_bit_field (word_mode, value, 0, thissize,
993                                             total_bits - bitsize + bitsdone,
994                                             NULL_RTX, 1);
995         }
996       else
997         {
998           /* Fetch successively more significant portions.  */
999           if (GET_CODE (value) == CONST_INT)
1000             part = GEN_INT (((unsigned HOST_WIDE_INT) (INTVAL (value))
1001                              >> bitsdone)
1002                             & (((HOST_WIDE_INT) 1 << thissize) - 1));
1003           else
1004             part = extract_fixed_bit_field (word_mode, value, 0, thissize,
1005                                             bitsdone, NULL_RTX, 1);
1006         }
1007
1008       /* If OP0 is a register, then handle OFFSET here.
1009
1010          When handling multiword bitfields, extract_bit_field may pass
1011          down a word_mode SUBREG of a larger REG for a bitfield that actually
1012          crosses a word boundary.  Thus, for a SUBREG, we must find
1013          the current word starting from the base register.  */
1014       if (GET_CODE (op0) == SUBREG)
1015         {
1016           int word_offset = (SUBREG_BYTE (op0) / UNITS_PER_WORD) + offset;
1017           word = operand_subword_force (SUBREG_REG (op0), word_offset,
1018                                         GET_MODE (SUBREG_REG (op0)));
1019           offset = 0;
1020         }
1021       else if (REG_P (op0))
1022         {
1023           word = operand_subword_force (op0, offset, GET_MODE (op0));
1024           offset = 0;
1025         }
1026       else
1027         word = op0;
1028
1029       /* OFFSET is in UNITs, and UNIT is in bits.
1030          store_fixed_bit_field wants offset in bytes.  */
1031       store_fixed_bit_field (word, offset * unit / BITS_PER_UNIT, thissize,
1032                              thispos, part);
1033       bitsdone += thissize;
1034     }
1035 }
1036 \f
1037 /* Generate code to extract a byte-field from STR_RTX
1038    containing BITSIZE bits, starting at BITNUM,
1039    and put it in TARGET if possible (if TARGET is nonzero).
1040    Regardless of TARGET, we return the rtx for where the value is placed.
1041
1042    STR_RTX is the structure containing the byte (a REG or MEM).
1043    UNSIGNEDP is nonzero if this is an unsigned bit field.
1044    MODE is the natural mode of the field value once extracted.
1045    TMODE is the mode the caller would like the value to have;
1046    but the value may be returned with type MODE instead.
1047
1048    TOTAL_SIZE is the size in bytes of the containing structure,
1049    or -1 if varying.
1050
1051    If a TARGET is specified and we can store in it at no extra cost,
1052    we do so, and return TARGET.
1053    Otherwise, we return a REG of mode TMODE or MODE, with TMODE preferred
1054    if they are equally easy.  */
1055
1056 rtx
1057 extract_bit_field (rtx str_rtx, unsigned HOST_WIDE_INT bitsize,
1058                    unsigned HOST_WIDE_INT bitnum, int unsignedp, rtx target,
1059                    enum machine_mode mode, enum machine_mode tmode)
1060 {
1061   unsigned int unit
1062     = (MEM_P (str_rtx)) ? BITS_PER_UNIT : BITS_PER_WORD;
1063   unsigned HOST_WIDE_INT offset, bitpos;
1064   rtx op0 = str_rtx;
1065   rtx spec_target = target;
1066   rtx spec_target_subreg = 0;
1067   enum machine_mode int_mode;
1068   enum machine_mode extv_mode = mode_for_extraction (EP_extv, 0);
1069   enum machine_mode extzv_mode = mode_for_extraction (EP_extzv, 0);
1070   enum machine_mode mode1;
1071   int byte_offset;
1072
1073   if (tmode == VOIDmode)
1074     tmode = mode;
1075
1076   while (GET_CODE (op0) == SUBREG)
1077     {
1078       bitnum += SUBREG_BYTE (op0) * BITS_PER_UNIT;
1079       op0 = SUBREG_REG (op0);
1080     }
1081
1082   /* If we have an out-of-bounds access to a register, just return an
1083      uninitialized register of the required mode.  This can occur if the
1084      source code contains an out-of-bounds access to a small array.  */
1085   if (REG_P (op0) && bitnum >= GET_MODE_BITSIZE (GET_MODE (op0)))
1086     return gen_reg_rtx (tmode);
1087
1088   if (REG_P (op0)
1089       && mode == GET_MODE (op0)
1090       && bitnum == 0
1091       && bitsize == GET_MODE_BITSIZE (GET_MODE (op0)))
1092     {
1093       /* We're trying to extract a full register from itself.  */
1094       return op0;
1095     }
1096
1097   /* Use vec_extract patterns for extracting parts of vectors whenever
1098      available.  */
1099   if (VECTOR_MODE_P (GET_MODE (op0))
1100       && !MEM_P (op0)
1101       && (vec_extract_optab->handlers[GET_MODE (op0)].insn_code
1102           != CODE_FOR_nothing)
1103       && ((bitnum + bitsize - 1) / GET_MODE_BITSIZE (GET_MODE_INNER (GET_MODE (op0)))
1104           == bitnum / GET_MODE_BITSIZE (GET_MODE_INNER (GET_MODE (op0)))))
1105     {
1106       enum machine_mode outermode = GET_MODE (op0);
1107       enum machine_mode innermode = GET_MODE_INNER (outermode);
1108       int icode = (int) vec_extract_optab->handlers[outermode].insn_code;
1109       unsigned HOST_WIDE_INT pos = bitnum / GET_MODE_BITSIZE (innermode);
1110       rtx rtxpos = GEN_INT (pos);
1111       rtx src = op0;
1112       rtx dest = NULL, pat, seq;
1113       enum machine_mode mode0 = insn_data[icode].operand[0].mode;
1114       enum machine_mode mode1 = insn_data[icode].operand[1].mode;
1115       enum machine_mode mode2 = insn_data[icode].operand[2].mode;
1116
1117       if (innermode == tmode || innermode == mode)
1118         dest = target;
1119
1120       if (!dest)
1121         dest = gen_reg_rtx (innermode);
1122
1123       start_sequence ();
1124
1125       if (! (*insn_data[icode].operand[0].predicate) (dest, mode0))
1126         dest = copy_to_mode_reg (mode0, dest);
1127
1128       if (! (*insn_data[icode].operand[1].predicate) (src, mode1))
1129         src = copy_to_mode_reg (mode1, src);
1130
1131       if (! (*insn_data[icode].operand[2].predicate) (rtxpos, mode2))
1132         rtxpos = copy_to_mode_reg (mode1, rtxpos);
1133
1134       /* We could handle this, but we should always be called with a pseudo
1135          for our targets and all insns should take them as outputs.  */
1136       gcc_assert ((*insn_data[icode].operand[0].predicate) (dest, mode0)
1137                   && (*insn_data[icode].operand[1].predicate) (src, mode1)
1138                   && (*insn_data[icode].operand[2].predicate) (rtxpos, mode2));
1139
1140       pat = GEN_FCN (icode) (dest, src, rtxpos);
1141       seq = get_insns ();
1142       end_sequence ();
1143       if (pat)
1144         {
1145           emit_insn (seq);
1146           emit_insn (pat);
1147           return dest;
1148         }
1149     }
1150
1151   /* Make sure we are playing with integral modes.  Pun with subregs
1152      if we aren't.  */
1153   {
1154     enum machine_mode imode = int_mode_for_mode (GET_MODE (op0));
1155     if (imode != GET_MODE (op0))
1156       {
1157         if (MEM_P (op0))
1158           op0 = adjust_address (op0, imode, 0);
1159         else
1160           {
1161             gcc_assert (imode != BLKmode);
1162             op0 = gen_lowpart (imode, op0);
1163
1164             /* If we got a SUBREG, force it into a register since we
1165                aren't going to be able to do another SUBREG on it.  */
1166             if (GET_CODE (op0) == SUBREG)
1167               op0 = force_reg (imode, op0);
1168           }
1169       }
1170   }
1171
1172   /* We may be accessing data outside the field, which means
1173      we can alias adjacent data.  */
1174   if (MEM_P (op0))
1175     {
1176       op0 = shallow_copy_rtx (op0);
1177       set_mem_alias_set (op0, 0);
1178       set_mem_expr (op0, 0);
1179     }
1180
1181   /* Extraction of a full-word or multi-word value from a structure
1182      in a register or aligned memory can be done with just a SUBREG.
1183      A subword value in the least significant part of a register
1184      can also be extracted with a SUBREG.  For this, we need the
1185      byte offset of the value in op0.  */
1186
1187   bitpos = bitnum % unit;
1188   offset = bitnum / unit;
1189   byte_offset = bitpos / BITS_PER_UNIT + offset * UNITS_PER_WORD;
1190
1191   /* If OP0 is a register, BITPOS must count within a word.
1192      But as we have it, it counts within whatever size OP0 now has.
1193      On a bigendian machine, these are not the same, so convert.  */
1194   if (BYTES_BIG_ENDIAN
1195       && !MEM_P (op0)
1196       && unit > GET_MODE_BITSIZE (GET_MODE (op0)))
1197     bitpos += unit - GET_MODE_BITSIZE (GET_MODE (op0));
1198
1199   /* ??? We currently assume TARGET is at least as big as BITSIZE.
1200      If that's wrong, the solution is to test for it and set TARGET to 0
1201      if needed.  */
1202
1203   /* Only scalar integer modes can be converted via subregs.  There is an
1204      additional problem for FP modes here in that they can have a precision
1205      which is different from the size.  mode_for_size uses precision, but
1206      we want a mode based on the size, so we must avoid calling it for FP
1207      modes.  */
1208   mode1  = (SCALAR_INT_MODE_P (tmode)
1209             ? mode_for_size (bitsize, GET_MODE_CLASS (tmode), 0)
1210             : mode);
1211
1212   if (((bitsize >= BITS_PER_WORD && bitsize == GET_MODE_BITSIZE (mode)
1213         && bitpos % BITS_PER_WORD == 0)
1214        || (mode1 != BLKmode
1215            /* ??? The big endian test here is wrong.  This is correct
1216               if the value is in a register, and if mode_for_size is not
1217               the same mode as op0.  This causes us to get unnecessarily
1218               inefficient code from the Thumb port when -mbig-endian.  */
1219            && (BYTES_BIG_ENDIAN
1220                ? bitpos + bitsize == BITS_PER_WORD
1221                : bitpos == 0)))
1222       && ((!MEM_P (op0)
1223            && TRULY_NOOP_TRUNCATION (GET_MODE_BITSIZE (mode),
1224                                      GET_MODE_BITSIZE (GET_MODE (op0)))
1225            && GET_MODE_SIZE (mode1) != 0
1226            && byte_offset % GET_MODE_SIZE (mode1) == 0)
1227           || (MEM_P (op0)
1228               && (! SLOW_UNALIGNED_ACCESS (mode, MEM_ALIGN (op0))
1229                   || (offset * BITS_PER_UNIT % bitsize == 0
1230                       && MEM_ALIGN (op0) % bitsize == 0)))))
1231     {
1232       if (mode1 != GET_MODE (op0))
1233         {
1234           if (MEM_P (op0))
1235             op0 = adjust_address (op0, mode1, offset);
1236           else
1237             {
1238               rtx sub = simplify_gen_subreg (mode1, op0, GET_MODE (op0),
1239                                              byte_offset);
1240               if (sub == NULL)
1241                 goto no_subreg_mode_swap;
1242               op0 = sub;
1243             }
1244         }
1245       if (mode1 != mode)
1246         return convert_to_mode (tmode, op0, unsignedp);
1247       return op0;
1248     }
1249  no_subreg_mode_swap:
1250
1251   /* Handle fields bigger than a word.  */
1252
1253   if (bitsize > BITS_PER_WORD)
1254     {
1255       /* Here we transfer the words of the field
1256          in the order least significant first.
1257          This is because the most significant word is the one which may
1258          be less than full.  */
1259
1260       unsigned int nwords = (bitsize + (BITS_PER_WORD - 1)) / BITS_PER_WORD;
1261       unsigned int i;
1262
1263       if (target == 0 || !REG_P (target))
1264         target = gen_reg_rtx (mode);
1265
1266       /* Indicate for flow that the entire target reg is being set.  */
1267       emit_insn (gen_rtx_CLOBBER (VOIDmode, target));
1268
1269       for (i = 0; i < nwords; i++)
1270         {
1271           /* If I is 0, use the low-order word in both field and target;
1272              if I is 1, use the next to lowest word; and so on.  */
1273           /* Word number in TARGET to use.  */
1274           unsigned int wordnum
1275             = (WORDS_BIG_ENDIAN
1276                ? GET_MODE_SIZE (GET_MODE (target)) / UNITS_PER_WORD - i - 1
1277                : i);
1278           /* Offset from start of field in OP0.  */
1279           unsigned int bit_offset = (WORDS_BIG_ENDIAN
1280                                      ? MAX (0, ((int) bitsize - ((int) i + 1)
1281                                                 * (int) BITS_PER_WORD))
1282                                      : (int) i * BITS_PER_WORD);
1283           rtx target_part = operand_subword (target, wordnum, 1, VOIDmode);
1284           rtx result_part
1285             = extract_bit_field (op0, MIN (BITS_PER_WORD,
1286                                            bitsize - i * BITS_PER_WORD),
1287                                  bitnum + bit_offset, 1, target_part, mode,
1288                                  word_mode);
1289
1290           gcc_assert (target_part);
1291
1292           if (result_part != target_part)
1293             emit_move_insn (target_part, result_part);
1294         }
1295
1296       if (unsignedp)
1297         {
1298           /* Unless we've filled TARGET, the upper regs in a multi-reg value
1299              need to be zero'd out.  */
1300           if (GET_MODE_SIZE (GET_MODE (target)) > nwords * UNITS_PER_WORD)
1301             {
1302               unsigned int i, total_words;
1303
1304               total_words = GET_MODE_SIZE (GET_MODE (target)) / UNITS_PER_WORD;
1305               for (i = nwords; i < total_words; i++)
1306                 emit_move_insn
1307                   (operand_subword (target,
1308                                     WORDS_BIG_ENDIAN ? total_words - i - 1 : i,
1309                                     1, VOIDmode),
1310                    const0_rtx);
1311             }
1312           return target;
1313         }
1314
1315       /* Signed bit field: sign-extend with two arithmetic shifts.  */
1316       target = expand_shift (LSHIFT_EXPR, mode, target,
1317                              build_int_cst (NULL_TREE,
1318                                             GET_MODE_BITSIZE (mode) - bitsize),
1319                              NULL_RTX, 0);
1320       return expand_shift (RSHIFT_EXPR, mode, target,
1321                            build_int_cst (NULL_TREE,
1322                                           GET_MODE_BITSIZE (mode) - bitsize),
1323                            NULL_RTX, 0);
1324     }
1325
1326   /* From here on we know the desired field is smaller than a word.  */
1327
1328   /* Check if there is a correspondingly-sized integer field, so we can
1329      safely extract it as one size of integer, if necessary; then
1330      truncate or extend to the size that is wanted; then use SUBREGs or
1331      convert_to_mode to get one of the modes we really wanted.  */
1332
1333   int_mode = int_mode_for_mode (tmode);
1334   if (int_mode == BLKmode)
1335     int_mode = int_mode_for_mode (mode);
1336   /* Should probably push op0 out to memory and then do a load.  */
1337   gcc_assert (int_mode != BLKmode);
1338
1339   /* OFFSET is the number of words or bytes (UNIT says which)
1340      from STR_RTX to the first word or byte containing part of the field.  */
1341   if (!MEM_P (op0))
1342     {
1343       if (offset != 0
1344           || GET_MODE_SIZE (GET_MODE (op0)) > UNITS_PER_WORD)
1345         {
1346           if (!REG_P (op0))
1347             op0 = copy_to_reg (op0);
1348           op0 = gen_rtx_SUBREG (mode_for_size (BITS_PER_WORD, MODE_INT, 0),
1349                                 op0, (offset * UNITS_PER_WORD));
1350         }
1351       offset = 0;
1352     }
1353
1354   /* Now OFFSET is nonzero only for memory operands.  */
1355
1356   if (unsignedp)
1357     {
1358       if (HAVE_extzv
1359           && (GET_MODE_BITSIZE (extzv_mode) >= bitsize)
1360           && ! ((REG_P (op0) || GET_CODE (op0) == SUBREG)
1361                 && (bitsize + bitpos > GET_MODE_BITSIZE (extzv_mode))))
1362         {
1363           unsigned HOST_WIDE_INT xbitpos = bitpos, xoffset = offset;
1364           rtx bitsize_rtx, bitpos_rtx;
1365           rtx last = get_last_insn ();
1366           rtx xop0 = op0;
1367           rtx xtarget = target;
1368           rtx xspec_target = spec_target;
1369           rtx xspec_target_subreg = spec_target_subreg;
1370           rtx pat;
1371           enum machine_mode maxmode = mode_for_extraction (EP_extzv, 0);
1372
1373           if (MEM_P (xop0))
1374             {
1375               int save_volatile_ok = volatile_ok;
1376               volatile_ok = 1;
1377
1378               /* Is the memory operand acceptable?  */
1379               if (! ((*insn_data[(int) CODE_FOR_extzv].operand[1].predicate)
1380                      (xop0, GET_MODE (xop0))))
1381                 {
1382                   /* No, load into a reg and extract from there.  */
1383                   enum machine_mode bestmode;
1384
1385                   /* Get the mode to use for inserting into this field.  If
1386                      OP0 is BLKmode, get the smallest mode consistent with the
1387                      alignment. If OP0 is a non-BLKmode object that is no
1388                      wider than MAXMODE, use its mode. Otherwise, use the
1389                      smallest mode containing the field.  */
1390
1391                   if (GET_MODE (xop0) == BLKmode
1392                       || (GET_MODE_SIZE (GET_MODE (op0))
1393                           > GET_MODE_SIZE (maxmode)))
1394                     bestmode = get_best_mode (bitsize, bitnum,
1395                                               MEM_ALIGN (xop0), maxmode,
1396                                               MEM_VOLATILE_P (xop0));
1397                   else
1398                     bestmode = GET_MODE (xop0);
1399
1400                   if (bestmode == VOIDmode
1401                       || (SLOW_UNALIGNED_ACCESS (bestmode, MEM_ALIGN (xop0))
1402                           && GET_MODE_BITSIZE (bestmode) > MEM_ALIGN (xop0)))
1403                     goto extzv_loses;
1404
1405                   /* Compute offset as multiple of this unit,
1406                      counting in bytes.  */
1407                   unit = GET_MODE_BITSIZE (bestmode);
1408                   xoffset = (bitnum / unit) * GET_MODE_SIZE (bestmode);
1409                   xbitpos = bitnum % unit;
1410                   xop0 = adjust_address (xop0, bestmode, xoffset);
1411
1412                   /* Fetch it to a register in that size.  */
1413                   xop0 = force_reg (bestmode, xop0);
1414
1415                   /* XBITPOS counts within UNIT, which is what is expected.  */
1416                 }
1417               else
1418                 /* Get ref to first byte containing part of the field.  */
1419                 xop0 = adjust_address (xop0, byte_mode, xoffset);
1420
1421               volatile_ok = save_volatile_ok;
1422             }
1423
1424           /* If op0 is a register, we need it in MAXMODE (which is usually
1425              SImode). to make it acceptable to the format of extzv.  */
1426           if (GET_CODE (xop0) == SUBREG && GET_MODE (xop0) != maxmode)
1427             goto extzv_loses;
1428           if (REG_P (xop0) && GET_MODE (xop0) != maxmode)
1429             xop0 = gen_rtx_SUBREG (maxmode, xop0, 0);
1430
1431           /* On big-endian machines, we count bits from the most significant.
1432              If the bit field insn does not, we must invert.  */
1433           if (BITS_BIG_ENDIAN != BYTES_BIG_ENDIAN)
1434             xbitpos = unit - bitsize - xbitpos;
1435
1436           /* Now convert from counting within UNIT to counting in MAXMODE.  */
1437           if (BITS_BIG_ENDIAN && !MEM_P (xop0))
1438             xbitpos += GET_MODE_BITSIZE (maxmode) - unit;
1439
1440           unit = GET_MODE_BITSIZE (maxmode);
1441
1442           if (xtarget == 0)
1443             xtarget = xspec_target = gen_reg_rtx (tmode);
1444
1445           if (GET_MODE (xtarget) != maxmode)
1446             {
1447               if (REG_P (xtarget))
1448                 {
1449                   int wider = (GET_MODE_SIZE (maxmode)
1450                                > GET_MODE_SIZE (GET_MODE (xtarget)));
1451                   xtarget = gen_lowpart (maxmode, xtarget);
1452                   if (wider)
1453                     xspec_target_subreg = xtarget;
1454                 }
1455               else
1456                 xtarget = gen_reg_rtx (maxmode);
1457             }
1458
1459           /* If this machine's extzv insists on a register target,
1460              make sure we have one.  */
1461           if (! ((*insn_data[(int) CODE_FOR_extzv].operand[0].predicate)
1462                  (xtarget, maxmode)))
1463             xtarget = gen_reg_rtx (maxmode);
1464
1465           bitsize_rtx = GEN_INT (bitsize);
1466           bitpos_rtx = GEN_INT (xbitpos);
1467
1468           pat = gen_extzv (xtarget, xop0, bitsize_rtx, bitpos_rtx);
1469           if (pat)
1470             {
1471               emit_insn (pat);
1472               target = xtarget;
1473               spec_target = xspec_target;
1474               spec_target_subreg = xspec_target_subreg;
1475             }
1476           else
1477             {
1478               delete_insns_since (last);
1479               target = extract_fixed_bit_field (int_mode, op0, offset, bitsize,
1480                                                 bitpos, target, 1);
1481             }
1482         }
1483       else
1484       extzv_loses:
1485         target = extract_fixed_bit_field (int_mode, op0, offset, bitsize,
1486                                           bitpos, target, 1);
1487     }
1488   else
1489     {
1490       if (HAVE_extv
1491           && (GET_MODE_BITSIZE (extv_mode) >= bitsize)
1492           && ! ((REG_P (op0) || GET_CODE (op0) == SUBREG)
1493                 && (bitsize + bitpos > GET_MODE_BITSIZE (extv_mode))))
1494         {
1495           int xbitpos = bitpos, xoffset = offset;
1496           rtx bitsize_rtx, bitpos_rtx;
1497           rtx last = get_last_insn ();
1498           rtx xop0 = op0, xtarget = target;
1499           rtx xspec_target = spec_target;
1500           rtx xspec_target_subreg = spec_target_subreg;
1501           rtx pat;
1502           enum machine_mode maxmode = mode_for_extraction (EP_extv, 0);
1503
1504           if (MEM_P (xop0))
1505             {
1506               /* Is the memory operand acceptable?  */
1507               if (! ((*insn_data[(int) CODE_FOR_extv].operand[1].predicate)
1508                      (xop0, GET_MODE (xop0))))
1509                 {
1510                   /* No, load into a reg and extract from there.  */
1511                   enum machine_mode bestmode;
1512
1513                   /* Get the mode to use for inserting into this field.  If
1514                      OP0 is BLKmode, get the smallest mode consistent with the
1515                      alignment. If OP0 is a non-BLKmode object that is no
1516                      wider than MAXMODE, use its mode. Otherwise, use the
1517                      smallest mode containing the field.  */
1518
1519                   if (GET_MODE (xop0) == BLKmode
1520                       || (GET_MODE_SIZE (GET_MODE (op0))
1521                           > GET_MODE_SIZE (maxmode)))
1522                     bestmode = get_best_mode (bitsize, bitnum,
1523                                               MEM_ALIGN (xop0), maxmode,
1524                                               MEM_VOLATILE_P (xop0));
1525                   else
1526                     bestmode = GET_MODE (xop0);
1527
1528                   if (bestmode == VOIDmode
1529                       || (SLOW_UNALIGNED_ACCESS (bestmode, MEM_ALIGN (xop0))
1530                           && GET_MODE_BITSIZE (bestmode) > MEM_ALIGN (xop0)))
1531                     goto extv_loses;
1532
1533                   /* Compute offset as multiple of this unit,
1534                      counting in bytes.  */
1535                   unit = GET_MODE_BITSIZE (bestmode);
1536                   xoffset = (bitnum / unit) * GET_MODE_SIZE (bestmode);
1537                   xbitpos = bitnum % unit;
1538                   xop0 = adjust_address (xop0, bestmode, xoffset);
1539
1540                   /* Fetch it to a register in that size.  */
1541                   xop0 = force_reg (bestmode, xop0);
1542
1543                   /* XBITPOS counts within UNIT, which is what is expected.  */
1544                 }
1545               else
1546                 /* Get ref to first byte containing part of the field.  */
1547                 xop0 = adjust_address (xop0, byte_mode, xoffset);
1548             }
1549
1550           /* If op0 is a register, we need it in MAXMODE (which is usually
1551              SImode) to make it acceptable to the format of extv.  */
1552           if (GET_CODE (xop0) == SUBREG && GET_MODE (xop0) != maxmode)
1553             goto extv_loses;
1554           if (REG_P (xop0) && GET_MODE (xop0) != maxmode)
1555             xop0 = gen_rtx_SUBREG (maxmode, xop0, 0);
1556
1557           /* On big-endian machines, we count bits from the most significant.
1558              If the bit field insn does not, we must invert.  */
1559           if (BITS_BIG_ENDIAN != BYTES_BIG_ENDIAN)
1560             xbitpos = unit - bitsize - xbitpos;
1561
1562           /* XBITPOS counts within a size of UNIT.
1563              Adjust to count within a size of MAXMODE.  */
1564           if (BITS_BIG_ENDIAN && !MEM_P (xop0))
1565             xbitpos += (GET_MODE_BITSIZE (maxmode) - unit);
1566
1567           unit = GET_MODE_BITSIZE (maxmode);
1568
1569           if (xtarget == 0)
1570             xtarget = xspec_target = gen_reg_rtx (tmode);
1571
1572           if (GET_MODE (xtarget) != maxmode)
1573             {
1574               if (REG_P (xtarget))
1575                 {
1576                   int wider = (GET_MODE_SIZE (maxmode)
1577                                > GET_MODE_SIZE (GET_MODE (xtarget)));
1578                   xtarget = gen_lowpart (maxmode, xtarget);
1579                   if (wider)
1580                     xspec_target_subreg = xtarget;
1581                 }
1582               else
1583                 xtarget = gen_reg_rtx (maxmode);
1584             }
1585
1586           /* If this machine's extv insists on a register target,
1587              make sure we have one.  */
1588           if (! ((*insn_data[(int) CODE_FOR_extv].operand[0].predicate)
1589                  (xtarget, maxmode)))
1590             xtarget = gen_reg_rtx (maxmode);
1591
1592           bitsize_rtx = GEN_INT (bitsize);
1593           bitpos_rtx = GEN_INT (xbitpos);
1594
1595           pat = gen_extv (xtarget, xop0, bitsize_rtx, bitpos_rtx);
1596           if (pat)
1597             {
1598               emit_insn (pat);
1599               target = xtarget;
1600               spec_target = xspec_target;
1601               spec_target_subreg = xspec_target_subreg;
1602             }
1603           else
1604             {
1605               delete_insns_since (last);
1606               target = extract_fixed_bit_field (int_mode, op0, offset, bitsize,
1607                                                 bitpos, target, 0);
1608             }
1609         }
1610       else
1611       extv_loses:
1612         target = extract_fixed_bit_field (int_mode, op0, offset, bitsize,
1613                                           bitpos, target, 0);
1614     }
1615   if (target == spec_target)
1616     return target;
1617   if (target == spec_target_subreg)
1618     return spec_target;
1619   if (GET_MODE (target) != tmode && GET_MODE (target) != mode)
1620     {
1621       /* If the target mode is not a scalar integral, first convert to the
1622          integer mode of that size and then access it as a floating-point
1623          value via a SUBREG.  */
1624       if (!SCALAR_INT_MODE_P (tmode))
1625         {
1626           enum machine_mode smode
1627             = mode_for_size (GET_MODE_BITSIZE (tmode), MODE_INT, 0);
1628           target = convert_to_mode (smode, target, unsignedp);
1629           target = force_reg (smode, target);
1630           return gen_lowpart (tmode, target);
1631         }
1632
1633       return convert_to_mode (tmode, target, unsignedp);
1634     }
1635   return target;
1636 }
1637 \f
1638 /* Extract a bit field using shifts and boolean operations
1639    Returns an rtx to represent the value.
1640    OP0 addresses a register (word) or memory (byte).
1641    BITPOS says which bit within the word or byte the bit field starts in.
1642    OFFSET says how many bytes farther the bit field starts;
1643     it is 0 if OP0 is a register.
1644    BITSIZE says how many bits long the bit field is.
1645     (If OP0 is a register, it may be narrower than a full word,
1646      but BITPOS still counts within a full word,
1647      which is significant on bigendian machines.)
1648
1649    UNSIGNEDP is nonzero for an unsigned bit field (don't sign-extend value).
1650    If TARGET is nonzero, attempts to store the value there
1651    and return TARGET, but this is not guaranteed.
1652    If TARGET is not used, create a pseudo-reg of mode TMODE for the value.  */
1653
1654 static rtx
1655 extract_fixed_bit_field (enum machine_mode tmode, rtx op0,
1656                          unsigned HOST_WIDE_INT offset,
1657                          unsigned HOST_WIDE_INT bitsize,
1658                          unsigned HOST_WIDE_INT bitpos, rtx target,
1659                          int unsignedp)
1660 {
1661   unsigned int total_bits = BITS_PER_WORD;
1662   enum machine_mode mode;
1663
1664   if (GET_CODE (op0) == SUBREG || REG_P (op0))
1665     {
1666       /* Special treatment for a bit field split across two registers.  */
1667       if (bitsize + bitpos > BITS_PER_WORD)
1668         return extract_split_bit_field (op0, bitsize, bitpos, unsignedp);
1669     }
1670   else
1671     {
1672       /* Get the proper mode to use for this field.  We want a mode that
1673          includes the entire field.  If such a mode would be larger than
1674          a word, we won't be doing the extraction the normal way.  */
1675
1676       mode = get_best_mode (bitsize, bitpos + offset * BITS_PER_UNIT,
1677                             MEM_ALIGN (op0), word_mode, MEM_VOLATILE_P (op0));
1678
1679       if (mode == VOIDmode)
1680         /* The only way this should occur is if the field spans word
1681            boundaries.  */
1682         return extract_split_bit_field (op0, bitsize,
1683                                         bitpos + offset * BITS_PER_UNIT,
1684                                         unsignedp);
1685
1686       total_bits = GET_MODE_BITSIZE (mode);
1687
1688       /* Make sure bitpos is valid for the chosen mode.  Adjust BITPOS to
1689          be in the range 0 to total_bits-1, and put any excess bytes in
1690          OFFSET.  */
1691       if (bitpos >= total_bits)
1692         {
1693           offset += (bitpos / total_bits) * (total_bits / BITS_PER_UNIT);
1694           bitpos -= ((bitpos / total_bits) * (total_bits / BITS_PER_UNIT)
1695                      * BITS_PER_UNIT);
1696         }
1697
1698       /* Get ref to an aligned byte, halfword, or word containing the field.
1699          Adjust BITPOS to be position within a word,
1700          and OFFSET to be the offset of that word.
1701          Then alter OP0 to refer to that word.  */
1702       bitpos += (offset % (total_bits / BITS_PER_UNIT)) * BITS_PER_UNIT;
1703       offset -= (offset % (total_bits / BITS_PER_UNIT));
1704       op0 = adjust_address (op0, mode, offset);
1705     }
1706
1707   mode = GET_MODE (op0);
1708
1709   if (BYTES_BIG_ENDIAN)
1710     /* BITPOS is the distance between our msb and that of OP0.
1711        Convert it to the distance from the lsb.  */
1712     bitpos = total_bits - bitsize - bitpos;
1713
1714   /* Now BITPOS is always the distance between the field's lsb and that of OP0.
1715      We have reduced the big-endian case to the little-endian case.  */
1716
1717   if (unsignedp)
1718     {
1719       if (bitpos)
1720         {
1721           /* If the field does not already start at the lsb,
1722              shift it so it does.  */
1723           tree amount = build_int_cst (NULL_TREE, bitpos);
1724           /* Maybe propagate the target for the shift.  */
1725           /* But not if we will return it--could confuse integrate.c.  */
1726           rtx subtarget = (target != 0 && REG_P (target) ? target : 0);
1727           if (tmode != mode) subtarget = 0;
1728           op0 = expand_shift (RSHIFT_EXPR, mode, op0, amount, subtarget, 1);
1729         }
1730       /* Convert the value to the desired mode.  */
1731       if (mode != tmode)
1732         op0 = convert_to_mode (tmode, op0, 1);
1733
1734       /* Unless the msb of the field used to be the msb when we shifted,
1735          mask out the upper bits.  */
1736
1737       if (GET_MODE_BITSIZE (mode) != bitpos + bitsize)
1738         return expand_binop (GET_MODE (op0), and_optab, op0,
1739                              mask_rtx (GET_MODE (op0), 0, bitsize, 0),
1740                              target, 1, OPTAB_LIB_WIDEN);
1741       return op0;
1742     }
1743
1744   /* To extract a signed bit-field, first shift its msb to the msb of the word,
1745      then arithmetic-shift its lsb to the lsb of the word.  */
1746   op0 = force_reg (mode, op0);
1747   if (mode != tmode)
1748     target = 0;
1749
1750   /* Find the narrowest integer mode that contains the field.  */
1751
1752   for (mode = GET_CLASS_NARROWEST_MODE (MODE_INT); mode != VOIDmode;
1753        mode = GET_MODE_WIDER_MODE (mode))
1754     if (GET_MODE_BITSIZE (mode) >= bitsize + bitpos)
1755       {
1756         op0 = convert_to_mode (mode, op0, 0);
1757         break;
1758       }
1759
1760   if (GET_MODE_BITSIZE (mode) != (bitsize + bitpos))
1761     {
1762       tree amount
1763         = build_int_cst (NULL_TREE,
1764                          GET_MODE_BITSIZE (mode) - (bitsize + bitpos));
1765       /* Maybe propagate the target for the shift.  */
1766       rtx subtarget = (target != 0 && REG_P (target) ? target : 0);
1767       op0 = expand_shift (LSHIFT_EXPR, mode, op0, amount, subtarget, 1);
1768     }
1769
1770   return expand_shift (RSHIFT_EXPR, mode, op0,
1771                        build_int_cst (NULL_TREE,
1772                                       GET_MODE_BITSIZE (mode) - bitsize),
1773                        target, 0);
1774 }
1775 \f
1776 /* Return a constant integer (CONST_INT or CONST_DOUBLE) mask value
1777    of mode MODE with BITSIZE ones followed by BITPOS zeros, or the
1778    complement of that if COMPLEMENT.  The mask is truncated if
1779    necessary to the width of mode MODE.  The mask is zero-extended if
1780    BITSIZE+BITPOS is too small for MODE.  */
1781
1782 static rtx
1783 mask_rtx (enum machine_mode mode, int bitpos, int bitsize, int complement)
1784 {
1785   HOST_WIDE_INT masklow, maskhigh;
1786
1787   if (bitsize == 0)
1788     masklow = 0;
1789   else if (bitpos < HOST_BITS_PER_WIDE_INT)
1790     masklow = (HOST_WIDE_INT) -1 << bitpos;
1791   else
1792     masklow = 0;
1793
1794   if (bitpos + bitsize < HOST_BITS_PER_WIDE_INT)
1795     masklow &= ((unsigned HOST_WIDE_INT) -1
1796                 >> (HOST_BITS_PER_WIDE_INT - bitpos - bitsize));
1797
1798   if (bitpos <= HOST_BITS_PER_WIDE_INT)
1799     maskhigh = -1;
1800   else
1801     maskhigh = (HOST_WIDE_INT) -1 << (bitpos - HOST_BITS_PER_WIDE_INT);
1802
1803   if (bitsize == 0)
1804     maskhigh = 0;
1805   else if (bitpos + bitsize > HOST_BITS_PER_WIDE_INT)
1806     maskhigh &= ((unsigned HOST_WIDE_INT) -1
1807                  >> (2 * HOST_BITS_PER_WIDE_INT - bitpos - bitsize));
1808   else
1809     maskhigh = 0;
1810
1811   if (complement)
1812     {
1813       maskhigh = ~maskhigh;
1814       masklow = ~masklow;
1815     }
1816
1817   return immed_double_const (masklow, maskhigh, mode);
1818 }
1819
1820 /* Return a constant integer (CONST_INT or CONST_DOUBLE) rtx with the value
1821    VALUE truncated to BITSIZE bits and then shifted left BITPOS bits.  */
1822
1823 static rtx
1824 lshift_value (enum machine_mode mode, rtx value, int bitpos, int bitsize)
1825 {
1826   unsigned HOST_WIDE_INT v = INTVAL (value);
1827   HOST_WIDE_INT low, high;
1828
1829   if (bitsize < HOST_BITS_PER_WIDE_INT)
1830     v &= ~((HOST_WIDE_INT) -1 << bitsize);
1831
1832   if (bitpos < HOST_BITS_PER_WIDE_INT)
1833     {
1834       low = v << bitpos;
1835       high = (bitpos > 0 ? (v >> (HOST_BITS_PER_WIDE_INT - bitpos)) : 0);
1836     }
1837   else
1838     {
1839       low = 0;
1840       high = v << (bitpos - HOST_BITS_PER_WIDE_INT);
1841     }
1842
1843   return immed_double_const (low, high, mode);
1844 }
1845 \f
1846 /* Extract a bit field from a memory by forcing the alignment of the
1847    memory.  This efficient only if the field spans at least 4 boundaries.
1848
1849    OP0 is the MEM.
1850    BITSIZE is the field width; BITPOS is the position of the first bit.
1851    UNSIGNEDP is true if the result should be zero-extended.  */
1852
1853 static rtx
1854 extract_force_align_mem_bit_field (rtx op0, unsigned HOST_WIDE_INT bitsize,
1855                                    unsigned HOST_WIDE_INT bitpos,
1856                                    int unsignedp)
1857 {
1858   enum machine_mode mode, dmode;
1859   unsigned int m_bitsize, m_size;
1860   unsigned int sign_shift_up, sign_shift_dn;
1861   rtx base, a1, a2, v1, v2, comb, shift, result, start;
1862
1863   /* Choose a mode that will fit BITSIZE.  */
1864   mode = smallest_mode_for_size (bitsize, MODE_INT);
1865   m_size = GET_MODE_SIZE (mode);
1866   m_bitsize = GET_MODE_BITSIZE (mode);
1867
1868   /* Choose a mode twice as wide.  Fail if no such mode exists.  */
1869   dmode = mode_for_size (m_bitsize * 2, MODE_INT, false);
1870   if (dmode == BLKmode)
1871     return NULL;
1872
1873   do_pending_stack_adjust ();
1874   start = get_last_insn ();
1875
1876   /* At the end, we'll need an additional shift to deal with sign/zero
1877      extension.  By default this will be a left+right shift of the
1878      appropriate size.  But we may be able to eliminate one of them.  */
1879   sign_shift_up = sign_shift_dn = m_bitsize - bitsize;
1880
1881   if (STRICT_ALIGNMENT)
1882     {
1883       base = plus_constant (XEXP (op0, 0), bitpos / BITS_PER_UNIT);
1884       bitpos %= BITS_PER_UNIT;
1885
1886       /* We load two values to be concatenate.  There's an edge condition
1887          that bears notice -- an aligned value at the end of a page can
1888          only load one value lest we segfault.  So the two values we load
1889          are at "base & -size" and "(base + size - 1) & -size".  If base
1890          is unaligned, the addresses will be aligned and sequential; if
1891          base is aligned, the addresses will both be equal to base.  */
1892
1893       a1 = expand_simple_binop (Pmode, AND, force_operand (base, NULL),
1894                                 GEN_INT (-(HOST_WIDE_INT)m_size),
1895                                 NULL, true, OPTAB_LIB_WIDEN);
1896       mark_reg_pointer (a1, m_bitsize);
1897       v1 = gen_rtx_MEM (mode, a1);
1898       set_mem_align (v1, m_bitsize);
1899       v1 = force_reg (mode, validize_mem (v1));
1900
1901       a2 = plus_constant (base, GET_MODE_SIZE (mode) - 1);
1902       a2 = expand_simple_binop (Pmode, AND, force_operand (a2, NULL),
1903                                 GEN_INT (-(HOST_WIDE_INT)m_size),
1904                                 NULL, true, OPTAB_LIB_WIDEN);
1905       v2 = gen_rtx_MEM (mode, a2);
1906       set_mem_align (v2, m_bitsize);
1907       v2 = force_reg (mode, validize_mem (v2));
1908
1909       /* Combine these two values into a double-word value.  */
1910       if (m_bitsize == BITS_PER_WORD)
1911         {
1912           comb = gen_reg_rtx (dmode);
1913           emit_insn (gen_rtx_CLOBBER (VOIDmode, comb));
1914           emit_move_insn (gen_rtx_SUBREG (mode, comb, 0), v1);
1915           emit_move_insn (gen_rtx_SUBREG (mode, comb, m_size), v2);
1916         }
1917       else
1918         {
1919           if (BYTES_BIG_ENDIAN)
1920             comb = v1, v1 = v2, v2 = comb;
1921           v1 = convert_modes (dmode, mode, v1, true);
1922           if (v1 == NULL)
1923             goto fail;
1924           v2 = convert_modes (dmode, mode, v2, true);
1925           v2 = expand_simple_binop (dmode, ASHIFT, v2, GEN_INT (m_bitsize),
1926                                     NULL, true, OPTAB_LIB_WIDEN);
1927           if (v2 == NULL)
1928             goto fail;
1929           comb = expand_simple_binop (dmode, IOR, v1, v2, NULL,
1930                                       true, OPTAB_LIB_WIDEN);
1931           if (comb == NULL)
1932             goto fail;
1933         }
1934
1935       shift = expand_simple_binop (Pmode, AND, base, GEN_INT (m_size - 1),
1936                                    NULL, true, OPTAB_LIB_WIDEN);
1937       shift = expand_mult (Pmode, shift, GEN_INT (BITS_PER_UNIT), NULL, 1);
1938
1939       if (bitpos != 0)
1940         {
1941           if (sign_shift_up <= bitpos)
1942             bitpos -= sign_shift_up, sign_shift_up = 0;
1943           shift = expand_simple_binop (Pmode, PLUS, shift, GEN_INT (bitpos),
1944                                        NULL, true, OPTAB_LIB_WIDEN);
1945         }
1946     }
1947   else
1948     {
1949       unsigned HOST_WIDE_INT offset = bitpos / BITS_PER_UNIT;
1950       bitpos %= BITS_PER_UNIT;
1951
1952       /* When strict alignment is not required, we can just load directly
1953          from memory without masking.  If the remaining BITPOS offset is
1954          small enough, we may be able to do all operations in MODE as 
1955          opposed to DMODE.  */
1956       if (bitpos + bitsize <= m_bitsize)
1957         dmode = mode;
1958       comb = adjust_address (op0, dmode, offset);
1959
1960       if (sign_shift_up <= bitpos)
1961         bitpos -= sign_shift_up, sign_shift_up = 0;
1962       shift = GEN_INT (bitpos);
1963     }
1964
1965   /* Shift down the double-word such that the requested value is at bit 0.  */
1966   if (shift != const0_rtx)
1967     comb = expand_simple_binop (dmode, unsignedp ? LSHIFTRT : ASHIFTRT,
1968                                 comb, shift, NULL, unsignedp, OPTAB_LIB_WIDEN);
1969   if (comb == NULL)
1970     goto fail;
1971
1972   /* If the field exactly matches MODE, then all we need to do is return the
1973      lowpart.  Otherwise, shift to get the sign bits set properly.  */
1974   result = force_reg (mode, gen_lowpart (mode, comb));
1975
1976   if (sign_shift_up)
1977     result = expand_simple_binop (mode, ASHIFT, result,
1978                                   GEN_INT (sign_shift_up),
1979                                   NULL_RTX, 0, OPTAB_LIB_WIDEN);
1980   if (sign_shift_dn)
1981     result = expand_simple_binop (mode, unsignedp ? LSHIFTRT : ASHIFTRT,
1982                                   result, GEN_INT (sign_shift_dn),
1983                                   NULL_RTX, 0, OPTAB_LIB_WIDEN);
1984
1985   return result;
1986
1987  fail:
1988   delete_insns_since (start);
1989   return NULL;
1990 }
1991
1992 /* Extract a bit field that is split across two words
1993    and return an RTX for the result.
1994
1995    OP0 is the REG, SUBREG or MEM rtx for the first of the two words.
1996    BITSIZE is the field width; BITPOS, position of its first bit, in the word.
1997    UNSIGNEDP is 1 if should zero-extend the contents; else sign-extend.  */
1998
1999 static rtx
2000 extract_split_bit_field (rtx op0, unsigned HOST_WIDE_INT bitsize,
2001                          unsigned HOST_WIDE_INT bitpos, int unsignedp)
2002 {
2003   unsigned int unit;
2004   unsigned int bitsdone = 0;
2005   rtx result = NULL_RTX;
2006   int first = 1;
2007
2008   /* Make sure UNIT isn't larger than BITS_PER_WORD, we can only handle that
2009      much at a time.  */
2010   if (REG_P (op0) || GET_CODE (op0) == SUBREG)
2011     unit = BITS_PER_WORD;
2012   else
2013     {
2014       unit = MIN (MEM_ALIGN (op0), BITS_PER_WORD);
2015       if (0 && bitsize / unit > 2)
2016         {
2017           rtx tmp = extract_force_align_mem_bit_field (op0, bitsize, bitpos,
2018                                                        unsignedp);
2019           if (tmp)
2020             return tmp;
2021         }
2022     }
2023
2024   while (bitsdone < bitsize)
2025     {
2026       unsigned HOST_WIDE_INT thissize;
2027       rtx part, word;
2028       unsigned HOST_WIDE_INT thispos;
2029       unsigned HOST_WIDE_INT offset;
2030
2031       offset = (bitpos + bitsdone) / unit;
2032       thispos = (bitpos + bitsdone) % unit;
2033
2034       /* THISSIZE must not overrun a word boundary.  Otherwise,
2035          extract_fixed_bit_field will call us again, and we will mutually
2036          recurse forever.  */
2037       thissize = MIN (bitsize - bitsdone, BITS_PER_WORD);
2038       thissize = MIN (thissize, unit - thispos);
2039
2040       /* If OP0 is a register, then handle OFFSET here.
2041
2042          When handling multiword bitfields, extract_bit_field may pass
2043          down a word_mode SUBREG of a larger REG for a bitfield that actually
2044          crosses a word boundary.  Thus, for a SUBREG, we must find
2045          the current word starting from the base register.  */
2046       if (GET_CODE (op0) == SUBREG)
2047         {
2048           int word_offset = (SUBREG_BYTE (op0) / UNITS_PER_WORD) + offset;
2049           word = operand_subword_force (SUBREG_REG (op0), word_offset,
2050                                         GET_MODE (SUBREG_REG (op0)));
2051           offset = 0;
2052         }
2053       else if (REG_P (op0))
2054         {
2055           word = operand_subword_force (op0, offset, GET_MODE (op0));
2056           offset = 0;
2057         }
2058       else
2059         word = op0;
2060
2061       /* Extract the parts in bit-counting order,
2062          whose meaning is determined by BYTES_PER_UNIT.
2063          OFFSET is in UNITs, and UNIT is in bits.
2064          extract_fixed_bit_field wants offset in bytes.  */
2065       part = extract_fixed_bit_field (word_mode, word,
2066                                       offset * unit / BITS_PER_UNIT,
2067                                       thissize, thispos, 0, 1);
2068       bitsdone += thissize;
2069
2070       /* Shift this part into place for the result.  */
2071       if (BYTES_BIG_ENDIAN)
2072         {
2073           if (bitsize != bitsdone)
2074             part = expand_shift (LSHIFT_EXPR, word_mode, part,
2075                                  build_int_cst (NULL_TREE, bitsize - bitsdone),
2076                                  0, 1);
2077         }
2078       else
2079         {
2080           if (bitsdone != thissize)
2081             part = expand_shift (LSHIFT_EXPR, word_mode, part,
2082                                  build_int_cst (NULL_TREE,
2083                                                 bitsdone - thissize), 0, 1);
2084         }
2085
2086       if (first)
2087         result = part;
2088       else
2089         /* Combine the parts with bitwise or.  This works
2090            because we extracted each part as an unsigned bit field.  */
2091         result = expand_binop (word_mode, ior_optab, part, result, NULL_RTX, 1,
2092                                OPTAB_LIB_WIDEN);
2093
2094       first = 0;
2095     }
2096
2097   /* Unsigned bit field: we are done.  */
2098   if (unsignedp)
2099     return result;
2100   /* Signed bit field: sign-extend with two arithmetic shifts.  */
2101   result = expand_shift (LSHIFT_EXPR, word_mode, result,
2102                          build_int_cst (NULL_TREE, BITS_PER_WORD - bitsize),
2103                          NULL_RTX, 0);
2104   return expand_shift (RSHIFT_EXPR, word_mode, result,
2105                        build_int_cst (NULL_TREE, BITS_PER_WORD - bitsize),
2106                        NULL_RTX, 0);
2107 }
2108 \f
2109 /* Add INC into TARGET.  */
2110
2111 void
2112 expand_inc (rtx target, rtx inc)
2113 {
2114   rtx value = expand_binop (GET_MODE (target), add_optab,
2115                             target, inc,
2116                             target, 0, OPTAB_LIB_WIDEN);
2117   if (value != target)
2118     emit_move_insn (target, value);
2119 }
2120
2121 /* Subtract DEC from TARGET.  */
2122
2123 void
2124 expand_dec (rtx target, rtx dec)
2125 {
2126   rtx value = expand_binop (GET_MODE (target), sub_optab,
2127                             target, dec,
2128                             target, 0, OPTAB_LIB_WIDEN);
2129   if (value != target)
2130     emit_move_insn (target, value);
2131 }
2132 \f
2133 /* Output a shift instruction for expression code CODE,
2134    with SHIFTED being the rtx for the value to shift,
2135    and AMOUNT the tree for the amount to shift by.
2136    Store the result in the rtx TARGET, if that is convenient.
2137    If UNSIGNEDP is nonzero, do a logical shift; otherwise, arithmetic.
2138    Return the rtx for where the value is.  */
2139
2140 rtx
2141 expand_shift (enum tree_code code, enum machine_mode mode, rtx shifted,
2142               tree amount, rtx target, int unsignedp)
2143 {
2144   rtx op1, temp = 0;
2145   int left = (code == LSHIFT_EXPR || code == LROTATE_EXPR);
2146   int rotate = (code == LROTATE_EXPR || code == RROTATE_EXPR);
2147   int try;
2148
2149   /* Previously detected shift-counts computed by NEGATE_EXPR
2150      and shifted in the other direction; but that does not work
2151      on all machines.  */
2152
2153   op1 = expand_expr (amount, NULL_RTX, VOIDmode, 0);
2154
2155   if (SHIFT_COUNT_TRUNCATED)
2156     {
2157       if (GET_CODE (op1) == CONST_INT
2158           && ((unsigned HOST_WIDE_INT) INTVAL (op1) >=
2159               (unsigned HOST_WIDE_INT) GET_MODE_BITSIZE (mode)))
2160         op1 = GEN_INT ((unsigned HOST_WIDE_INT) INTVAL (op1)
2161                        % GET_MODE_BITSIZE (mode));
2162       else if (GET_CODE (op1) == SUBREG
2163                && subreg_lowpart_p (op1))
2164         op1 = SUBREG_REG (op1);
2165     }
2166
2167   if (op1 == const0_rtx)
2168     return shifted;
2169
2170   /* Check whether its cheaper to implement a left shift by a constant
2171      bit count by a sequence of additions.  */
2172   if (code == LSHIFT_EXPR
2173       && GET_CODE (op1) == CONST_INT
2174       && INTVAL (op1) > 0
2175       && INTVAL (op1) < GET_MODE_BITSIZE (mode)
2176       && shift_cost[mode][INTVAL (op1)] > INTVAL (op1) * add_cost[mode])
2177     {
2178       int i;
2179       for (i = 0; i < INTVAL (op1); i++)
2180         {
2181           temp = force_reg (mode, shifted);
2182           shifted = expand_binop (mode, add_optab, temp, temp, NULL_RTX,
2183                                   unsignedp, OPTAB_LIB_WIDEN);
2184         }
2185       return shifted;
2186     }
2187
2188   for (try = 0; temp == 0 && try < 3; try++)
2189     {
2190       enum optab_methods methods;
2191
2192       if (try == 0)
2193         methods = OPTAB_DIRECT;
2194       else if (try == 1)
2195         methods = OPTAB_WIDEN;
2196       else
2197         methods = OPTAB_LIB_WIDEN;
2198
2199       if (rotate)
2200         {
2201           /* Widening does not work for rotation.  */
2202           if (methods == OPTAB_WIDEN)
2203             continue;
2204           else if (methods == OPTAB_LIB_WIDEN)
2205             {
2206               /* If we have been unable to open-code this by a rotation,
2207                  do it as the IOR of two shifts.  I.e., to rotate A
2208                  by N bits, compute (A << N) | ((unsigned) A >> (C - N))
2209                  where C is the bitsize of A.
2210
2211                  It is theoretically possible that the target machine might
2212                  not be able to perform either shift and hence we would
2213                  be making two libcalls rather than just the one for the
2214                  shift (similarly if IOR could not be done).  We will allow
2215                  this extremely unlikely lossage to avoid complicating the
2216                  code below.  */
2217
2218               rtx subtarget = target == shifted ? 0 : target;
2219               rtx temp1;
2220               tree type = TREE_TYPE (amount);
2221               tree new_amount = make_tree (type, op1);
2222               tree other_amount
2223                 = fold_build2 (MINUS_EXPR, type,
2224                                build_int_cst (type, GET_MODE_BITSIZE (mode)),
2225                                amount);
2226
2227               shifted = force_reg (mode, shifted);
2228
2229               temp = expand_shift (left ? LSHIFT_EXPR : RSHIFT_EXPR,
2230                                    mode, shifted, new_amount, 0, 1);
2231               temp1 = expand_shift (left ? RSHIFT_EXPR : LSHIFT_EXPR,
2232                                     mode, shifted, other_amount, subtarget, 1);
2233               return expand_binop (mode, ior_optab, temp, temp1, target,
2234                                    unsignedp, methods);
2235             }
2236
2237           temp = expand_binop (mode,
2238                                left ? rotl_optab : rotr_optab,
2239                                shifted, op1, target, unsignedp, methods);
2240         }
2241       else if (unsignedp)
2242         temp = expand_binop (mode,
2243                              left ? ashl_optab : lshr_optab,
2244                              shifted, op1, target, unsignedp, methods);
2245
2246       /* Do arithmetic shifts.
2247          Also, if we are going to widen the operand, we can just as well
2248          use an arithmetic right-shift instead of a logical one.  */
2249       if (temp == 0 && ! rotate
2250           && (! unsignedp || (! left && methods == OPTAB_WIDEN)))
2251         {
2252           enum optab_methods methods1 = methods;
2253
2254           /* If trying to widen a log shift to an arithmetic shift,
2255              don't accept an arithmetic shift of the same size.  */
2256           if (unsignedp)
2257             methods1 = OPTAB_MUST_WIDEN;
2258
2259           /* Arithmetic shift */
2260
2261           temp = expand_binop (mode,
2262                                left ? ashl_optab : ashr_optab,
2263                                shifted, op1, target, unsignedp, methods1);
2264         }
2265
2266       /* We used to try extzv here for logical right shifts, but that was
2267          only useful for one machine, the VAX, and caused poor code
2268          generation there for lshrdi3, so the code was deleted and a
2269          define_expand for lshrsi3 was added to vax.md.  */
2270     }
2271
2272   gcc_assert (temp);
2273   return temp;
2274 }
2275 \f
2276 enum alg_code {
2277   alg_unknown,
2278   alg_zero,
2279   alg_m, alg_shift,
2280   alg_add_t_m2,
2281   alg_sub_t_m2,
2282   alg_add_factor,
2283   alg_sub_factor,
2284   alg_add_t2_m,
2285   alg_sub_t2_m,
2286   alg_impossible
2287 };
2288
2289 /* This structure holds the "cost" of a multiply sequence.  The
2290    "cost" field holds the total rtx_cost of every operator in the
2291    synthetic multiplication sequence, hence cost(a op b) is defined
2292    as rtx_cost(op) + cost(a) + cost(b), where cost(leaf) is zero.
2293    The "latency" field holds the minimum possible latency of the
2294    synthetic multiply, on a hypothetical infinitely parallel CPU.
2295    This is the critical path, or the maximum height, of the expression
2296    tree which is the sum of rtx_costs on the most expensive path from
2297    any leaf to the root.  Hence latency(a op b) is defined as zero for
2298    leaves and rtx_cost(op) + max(latency(a), latency(b)) otherwise.  */
2299
2300 struct mult_cost {
2301   short cost;     /* Total rtx_cost of the multiplication sequence.  */
2302   short latency;  /* The latency of the multiplication sequence.  */
2303 };
2304
2305 /* This macro is used to compare a pointer to a mult_cost against an
2306    single integer "rtx_cost" value.  This is equivalent to the macro
2307    CHEAPER_MULT_COST(X,Z) where Z = {Y,Y}.  */
2308 #define MULT_COST_LESS(X,Y) ((X)->cost < (Y)    \
2309                              || ((X)->cost == (Y) && (X)->latency < (Y)))
2310
2311 /* This macro is used to compare two pointers to mult_costs against
2312    each other.  The macro returns true if X is cheaper than Y.
2313    Currently, the cheaper of two mult_costs is the one with the
2314    lower "cost".  If "cost"s are tied, the lower latency is cheaper.  */
2315 #define CHEAPER_MULT_COST(X,Y)  ((X)->cost < (Y)->cost          \
2316                                  || ((X)->cost == (Y)->cost     \
2317                                      && (X)->latency < (Y)->latency))
2318
2319 /* This structure records a sequence of operations.
2320    `ops' is the number of operations recorded.
2321    `cost' is their total cost.
2322    The operations are stored in `op' and the corresponding
2323    logarithms of the integer coefficients in `log'.
2324
2325    These are the operations:
2326    alg_zero             total := 0;
2327    alg_m                total := multiplicand;
2328    alg_shift            total := total * coeff
2329    alg_add_t_m2         total := total + multiplicand * coeff;
2330    alg_sub_t_m2         total := total - multiplicand * coeff;
2331    alg_add_factor       total := total * coeff + total;
2332    alg_sub_factor       total := total * coeff - total;
2333    alg_add_t2_m         total := total * coeff + multiplicand;
2334    alg_sub_t2_m         total := total * coeff - multiplicand;
2335
2336    The first operand must be either alg_zero or alg_m.  */
2337
2338 struct algorithm
2339 {
2340   struct mult_cost cost;
2341   short ops;
2342   /* The size of the OP and LOG fields are not directly related to the
2343      word size, but the worst-case algorithms will be if we have few
2344      consecutive ones or zeros, i.e., a multiplicand like 10101010101...
2345      In that case we will generate shift-by-2, add, shift-by-2, add,...,
2346      in total wordsize operations.  */
2347   enum alg_code op[MAX_BITS_PER_WORD];
2348   char log[MAX_BITS_PER_WORD];
2349 };
2350
2351 /* The entry for our multiplication cache/hash table.  */
2352 struct alg_hash_entry {
2353   /* The number we are multiplying by.  */
2354   unsigned int t;
2355
2356   /* The mode in which we are multiplying something by T.  */
2357   enum machine_mode mode;
2358
2359   /* The best multiplication algorithm for t.  */
2360   enum alg_code alg;
2361
2362   /* The cost of multiplication if ALG_CODE is not alg_impossible.
2363      Otherwise, the cost within which multiplication by T is
2364      impossible.  */
2365   struct mult_cost cost;
2366 };
2367
2368 /* The number of cache/hash entries.  */
2369 #define NUM_ALG_HASH_ENTRIES 307
2370
2371 /* Each entry of ALG_HASH caches alg_code for some integer.  This is
2372    actually a hash table.  If we have a collision, that the older
2373    entry is kicked out.  */
2374 static struct alg_hash_entry alg_hash[NUM_ALG_HASH_ENTRIES];
2375
2376 /* Indicates the type of fixup needed after a constant multiplication.
2377    BASIC_VARIANT means no fixup is needed, NEGATE_VARIANT means that
2378    the result should be negated, and ADD_VARIANT means that the
2379    multiplicand should be added to the result.  */
2380 enum mult_variant {basic_variant, negate_variant, add_variant};
2381
2382 static void synth_mult (struct algorithm *, unsigned HOST_WIDE_INT,
2383                         const struct mult_cost *, enum machine_mode mode);
2384 static bool choose_mult_variant (enum machine_mode, HOST_WIDE_INT,
2385                                  struct algorithm *, enum mult_variant *, int);
2386 static rtx expand_mult_const (enum machine_mode, rtx, HOST_WIDE_INT, rtx,
2387                               const struct algorithm *, enum mult_variant);
2388 static unsigned HOST_WIDE_INT choose_multiplier (unsigned HOST_WIDE_INT, int,
2389                                                  int, rtx *, int *, int *);
2390 static unsigned HOST_WIDE_INT invert_mod2n (unsigned HOST_WIDE_INT, int);
2391 static rtx extract_high_half (enum machine_mode, rtx);
2392 static rtx expand_mult_highpart (enum machine_mode, rtx, rtx, rtx, int, int);
2393 static rtx expand_mult_highpart_optab (enum machine_mode, rtx, rtx, rtx,
2394                                        int, int);
2395 /* Compute and return the best algorithm for multiplying by T.
2396    The algorithm must cost less than cost_limit
2397    If retval.cost >= COST_LIMIT, no algorithm was found and all
2398    other field of the returned struct are undefined.
2399    MODE is the machine mode of the multiplication.  */
2400
2401 static void
2402 synth_mult (struct algorithm *alg_out, unsigned HOST_WIDE_INT t,
2403             const struct mult_cost *cost_limit, enum machine_mode mode)
2404 {
2405   int m;
2406   struct algorithm *alg_in, *best_alg;
2407   struct mult_cost best_cost;
2408   struct mult_cost new_limit;
2409   int op_cost, op_latency;
2410   unsigned HOST_WIDE_INT q;
2411   int maxm = MIN (BITS_PER_WORD, GET_MODE_BITSIZE (mode));
2412   int hash_index;
2413   bool cache_hit = false;
2414   enum alg_code cache_alg = alg_zero;
2415
2416   /* Indicate that no algorithm is yet found.  If no algorithm
2417      is found, this value will be returned and indicate failure.  */
2418   alg_out->cost.cost = cost_limit->cost + 1;
2419   alg_out->cost.latency = cost_limit->latency + 1;
2420
2421   if (cost_limit->cost < 0
2422       || (cost_limit->cost == 0 && cost_limit->latency <= 0))
2423     return;
2424
2425   /* Restrict the bits of "t" to the multiplication's mode.  */
2426   t &= GET_MODE_MASK (mode);
2427
2428   /* t == 1 can be done in zero cost.  */
2429   if (t == 1)
2430     {
2431       alg_out->ops = 1;
2432       alg_out->cost.cost = 0;
2433       alg_out->cost.latency = 0;
2434       alg_out->op[0] = alg_m;
2435       return;
2436     }
2437
2438   /* t == 0 sometimes has a cost.  If it does and it exceeds our limit,
2439      fail now.  */
2440   if (t == 0)
2441     {
2442       if (MULT_COST_LESS (cost_limit, zero_cost))
2443         return;
2444       else
2445         {
2446           alg_out->ops = 1;
2447           alg_out->cost.cost = zero_cost;
2448           alg_out->cost.latency = zero_cost;
2449           alg_out->op[0] = alg_zero;
2450           return;
2451         }
2452     }
2453
2454   /* We'll be needing a couple extra algorithm structures now.  */
2455
2456   alg_in = alloca (sizeof (struct algorithm));
2457   best_alg = alloca (sizeof (struct algorithm));
2458   best_cost = *cost_limit;
2459
2460   /* Compute the hash index.  */
2461   hash_index = (t ^ (unsigned int) mode) % NUM_ALG_HASH_ENTRIES;
2462
2463   /* See if we already know what to do for T.  */
2464   if (alg_hash[hash_index].t == t
2465       && alg_hash[hash_index].mode == mode
2466       && alg_hash[hash_index].alg != alg_unknown)
2467     {
2468       cache_alg = alg_hash[hash_index].alg;
2469
2470       if (cache_alg == alg_impossible)
2471         {
2472           /* The cache tells us that it's impossible to synthesize
2473              multiplication by T within alg_hash[hash_index].cost.  */
2474           if (!CHEAPER_MULT_COST (&alg_hash[hash_index].cost, cost_limit))
2475             /* COST_LIMIT is at least as restrictive as the one
2476                recorded in the hash table, in which case we have no
2477                hope of synthesizing a multiplication.  Just
2478                return.  */
2479             return;
2480
2481           /* If we get here, COST_LIMIT is less restrictive than the
2482              one recorded in the hash table, so we may be able to
2483              synthesize a multiplication.  Proceed as if we didn't
2484              have the cache entry.  */
2485         }
2486       else
2487         {
2488           if (CHEAPER_MULT_COST (cost_limit, &alg_hash[hash_index].cost))
2489             /* The cached algorithm shows that this multiplication
2490                requires more cost than COST_LIMIT.  Just return.  This
2491                way, we don't clobber this cache entry with
2492                alg_impossible but retain useful information.  */
2493             return;
2494
2495           cache_hit = true;
2496
2497           switch (cache_alg)
2498             {
2499             case alg_shift:
2500               goto do_alg_shift;
2501
2502             case alg_add_t_m2:
2503             case alg_sub_t_m2:
2504               goto do_alg_addsub_t_m2;
2505
2506             case alg_add_factor:
2507             case alg_sub_factor:
2508               goto do_alg_addsub_factor;
2509
2510             case alg_add_t2_m:
2511               goto do_alg_add_t2_m;
2512
2513             case alg_sub_t2_m:
2514               goto do_alg_sub_t2_m;
2515
2516             default:
2517               gcc_unreachable ();
2518             }
2519         }
2520     }
2521
2522   /* If we have a group of zero bits at the low-order part of T, try
2523      multiplying by the remaining bits and then doing a shift.  */
2524
2525   if ((t & 1) == 0)
2526     {
2527     do_alg_shift:
2528       m = floor_log2 (t & -t);  /* m = number of low zero bits */
2529       if (m < maxm)
2530         {
2531           q = t >> m;
2532           /* The function expand_shift will choose between a shift and
2533              a sequence of additions, so the observed cost is given as
2534              MIN (m * add_cost[mode], shift_cost[mode][m]).  */
2535           op_cost = m * add_cost[mode];
2536           if (shift_cost[mode][m] < op_cost)
2537             op_cost = shift_cost[mode][m];
2538           new_limit.cost = best_cost.cost - op_cost;
2539           new_limit.latency = best_cost.latency - op_cost;
2540           synth_mult (alg_in, q, &new_limit, mode);
2541
2542           alg_in->cost.cost += op_cost;
2543           alg_in->cost.latency += op_cost;
2544           if (CHEAPER_MULT_COST (&alg_in->cost, &best_cost))
2545             {
2546               struct algorithm *x;
2547               best_cost = alg_in->cost;
2548               x = alg_in, alg_in = best_alg, best_alg = x;
2549               best_alg->log[best_alg->ops] = m;
2550               best_alg->op[best_alg->ops] = alg_shift;
2551             }
2552         }
2553       if (cache_hit)
2554         goto done;
2555     }
2556
2557   /* If we have an odd number, add or subtract one.  */
2558   if ((t & 1) != 0)
2559     {
2560       unsigned HOST_WIDE_INT w;
2561
2562     do_alg_addsub_t_m2:
2563       for (w = 1; (w & t) != 0; w <<= 1)
2564         ;
2565       /* If T was -1, then W will be zero after the loop.  This is another
2566          case where T ends with ...111.  Handling this with (T + 1) and
2567          subtract 1 produces slightly better code and results in algorithm
2568          selection much faster than treating it like the ...0111 case
2569          below.  */
2570       if (w == 0
2571           || (w > 2
2572               /* Reject the case where t is 3.
2573                  Thus we prefer addition in that case.  */
2574               && t != 3))
2575         {
2576           /* T ends with ...111.  Multiply by (T + 1) and subtract 1.  */
2577
2578           op_cost = add_cost[mode];
2579           new_limit.cost = best_cost.cost - op_cost;
2580           new_limit.latency = best_cost.latency - op_cost;
2581           synth_mult (alg_in, t + 1, &new_limit, mode);
2582
2583           alg_in->cost.cost += op_cost;
2584           alg_in->cost.latency += op_cost;
2585           if (CHEAPER_MULT_COST (&alg_in->cost, &best_cost))
2586             {
2587               struct algorithm *x;
2588               best_cost = alg_in->cost;
2589               x = alg_in, alg_in = best_alg, best_alg = x;
2590               best_alg->log[best_alg->ops] = 0;
2591               best_alg->op[best_alg->ops] = alg_sub_t_m2;
2592             }
2593         }
2594       else
2595         {
2596           /* T ends with ...01 or ...011.  Multiply by (T - 1) and add 1.  */
2597
2598           op_cost = add_cost[mode];
2599           new_limit.cost = best_cost.cost - op_cost;
2600           new_limit.latency = best_cost.latency - op_cost;
2601           synth_mult (alg_in, t - 1, &new_limit, mode);
2602
2603           alg_in->cost.cost += op_cost;
2604           alg_in->cost.latency += op_cost;
2605           if (CHEAPER_MULT_COST (&alg_in->cost, &best_cost))
2606             {
2607               struct algorithm *x;
2608               best_cost = alg_in->cost;
2609               x = alg_in, alg_in = best_alg, best_alg = x;
2610               best_alg->log[best_alg->ops] = 0;
2611               best_alg->op[best_alg->ops] = alg_add_t_m2;
2612             }
2613         }
2614       if (cache_hit)
2615         goto done;
2616     }
2617
2618   /* Look for factors of t of the form
2619      t = q(2**m +- 1), 2 <= m <= floor(log2(t - 1)).
2620      If we find such a factor, we can multiply by t using an algorithm that
2621      multiplies by q, shift the result by m and add/subtract it to itself.
2622
2623      We search for large factors first and loop down, even if large factors
2624      are less probable than small; if we find a large factor we will find a
2625      good sequence quickly, and therefore be able to prune (by decreasing
2626      COST_LIMIT) the search.  */
2627
2628  do_alg_addsub_factor:
2629   for (m = floor_log2 (t - 1); m >= 2; m--)
2630     {
2631       unsigned HOST_WIDE_INT d;
2632
2633       d = ((unsigned HOST_WIDE_INT) 1 << m) + 1;
2634       if (t % d == 0 && t > d && m < maxm
2635           && (!cache_hit || cache_alg == alg_add_factor))
2636         {
2637           /* If the target has a cheap shift-and-add instruction use
2638              that in preference to a shift insn followed by an add insn.
2639              Assume that the shift-and-add is "atomic" with a latency
2640              equal to its cost, otherwise assume that on superscalar
2641              hardware the shift may be executed concurrently with the
2642              earlier steps in the algorithm.  */
2643           op_cost = add_cost[mode] + shift_cost[mode][m];
2644           if (shiftadd_cost[mode][m] < op_cost)
2645             {
2646               op_cost = shiftadd_cost[mode][m];
2647               op_latency = op_cost;
2648             }
2649           else
2650             op_latency = add_cost[mode];
2651
2652           new_limit.cost = best_cost.cost - op_cost;
2653           new_limit.latency = best_cost.latency - op_latency;
2654           synth_mult (alg_in, t / d, &new_limit, mode);
2655
2656           alg_in->cost.cost += op_cost;
2657           alg_in->cost.latency += op_latency;
2658           if (alg_in->cost.latency < op_cost)
2659             alg_in->cost.latency = op_cost;
2660           if (CHEAPER_MULT_COST (&alg_in->cost, &best_cost))
2661             {
2662               struct algorithm *x;
2663               best_cost = alg_in->cost;
2664               x = alg_in, alg_in = best_alg, best_alg = x;
2665               best_alg->log[best_alg->ops] = m;
2666               best_alg->op[best_alg->ops] = alg_add_factor;
2667             }
2668           /* Other factors will have been taken care of in the recursion.  */
2669           break;
2670         }
2671
2672       d = ((unsigned HOST_WIDE_INT) 1 << m) - 1;
2673       if (t % d == 0 && t > d && m < maxm
2674           && (!cache_hit || cache_alg == alg_sub_factor))
2675         {
2676           /* If the target has a cheap shift-and-subtract insn use
2677              that in preference to a shift insn followed by a sub insn.
2678              Assume that the shift-and-sub is "atomic" with a latency
2679              equal to it's cost, otherwise assume that on superscalar
2680              hardware the shift may be executed concurrently with the
2681              earlier steps in the algorithm.  */
2682           op_cost = add_cost[mode] + shift_cost[mode][m];
2683           if (shiftsub_cost[mode][m] < op_cost)
2684             {
2685               op_cost = shiftsub_cost[mode][m];
2686               op_latency = op_cost;
2687             }
2688           else
2689             op_latency = add_cost[mode];
2690
2691           new_limit.cost = best_cost.cost - op_cost;
2692           new_limit.latency = best_cost.latency - op_latency;
2693           synth_mult (alg_in, t / d, &new_limit, mode);
2694
2695           alg_in->cost.cost += op_cost;
2696           alg_in->cost.latency += op_latency;
2697           if (alg_in->cost.latency < op_cost)
2698             alg_in->cost.latency = op_cost;
2699           if (CHEAPER_MULT_COST (&alg_in->cost, &best_cost))
2700             {
2701               struct algorithm *x;
2702               best_cost = alg_in->cost;
2703               x = alg_in, alg_in = best_alg, best_alg = x;
2704               best_alg->log[best_alg->ops] = m;
2705               best_alg->op[best_alg->ops] = alg_sub_factor;
2706             }
2707           break;
2708         }
2709     }
2710   if (cache_hit)
2711     goto done;
2712
2713   /* Try shift-and-add (load effective address) instructions,
2714      i.e. do a*3, a*5, a*9.  */
2715   if ((t & 1) != 0)
2716     {
2717     do_alg_add_t2_m:
2718       q = t - 1;
2719       q = q & -q;
2720       m = exact_log2 (q);
2721       if (m >= 0 && m < maxm)
2722         {
2723           op_cost = shiftadd_cost[mode][m];
2724           new_limit.cost = best_cost.cost - op_cost;
2725           new_limit.latency = best_cost.latency - op_cost;
2726           synth_mult (alg_in, (t - 1) >> m, &new_limit, mode);
2727
2728           alg_in->cost.cost += op_cost;
2729           alg_in->cost.latency += op_cost;
2730           if (CHEAPER_MULT_COST (&alg_in->cost, &best_cost))
2731             {
2732               struct algorithm *x;
2733               best_cost = alg_in->cost;
2734               x = alg_in, alg_in = best_alg, best_alg = x;
2735               best_alg->log[best_alg->ops] = m;
2736               best_alg->op[best_alg->ops] = alg_add_t2_m;
2737             }
2738         }
2739       if (cache_hit)
2740         goto done;
2741
2742     do_alg_sub_t2_m:
2743       q = t + 1;
2744       q = q & -q;
2745       m = exact_log2 (q);
2746       if (m >= 0 && m < maxm)
2747         {
2748           op_cost = shiftsub_cost[mode][m];
2749           new_limit.cost = best_cost.cost - op_cost;
2750           new_limit.latency = best_cost.latency - op_cost;
2751           synth_mult (alg_in, (t + 1) >> m, &new_limit, mode);
2752
2753           alg_in->cost.cost += op_cost;
2754           alg_in->cost.latency += op_cost;
2755           if (CHEAPER_MULT_COST (&alg_in->cost, &best_cost))
2756             {
2757               struct algorithm *x;
2758               best_cost = alg_in->cost;
2759               x = alg_in, alg_in = best_alg, best_alg = x;
2760               best_alg->log[best_alg->ops] = m;
2761               best_alg->op[best_alg->ops] = alg_sub_t2_m;
2762             }
2763         }
2764       if (cache_hit)
2765         goto done;
2766     }
2767
2768  done:
2769   /* If best_cost has not decreased, we have not found any algorithm.  */
2770   if (!CHEAPER_MULT_COST (&best_cost, cost_limit))
2771     {
2772       /* We failed to find an algorithm.  Record alg_impossible for
2773          this case (that is, <T, MODE, COST_LIMIT>) so that next time
2774          we are asked to find an algorithm for T within the same or
2775          lower COST_LIMIT, we can immediately return to the
2776          caller.  */
2777       alg_hash[hash_index].t = t;
2778       alg_hash[hash_index].mode = mode;
2779       alg_hash[hash_index].alg = alg_impossible;
2780       alg_hash[hash_index].cost = *cost_limit;
2781       return;
2782     }
2783
2784   /* Cache the result.  */
2785   if (!cache_hit)
2786     {
2787       alg_hash[hash_index].t = t;
2788       alg_hash[hash_index].mode = mode;
2789       alg_hash[hash_index].alg = best_alg->op[best_alg->ops];
2790       alg_hash[hash_index].cost.cost = best_cost.cost;
2791       alg_hash[hash_index].cost.latency = best_cost.latency;
2792     }
2793
2794   /* If we are getting a too long sequence for `struct algorithm'
2795      to record, make this search fail.  */
2796   if (best_alg->ops == MAX_BITS_PER_WORD)
2797     return;
2798
2799   /* Copy the algorithm from temporary space to the space at alg_out.
2800      We avoid using structure assignment because the majority of
2801      best_alg is normally undefined, and this is a critical function.  */
2802   alg_out->ops = best_alg->ops + 1;
2803   alg_out->cost = best_cost;
2804   memcpy (alg_out->op, best_alg->op,
2805           alg_out->ops * sizeof *alg_out->op);
2806   memcpy (alg_out->log, best_alg->log,
2807           alg_out->ops * sizeof *alg_out->log);
2808 }
2809 \f
2810 /* Find the cheapest way of multiplying a value of mode MODE by VAL.
2811    Try three variations:
2812
2813        - a shift/add sequence based on VAL itself
2814        - a shift/add sequence based on -VAL, followed by a negation
2815        - a shift/add sequence based on VAL - 1, followed by an addition.
2816
2817    Return true if the cheapest of these cost less than MULT_COST,
2818    describing the algorithm in *ALG and final fixup in *VARIANT.  */
2819
2820 static bool
2821 choose_mult_variant (enum machine_mode mode, HOST_WIDE_INT val,
2822                      struct algorithm *alg, enum mult_variant *variant,
2823                      int mult_cost)
2824 {
2825   struct algorithm alg2;
2826   struct mult_cost limit;
2827   int op_cost;
2828
2829   *variant = basic_variant;
2830   limit.cost = mult_cost;
2831   limit.latency = mult_cost;
2832   synth_mult (alg, val, &limit, mode);
2833
2834   /* This works only if the inverted value actually fits in an
2835      `unsigned int' */
2836   if (HOST_BITS_PER_INT >= GET_MODE_BITSIZE (mode))
2837     {
2838       op_cost = neg_cost[mode];
2839       if (MULT_COST_LESS (&alg->cost, mult_cost))
2840         {
2841           limit.cost = alg->cost.cost - op_cost;
2842           limit.latency = alg->cost.latency - op_cost;
2843         }
2844       else
2845         {
2846           limit.cost = mult_cost - op_cost;
2847           limit.latency = mult_cost - op_cost;
2848         }
2849
2850       synth_mult (&alg2, -val, &limit, mode);
2851       alg2.cost.cost += op_cost;
2852       alg2.cost.latency += op_cost;
2853       if (CHEAPER_MULT_COST (&alg2.cost, &alg->cost))
2854         *alg = alg2, *variant = negate_variant;
2855     }
2856
2857   /* This proves very useful for division-by-constant.  */
2858   op_cost = add_cost[mode];
2859   if (MULT_COST_LESS (&alg->cost, mult_cost))
2860     {
2861       limit.cost = alg->cost.cost - op_cost;
2862       limit.latency = alg->cost.latency - op_cost;
2863     }
2864   else
2865     {
2866       limit.cost = mult_cost - op_cost;
2867       limit.latency = mult_cost - op_cost;
2868     }
2869
2870   synth_mult (&alg2, val - 1, &limit, mode);
2871   alg2.cost.cost += op_cost;
2872   alg2.cost.latency += op_cost;
2873   if (CHEAPER_MULT_COST (&alg2.cost, &alg->cost))
2874     *alg = alg2, *variant = add_variant;
2875
2876   return MULT_COST_LESS (&alg->cost, mult_cost);
2877 }
2878
2879 /* A subroutine of expand_mult, used for constant multiplications.
2880    Multiply OP0 by VAL in mode MODE, storing the result in TARGET if
2881    convenient.  Use the shift/add sequence described by ALG and apply
2882    the final fixup specified by VARIANT.  */
2883
2884 static rtx
2885 expand_mult_const (enum machine_mode mode, rtx op0, HOST_WIDE_INT val,
2886                    rtx target, const struct algorithm *alg,
2887                    enum mult_variant variant)
2888 {
2889   HOST_WIDE_INT val_so_far;
2890   rtx insn, accum, tem;
2891   int opno;
2892   enum machine_mode nmode;
2893
2894   /* Avoid referencing memory over and over.
2895      For speed, but also for correctness when mem is volatile.  */
2896   if (MEM_P (op0))
2897     op0 = force_reg (mode, op0);
2898
2899   /* ACCUM starts out either as OP0 or as a zero, depending on
2900      the first operation.  */
2901
2902   if (alg->op[0] == alg_zero)
2903     {
2904       accum = copy_to_mode_reg (mode, const0_rtx);
2905       val_so_far = 0;
2906     }
2907   else if (alg->op[0] == alg_m)
2908     {
2909       accum = copy_to_mode_reg (mode, op0);
2910       val_so_far = 1;
2911     }
2912   else
2913     gcc_unreachable ();
2914
2915   for (opno = 1; opno < alg->ops; opno++)
2916     {
2917       int log = alg->log[opno];
2918       rtx shift_subtarget = optimize ? 0 : accum;
2919       rtx add_target
2920         = (opno == alg->ops - 1 && target != 0 && variant != add_variant
2921            && !optimize)
2922           ? target : 0;
2923       rtx accum_target = optimize ? 0 : accum;
2924
2925       switch (alg->op[opno])
2926         {
2927         case alg_shift:
2928           accum = expand_shift (LSHIFT_EXPR, mode, accum,
2929                                 build_int_cst (NULL_TREE, log),
2930                                 NULL_RTX, 0);
2931           val_so_far <<= log;
2932           break;
2933
2934         case alg_add_t_m2:
2935           tem = expand_shift (LSHIFT_EXPR, mode, op0,
2936                               build_int_cst (NULL_TREE, log),
2937                               NULL_RTX, 0);
2938           accum = force_operand (gen_rtx_PLUS (mode, accum, tem),
2939                                  add_target ? add_target : accum_target);
2940           val_so_far += (HOST_WIDE_INT) 1 << log;
2941           break;
2942
2943         case alg_sub_t_m2:
2944           tem = expand_shift (LSHIFT_EXPR, mode, op0,
2945                               build_int_cst (NULL_TREE, log),
2946                               NULL_RTX, 0);
2947           accum = force_operand (gen_rtx_MINUS (mode, accum, tem),
2948                                  add_target ? add_target : accum_target);
2949           val_so_far -= (HOST_WIDE_INT) 1 << log;
2950           break;
2951
2952         case alg_add_t2_m:
2953           accum = expand_shift (LSHIFT_EXPR, mode, accum,
2954                                 build_int_cst (NULL_TREE, log),
2955                                 shift_subtarget,
2956                                 0);
2957           accum = force_operand (gen_rtx_PLUS (mode, accum, op0),
2958                                  add_target ? add_target : accum_target);
2959           val_so_far = (val_so_far << log) + 1;
2960           break;
2961
2962         case alg_sub_t2_m:
2963           accum = expand_shift (LSHIFT_EXPR, mode, accum,
2964                                 build_int_cst (NULL_TREE, log),
2965                                 shift_subtarget, 0);
2966           accum = force_operand (gen_rtx_MINUS (mode, accum, op0),
2967                                  add_target ? add_target : accum_target);
2968           val_so_far = (val_so_far << log) - 1;
2969           break;
2970
2971         case alg_add_factor:
2972           tem = expand_shift (LSHIFT_EXPR, mode, accum,
2973                               build_int_cst (NULL_TREE, log),
2974                               NULL_RTX, 0);
2975           accum = force_operand (gen_rtx_PLUS (mode, accum, tem),
2976                                  add_target ? add_target : accum_target);
2977           val_so_far += val_so_far << log;
2978           break;
2979
2980         case alg_sub_factor:
2981           tem = expand_shift (LSHIFT_EXPR, mode, accum,
2982                               build_int_cst (NULL_TREE, log),
2983                               NULL_RTX, 0);
2984           accum = force_operand (gen_rtx_MINUS (mode, tem, accum),
2985                                  (add_target
2986                                   ? add_target : (optimize ? 0 : tem)));
2987           val_so_far = (val_so_far << log) - val_so_far;
2988           break;
2989
2990         default:
2991           gcc_unreachable ();
2992         }
2993
2994       /* Write a REG_EQUAL note on the last insn so that we can cse
2995          multiplication sequences.  Note that if ACCUM is a SUBREG,
2996          we've set the inner register and must properly indicate
2997          that.  */
2998
2999       tem = op0, nmode = mode;
3000       if (GET_CODE (accum) == SUBREG)
3001         {
3002           nmode = GET_MODE (SUBREG_REG (accum));
3003           tem = gen_lowpart (nmode, op0);
3004         }
3005
3006       insn = get_last_insn ();
3007       set_unique_reg_note (insn, REG_EQUAL,
3008                            gen_rtx_MULT (nmode, tem, GEN_INT (val_so_far)));
3009     }
3010
3011   if (variant == negate_variant)
3012     {
3013       val_so_far = -val_so_far;
3014       accum = expand_unop (mode, neg_optab, accum, target, 0);
3015     }
3016   else if (variant == add_variant)
3017     {
3018       val_so_far = val_so_far + 1;
3019       accum = force_operand (gen_rtx_PLUS (mode, accum, op0), target);
3020     }
3021
3022   /* Compare only the bits of val and val_so_far that are significant
3023      in the result mode, to avoid sign-/zero-extension confusion.  */
3024   val &= GET_MODE_MASK (mode);
3025   val_so_far &= GET_MODE_MASK (mode);
3026   gcc_assert (val == val_so_far);
3027
3028   return accum;
3029 }
3030
3031 /* Perform a multiplication and return an rtx for the result.
3032    MODE is mode of value; OP0 and OP1 are what to multiply (rtx's);
3033    TARGET is a suggestion for where to store the result (an rtx).
3034
3035    We check specially for a constant integer as OP1.
3036    If you want this check for OP0 as well, then before calling
3037    you should swap the two operands if OP0 would be constant.  */
3038
3039 rtx
3040 expand_mult (enum machine_mode mode, rtx op0, rtx op1, rtx target,
3041              int unsignedp)
3042 {
3043   enum mult_variant variant;
3044   struct algorithm algorithm;
3045   int max_cost;
3046
3047   /* Handling const0_rtx here allows us to use zero as a rogue value for
3048      coeff below.  */
3049   if (op1 == const0_rtx)
3050     return const0_rtx;
3051   if (op1 == const1_rtx)
3052     return op0;
3053   if (op1 == constm1_rtx)
3054     return expand_unop (mode,
3055                         GET_MODE_CLASS (mode) == MODE_INT
3056                         && !unsignedp && flag_trapv
3057                         ? negv_optab : neg_optab,
3058                         op0, target, 0);
3059
3060   /* These are the operations that are potentially turned into a sequence
3061      of shifts and additions.  */
3062   if (SCALAR_INT_MODE_P (mode)
3063       && (unsignedp || !flag_trapv))
3064     {
3065       HOST_WIDE_INT coeff = 0;
3066       rtx fake_reg = gen_raw_REG (mode, LAST_VIRTUAL_REGISTER + 1);
3067
3068       /* synth_mult does an `unsigned int' multiply.  As long as the mode is
3069          less than or equal in size to `unsigned int' this doesn't matter.
3070          If the mode is larger than `unsigned int', then synth_mult works
3071          only if the constant value exactly fits in an `unsigned int' without
3072          any truncation.  This means that multiplying by negative values does
3073          not work; results are off by 2^32 on a 32 bit machine.  */
3074
3075       if (GET_CODE (op1) == CONST_INT)
3076         {
3077           /* Attempt to handle multiplication of DImode values by negative
3078              coefficients, by performing the multiplication by a positive
3079              multiplier and then inverting the result.  */
3080           if (INTVAL (op1) < 0
3081               && GET_MODE_BITSIZE (mode) > HOST_BITS_PER_WIDE_INT)
3082             {
3083               /* Its safe to use -INTVAL (op1) even for INT_MIN, as the
3084                  result is interpreted as an unsigned coefficient.
3085                  Exclude cost of op0 from max_cost to match the cost
3086                  calculation of the synth_mult.  */
3087               max_cost = rtx_cost (gen_rtx_MULT (mode, fake_reg, op1), SET)
3088                          - neg_cost[mode];
3089               if (max_cost > 0
3090                   && choose_mult_variant (mode, -INTVAL (op1), &algorithm,
3091                                           &variant, max_cost))
3092                 {
3093                   rtx temp = expand_mult_const (mode, op0, -INTVAL (op1),
3094                                                 NULL_RTX, &algorithm,
3095                                                 variant);
3096                   return expand_unop (mode, neg_optab, temp, target, 0);
3097                 }
3098             }
3099           else coeff = INTVAL (op1);
3100         }
3101       else if (GET_CODE (op1) == CONST_DOUBLE)
3102         {
3103           /* If we are multiplying in DImode, it may still be a win
3104              to try to work with shifts and adds.  */
3105           if (CONST_DOUBLE_HIGH (op1) == 0)
3106             coeff = CONST_DOUBLE_LOW (op1);
3107           else if (CONST_DOUBLE_LOW (op1) == 0
3108                    && EXACT_POWER_OF_2_OR_ZERO_P (CONST_DOUBLE_HIGH (op1)))
3109             {
3110               int shift = floor_log2 (CONST_DOUBLE_HIGH (op1))
3111                           + HOST_BITS_PER_WIDE_INT;
3112               return expand_shift (LSHIFT_EXPR, mode, op0,
3113                                    build_int_cst (NULL_TREE, shift),
3114                                    target, unsignedp);
3115             }
3116         }
3117         
3118       /* We used to test optimize here, on the grounds that it's better to
3119          produce a smaller program when -O is not used.  But this causes
3120          such a terrible slowdown sometimes that it seems better to always
3121          use synth_mult.  */
3122       if (coeff != 0)
3123         {
3124           /* Special case powers of two.  */
3125           if (EXACT_POWER_OF_2_OR_ZERO_P (coeff))
3126             return expand_shift (LSHIFT_EXPR, mode, op0,
3127                                  build_int_cst (NULL_TREE, floor_log2 (coeff)),
3128                                  target, unsignedp);
3129
3130           /* Exclude cost of op0 from max_cost to match the cost
3131              calculation of the synth_mult.  */
3132           max_cost = rtx_cost (gen_rtx_MULT (mode, fake_reg, op1), SET);
3133           if (choose_mult_variant (mode, coeff, &algorithm, &variant,
3134                                    max_cost))
3135             return expand_mult_const (mode, op0, coeff, target,
3136                                       &algorithm, variant);
3137         }
3138     }
3139
3140   if (GET_CODE (op0) == CONST_DOUBLE)
3141     {
3142       rtx temp = op0;
3143       op0 = op1;
3144       op1 = temp;
3145     }
3146
3147   /* Expand x*2.0 as x+x.  */
3148   if (GET_CODE (op1) == CONST_DOUBLE
3149       && GET_MODE_CLASS (mode) == MODE_FLOAT)
3150     {
3151       REAL_VALUE_TYPE d;
3152       REAL_VALUE_FROM_CONST_DOUBLE (d, op1);
3153
3154       if (REAL_VALUES_EQUAL (d, dconst2))
3155         {
3156           op0 = force_reg (GET_MODE (op0), op0);
3157           return expand_binop (mode, add_optab, op0, op0,
3158                                target, unsignedp, OPTAB_LIB_WIDEN);
3159         }
3160     }
3161
3162   /* This used to use umul_optab if unsigned, but for non-widening multiply
3163      there is no difference between signed and unsigned.  */
3164   op0 = expand_binop (mode,
3165                       ! unsignedp
3166                       && flag_trapv && (GET_MODE_CLASS(mode) == MODE_INT)
3167                       ? smulv_optab : smul_optab,
3168                       op0, op1, target, unsignedp, OPTAB_LIB_WIDEN);
3169   gcc_assert (op0);
3170   return op0;
3171 }
3172 \f
3173 /* Return the smallest n such that 2**n >= X.  */
3174
3175 int
3176 ceil_log2 (unsigned HOST_WIDE_INT x)
3177 {
3178   return floor_log2 (x - 1) + 1;
3179 }
3180
3181 /* Choose a minimal N + 1 bit approximation to 1/D that can be used to
3182    replace division by D, and put the least significant N bits of the result
3183    in *MULTIPLIER_PTR and return the most significant bit.
3184
3185    The width of operations is N (should be <= HOST_BITS_PER_WIDE_INT), the
3186    needed precision is in PRECISION (should be <= N).
3187
3188    PRECISION should be as small as possible so this function can choose
3189    multiplier more freely.
3190
3191    The rounded-up logarithm of D is placed in *lgup_ptr.  A shift count that
3192    is to be used for a final right shift is placed in *POST_SHIFT_PTR.
3193
3194    Using this function, x/D will be equal to (x * m) >> (*POST_SHIFT_PTR),
3195    where m is the full HOST_BITS_PER_WIDE_INT + 1 bit multiplier.  */
3196
3197 static
3198 unsigned HOST_WIDE_INT
3199 choose_multiplier (unsigned HOST_WIDE_INT d, int n, int precision,
3200                    rtx *multiplier_ptr, int *post_shift_ptr, int *lgup_ptr)
3201 {
3202   HOST_WIDE_INT mhigh_hi, mlow_hi;
3203   unsigned HOST_WIDE_INT mhigh_lo, mlow_lo;
3204   int lgup, post_shift;
3205   int pow, pow2;
3206   unsigned HOST_WIDE_INT nl, dummy1;
3207   HOST_WIDE_INT nh, dummy2;
3208
3209   /* lgup = ceil(log2(divisor)); */
3210   lgup = ceil_log2 (d);
3211
3212   gcc_assert (lgup <= n);
3213
3214   pow = n + lgup;
3215   pow2 = n + lgup - precision;
3216
3217   /* We could handle this with some effort, but this case is much
3218      better handled directly with a scc insn, so rely on caller using
3219      that.  */
3220   gcc_assert (pow != 2 * HOST_BITS_PER_WIDE_INT);
3221
3222   /* mlow = 2^(N + lgup)/d */
3223  if (pow >= HOST_BITS_PER_WIDE_INT)
3224     {
3225       nh = (HOST_WIDE_INT) 1 << (pow - HOST_BITS_PER_WIDE_INT);
3226       nl = 0;
3227     }
3228   else
3229     {
3230       nh = 0;
3231       nl = (unsigned HOST_WIDE_INT) 1 << pow;
3232     }
3233   div_and_round_double (TRUNC_DIV_EXPR, 1, nl, nh, d, (HOST_WIDE_INT) 0,
3234                         &mlow_lo, &mlow_hi, &dummy1, &dummy2);
3235
3236   /* mhigh = (2^(N + lgup) + 2^N + lgup - precision)/d */
3237   if (pow2 >= HOST_BITS_PER_WIDE_INT)
3238     nh |= (HOST_WIDE_INT) 1 << (pow2 - HOST_BITS_PER_WIDE_INT);
3239   else
3240     nl |= (unsigned HOST_WIDE_INT) 1 << pow2;
3241   div_and_round_double (TRUNC_DIV_EXPR, 1, nl, nh, d, (HOST_WIDE_INT) 0,
3242                         &mhigh_lo, &mhigh_hi, &dummy1, &dummy2);
3243
3244   gcc_assert (!mhigh_hi || nh - d < d);
3245   gcc_assert (mhigh_hi <= 1 && mlow_hi <= 1);
3246   /* Assert that mlow < mhigh.  */
3247   gcc_assert (mlow_hi < mhigh_hi
3248               || (mlow_hi == mhigh_hi && mlow_lo < mhigh_lo));
3249
3250   /* If precision == N, then mlow, mhigh exceed 2^N
3251      (but they do not exceed 2^(N+1)).  */
3252
3253   /* Reduce to lowest terms.  */
3254   for (post_shift = lgup; post_shift > 0; post_shift--)
3255     {
3256       unsigned HOST_WIDE_INT ml_lo = (mlow_hi << (HOST_BITS_PER_WIDE_INT - 1)) | (mlow_lo >> 1);
3257       unsigned HOST_WIDE_INT mh_lo = (mhigh_hi << (HOST_BITS_PER_WIDE_INT - 1)) | (mhigh_lo >> 1);
3258       if (ml_lo >= mh_lo)
3259         break;
3260
3261       mlow_hi = 0;
3262       mlow_lo = ml_lo;
3263       mhigh_hi = 0;
3264       mhigh_lo = mh_lo;
3265     }
3266
3267   *post_shift_ptr = post_shift;
3268   *lgup_ptr = lgup;
3269   if (n < HOST_BITS_PER_WIDE_INT)
3270     {
3271       unsigned HOST_WIDE_INT mask = ((unsigned HOST_WIDE_INT) 1 << n) - 1;
3272       *multiplier_ptr = GEN_INT (mhigh_lo & mask);
3273       return mhigh_lo >= mask;
3274     }
3275   else
3276     {
3277       *multiplier_ptr = GEN_INT (mhigh_lo);
3278       return mhigh_hi;
3279     }
3280 }
3281
3282 /* Compute the inverse of X mod 2**n, i.e., find Y such that X * Y is
3283    congruent to 1 (mod 2**N).  */
3284
3285 static unsigned HOST_WIDE_INT
3286 invert_mod2n (unsigned HOST_WIDE_INT x, int n)
3287 {
3288   /* Solve x*y == 1 (mod 2^n), where x is odd.  Return y.  */
3289
3290   /* The algorithm notes that the choice y = x satisfies
3291      x*y == 1 mod 2^3, since x is assumed odd.
3292      Each iteration doubles the number of bits of significance in y.  */
3293
3294   unsigned HOST_WIDE_INT mask;
3295   unsigned HOST_WIDE_INT y = x;
3296   int nbit = 3;
3297
3298   mask = (n == HOST_BITS_PER_WIDE_INT
3299           ? ~(unsigned HOST_WIDE_INT) 0
3300           : ((unsigned HOST_WIDE_INT) 1 << n) - 1);
3301
3302   while (nbit < n)
3303     {
3304       y = y * (2 - x*y) & mask;         /* Modulo 2^N */
3305       nbit *= 2;
3306     }
3307   return y;
3308 }
3309
3310 /* Emit code to adjust ADJ_OPERAND after multiplication of wrong signedness
3311    flavor of OP0 and OP1.  ADJ_OPERAND is already the high half of the
3312    product OP0 x OP1.  If UNSIGNEDP is nonzero, adjust the signed product
3313    to become unsigned, if UNSIGNEDP is zero, adjust the unsigned product to
3314    become signed.
3315
3316    The result is put in TARGET if that is convenient.
3317
3318    MODE is the mode of operation.  */
3319
3320 rtx
3321 expand_mult_highpart_adjust (enum machine_mode mode, rtx adj_operand, rtx op0,
3322                              rtx op1, rtx target, int unsignedp)
3323 {
3324   rtx tem;
3325   enum rtx_code adj_code = unsignedp ? PLUS : MINUS;
3326
3327   tem = expand_shift (RSHIFT_EXPR, mode, op0,
3328                       build_int_cst (NULL_TREE, GET_MODE_BITSIZE (mode) - 1),
3329                       NULL_RTX, 0);
3330   tem = expand_and (mode, tem, op1, NULL_RTX);
3331   adj_operand
3332     = force_operand (gen_rtx_fmt_ee (adj_code, mode, adj_operand, tem),
3333                      adj_operand);
3334
3335   tem = expand_shift (RSHIFT_EXPR, mode, op1,
3336                       build_int_cst (NULL_TREE, GET_MODE_BITSIZE (mode) - 1),
3337                       NULL_RTX, 0);
3338   tem = expand_and (mode, tem, op0, NULL_RTX);
3339   target = force_operand (gen_rtx_fmt_ee (adj_code, mode, adj_operand, tem),
3340                           target);
3341
3342   return target;
3343 }
3344
3345 /* Subroutine of expand_mult_highpart.  Return the MODE high part of OP.  */
3346
3347 static rtx
3348 extract_high_half (enum machine_mode mode, rtx op)
3349 {
3350   enum machine_mode wider_mode;
3351
3352   if (mode == word_mode)
3353     return gen_highpart (mode, op);
3354
3355   wider_mode = GET_MODE_WIDER_MODE (mode);
3356   op = expand_shift (RSHIFT_EXPR, wider_mode, op,
3357                      build_int_cst (NULL_TREE, GET_MODE_BITSIZE (mode)), 0, 1);
3358   return convert_modes (mode, wider_mode, op, 0);
3359 }
3360
3361 /* Like expand_mult_highpart, but only consider using a multiplication
3362    optab.  OP1 is an rtx for the constant operand.  */
3363
3364 static rtx
3365 expand_mult_highpart_optab (enum machine_mode mode, rtx op0, rtx op1,
3366                             rtx target, int unsignedp, int max_cost)
3367 {
3368   rtx narrow_op1 = gen_int_mode (INTVAL (op1), mode);
3369   enum machine_mode wider_mode;
3370   optab moptab;
3371   rtx tem;
3372   int size;
3373
3374   wider_mode = GET_MODE_WIDER_MODE (mode);
3375   size = GET_MODE_BITSIZE (mode);
3376
3377   /* Firstly, try using a multiplication insn that only generates the needed
3378      high part of the product, and in the sign flavor of unsignedp.  */
3379   if (mul_highpart_cost[mode] < max_cost)
3380     {
3381       moptab = unsignedp ? umul_highpart_optab : smul_highpart_optab;
3382       tem = expand_binop (mode, moptab, op0, narrow_op1, target,
3383                           unsignedp, OPTAB_DIRECT);
3384       if (tem)
3385         return tem;
3386     }
3387
3388   /* Secondly, same as above, but use sign flavor opposite of unsignedp.
3389      Need to adjust the result after the multiplication.  */
3390   if (size - 1 < BITS_PER_WORD
3391       && (mul_highpart_cost[mode] + 2 * shift_cost[mode][size-1]
3392           + 4 * add_cost[mode] < max_cost))
3393     {
3394       moptab = unsignedp ? smul_highpart_optab : umul_highpart_optab;
3395       tem = expand_binop (mode, moptab, op0, narrow_op1, target,
3396                           unsignedp, OPTAB_DIRECT);
3397       if (tem)
3398         /* We used the wrong signedness.  Adjust the result.  */
3399         return expand_mult_highpart_adjust (mode, tem, op0, narrow_op1,
3400                                             tem, unsignedp);
3401     }
3402
3403   /* Try widening multiplication.  */
3404   moptab = unsignedp ? umul_widen_optab : smul_widen_optab;
3405   if (moptab->handlers[wider_mode].insn_code != CODE_FOR_nothing
3406       && mul_widen_cost[wider_mode] < max_cost)
3407     {
3408       tem = expand_binop (wider_mode, moptab, op0, narrow_op1, 0,
3409                           unsignedp, OPTAB_WIDEN);
3410       if (tem)
3411         return extract_high_half (mode, tem);
3412     }
3413
3414   /* Try widening the mode and perform a non-widening multiplication.  */
3415   if (smul_optab->handlers[wider_mode].insn_code != CODE_FOR_nothing
3416       && size - 1 < BITS_PER_WORD
3417       && mul_cost[wider_mode] + shift_cost[mode][size-1] < max_cost)
3418     {
3419       rtx insns, wop0, wop1;
3420
3421       /* We need to widen the operands, for example to ensure the
3422          constant multiplier is correctly sign or zero extended.
3423          Use a sequence to clean-up any instructions emitted by
3424          the conversions if things don't work out.  */
3425       start_sequence ();
3426       wop0 = convert_modes (wider_mode, mode, op0, unsignedp);
3427       wop1 = convert_modes (wider_mode, mode, op1, unsignedp);
3428       tem = expand_binop (wider_mode, smul_optab, wop0, wop1, 0,
3429                           unsignedp, OPTAB_WIDEN);
3430       insns = get_insns ();
3431       end_sequence ();
3432
3433       if (tem)
3434         {
3435           emit_insn (insns);
3436           return extract_high_half (mode, tem);
3437         }
3438     }
3439
3440   /* Try widening multiplication of opposite signedness, and adjust.  */
3441   moptab = unsignedp ? smul_widen_optab : umul_widen_optab;
3442   if (moptab->handlers[wider_mode].insn_code != CODE_FOR_nothing
3443       && size - 1 < BITS_PER_WORD
3444       && (mul_widen_cost[wider_mode] + 2 * shift_cost[mode][size-1]
3445           + 4 * add_cost[mode] < max_cost))
3446     {
3447       tem = expand_binop (wider_mode, moptab, op0, narrow_op1,
3448                           NULL_RTX, ! unsignedp, OPTAB_WIDEN);
3449       if (tem != 0)
3450         {
3451           tem = extract_high_half (mode, tem);
3452           /* We used the wrong signedness.  Adjust the result.  */
3453           return expand_mult_highpart_adjust (mode, tem, op0, narrow_op1,
3454                                               target, unsignedp);
3455         }
3456     }
3457
3458   return 0;
3459 }
3460
3461 /* Emit code to multiply OP0 and OP1 (where OP1 is an integer constant),
3462    putting the high half of the result in TARGET if that is convenient,
3463    and return where the result is.  If the operation can not be performed,
3464    0 is returned.
3465
3466    MODE is the mode of operation and result.
3467
3468    UNSIGNEDP nonzero means unsigned multiply.
3469
3470    MAX_COST is the total allowed cost for the expanded RTL.  */
3471
3472 static rtx
3473 expand_mult_highpart (enum machine_mode mode, rtx op0, rtx op1,
3474                       rtx target, int unsignedp, int max_cost)
3475 {
3476   enum machine_mode wider_mode = GET_MODE_WIDER_MODE (mode);
3477   unsigned HOST_WIDE_INT cnst1;
3478   int extra_cost;
3479   bool sign_adjust = false;
3480   enum mult_variant variant;
3481   struct algorithm alg;
3482   rtx tem;
3483
3484   /* We can't support modes wider than HOST_BITS_PER_INT.  */
3485   gcc_assert (GET_MODE_BITSIZE (mode) <= HOST_BITS_PER_WIDE_INT);
3486
3487   cnst1 = INTVAL (op1) & GET_MODE_MASK (mode);
3488
3489   /* We can't optimize modes wider than BITS_PER_WORD. 
3490      ??? We might be able to perform double-word arithmetic if 
3491      mode == word_mode, however all the cost calculations in
3492      synth_mult etc. assume single-word operations.  */
3493   if (GET_MODE_BITSIZE (wider_mode) > BITS_PER_WORD)
3494     return expand_mult_highpart_optab (mode, op0, op1, target,
3495                                        unsignedp, max_cost);
3496
3497   extra_cost = shift_cost[mode][GET_MODE_BITSIZE (mode) - 1];
3498
3499   /* Check whether we try to multiply by a negative constant.  */
3500   if (!unsignedp && ((cnst1 >> (GET_MODE_BITSIZE (mode) - 1)) & 1))
3501     {
3502       sign_adjust = true;
3503       extra_cost += add_cost[mode];
3504     }
3505
3506   /* See whether shift/add multiplication is cheap enough.  */
3507   if (choose_mult_variant (wider_mode, cnst1, &alg, &variant,
3508                            max_cost - extra_cost))
3509     {
3510       /* See whether the specialized multiplication optabs are
3511          cheaper than the shift/add version.  */
3512       tem = expand_mult_highpart_optab (mode, op0, op1, target, unsignedp,
3513                                         alg.cost.cost + extra_cost);
3514       if (tem)
3515         return tem;
3516
3517       tem = convert_to_mode (wider_mode, op0, unsignedp);
3518       tem = expand_mult_const (wider_mode, tem, cnst1, 0, &alg, variant);
3519       tem = extract_high_half (mode, tem);
3520
3521       /* Adjust result for signedness.  */
3522       if (sign_adjust)
3523         tem = force_operand (gen_rtx_MINUS (mode, tem, op0), tem);
3524
3525       return tem;
3526     }
3527   return expand_mult_highpart_optab (mode, op0, op1, target,
3528                                      unsignedp, max_cost);
3529 }
3530
3531
3532 /* Expand signed modulus of OP0 by a power of two D in mode MODE.  */
3533
3534 static rtx
3535 expand_smod_pow2 (enum machine_mode mode, rtx op0, HOST_WIDE_INT d)
3536 {
3537   unsigned HOST_WIDE_INT masklow, maskhigh;
3538   rtx result, temp, shift, label;
3539   int logd;
3540
3541   logd = floor_log2 (d);
3542   result = gen_reg_rtx (mode);
3543
3544   /* Avoid conditional branches when they're expensive.  */
3545   if (BRANCH_COST >= 2
3546       && !optimize_size)
3547     {
3548       rtx signmask = emit_store_flag (result, LT, op0, const0_rtx,
3549                                       mode, 0, -1);
3550       if (signmask)
3551         {
3552           signmask = force_reg (mode, signmask);
3553           masklow = ((HOST_WIDE_INT) 1 << logd) - 1;
3554           shift = GEN_INT (GET_MODE_BITSIZE (mode) - logd);
3555
3556           /* Use the rtx_cost of a LSHIFTRT instruction to determine
3557              which instruction sequence to use.  If logical right shifts
3558              are expensive the use 2 XORs, 2 SUBs and an AND, otherwise
3559              use a LSHIFTRT, 1 ADD, 1 SUB and an AND.  */
3560
3561           temp = gen_rtx_LSHIFTRT (mode, result, shift);
3562           if (lshr_optab->handlers[mode].insn_code == CODE_FOR_nothing
3563               || rtx_cost (temp, SET) > COSTS_N_INSNS (2))
3564             {
3565               temp = expand_binop (mode, xor_optab, op0, signmask,
3566                                    NULL_RTX, 1, OPTAB_LIB_WIDEN);
3567               temp = expand_binop (mode, sub_optab, temp, signmask,
3568                                    NULL_RTX, 1, OPTAB_LIB_WIDEN);
3569               temp = expand_binop (mode, and_optab, temp, GEN_INT (masklow),
3570                                    NULL_RTX, 1, OPTAB_LIB_WIDEN);
3571               temp = expand_binop (mode, xor_optab, temp, signmask,
3572                                    NULL_RTX, 1, OPTAB_LIB_WIDEN);
3573               temp = expand_binop (mode, sub_optab, temp, signmask,
3574                                    NULL_RTX, 1, OPTAB_LIB_WIDEN);
3575             }
3576           else
3577             {
3578               signmask = expand_binop (mode, lshr_optab, signmask, shift,
3579                                        NULL_RTX, 1, OPTAB_LIB_WIDEN);
3580               signmask = force_reg (mode, signmask);
3581
3582               temp = expand_binop (mode, add_optab, op0, signmask,
3583                                    NULL_RTX, 1, OPTAB_LIB_WIDEN);
3584               temp = expand_binop (mode, and_optab, temp, GEN_INT (masklow),
3585                                    NULL_RTX, 1, OPTAB_LIB_WIDEN);
3586               temp = expand_binop (mode, sub_optab, temp, signmask,
3587                                    NULL_RTX, 1, OPTAB_LIB_WIDEN);
3588             }
3589           return temp;
3590         }
3591     }
3592
3593   /* Mask contains the mode's signbit and the significant bits of the
3594      modulus.  By including the signbit in the operation, many targets
3595      can avoid an explicit compare operation in the following comparison
3596      against zero.  */
3597
3598   masklow = ((HOST_WIDE_INT) 1 << logd) - 1;
3599   if (GET_MODE_BITSIZE (mode) <= HOST_BITS_PER_WIDE_INT)
3600     {
3601       masklow |= (HOST_WIDE_INT) -1 << (GET_MODE_BITSIZE (mode) - 1);
3602       maskhigh = -1;
3603     }
3604   else
3605     maskhigh = (HOST_WIDE_INT) -1
3606                  << (GET_MODE_BITSIZE (mode) - HOST_BITS_PER_WIDE_INT - 1);
3607
3608   temp = expand_binop (mode, and_optab, op0,
3609                        immed_double_const (masklow, maskhigh, mode),
3610                        result, 1, OPTAB_LIB_WIDEN);
3611   if (temp != result)
3612     emit_move_insn (result, temp);
3613
3614   label = gen_label_rtx ();
3615   do_cmp_and_jump (result, const0_rtx, GE, mode, label);
3616
3617   temp = expand_binop (mode, sub_optab, result, const1_rtx, result,
3618                        0, OPTAB_LIB_WIDEN);
3619   masklow = (HOST_WIDE_INT) -1 << logd;
3620   maskhigh = -1;
3621   temp = expand_binop (mode, ior_optab, temp,
3622                        immed_double_const (masklow, maskhigh, mode),
3623                        result, 1, OPTAB_LIB_WIDEN);
3624   temp = expand_binop (mode, add_optab, temp, const1_rtx, result,
3625                        0, OPTAB_LIB_WIDEN);
3626   if (temp != result)
3627     emit_move_insn (result, temp);
3628   emit_label (label);
3629   return result;
3630 }
3631
3632 /* Expand signed division of OP0 by a power of two D in mode MODE.
3633    This routine is only called for positive values of D.  */
3634
3635 static rtx
3636 expand_sdiv_pow2 (enum machine_mode mode, rtx op0, HOST_WIDE_INT d)
3637 {
3638   rtx temp, label;
3639   tree shift;
3640   int logd;
3641
3642   logd = floor_log2 (d);
3643   shift = build_int_cst (NULL_TREE, logd);
3644
3645   if (d == 2 && BRANCH_COST >= 1)
3646     {
3647       temp = gen_reg_rtx (mode);
3648       temp = emit_store_flag (temp, LT, op0, const0_rtx, mode, 0, 1);
3649       temp = expand_binop (mode, add_optab, temp, op0, NULL_RTX,
3650                            0, OPTAB_LIB_WIDEN);
3651       return expand_shift (RSHIFT_EXPR, mode, temp, shift, NULL_RTX, 0);
3652     }
3653
3654 #ifdef HAVE_conditional_move
3655   if (BRANCH_COST >= 2)
3656     {
3657       rtx temp2;
3658
3659       /* ??? emit_conditional_move forces a stack adjustment via
3660          compare_from_rtx so, if the sequence is discarded, it will
3661          be lost.  Do it now instead.  */
3662       do_pending_stack_adjust ();
3663
3664       start_sequence ();
3665       temp2 = copy_to_mode_reg (mode, op0);
3666       temp = expand_binop (mode, add_optab, temp2, GEN_INT (d-1),
3667                            NULL_RTX, 0, OPTAB_LIB_WIDEN);
3668       temp = force_reg (mode, temp);
3669
3670       /* Construct "temp2 = (temp2 < 0) ? temp : temp2".  */
3671       temp2 = emit_conditional_move (temp2, LT, temp2, const0_rtx,
3672                                      mode, temp, temp2, mode, 0);
3673       if (temp2)
3674         {
3675           rtx seq = get_insns ();
3676           end_sequence ();
3677           emit_insn (seq);
3678           return expand_shift (RSHIFT_EXPR, mode, temp2, shift, NULL_RTX, 0);
3679         }
3680       end_sequence ();
3681     }
3682 #endif
3683
3684   if (BRANCH_COST >= 2)
3685     {
3686       int ushift = GET_MODE_BITSIZE (mode) - logd;
3687
3688       temp = gen_reg_rtx (mode);
3689       temp = emit_store_flag (temp, LT, op0, const0_rtx, mode, 0, -1);
3690       if (shift_cost[mode][ushift] > COSTS_N_INSNS (1))
3691         temp = expand_binop (mode, and_optab, temp, GEN_INT (d - 1),
3692                              NULL_RTX, 0, OPTAB_LIB_WIDEN);
3693       else
3694         temp = expand_shift (RSHIFT_EXPR, mode, temp,
3695                              build_int_cst (NULL_TREE, ushift),
3696                              NULL_RTX, 1);
3697       temp = expand_binop (mode, add_optab, temp, op0, NULL_RTX,
3698                            0, OPTAB_LIB_WIDEN);
3699       return expand_shift (RSHIFT_EXPR, mode, temp, shift, NULL_RTX, 0);
3700     }
3701
3702   label = gen_label_rtx ();
3703   temp = copy_to_mode_reg (mode, op0);
3704   do_cmp_and_jump (temp, const0_rtx, GE, mode, label);
3705   expand_inc (temp, GEN_INT (d - 1));
3706   emit_label (label);
3707   return expand_shift (RSHIFT_EXPR, mode, temp, shift, NULL_RTX, 0);
3708 }
3709 \f
3710 /* Emit the code to divide OP0 by OP1, putting the result in TARGET
3711    if that is convenient, and returning where the result is.
3712    You may request either the quotient or the remainder as the result;
3713    specify REM_FLAG nonzero to get the remainder.
3714
3715    CODE is the expression code for which kind of division this is;
3716    it controls how rounding is done.  MODE is the machine mode to use.
3717    UNSIGNEDP nonzero means do unsigned division.  */
3718
3719 /* ??? For CEIL_MOD_EXPR, can compute incorrect remainder with ANDI
3720    and then correct it by or'ing in missing high bits
3721    if result of ANDI is nonzero.
3722    For ROUND_MOD_EXPR, can use ANDI and then sign-extend the result.
3723    This could optimize to a bfexts instruction.
3724    But C doesn't use these operations, so their optimizations are
3725    left for later.  */
3726 /* ??? For modulo, we don't actually need the highpart of the first product,
3727    the low part will do nicely.  And for small divisors, the second multiply
3728    can also be a low-part only multiply or even be completely left out.
3729    E.g. to calculate the remainder of a division by 3 with a 32 bit
3730    multiply, multiply with 0x55555556 and extract the upper two bits;
3731    the result is exact for inputs up to 0x1fffffff.
3732    The input range can be reduced by using cross-sum rules.
3733    For odd divisors >= 3, the following table gives right shift counts
3734    so that if a number is shifted by an integer multiple of the given
3735    amount, the remainder stays the same:
3736    2, 4, 3, 6, 10, 12, 4, 8, 18, 6, 11, 20, 18, 0, 5, 10, 12, 0, 12, 20,
3737    14, 12, 23, 21, 8, 0, 20, 18, 0, 0, 6, 12, 0, 22, 0, 18, 20, 30, 0, 0,
3738    0, 8, 0, 11, 12, 10, 36, 0, 30, 0, 0, 12, 0, 0, 0, 0, 44, 12, 24, 0,
3739    20, 0, 7, 14, 0, 18, 36, 0, 0, 46, 60, 0, 42, 0, 15, 24, 20, 0, 0, 33,
3740    0, 20, 0, 0, 18, 0, 60, 0, 0, 0, 0, 0, 40, 18, 0, 0, 12
3741
3742    Cross-sum rules for even numbers can be derived by leaving as many bits
3743    to the right alone as the divisor has zeros to the right.
3744    E.g. if x is an unsigned 32 bit number:
3745    (x mod 12) == (((x & 1023) + ((x >> 8) & ~3)) * 0x15555558 >> 2 * 3) >> 28
3746    */
3747
3748 rtx
3749 expand_divmod (int rem_flag, enum tree_code code, enum machine_mode mode,
3750                rtx op0, rtx op1, rtx target, int unsignedp)
3751 {
3752   enum machine_mode compute_mode;
3753   rtx tquotient;
3754   rtx quotient = 0, remainder = 0;
3755   rtx last;
3756   int size;
3757   rtx insn, set;
3758   optab optab1, optab2;
3759   int op1_is_constant, op1_is_pow2 = 0;
3760   int max_cost, extra_cost;
3761   static HOST_WIDE_INT last_div_const = 0;
3762   static HOST_WIDE_INT ext_op1;
3763
3764   op1_is_constant = GET_CODE (op1) == CONST_INT;
3765   if (op1_is_constant)
3766     {
3767       ext_op1 = INTVAL (op1);
3768       if (unsignedp)
3769         ext_op1 &= GET_MODE_MASK (mode);
3770       op1_is_pow2 = ((EXACT_POWER_OF_2_OR_ZERO_P (ext_op1)
3771                      || (! unsignedp && EXACT_POWER_OF_2_OR_ZERO_P (-ext_op1))));
3772     }
3773
3774   /*
3775      This is the structure of expand_divmod:
3776
3777      First comes code to fix up the operands so we can perform the operations
3778      correctly and efficiently.
3779
3780      Second comes a switch statement with code specific for each rounding mode.
3781      For some special operands this code emits all RTL for the desired
3782      operation, for other cases, it generates only a quotient and stores it in
3783      QUOTIENT.  The case for trunc division/remainder might leave quotient = 0,
3784      to indicate that it has not done anything.
3785
3786      Last comes code that finishes the operation.  If QUOTIENT is set and
3787      REM_FLAG is set, the remainder is computed as OP0 - QUOTIENT * OP1.  If
3788      QUOTIENT is not set, it is computed using trunc rounding.
3789
3790      We try to generate special code for division and remainder when OP1 is a
3791      constant.  If |OP1| = 2**n we can use shifts and some other fast
3792      operations.  For other values of OP1, we compute a carefully selected
3793      fixed-point approximation m = 1/OP1, and generate code that multiplies OP0
3794      by m.
3795
3796      In all cases but EXACT_DIV_EXPR, this multiplication requires the upper
3797      half of the product.  Different strategies for generating the product are
3798      implemented in expand_mult_highpart.
3799
3800      If what we actually want is the remainder, we generate that by another
3801      by-constant multiplication and a subtraction.  */
3802
3803   /* We shouldn't be called with OP1 == const1_rtx, but some of the
3804      code below will malfunction if we are, so check here and handle
3805      the special case if so.  */
3806   if (op1 == const1_rtx)
3807     return rem_flag ? const0_rtx : op0;
3808
3809     /* When dividing by -1, we could get an overflow.
3810      negv_optab can handle overflows.  */
3811   if (! unsignedp && op1 == constm1_rtx)
3812     {
3813       if (rem_flag)
3814         return const0_rtx;
3815       return expand_unop (mode, flag_trapv && GET_MODE_CLASS(mode) == MODE_INT
3816                           ? negv_optab : neg_optab, op0, target, 0);
3817     }
3818
3819   if (target
3820       /* Don't use the function value register as a target
3821          since we have to read it as well as write it,
3822          and function-inlining gets confused by this.  */
3823       && ((REG_P (target) && REG_FUNCTION_VALUE_P (target))
3824           /* Don't clobber an operand while doing a multi-step calculation.  */
3825           || ((rem_flag || op1_is_constant)
3826               && (reg_mentioned_p (target, op0)
3827                   || (MEM_P (op0) && MEM_P (target))))
3828           || reg_mentioned_p (target, op1)
3829           || (MEM_P (op1) && MEM_P (target))))
3830     target = 0;
3831
3832   /* Get the mode in which to perform this computation.  Normally it will
3833      be MODE, but sometimes we can't do the desired operation in MODE.
3834      If so, pick a wider mode in which we can do the operation.  Convert
3835      to that mode at the start to avoid repeated conversions.
3836
3837      First see what operations we need.  These depend on the expression
3838      we are evaluating.  (We assume that divxx3 insns exist under the
3839      same conditions that modxx3 insns and that these insns don't normally
3840      fail.  If these assumptions are not correct, we may generate less
3841      efficient code in some cases.)
3842
3843      Then see if we find a mode in which we can open-code that operation
3844      (either a division, modulus, or shift).  Finally, check for the smallest
3845      mode for which we can do the operation with a library call.  */
3846
3847   /* We might want to refine this now that we have division-by-constant
3848      optimization.  Since expand_mult_highpart tries so many variants, it is
3849      not straightforward to generalize this.  Maybe we should make an array
3850      of possible modes in init_expmed?  Save this for GCC 2.7.  */
3851
3852   optab1 = ((op1_is_pow2 && op1 != const0_rtx)
3853             ? (unsignedp ? lshr_optab : ashr_optab)
3854             : (unsignedp ? udiv_optab : sdiv_optab));
3855   optab2 = ((op1_is_pow2 && op1 != const0_rtx)
3856             ? optab1
3857             : (unsignedp ? udivmod_optab : sdivmod_optab));
3858
3859   for (compute_mode = mode; compute_mode != VOIDmode;
3860        compute_mode = GET_MODE_WIDER_MODE (compute_mode))
3861     if (optab1->handlers[compute_mode].insn_code != CODE_FOR_nothing
3862         || optab2->handlers[compute_mode].insn_code != CODE_FOR_nothing)
3863       break;
3864
3865   if (compute_mode == VOIDmode)
3866     for (compute_mode = mode; compute_mode != VOIDmode;
3867          compute_mode = GET_MODE_WIDER_MODE (compute_mode))
3868       if (optab1->handlers[compute_mode].libfunc
3869           || optab2->handlers[compute_mode].libfunc)
3870         break;
3871
3872   /* If we still couldn't find a mode, use MODE, but expand_binop will
3873      probably die.  */
3874   if (compute_mode == VOIDmode)
3875     compute_mode = mode;
3876
3877   if (target && GET_MODE (target) == compute_mode)
3878     tquotient = target;
3879   else
3880     tquotient = gen_reg_rtx (compute_mode);
3881
3882   size = GET_MODE_BITSIZE (compute_mode);
3883 #if 0
3884   /* It should be possible to restrict the precision to GET_MODE_BITSIZE
3885      (mode), and thereby get better code when OP1 is a constant.  Do that
3886      later.  It will require going over all usages of SIZE below.  */
3887   size = GET_MODE_BITSIZE (mode);
3888 #endif
3889
3890   /* Only deduct something for a REM if the last divide done was
3891      for a different constant.   Then set the constant of the last
3892      divide.  */
3893   max_cost = div_cost[compute_mode]
3894     - (rem_flag && ! (last_div_const != 0 && op1_is_constant
3895                       && INTVAL (op1) == last_div_const)
3896        ? mul_cost[compute_mode] + add_cost[compute_mode]
3897        : 0);
3898
3899   last_div_const = ! rem_flag && op1_is_constant ? INTVAL (op1) : 0;
3900
3901   /* Now convert to the best mode to use.  */
3902   if (compute_mode != mode)
3903     {
3904       op0 = convert_modes (compute_mode, mode, op0, unsignedp);
3905       op1 = convert_modes (compute_mode, mode, op1, unsignedp);
3906
3907       /* convert_modes may have placed op1 into a register, so we
3908          must recompute the following.  */
3909       op1_is_constant = GET_CODE (op1) == CONST_INT;
3910       op1_is_pow2 = (op1_is_constant
3911                      && ((EXACT_POWER_OF_2_OR_ZERO_P (INTVAL (op1))
3912                           || (! unsignedp
3913                               && EXACT_POWER_OF_2_OR_ZERO_P (-INTVAL (op1)))))) ;
3914     }
3915
3916   /* If one of the operands is a volatile MEM, copy it into a register.  */
3917
3918   if (MEM_P (op0) && MEM_VOLATILE_P (op0))
3919     op0 = force_reg (compute_mode, op0);
3920   if (MEM_P (op1) && MEM_VOLATILE_P (op1))
3921     op1 = force_reg (compute_mode, op1);
3922
3923   /* If we need the remainder or if OP1 is constant, we need to
3924      put OP0 in a register in case it has any queued subexpressions.  */
3925   if (rem_flag || op1_is_constant)
3926     op0 = force_reg (compute_mode, op0);
3927
3928   last = get_last_insn ();
3929
3930   /* Promote floor rounding to trunc rounding for unsigned operations.  */
3931   if (unsignedp)
3932     {
3933       if (code == FLOOR_DIV_EXPR)
3934         code = TRUNC_DIV_EXPR;
3935       if (code == FLOOR_MOD_EXPR)
3936         code = TRUNC_MOD_EXPR;
3937       if (code == EXACT_DIV_EXPR && op1_is_pow2)
3938         code = TRUNC_DIV_EXPR;
3939     }
3940
3941   if (op1 != const0_rtx)
3942     switch (code)
3943       {
3944       case TRUNC_MOD_EXPR:
3945       case TRUNC_DIV_EXPR:
3946         if (op1_is_constant)
3947           {
3948             if (unsignedp)
3949               {
3950                 unsigned HOST_WIDE_INT mh;
3951                 int pre_shift, post_shift;
3952                 int dummy;
3953                 rtx ml;
3954                 unsigned HOST_WIDE_INT d = (INTVAL (op1)
3955                                             & GET_MODE_MASK (compute_mode));
3956
3957                 if (EXACT_POWER_OF_2_OR_ZERO_P (d))
3958                   {
3959                     pre_shift = floor_log2 (d);
3960                     if (rem_flag)
3961                       {
3962                         remainder
3963                           = expand_binop (compute_mode, and_optab, op0,
3964                                           GEN_INT (((HOST_WIDE_INT) 1 << pre_shift) - 1),
3965                                           remainder, 1,
3966                                           OPTAB_LIB_WIDEN);
3967                         if (remainder)
3968                           return gen_lowpart (mode, remainder);
3969                       }
3970                     quotient = expand_shift (RSHIFT_EXPR, compute_mode, op0,
3971                                              build_int_cst (NULL_TREE,
3972                                                             pre_shift),
3973                                              tquotient, 1);
3974                   }
3975                 else if (size <= HOST_BITS_PER_WIDE_INT)
3976                   {
3977                     if (d >= ((unsigned HOST_WIDE_INT) 1 << (size - 1)))
3978                       {
3979                         /* Most significant bit of divisor is set; emit an scc
3980                            insn.  */
3981                         quotient = emit_store_flag (tquotient, GEU, op0, op1,
3982                                                     compute_mode, 1, 1);
3983                         if (quotient == 0)
3984                           goto fail1;
3985                       }
3986                     else
3987                       {
3988                         /* Find a suitable multiplier and right shift count
3989                            instead of multiplying with D.  */
3990
3991                         mh = choose_multiplier (d, size, size,
3992                                                 &ml, &post_shift, &dummy);
3993
3994                         /* If the suggested multiplier is more than SIZE bits,
3995                            we can do better for even divisors, using an
3996                            initial right shift.  */
3997                         if (mh != 0 && (d & 1) == 0)
3998                           {
3999                             pre_shift = floor_log2 (d & -d);
4000                             mh = choose_multiplier (d >> pre_shift, size,
4001                                                     size - pre_shift,
4002                                                     &ml, &post_shift, &dummy);
4003                             gcc_assert (!mh);
4004                           }
4005                         else
4006                           pre_shift = 0;
4007
4008                         if (mh != 0)
4009                           {
4010                             rtx t1, t2, t3, t4;
4011
4012                             if (post_shift - 1 >= BITS_PER_WORD)
4013                               goto fail1;
4014
4015                             extra_cost
4016                               = (shift_cost[compute_mode][post_shift - 1]
4017                                  + shift_cost[compute_mode][1]
4018                                  + 2 * add_cost[compute_mode]);
4019                             t1 = expand_mult_highpart (compute_mode, op0, ml,
4020                                                        NULL_RTX, 1,
4021                                                        max_cost - extra_cost);
4022                             if (t1 == 0)
4023                               goto fail1;
4024                             t2 = force_operand (gen_rtx_MINUS (compute_mode,
4025                                                                op0, t1),
4026                                                 NULL_RTX);
4027                             t3 = expand_shift
4028                               (RSHIFT_EXPR, compute_mode, t2,
4029                                build_int_cst (NULL_TREE, 1),
4030                                NULL_RTX,1);
4031                             t4 = force_operand (gen_rtx_PLUS (compute_mode,
4032                                                               t1, t3),
4033                                                 NULL_RTX);
4034                             quotient = expand_shift
4035                               (RSHIFT_EXPR, compute_mode, t4,
4036                                build_int_cst (NULL_TREE, post_shift - 1),
4037                                tquotient, 1);
4038                           }
4039                         else
4040                           {
4041                             rtx t1, t2;
4042
4043                             if (pre_shift >= BITS_PER_WORD
4044                                 || post_shift >= BITS_PER_WORD)
4045                               goto fail1;
4046
4047                             t1 = expand_shift
4048                               (RSHIFT_EXPR, compute_mode, op0,
4049                                build_int_cst (NULL_TREE, pre_shift),
4050                                NULL_RTX, 1);
4051                             extra_cost
4052                               = (shift_cost[compute_mode][pre_shift]
4053                                  + shift_cost[compute_mode][post_shift]);
4054                             t2 = expand_mult_highpart (compute_mode, t1, ml,
4055                                                        NULL_RTX, 1,
4056                                                        max_cost - extra_cost);
4057                             if (t2 == 0)
4058                               goto fail1;
4059                             quotient = expand_shift
4060                               (RSHIFT_EXPR, compute_mode, t2,
4061                                build_int_cst (NULL_TREE, post_shift),
4062                                tquotient, 1);
4063                           }
4064                       }
4065                   }
4066                 else            /* Too wide mode to use tricky code */
4067                   break;
4068
4069                 insn = get_last_insn ();
4070                 if (insn != last
4071                     && (set = single_set (insn)) != 0
4072                     && SET_DEST (set) == quotient)
4073                   set_unique_reg_note (insn,
4074                                        REG_EQUAL,
4075                                        gen_rtx_UDIV (compute_mode, op0, op1));
4076               }
4077             else                /* TRUNC_DIV, signed */
4078               {
4079                 unsigned HOST_WIDE_INT ml;
4080                 int lgup, post_shift;
4081                 rtx mlr;
4082                 HOST_WIDE_INT d = INTVAL (op1);
4083                 unsigned HOST_WIDE_INT abs_d = d >= 0 ? d : -d;
4084
4085                 /* n rem d = n rem -d */
4086                 if (rem_flag && d < 0)
4087                   {
4088                     d = abs_d;
4089                     op1 = gen_int_mode (abs_d, compute_mode);
4090                   }
4091
4092                 if (d == 1)
4093                   quotient = op0;
4094                 else if (d == -1)
4095                   quotient = expand_unop (compute_mode, neg_optab, op0,
4096                                           tquotient, 0);
4097                 else if (abs_d == (unsigned HOST_WIDE_INT) 1 << (size - 1))
4098                   {
4099                     /* This case is not handled correctly below.  */
4100                     quotient = emit_store_flag (tquotient, EQ, op0, op1,
4101                                                 compute_mode, 1, 1);
4102                     if (quotient == 0)
4103                       goto fail1;
4104                   }
4105                 else if (EXACT_POWER_OF_2_OR_ZERO_P (d)
4106                          && (rem_flag ? smod_pow2_cheap[compute_mode]
4107                                       : sdiv_pow2_cheap[compute_mode])
4108                          /* We assume that cheap metric is true if the
4109                             optab has an expander for this mode.  */
4110                          && (((rem_flag ? smod_optab : sdiv_optab)
4111                               ->handlers[compute_mode].insn_code
4112                               != CODE_FOR_nothing)
4113                              || (sdivmod_optab->handlers[compute_mode]
4114                                  .insn_code != CODE_FOR_nothing)))
4115                   ;
4116                 else if (EXACT_POWER_OF_2_OR_ZERO_P (abs_d))
4117                   {
4118                     if (rem_flag)
4119                       {
4120                         remainder = expand_smod_pow2 (compute_mode, op0, d);
4121                         if (remainder)
4122                           return gen_lowpart (mode, remainder);
4123                       }
4124
4125                     if (sdiv_pow2_cheap[compute_mode]
4126                         && ((sdiv_optab->handlers[compute_mode].insn_code
4127                              != CODE_FOR_nothing)
4128                             || (sdivmod_optab->handlers[compute_mode].insn_code
4129                                 != CODE_FOR_nothing)))
4130                       quotient = expand_divmod (0, TRUNC_DIV_EXPR,
4131                                                 compute_mode, op0,
4132                                                 gen_int_mode (abs_d,
4133                                                               compute_mode),
4134                                                 NULL_RTX, 0);
4135                     else
4136                       quotient = expand_sdiv_pow2 (compute_mode, op0, abs_d);
4137
4138                     /* We have computed OP0 / abs(OP1).  If OP1 is negative,
4139                        negate the quotient.  */
4140                     if (d < 0)
4141                       {
4142                         insn = get_last_insn ();
4143                         if (insn != last
4144                             && (set = single_set (insn)) != 0
4145                             && SET_DEST (set) == quotient
4146                             && abs_d < ((unsigned HOST_WIDE_INT) 1
4147                                         << (HOST_BITS_PER_WIDE_INT - 1)))
4148                           set_unique_reg_note (insn,
4149                                                REG_EQUAL,
4150                                                gen_rtx_DIV (compute_mode,
4151                                                             op0,
4152                                                             GEN_INT
4153                                                             (trunc_int_for_mode
4154                                                              (abs_d,
4155                                                               compute_mode))));
4156
4157                         quotient = expand_unop (compute_mode, neg_optab,
4158                                                 quotient, quotient, 0);
4159                       }
4160                   }
4161                 else if (size <= HOST_BITS_PER_WIDE_INT)
4162                   {
4163                     choose_multiplier (abs_d, size, size - 1,
4164                                        &mlr, &post_shift, &lgup);
4165                     ml = (unsigned HOST_WIDE_INT) INTVAL (mlr);
4166                     if (ml < (unsigned HOST_WIDE_INT) 1 << (size - 1))
4167                       {
4168                         rtx t1, t2, t3;
4169
4170                         if (post_shift >= BITS_PER_WORD
4171                             || size - 1 >= BITS_PER_WORD)
4172                           goto fail1;
4173
4174                         extra_cost = (shift_cost[compute_mode][post_shift]
4175                                       + shift_cost[compute_mode][size - 1]
4176                                       + add_cost[compute_mode]);
4177                         t1 = expand_mult_highpart (compute_mode, op0, mlr,
4178                                                    NULL_RTX, 0,
4179                                                    max_cost - extra_cost);
4180                         if (t1 == 0)
4181                           goto fail1;
4182                         t2 = expand_shift
4183                           (RSHIFT_EXPR, compute_mode, t1,
4184                            build_int_cst (NULL_TREE, post_shift),
4185                            NULL_RTX, 0);
4186                         t3 = expand_shift
4187                           (RSHIFT_EXPR, compute_mode, op0,
4188                            build_int_cst (NULL_TREE, size - 1),
4189                            NULL_RTX, 0);
4190                         if (d < 0)
4191                           quotient
4192                             = force_operand (gen_rtx_MINUS (compute_mode,
4193                                                             t3, t2),
4194                                              tquotient);
4195                         else
4196                           quotient
4197                             = force_operand (gen_rtx_MINUS (compute_mode,
4198                                                             t2, t3),
4199                                              tquotient);
4200                       }
4201                     else
4202                       {
4203                         rtx t1, t2, t3, t4;
4204
4205                         if (post_shift >= BITS_PER_WORD
4206                             || size - 1 >= BITS_PER_WORD)
4207                           goto fail1;
4208
4209                         ml |= (~(unsigned HOST_WIDE_INT) 0) << (size - 1);
4210                         mlr = gen_int_mode (ml, compute_mode);
4211                         extra_cost = (shift_cost[compute_mode][post_shift]
4212                                       + shift_cost[compute_mode][size - 1]
4213                                       + 2 * add_cost[compute_mode]);
4214                         t1 = expand_mult_highpart (compute_mode, op0, mlr,
4215                                                    NULL_RTX, 0,
4216                                                    max_cost - extra_cost);
4217                         if (t1 == 0)
4218                           goto fail1;
4219                         t2 = force_operand (gen_rtx_PLUS (compute_mode,
4220                                                           t1, op0),
4221                                             NULL_RTX);
4222                         t3 = expand_shift
4223                           (RSHIFT_EXPR, compute_mode, t2,
4224                            build_int_cst (NULL_TREE, post_shift),
4225                            NULL_RTX, 0);
4226                         t4 = expand_shift
4227                           (RSHIFT_EXPR, compute_mode, op0,
4228                            build_int_cst (NULL_TREE, size - 1),
4229                            NULL_RTX, 0);
4230                         if (d < 0)
4231                           quotient
4232                             = force_operand (gen_rtx_MINUS (compute_mode,
4233                                                             t4, t3),
4234                                              tquotient);
4235                         else
4236                           quotient
4237                             = force_operand (gen_rtx_MINUS (compute_mode,
4238                                                             t3, t4),
4239                                              tquotient);
4240                       }
4241                   }
4242                 else            /* Too wide mode to use tricky code */
4243                   break;
4244
4245                 insn = get_last_insn ();
4246                 if (insn != last
4247                     && (set = single_set (insn)) != 0
4248                     && SET_DEST (set) == quotient)
4249                   set_unique_reg_note (insn,
4250                                        REG_EQUAL,
4251                                        gen_rtx_DIV (compute_mode, op0, op1));
4252               }
4253             break;
4254           }
4255       fail1:
4256         delete_insns_since (last);
4257         break;
4258
4259       case FLOOR_DIV_EXPR:
4260       case FLOOR_MOD_EXPR:
4261       /* We will come here only for signed operations.  */
4262         if (op1_is_constant && HOST_BITS_PER_WIDE_INT >= size)
4263           {
4264             unsigned HOST_WIDE_INT mh;
4265             int pre_shift, lgup, post_shift;
4266             HOST_WIDE_INT d = INTVAL (op1);
4267             rtx ml;
4268
4269             if (d > 0)
4270               {
4271                 /* We could just as easily deal with negative constants here,
4272                    but it does not seem worth the trouble for GCC 2.6.  */
4273                 if (EXACT_POWER_OF_2_OR_ZERO_P (d))
4274                   {
4275                     pre_shift = floor_log2 (d);
4276                     if (rem_flag)
4277                       {
4278                         remainder = expand_binop (compute_mode, and_optab, op0,
4279                                                   GEN_INT (((HOST_WIDE_INT) 1 << pre_shift) - 1),
4280                                                   remainder, 0, OPTAB_LIB_WIDEN);
4281                         if (remainder)
4282                           return gen_lowpart (mode, remainder);
4283                       }
4284                     quotient = expand_shift
4285                       (RSHIFT_EXPR, compute_mode, op0,
4286                        build_int_cst (NULL_TREE, pre_shift),
4287                        tquotient, 0);
4288                   }
4289                 else
4290                   {
4291                     rtx t1, t2, t3, t4;
4292
4293                     mh = choose_multiplier (d, size, size - 1,
4294                                             &ml, &post_shift, &lgup);
4295                     gcc_assert (!mh);
4296
4297                     if (post_shift < BITS_PER_WORD
4298                         && size - 1 < BITS_PER_WORD)
4299                       {
4300                         t1 = expand_shift
4301                           (RSHIFT_EXPR, compute_mode, op0,
4302                            build_int_cst (NULL_TREE, size - 1),
4303                            NULL_RTX, 0);
4304                         t2 = expand_binop (compute_mode, xor_optab, op0, t1,
4305                                            NULL_RTX, 0, OPTAB_WIDEN);
4306                         extra_cost = (shift_cost[compute_mode][post_shift]
4307                                       + shift_cost[compute_mode][size - 1]
4308                                       + 2 * add_cost[compute_mode]);
4309                         t3 = expand_mult_highpart (compute_mode, t2, ml,
4310                                                    NULL_RTX, 1,
4311                                                    max_cost - extra_cost);
4312                         if (t3 != 0)
4313                           {
4314                             t4 = expand_shift
4315                               (RSHIFT_EXPR, compute_mode, t3,
4316                                build_int_cst (NULL_TREE, post_shift),
4317                                NULL_RTX, 1);
4318                             quotient = expand_binop (compute_mode, xor_optab,
4319                                                      t4, t1, tquotient, 0,
4320                                                      OPTAB_WIDEN);
4321                           }
4322                       }
4323                   }
4324               }
4325             else
4326               {
4327                 rtx nsign, t1, t2, t3, t4;
4328                 t1 = force_operand (gen_rtx_PLUS (compute_mode,
4329                                                   op0, constm1_rtx), NULL_RTX);
4330                 t2 = expand_binop (compute_mode, ior_optab, op0, t1, NULL_RTX,
4331                                    0, OPTAB_WIDEN);
4332                 nsign = expand_shift
4333                   (RSHIFT_EXPR, compute_mode, t2,
4334                    build_int_cst (NULL_TREE, size - 1),
4335                    NULL_RTX, 0);
4336                 t3 = force_operand (gen_rtx_MINUS (compute_mode, t1, nsign),
4337                                     NULL_RTX);
4338                 t4 = expand_divmod (0, TRUNC_DIV_EXPR, compute_mode, t3, op1,
4339                                     NULL_RTX, 0);
4340                 if (t4)
4341                   {
4342                     rtx t5;
4343                     t5 = expand_unop (compute_mode, one_cmpl_optab, nsign,
4344                                       NULL_RTX, 0);
4345                     quotient = force_operand (gen_rtx_PLUS (compute_mode,
4346                                                             t4, t5),
4347                                               tquotient);
4348                   }
4349               }
4350           }
4351
4352         if (quotient != 0)
4353           break;
4354         delete_insns_since (last);
4355
4356         /* Try using an instruction that produces both the quotient and
4357            remainder, using truncation.  We can easily compensate the quotient
4358            or remainder to get floor rounding, once we have the remainder.
4359            Notice that we compute also the final remainder value here,
4360            and return the result right away.  */
4361         if (target == 0 || GET_MODE (target) != compute_mode)
4362           target = gen_reg_rtx (compute_mode);
4363
4364         if (rem_flag)
4365           {
4366             remainder
4367               = REG_P (target) ? target : gen_reg_rtx (compute_mode);
4368             quotient = gen_reg_rtx (compute_mode);
4369           }
4370         else
4371           {
4372             quotient
4373               = REG_P (target) ? target : gen_reg_rtx (compute_mode);
4374             remainder = gen_reg_rtx (compute_mode);
4375           }
4376
4377         if (expand_twoval_binop (sdivmod_optab, op0, op1,
4378                                  quotient, remainder, 0))
4379           {
4380             /* This could be computed with a branch-less sequence.
4381                Save that for later.  */
4382             rtx tem;
4383             rtx label = gen_label_rtx ();
4384             do_cmp_and_jump (remainder, const0_rtx, EQ, compute_mode, label);
4385             tem = expand_binop (compute_mode, xor_optab, op0, op1,
4386                                 NULL_RTX, 0, OPTAB_WIDEN);
4387             do_cmp_and_jump (tem, const0_rtx, GE, compute_mode, label);
4388             expand_dec (quotient, const1_rtx);
4389             expand_inc (remainder, op1);
4390             emit_label (label);
4391             return gen_lowpart (mode, rem_flag ? remainder : quotient);
4392           }
4393
4394         /* No luck with division elimination or divmod.  Have to do it
4395            by conditionally adjusting op0 *and* the result.  */
4396         {
4397           rtx label1, label2, label3, label4, label5;
4398           rtx adjusted_op0;
4399           rtx tem;
4400
4401           quotient = gen_reg_rtx (compute_mode);
4402           adjusted_op0 = copy_to_mode_reg (compute_mode, op0);
4403           label1 = gen_label_rtx ();
4404           label2 = gen_label_rtx ();
4405           label3 = gen_label_rtx ();
4406           label4 = gen_label_rtx ();
4407           label5 = gen_label_rtx ();
4408           do_cmp_and_jump (op1, const0_rtx, LT, compute_mode, label2);
4409           do_cmp_and_jump (adjusted_op0, const0_rtx, LT, compute_mode, label1);
4410           tem = expand_binop (compute_mode, sdiv_optab, adjusted_op0, op1,
4411                               quotient, 0, OPTAB_LIB_WIDEN);
4412           if (tem != quotient)
4413             emit_move_insn (quotient, tem);
4414           emit_jump_insn (gen_jump (label5));
4415           emit_barrier ();
4416           emit_label (label1);
4417           expand_inc (adjusted_op0, const1_rtx);
4418           emit_jump_insn (gen_jump (label4));
4419           emit_barrier ();
4420           emit_label (label2);
4421           do_cmp_and_jump (adjusted_op0, const0_rtx, GT, compute_mode, label3);
4422           tem = expand_binop (compute_mode, sdiv_optab, adjusted_op0, op1,
4423                               quotient, 0, OPTAB_LIB_WIDEN);
4424           if (tem != quotient)
4425             emit_move_insn (quotient, tem);
4426           emit_jump_insn (gen_jump (label5));
4427           emit_barrier ();
4428           emit_label (label3);
4429           expand_dec (adjusted_op0, const1_rtx);
4430           emit_label (label4);
4431           tem = expand_binop (compute_mode, sdiv_optab, adjusted_op0, op1,
4432                               quotient, 0, OPTAB_LIB_WIDEN);
4433           if (tem != quotient)
4434             emit_move_insn (quotient, tem);
4435           expand_dec (quotient, const1_rtx);
4436           emit_label (label5);
4437         }
4438         break;
4439
4440       case CEIL_DIV_EXPR:
4441       case CEIL_MOD_EXPR:
4442         if (unsignedp)
4443           {
4444             if (op1_is_constant && EXACT_POWER_OF_2_OR_ZERO_P (INTVAL (op1)))
4445               {
4446                 rtx t1, t2, t3;
4447                 unsigned HOST_WIDE_INT d = INTVAL (op1);
4448                 t1 = expand_shift (RSHIFT_EXPR, compute_mode, op0,
4449                                    build_int_cst (NULL_TREE, floor_log2 (d)),
4450                                    tquotient, 1);
4451                 t2 = expand_binop (compute_mode, and_optab, op0,
4452                                    GEN_INT (d - 1),
4453                                    NULL_RTX, 1, OPTAB_LIB_WIDEN);
4454                 t3 = gen_reg_rtx (compute_mode);
4455                 t3 = emit_store_flag (t3, NE, t2, const0_rtx,
4456                                       compute_mode, 1, 1);
4457                 if (t3 == 0)
4458                   {
4459                     rtx lab;
4460                     lab = gen_label_rtx ();
4461                     do_cmp_and_jump (t2, const0_rtx, EQ, compute_mode, lab);
4462                     expand_inc (t1, const1_rtx);
4463                     emit_label (lab);
4464                     quotient = t1;
4465                   }
4466                 else
4467                   quotient = force_operand (gen_rtx_PLUS (compute_mode,
4468                                                           t1, t3),
4469                                             tquotient);
4470                 break;
4471               }
4472
4473             /* Try using an instruction that produces both the quotient and
4474                remainder, using truncation.  We can easily compensate the
4475                quotient or remainder to get ceiling rounding, once we have the
4476                remainder.  Notice that we compute also the final remainder
4477                value here, and return the result right away.  */
4478             if (target == 0 || GET_MODE (target) != compute_mode)
4479               target = gen_reg_rtx (compute_mode);
4480
4481             if (rem_flag)
4482               {
4483                 remainder = (REG_P (target)
4484                              ? target : gen_reg_rtx (compute_mode));
4485                 quotient = gen_reg_rtx (compute_mode);
4486               }
4487             else
4488               {
4489                 quotient = (REG_P (target)
4490                             ? target : gen_reg_rtx (compute_mode));
4491                 remainder = gen_reg_rtx (compute_mode);
4492               }
4493
4494             if (expand_twoval_binop (udivmod_optab, op0, op1, quotient,
4495                                      remainder, 1))
4496               {
4497                 /* This could be computed with a branch-less sequence.
4498                    Save that for later.  */
4499                 rtx label = gen_label_rtx ();
4500                 do_cmp_and_jump (remainder, const0_rtx, EQ,
4501                                  compute_mode, label);
4502                 expand_inc (quotient, const1_rtx);
4503                 expand_dec (remainder, op1);
4504                 emit_label (label);
4505                 return gen_lowpart (mode, rem_flag ? remainder : quotient);
4506               }
4507
4508             /* No luck with division elimination or divmod.  Have to do it
4509                by conditionally adjusting op0 *and* the result.  */
4510             {
4511               rtx label1, label2;
4512               rtx adjusted_op0, tem;
4513
4514               quotient = gen_reg_rtx (compute_mode);
4515               adjusted_op0 = copy_to_mode_reg (compute_mode, op0);
4516               label1 = gen_label_rtx ();
4517               label2 = gen_label_rtx ();
4518               do_cmp_and_jump (adjusted_op0, const0_rtx, NE,
4519                                compute_mode, label1);
4520               emit_move_insn  (quotient, const0_rtx);
4521               emit_jump_insn (gen_jump (label2));
4522               emit_barrier ();
4523               emit_label (label1);
4524               expand_dec (adjusted_op0, const1_rtx);
4525               tem = expand_binop (compute_mode, udiv_optab, adjusted_op0, op1,
4526                                   quotient, 1, OPTAB_LIB_WIDEN);
4527               if (tem != quotient)
4528                 emit_move_insn (quotient, tem);
4529               expand_inc (quotient, const1_rtx);
4530               emit_label (label2);
4531             }
4532           }
4533         else /* signed */
4534           {
4535             if (op1_is_constant && EXACT_POWER_OF_2_OR_ZERO_P (INTVAL (op1))
4536                 && INTVAL (op1) >= 0)
4537               {
4538                 /* This is extremely similar to the code for the unsigned case
4539                    above.  For 2.7 we should merge these variants, but for
4540                    2.6.1 I don't want to touch the code for unsigned since that
4541                    get used in C.  The signed case will only be used by other
4542                    languages (Ada).  */
4543
4544                 rtx t1, t2, t3;
4545                 unsigned HOST_WIDE_INT d = INTVAL (op1);
4546                 t1 = expand_shift (RSHIFT_EXPR, compute_mode, op0,
4547                                    build_int_cst (NULL_TREE, floor_log2 (d)),
4548                                    tquotient, 0);
4549                 t2 = expand_binop (compute_mode, and_optab, op0,
4550                                    GEN_INT (d - 1),
4551                                    NULL_RTX, 1, OPTAB_LIB_WIDEN);
4552                 t3 = gen_reg_rtx (compute_mode);
4553                 t3 = emit_store_flag (t3, NE, t2, const0_rtx,
4554                                       compute_mode, 1, 1);
4555                 if (t3 == 0)
4556                   {
4557                     rtx lab;
4558                     lab = gen_label_rtx ();
4559                     do_cmp_and_jump (t2, const0_rtx, EQ, compute_mode, lab);
4560                     expand_inc (t1, const1_rtx);
4561                     emit_label (lab);
4562                     quotient = t1;
4563                   }
4564                 else
4565                   quotient = force_operand (gen_rtx_PLUS (compute_mode,
4566                                                           t1, t3),
4567                                             tquotient);
4568                 break;
4569               }
4570
4571             /* Try using an instruction that produces both the quotient and
4572                remainder, using truncation.  We can easily compensate the
4573                quotient or remainder to get ceiling rounding, once we have the
4574                remainder.  Notice that we compute also the final remainder
4575                value here, and return the result right away.  */
4576             if (target == 0 || GET_MODE (target) != compute_mode)
4577               target = gen_reg_rtx (compute_mode);
4578             if (rem_flag)
4579               {
4580                 remainder= (REG_P (target)
4581                             ? target : gen_reg_rtx (compute_mode));
4582                 quotient = gen_reg_rtx (compute_mode);
4583               }
4584             else
4585               {
4586                 quotient = (REG_P (target)
4587                             ? target : gen_reg_rtx (compute_mode));
4588                 remainder = gen_reg_rtx (compute_mode);
4589               }
4590
4591             if (expand_twoval_binop (sdivmod_optab, op0, op1, quotient,
4592                                      remainder, 0))
4593               {
4594                 /* This could be computed with a branch-less sequence.
4595                    Save that for later.  */
4596                 rtx tem;
4597                 rtx label = gen_label_rtx ();
4598                 do_cmp_and_jump (remainder, const0_rtx, EQ,
4599                                  compute_mode, label);
4600                 tem = expand_binop (compute_mode, xor_optab, op0, op1,
4601                                     NULL_RTX, 0, OPTAB_WIDEN);
4602                 do_cmp_and_jump (tem, const0_rtx, LT, compute_mode, label);
4603                 expand_inc (quotient, const1_rtx);
4604                 expand_dec (remainder, op1);
4605                 emit_label (label);
4606                 return gen_lowpart (mode, rem_flag ? remainder : quotient);
4607               }
4608
4609             /* No luck with division elimination or divmod.  Have to do it
4610                by conditionally adjusting op0 *and* the result.  */
4611             {
4612               rtx label1, label2, label3, label4, label5;
4613               rtx adjusted_op0;
4614               rtx tem;
4615
4616               quotient = gen_reg_rtx (compute_mode);
4617               adjusted_op0 = copy_to_mode_reg (compute_mode, op0);
4618               label1 = gen_label_rtx ();
4619               label2 = gen_label_rtx ();
4620               label3 = gen_label_rtx ();
4621               label4 = gen_label_rtx ();
4622               label5 = gen_label_rtx ();
4623               do_cmp_and_jump (op1, const0_rtx, LT, compute_mode, label2);
4624               do_cmp_and_jump (adjusted_op0, const0_rtx, GT,
4625                                compute_mode, label1);
4626               tem = expand_binop (compute_mode, sdiv_optab, adjusted_op0, op1,
4627                                   quotient, 0, OPTAB_LIB_WIDEN);
4628               if (tem != quotient)
4629                 emit_move_insn (quotient, tem);
4630               emit_jump_insn (gen_jump (label5));
4631               emit_barrier ();
4632               emit_label (label1);
4633               expand_dec (adjusted_op0, const1_rtx);
4634               emit_jump_insn (gen_jump (label4));
4635               emit_barrier ();
4636               emit_label (label2);
4637               do_cmp_and_jump (adjusted_op0, const0_rtx, LT,
4638                                compute_mode, label3);
4639               tem = expand_binop (compute_mode, sdiv_optab, adjusted_op0, op1,
4640                                   quotient, 0, OPTAB_LIB_WIDEN);
4641               if (tem != quotient)
4642                 emit_move_insn (quotient, tem);
4643               emit_jump_insn (gen_jump (label5));
4644               emit_barrier ();
4645               emit_label (label3);
4646               expand_inc (adjusted_op0, const1_rtx);
4647               emit_label (label4);
4648               tem = expand_binop (compute_mode, sdiv_optab, adjusted_op0, op1,
4649                                   quotient, 0, OPTAB_LIB_WIDEN);
4650               if (tem != quotient)
4651                 emit_move_insn (quotient, tem);
4652               expand_inc (quotient, const1_rtx);
4653               emit_label (label5);
4654             }
4655           }
4656         break;
4657
4658       case EXACT_DIV_EXPR:
4659         if (op1_is_constant && HOST_BITS_PER_WIDE_INT >= size)
4660           {
4661             HOST_WIDE_INT d = INTVAL (op1);
4662             unsigned HOST_WIDE_INT ml;
4663             int pre_shift;
4664             rtx t1;
4665
4666             pre_shift = floor_log2 (d & -d);
4667             ml = invert_mod2n (d >> pre_shift, size);
4668             t1 = expand_shift (RSHIFT_EXPR, compute_mode, op0,
4669                                build_int_cst (NULL_TREE, pre_shift),
4670                                NULL_RTX, unsignedp);
4671             quotient = expand_mult (compute_mode, t1,
4672                                     gen_int_mode (ml, compute_mode),
4673                                     NULL_RTX, 1);
4674
4675             insn = get_last_insn ();
4676             set_unique_reg_note (insn,
4677                                  REG_EQUAL,
4678                                  gen_rtx_fmt_ee (unsignedp ? UDIV : DIV,
4679                                                  compute_mode,
4680                                                  op0, op1));
4681           }
4682         break;
4683
4684       case ROUND_DIV_EXPR:
4685       case ROUND_MOD_EXPR:
4686         if (unsignedp)
4687           {
4688             rtx tem;
4689             rtx label;
4690             label = gen_label_rtx ();
4691             quotient = gen_reg_rtx (compute_mode);
4692             remainder = gen_reg_rtx (compute_mode);
4693             if (expand_twoval_binop (udivmod_optab, op0, op1, quotient, remainder, 1) == 0)
4694               {
4695                 rtx tem;
4696                 quotient = expand_binop (compute_mode, udiv_optab, op0, op1,
4697                                          quotient, 1, OPTAB_LIB_WIDEN);
4698                 tem = expand_mult (compute_mode, quotient, op1, NULL_RTX, 1);
4699                 remainder = expand_binop (compute_mode, sub_optab, op0, tem,
4700                                           remainder, 1, OPTAB_LIB_WIDEN);
4701               }
4702             tem = plus_constant (op1, -1);
4703             tem = expand_shift (RSHIFT_EXPR, compute_mode, tem,
4704                                 build_int_cst (NULL_TREE, 1),
4705                                 NULL_RTX, 1);
4706             do_cmp_and_jump (remainder, tem, LEU, compute_mode, label);
4707             expand_inc (quotient, const1_rtx);
4708             expand_dec (remainder, op1);
4709             emit_label (label);
4710           }
4711         else
4712           {
4713             rtx abs_rem, abs_op1, tem, mask;
4714             rtx label;
4715             label = gen_label_rtx ();
4716             quotient = gen_reg_rtx (compute_mode);
4717             remainder = gen_reg_rtx (compute_mode);
4718             if (expand_twoval_binop (sdivmod_optab, op0, op1, quotient, remainder, 0) == 0)
4719               {
4720                 rtx tem;
4721                 quotient = expand_binop (compute_mode, sdiv_optab, op0, op1,
4722                                          quotient, 0, OPTAB_LIB_WIDEN);
4723                 tem = expand_mult (compute_mode, quotient, op1, NULL_RTX, 0);
4724                 remainder = expand_binop (compute_mode, sub_optab, op0, tem,
4725                                           remainder, 0, OPTAB_LIB_WIDEN);
4726               }
4727             abs_rem = expand_abs (compute_mode, remainder, NULL_RTX, 1, 0);
4728             abs_op1 = expand_abs (compute_mode, op1, NULL_RTX, 1, 0);
4729             tem = expand_shift (LSHIFT_EXPR, compute_mode, abs_rem,
4730                                 build_int_cst (NULL_TREE, 1),
4731                                 NULL_RTX, 1);
4732             do_cmp_and_jump (tem, abs_op1, LTU, compute_mode, label);
4733             tem = expand_binop (compute_mode, xor_optab, op0, op1,
4734                                 NULL_RTX, 0, OPTAB_WIDEN);
4735             mask = expand_shift (RSHIFT_EXPR, compute_mode, tem,
4736                                  build_int_cst (NULL_TREE, size - 1),
4737                                  NULL_RTX, 0);
4738             tem = expand_binop (compute_mode, xor_optab, mask, const1_rtx,
4739                                 NULL_RTX, 0, OPTAB_WIDEN);
4740             tem = expand_binop (compute_mode, sub_optab, tem, mask,
4741                                 NULL_RTX, 0, OPTAB_WIDEN);
4742             expand_inc (quotient, tem);
4743             tem = expand_binop (compute_mode, xor_optab, mask, op1,
4744                                 NULL_RTX, 0, OPTAB_WIDEN);
4745             tem = expand_binop (compute_mode, sub_optab, tem, mask,
4746                                 NULL_RTX, 0, OPTAB_WIDEN);
4747             expand_dec (remainder, tem);
4748             emit_label (label);
4749           }
4750         return gen_lowpart (mode, rem_flag ? remainder : quotient);
4751
4752       default:
4753         gcc_unreachable ();
4754       }
4755
4756   if (quotient == 0)
4757     {
4758       if (target && GET_MODE (target) != compute_mode)
4759         target = 0;
4760
4761       if (rem_flag)
4762         {
4763           /* Try to produce the remainder without producing the quotient.
4764              If we seem to have a divmod pattern that does not require widening,
4765              don't try widening here.  We should really have a WIDEN argument
4766              to expand_twoval_binop, since what we'd really like to do here is
4767              1) try a mod insn in compute_mode
4768              2) try a divmod insn in compute_mode
4769              3) try a div insn in compute_mode and multiply-subtract to get
4770                 remainder
4771              4) try the same things with widening allowed.  */
4772           remainder
4773             = sign_expand_binop (compute_mode, umod_optab, smod_optab,
4774                                  op0, op1, target,
4775                                  unsignedp,
4776                                  ((optab2->handlers[compute_mode].insn_code
4777                                    != CODE_FOR_nothing)
4778                                   ? OPTAB_DIRECT : OPTAB_WIDEN));
4779           if (remainder == 0)
4780             {
4781               /* No luck there.  Can we do remainder and divide at once
4782                  without a library call?  */
4783               remainder = gen_reg_rtx (compute_mode);
4784               if (! expand_twoval_binop ((unsignedp
4785                                           ? udivmod_optab
4786                                           : sdivmod_optab),
4787                                          op0, op1,
4788                                          NULL_RTX, remainder, unsignedp))
4789                 remainder = 0;
4790             }
4791
4792           if (remainder)
4793             return gen_lowpart (mode, remainder);
4794         }
4795
4796       /* Produce the quotient.  Try a quotient insn, but not a library call.
4797          If we have a divmod in this mode, use it in preference to widening
4798          the div (for this test we assume it will not fail). Note that optab2
4799          is set to the one of the two optabs that the call below will use.  */
4800       quotient
4801         = sign_expand_binop (compute_mode, udiv_optab, sdiv_optab,
4802                              op0, op1, rem_flag ? NULL_RTX : target,
4803                              unsignedp,
4804                              ((optab2->handlers[compute_mode].insn_code
4805                                != CODE_FOR_nothing)
4806                               ? OPTAB_DIRECT : OPTAB_WIDEN));
4807
4808       if (quotient == 0)
4809         {
4810           /* No luck there.  Try a quotient-and-remainder insn,
4811              keeping the quotient alone.  */
4812           quotient = gen_reg_rtx (compute_mode);
4813           if (! expand_twoval_binop (unsignedp ? udivmod_optab : sdivmod_optab,
4814                                      op0, op1,
4815                                      quotient, NULL_RTX, unsignedp))
4816             {
4817               quotient = 0;
4818               if (! rem_flag)
4819                 /* Still no luck.  If we are not computing the remainder,
4820                    use a library call for the quotient.  */
4821                 quotient = sign_expand_binop (compute_mode,
4822                                               udiv_optab, sdiv_optab,
4823                                               op0, op1, target,
4824                                               unsignedp, OPTAB_LIB_WIDEN);
4825             }
4826         }
4827     }
4828
4829   if (rem_flag)
4830     {
4831       if (target && GET_MODE (target) != compute_mode)
4832         target = 0;
4833
4834       if (quotient == 0)
4835         {
4836           /* No divide instruction either.  Use library for remainder.  */
4837           remainder = sign_expand_binop (compute_mode, umod_optab, smod_optab,
4838                                          op0, op1, target,
4839                                          unsignedp, OPTAB_LIB_WIDEN);
4840           /* No remainder function.  Try a quotient-and-remainder
4841              function, keeping the remainder.  */
4842           if (!remainder)
4843             {
4844               remainder = gen_reg_rtx (compute_mode);
4845               if (!expand_twoval_binop_libfunc 
4846                   (unsignedp ? udivmod_optab : sdivmod_optab,
4847                    op0, op1,
4848                    NULL_RTX, remainder,
4849                    unsignedp ? UMOD : MOD))
4850                 remainder = NULL_RTX;
4851             }
4852         }
4853       else
4854         {
4855           /* We divided.  Now finish doing X - Y * (X / Y).  */
4856           remainder = expand_mult (compute_mode, quotient, op1,
4857                                    NULL_RTX, unsignedp);
4858           remainder = expand_binop (compute_mode, sub_optab, op0,
4859                                     remainder, target, unsignedp,
4860                                     OPTAB_LIB_WIDEN);
4861         }
4862     }
4863
4864   return gen_lowpart (mode, rem_flag ? remainder : quotient);
4865 }
4866 \f
4867 /* Return a tree node with data type TYPE, describing the value of X.
4868    Usually this is an VAR_DECL, if there is no obvious better choice.
4869    X may be an expression, however we only support those expressions
4870    generated by loop.c.  */
4871
4872 tree
4873 make_tree (tree type, rtx x)
4874 {
4875   tree t;
4876
4877   switch (GET_CODE (x))
4878     {
4879     case CONST_INT:
4880       {
4881         HOST_WIDE_INT hi = 0;
4882
4883         if (INTVAL (x) < 0
4884             && !(TYPE_UNSIGNED (type)
4885                  && (GET_MODE_BITSIZE (TYPE_MODE (type))
4886                      < HOST_BITS_PER_WIDE_INT)))
4887           hi = -1;
4888       
4889         t = build_int_cst_wide (type, INTVAL (x), hi);
4890         
4891         return t;
4892       }
4893       
4894     case CONST_DOUBLE:
4895       if (GET_MODE (x) == VOIDmode)
4896         t = build_int_cst_wide (type,
4897                                 CONST_DOUBLE_LOW (x), CONST_DOUBLE_HIGH (x));
4898       else
4899         {
4900           REAL_VALUE_TYPE d;
4901
4902           REAL_VALUE_FROM_CONST_DOUBLE (d, x);
4903           t = build_real (type, d);
4904         }
4905
4906       return t;
4907
4908     case CONST_VECTOR:
4909       {
4910         int i, units;
4911         rtx elt;
4912         tree t = NULL_TREE;
4913
4914         units = CONST_VECTOR_NUNITS (x);
4915
4916         /* Build a tree with vector elements.  */
4917         for (i = units - 1; i >= 0; --i)
4918           {
4919             elt = CONST_VECTOR_ELT (x, i);
4920             t = tree_cons (NULL_TREE, make_tree (type, elt), t);
4921           }
4922
4923         return build_vector (type, t);
4924       }
4925
4926     case PLUS:
4927       return fold_build2 (PLUS_EXPR, type, make_tree (type, XEXP (x, 0)),
4928                           make_tree (type, XEXP (x, 1)));
4929
4930     case MINUS:
4931       return fold_build2 (MINUS_EXPR, type, make_tree (type, XEXP (x, 0)),
4932                           make_tree (type, XEXP (x, 1)));
4933
4934     case NEG:
4935       return fold_build1 (NEGATE_EXPR, type, make_tree (type, XEXP (x, 0)));
4936
4937     case MULT:
4938       return fold_build2 (MULT_EXPR, type, make_tree (type, XEXP (x, 0)),
4939                           make_tree (type, XEXP (x, 1)));
4940
4941     case ASHIFT:
4942       return fold_build2 (LSHIFT_EXPR, type, make_tree (type, XEXP (x, 0)),
4943                           make_tree (type, XEXP (x, 1)));
4944
4945     case LSHIFTRT:
4946       t = lang_hooks.types.unsigned_type (type);
4947       return fold_convert (type, build2 (RSHIFT_EXPR, t,
4948                                          make_tree (t, XEXP (x, 0)),
4949                                          make_tree (type, XEXP (x, 1))));
4950
4951     case ASHIFTRT:
4952       t = lang_hooks.types.signed_type (type);
4953       return fold_convert (type, build2 (RSHIFT_EXPR, t,
4954                                          make_tree (t, XEXP (x, 0)),
4955                                          make_tree (type, XEXP (x, 1))));
4956
4957     case DIV:
4958       if (TREE_CODE (type) != REAL_TYPE)
4959         t = lang_hooks.types.signed_type (type);
4960       else
4961         t = type;
4962
4963       return fold_convert (type, build2 (TRUNC_DIV_EXPR, t,
4964                                          make_tree (t, XEXP (x, 0)),
4965                                          make_tree (t, XEXP (x, 1))));
4966     case UDIV:
4967       t = lang_hooks.types.unsigned_type (type);
4968       return fold_convert (type, build2 (TRUNC_DIV_EXPR, t,
4969                                          make_tree (t, XEXP (x, 0)),
4970                                          make_tree (t, XEXP (x, 1))));
4971
4972     case SIGN_EXTEND:
4973     case ZERO_EXTEND:
4974       t = lang_hooks.types.type_for_mode (GET_MODE (XEXP (x, 0)),
4975                                           GET_CODE (x) == ZERO_EXTEND);
4976       return fold_convert (type, make_tree (t, XEXP (x, 0)));
4977
4978     default:
4979       t = build_decl (VAR_DECL, NULL_TREE, type);
4980
4981       /* If TYPE is a POINTER_TYPE, X might be Pmode with TYPE_MODE being
4982          ptr_mode.  So convert.  */
4983       if (POINTER_TYPE_P (type))
4984         x = convert_memory_address (TYPE_MODE (type), x);
4985
4986       /* Note that we do *not* use SET_DECL_RTL here, because we do not
4987          want set_decl_rtl to go adjusting REG_ATTRS for this temporary.  */
4988       t->decl_with_rtl.rtl = x;
4989
4990       return t;
4991     }
4992 }
4993
4994 /* Check whether the multiplication X * MULT + ADD overflows.
4995    X, MULT and ADD must be CONST_*.
4996    MODE is the machine mode for the computation.
4997    X and MULT must have mode MODE.  ADD may have a different mode.
4998    So can X (defaults to same as MODE).
4999    UNSIGNEDP is nonzero to do unsigned multiplication.  */
5000
5001 bool
5002 const_mult_add_overflow_p (rtx x, rtx mult, rtx add,
5003                            enum machine_mode mode, int unsignedp)
5004 {
5005   tree type, mult_type, add_type, result;
5006
5007   type = lang_hooks.types.type_for_mode (mode, unsignedp);
5008
5009   /* In order to get a proper overflow indication from an unsigned
5010      type, we have to pretend that it's a sizetype.  */
5011   mult_type = type;
5012   if (unsignedp)
5013     {
5014       /* FIXME:It would be nice if we could step directly from this
5015          type to its sizetype equivalent.  */
5016       mult_type = build_distinct_type_copy (type);
5017       TYPE_IS_SIZETYPE (mult_type) = 1;
5018     }
5019
5020   add_type = (GET_MODE (add) == VOIDmode ? mult_type
5021               : lang_hooks.types.type_for_mode (GET_MODE (add), unsignedp));
5022
5023   result = fold_build2 (PLUS_EXPR, mult_type,
5024                         fold_build2 (MULT_EXPR, mult_type,
5025                                      make_tree (mult_type, x),
5026                                      make_tree (mult_type, mult)),
5027                         make_tree (add_type, add));
5028
5029   return TREE_CONSTANT_OVERFLOW (result);
5030 }
5031
5032 /* Return an rtx representing the value of X * MULT + ADD.
5033    TARGET is a suggestion for where to store the result (an rtx).
5034    MODE is the machine mode for the computation.
5035    X and MULT must have mode MODE.  ADD may have a different mode.
5036    So can X (defaults to same as MODE).
5037    UNSIGNEDP is nonzero to do unsigned multiplication.
5038    This may emit insns.  */
5039
5040 rtx
5041 expand_mult_add (rtx x, rtx target, rtx mult, rtx add, enum machine_mode mode,
5042                  int unsignedp)
5043 {
5044   tree type = lang_hooks.types.type_for_mode (mode, unsignedp);
5045   tree add_type = (GET_MODE (add) == VOIDmode
5046                    ? type: lang_hooks.types.type_for_mode (GET_MODE (add),
5047                                                            unsignedp));
5048   tree result = fold_build2 (PLUS_EXPR, type,
5049                              fold_build2 (MULT_EXPR, type,
5050                                           make_tree (type, x),
5051                                           make_tree (type, mult)),
5052                              make_tree (add_type, add));
5053
5054   return expand_expr (result, target, VOIDmode, 0);
5055 }
5056 \f
5057 /* Compute the logical-and of OP0 and OP1, storing it in TARGET
5058    and returning TARGET.
5059
5060    If TARGET is 0, a pseudo-register or constant is returned.  */
5061
5062 rtx
5063 expand_and (enum machine_mode mode, rtx op0, rtx op1, rtx target)
5064 {
5065   rtx tem = 0;
5066
5067   if (GET_MODE (op0) == VOIDmode && GET_MODE (op1) == VOIDmode)
5068     tem = simplify_binary_operation (AND, mode, op0, op1);
5069   if (tem == 0)
5070     tem = expand_binop (mode, and_optab, op0, op1, target, 0, OPTAB_LIB_WIDEN);
5071
5072   if (target == 0)
5073     target = tem;
5074   else if (tem != target)
5075     emit_move_insn (target, tem);
5076   return target;
5077 }
5078 \f
5079 /* Emit a store-flags instruction for comparison CODE on OP0 and OP1
5080    and storing in TARGET.  Normally return TARGET.
5081    Return 0 if that cannot be done.
5082
5083    MODE is the mode to use for OP0 and OP1 should they be CONST_INTs.  If
5084    it is VOIDmode, they cannot both be CONST_INT.
5085
5086    UNSIGNEDP is for the case where we have to widen the operands
5087    to perform the operation.  It says to use zero-extension.
5088
5089    NORMALIZEP is 1 if we should convert the result to be either zero
5090    or one.  Normalize is -1 if we should convert the result to be
5091    either zero or -1.  If NORMALIZEP is zero, the result will be left
5092    "raw" out of the scc insn.  */
5093
5094 rtx
5095 emit_store_flag (rtx target, enum rtx_code code, rtx op0, rtx op1,
5096                  enum machine_mode mode, int unsignedp, int normalizep)
5097 {
5098   rtx subtarget;
5099   enum insn_code icode;
5100   enum machine_mode compare_mode;
5101   enum machine_mode target_mode = GET_MODE (target);
5102   rtx tem;
5103   rtx last = get_last_insn ();
5104   rtx pattern, comparison;
5105
5106   if (unsignedp)
5107     code = unsigned_condition (code);
5108
5109   /* If one operand is constant, make it the second one.  Only do this
5110      if the other operand is not constant as well.  */
5111
5112   if (swap_commutative_operands_p (op0, op1))
5113     {
5114       tem = op0;
5115       op0 = op1;
5116       op1 = tem;
5117       code = swap_condition (code);
5118     }
5119
5120   if (mode == VOIDmode)
5121     mode = GET_MODE (op0);
5122
5123   /* For some comparisons with 1 and -1, we can convert this to
5124      comparisons with zero.  This will often produce more opportunities for
5125      store-flag insns.  */
5126
5127   switch (code)
5128     {
5129     case LT:
5130       if (op1 == const1_rtx)
5131         op1 = const0_rtx, code = LE;
5132       break;
5133     case LE:
5134       if (op1 == constm1_rtx)
5135         op1 = const0_rtx, code = LT;
5136       break;
5137     case GE:
5138       if (op1 == const1_rtx)
5139         op1 = const0_rtx, code = GT;
5140       break;
5141     case GT:
5142       if (op1 == constm1_rtx)
5143         op1 = const0_rtx, code = GE;
5144       break;
5145     case GEU:
5146       if (op1 == const1_rtx)
5147         op1 = const0_rtx, code = NE;
5148       break;
5149     case LTU:
5150       if (op1 == const1_rtx)
5151         op1 = const0_rtx, code = EQ;
5152       break;
5153     default:
5154       break;
5155     }
5156
5157   /* If we are comparing a double-word integer with zero or -1, we can
5158      convert the comparison into one involving a single word.  */
5159   if (GET_MODE_BITSIZE (mode) == BITS_PER_WORD * 2
5160       && GET_MODE_CLASS (mode) == MODE_INT
5161       && (!MEM_P (op0) || ! MEM_VOLATILE_P (op0)))
5162     {
5163       if ((code == EQ || code == NE)
5164           && (op1 == const0_rtx || op1 == constm1_rtx))
5165         {
5166           rtx op00, op01, op0both;
5167
5168           /* Do a logical OR or AND of the two words and compare the result.  */
5169           op00 = simplify_gen_subreg (word_mode, op0, mode, 0);
5170           op01 = simplify_gen_subreg (word_mode, op0, mode, UNITS_PER_WORD);
5171           op0both = expand_binop (word_mode,
5172                                   op1 == const0_rtx ? ior_optab : and_optab,
5173                                   op00, op01, NULL_RTX, unsignedp, OPTAB_DIRECT);
5174
5175           if (op0both != 0)
5176             return emit_store_flag (target, code, op0both, op1, word_mode,
5177                                     unsignedp, normalizep);
5178         }
5179       else if ((code == LT || code == GE) && op1 == const0_rtx)
5180         {
5181           rtx op0h;
5182
5183           /* If testing the sign bit, can just test on high word.  */
5184           op0h = simplify_gen_subreg (word_mode, op0, mode,
5185                                       subreg_highpart_offset (word_mode, mode));
5186           return emit_store_flag (target, code, op0h, op1, word_mode,
5187                                   unsignedp, normalizep);
5188         }
5189     }
5190
5191   /* From now on, we won't change CODE, so set ICODE now.  */
5192   icode = setcc_gen_code[(int) code];
5193
5194   /* If this is A < 0 or A >= 0, we can do this by taking the ones
5195      complement of A (for GE) and shifting the sign bit to the low bit.  */
5196   if (op1 == const0_rtx && (code == LT || code == GE)
5197       && GET_MODE_CLASS (mode) == MODE_INT
5198       && (normalizep || STORE_FLAG_VALUE == 1
5199           || (GET_MODE_BITSIZE (mode) <= HOST_BITS_PER_WIDE_INT
5200               && ((STORE_FLAG_VALUE & GET_MODE_MASK (mode))
5201                   == (unsigned HOST_WIDE_INT) 1 << (GET_MODE_BITSIZE (mode) - 1)))))
5202     {
5203       subtarget = target;
5204
5205       /* If the result is to be wider than OP0, it is best to convert it
5206          first.  If it is to be narrower, it is *incorrect* to convert it
5207          first.  */
5208       if (GET_MODE_SIZE (target_mode) > GET_MODE_SIZE (mode))
5209         {
5210           op0 = convert_modes (target_mode, mode, op0, 0);
5211           mode = target_mode;
5212         }
5213
5214       if (target_mode != mode)
5215         subtarget = 0;
5216
5217       if (code == GE)
5218         op0 = expand_unop (mode, one_cmpl_optab, op0,
5219                            ((STORE_FLAG_VALUE == 1 || normalizep)
5220                             ? 0 : subtarget), 0);
5221
5222       if (STORE_FLAG_VALUE == 1 || normalizep)
5223         /* If we are supposed to produce a 0/1 value, we want to do
5224            a logical shift from the sign bit to the low-order bit; for
5225            a -1/0 value, we do an arithmetic shift.  */
5226         op0 = expand_shift (RSHIFT_EXPR, mode, op0,
5227                             size_int (GET_MODE_BITSIZE (mode) - 1),
5228                             subtarget, normalizep != -1);
5229
5230       if (mode != target_mode)
5231         op0 = convert_modes (target_mode, mode, op0, 0);
5232
5233       return op0;
5234     }
5235
5236   if (icode != CODE_FOR_nothing)
5237     {
5238       insn_operand_predicate_fn pred;
5239
5240       /* We think we may be able to do this with a scc insn.  Emit the
5241          comparison and then the scc insn.  */
5242
5243       do_pending_stack_adjust ();
5244       last = get_last_insn ();
5245
5246       comparison
5247         = compare_from_rtx (op0, op1, code, unsignedp, mode, NULL_RTX);
5248       if (CONSTANT_P (comparison))
5249         {
5250           switch (GET_CODE (comparison))
5251             {
5252             case CONST_INT:
5253               if (comparison == const0_rtx)
5254                 return const0_rtx;
5255               break;
5256               
5257 #ifdef FLOAT_STORE_FLAG_VALUE
5258             case CONST_DOUBLE:
5259               if (comparison == CONST0_RTX (GET_MODE (comparison)))
5260                 return const0_rtx;
5261               break;
5262 #endif
5263             default:
5264               gcc_unreachable ();
5265             }
5266           
5267           if (normalizep == 1)
5268             return const1_rtx;
5269           if (normalizep == -1)
5270             return constm1_rtx;
5271           return const_true_rtx;
5272         }
5273
5274       /* The code of COMPARISON may not match CODE if compare_from_rtx
5275          decided to swap its operands and reverse the original code.
5276
5277          We know that compare_from_rtx returns either a CONST_INT or
5278          a new comparison code, so it is safe to just extract the
5279          code from COMPARISON.  */
5280       code = GET_CODE (comparison);
5281
5282       /* Get a reference to the target in the proper mode for this insn.  */
5283       compare_mode = insn_data[(int) icode].operand[0].mode;
5284       subtarget = target;
5285       pred = insn_data[(int) icode].operand[0].predicate;
5286       if (optimize || ! (*pred) (subtarget, compare_mode))
5287         subtarget = gen_reg_rtx (compare_mode);
5288
5289       pattern = GEN_FCN (icode) (subtarget);
5290       if (pattern)
5291         {
5292           emit_insn (pattern);
5293
5294           /* If we are converting to a wider mode, first convert to
5295              TARGET_MODE, then normalize.  This produces better combining
5296              opportunities on machines that have a SIGN_EXTRACT when we are
5297              testing a single bit.  This mostly benefits the 68k.
5298
5299              If STORE_FLAG_VALUE does not have the sign bit set when
5300              interpreted in COMPARE_MODE, we can do this conversion as
5301              unsigned, which is usually more efficient.  */
5302           if (GET_MODE_SIZE (target_mode) > GET_MODE_SIZE (compare_mode))
5303             {
5304               convert_move (target, subtarget,
5305                             (GET_MODE_BITSIZE (compare_mode)
5306                              <= HOST_BITS_PER_WIDE_INT)
5307                             && 0 == (STORE_FLAG_VALUE
5308                                      & ((HOST_WIDE_INT) 1
5309                                         << (GET_MODE_BITSIZE (compare_mode) -1))));
5310               op0 = target;
5311               compare_mode = target_mode;
5312             }
5313           else
5314             op0 = subtarget;
5315
5316           /* If we want to keep subexpressions around, don't reuse our
5317              last target.  */
5318
5319           if (optimize)
5320             subtarget = 0;
5321
5322           /* Now normalize to the proper value in COMPARE_MODE.  Sometimes
5323              we don't have to do anything.  */
5324           if (normalizep == 0 || normalizep == STORE_FLAG_VALUE)
5325             ;
5326           /* STORE_FLAG_VALUE might be the most negative number, so write
5327              the comparison this way to avoid a compiler-time warning.  */
5328           else if (- normalizep == STORE_FLAG_VALUE)
5329             op0 = expand_unop (compare_mode, neg_optab, op0, subtarget, 0);
5330
5331           /* We don't want to use STORE_FLAG_VALUE < 0 below since this
5332              makes it hard to use a value of just the sign bit due to
5333              ANSI integer constant typing rules.  */
5334           else if (GET_MODE_BITSIZE (compare_mode) <= HOST_BITS_PER_WIDE_INT
5335                    && (STORE_FLAG_VALUE
5336                        & ((HOST_WIDE_INT) 1
5337                           << (GET_MODE_BITSIZE (compare_mode) - 1))))
5338             op0 = expand_shift (RSHIFT_EXPR, compare_mode, op0,
5339                                 size_int (GET_MODE_BITSIZE (compare_mode) - 1),
5340                                 subtarget, normalizep == 1);
5341           else
5342             {
5343               gcc_assert (STORE_FLAG_VALUE & 1);
5344               
5345               op0 = expand_and (compare_mode, op0, const1_rtx, subtarget);
5346               if (normalizep == -1)
5347                 op0 = expand_unop (compare_mode, neg_optab, op0, op0, 0);
5348             }
5349
5350           /* If we were converting to a smaller mode, do the
5351              conversion now.  */
5352           if (target_mode != compare_mode)
5353             {
5354               convert_move (target, op0, 0);
5355               return target;
5356             }
5357           else
5358             return op0;
5359         }
5360     }
5361
5362   delete_insns_since (last);
5363
5364   /* If optimizing, use different pseudo registers for each insn, instead
5365      of reusing the same pseudo.  This leads to better CSE, but slows
5366      down the compiler, since there are more pseudos */
5367   subtarget = (!optimize
5368                && (target_mode == mode)) ? target : NULL_RTX;
5369
5370   /* If we reached here, we can't do this with a scc insn.  However, there
5371      are some comparisons that can be done directly.  For example, if
5372      this is an equality comparison of integers, we can try to exclusive-or
5373      (or subtract) the two operands and use a recursive call to try the
5374      comparison with zero.  Don't do any of these cases if branches are
5375      very cheap.  */
5376
5377   if (BRANCH_COST > 0
5378       && GET_MODE_CLASS (mode) == MODE_INT && (code == EQ || code == NE)
5379       && op1 != const0_rtx)
5380     {
5381       tem = expand_binop (mode, xor_optab, op0, op1, subtarget, 1,
5382                           OPTAB_WIDEN);
5383
5384       if (tem == 0)
5385         tem = expand_binop (mode, sub_optab, op0, op1, subtarget, 1,
5386                             OPTAB_WIDEN);
5387       if (tem != 0)
5388         tem = emit_store_flag (target, code, tem, const0_rtx,
5389                                mode, unsignedp, normalizep);
5390       if (tem == 0)
5391         delete_insns_since (last);
5392       return tem;
5393     }
5394
5395   /* Some other cases we can do are EQ, NE, LE, and GT comparisons with
5396      the constant zero.  Reject all other comparisons at this point.  Only
5397      do LE and GT if branches are expensive since they are expensive on
5398      2-operand machines.  */
5399
5400   if (BRANCH_COST == 0
5401       || GET_MODE_CLASS (mode) != MODE_INT || op1 != const0_rtx
5402       || (code != EQ && code != NE
5403           && (BRANCH_COST <= 1 || (code != LE && code != GT))))
5404     return 0;
5405
5406   /* See what we need to return.  We can only return a 1, -1, or the
5407      sign bit.  */
5408
5409   if (normalizep == 0)
5410     {
5411       if (STORE_FLAG_VALUE == 1 || STORE_FLAG_VALUE == -1)
5412         normalizep = STORE_FLAG_VALUE;
5413
5414       else if (GET_MODE_BITSIZE (mode) <= HOST_BITS_PER_WIDE_INT
5415                && ((STORE_FLAG_VALUE & GET_MODE_MASK (mode))
5416                    == (unsigned HOST_WIDE_INT) 1 << (GET_MODE_BITSIZE (mode) - 1)))
5417         ;
5418       else
5419         return 0;
5420     }
5421
5422   /* Try to put the result of the comparison in the sign bit.  Assume we can't
5423      do the necessary operation below.  */
5424
5425   tem = 0;
5426
5427   /* To see if A <= 0, compute (A | (A - 1)).  A <= 0 iff that result has
5428      the sign bit set.  */
5429
5430   if (code == LE)
5431     {
5432       /* This is destructive, so SUBTARGET can't be OP0.  */
5433       if (rtx_equal_p (subtarget, op0))
5434         subtarget = 0;
5435
5436       tem = expand_binop (mode, sub_optab, op0, const1_rtx, subtarget, 0,
5437                           OPTAB_WIDEN);
5438       if (tem)
5439         tem = expand_binop (mode, ior_optab, op0, tem, subtarget, 0,
5440                             OPTAB_WIDEN);
5441     }
5442
5443   /* To see if A > 0, compute (((signed) A) << BITS) - A, where BITS is the
5444      number of bits in the mode of OP0, minus one.  */
5445
5446   if (code == GT)
5447     {
5448       if (rtx_equal_p (subtarget, op0))
5449         subtarget = 0;
5450
5451       tem = expand_shift (RSHIFT_EXPR, mode, op0,
5452                           size_int (GET_MODE_BITSIZE (mode) - 1),
5453                           subtarget, 0);
5454       tem = expand_binop (mode, sub_optab, tem, op0, subtarget, 0,
5455                           OPTAB_WIDEN);
5456     }
5457
5458   if (code == EQ || code == NE)
5459     {
5460       /* For EQ or NE, one way to do the comparison is to apply an operation
5461          that converts the operand into a positive number if it is nonzero
5462          or zero if it was originally zero.  Then, for EQ, we subtract 1 and
5463          for NE we negate.  This puts the result in the sign bit.  Then we
5464          normalize with a shift, if needed.
5465
5466          Two operations that can do the above actions are ABS and FFS, so try
5467          them.  If that doesn't work, and MODE is smaller than a full word,
5468          we can use zero-extension to the wider mode (an unsigned conversion)
5469          as the operation.  */
5470
5471       /* Note that ABS doesn't yield a positive number for INT_MIN, but
5472          that is compensated by the subsequent overflow when subtracting
5473          one / negating.  */
5474
5475       if (abs_optab->handlers[mode].insn_code != CODE_FOR_nothing)
5476         tem = expand_unop (mode, abs_optab, op0, subtarget, 1);
5477       else if (ffs_optab->handlers[mode].insn_code != CODE_FOR_nothing)
5478         tem = expand_unop (mode, ffs_optab, op0, subtarget, 1);
5479       else if (GET_MODE_SIZE (mode) < UNITS_PER_WORD)
5480         {
5481           tem = convert_modes (word_mode, mode, op0, 1);
5482           mode = word_mode;
5483         }
5484
5485       if (tem != 0)
5486         {
5487           if (code == EQ)
5488             tem = expand_binop (mode, sub_optab, tem, const1_rtx, subtarget,
5489                                 0, OPTAB_WIDEN);
5490           else
5491             tem = expand_unop (mode, neg_optab, tem, subtarget, 0);
5492         }
5493
5494       /* If we couldn't do it that way, for NE we can "or" the two's complement
5495          of the value with itself.  For EQ, we take the one's complement of
5496          that "or", which is an extra insn, so we only handle EQ if branches
5497          are expensive.  */
5498
5499       if (tem == 0 && (code == NE || BRANCH_COST > 1))
5500         {
5501           if (rtx_equal_p (subtarget, op0))
5502             subtarget = 0;
5503
5504           tem = expand_unop (mode, neg_optab, op0, subtarget, 0);
5505           tem = expand_binop (mode, ior_optab, tem, op0, subtarget, 0,
5506                               OPTAB_WIDEN);
5507
5508           if (tem && code == EQ)
5509             tem = expand_unop (mode, one_cmpl_optab, tem, subtarget, 0);
5510         }
5511     }
5512
5513   if (tem && normalizep)
5514     tem = expand_shift (RSHIFT_EXPR, mode, tem,
5515                         size_int (GET_MODE_BITSIZE (mode) - 1),
5516                         subtarget, normalizep == 1);
5517
5518   if (tem)
5519     {
5520       if (GET_MODE (tem) != target_mode)
5521         {
5522           convert_move (target, tem, 0);
5523           tem = target;
5524         }
5525       else if (!subtarget)
5526         {
5527           emit_move_insn (target, tem);
5528           tem = target;
5529         }
5530     }
5531   else
5532     delete_insns_since (last);
5533
5534   return tem;
5535 }
5536
5537 /* Like emit_store_flag, but always succeeds.  */
5538
5539 rtx
5540 emit_store_flag_force (rtx target, enum rtx_code code, rtx op0, rtx op1,
5541                        enum machine_mode mode, int unsignedp, int normalizep)
5542 {
5543   rtx tem, label;
5544
5545   /* First see if emit_store_flag can do the job.  */
5546   tem = emit_store_flag (target, code, op0, op1, mode, unsignedp, normalizep);
5547   if (tem != 0)
5548     return tem;
5549
5550   if (normalizep == 0)
5551     normalizep = 1;
5552
5553   /* If this failed, we have to do this with set/compare/jump/set code.  */
5554
5555   if (!REG_P (target)
5556       || reg_mentioned_p (target, op0) || reg_mentioned_p (target, op1))
5557     target = gen_reg_rtx (GET_MODE (target));
5558
5559   emit_move_insn (target, const1_rtx);
5560   label = gen_label_rtx ();
5561   do_compare_rtx_and_jump (op0, op1, code, unsignedp, mode, NULL_RTX,
5562                            NULL_RTX, label);
5563
5564   emit_move_insn (target, const0_rtx);
5565   emit_label (label);
5566
5567   return target;
5568 }
5569 \f
5570 /* Perform possibly multi-word comparison and conditional jump to LABEL
5571    if ARG1 OP ARG2 true where ARG1 and ARG2 are of mode MODE
5572
5573    The algorithm is based on the code in expr.c:do_jump.
5574
5575    Note that this does not perform a general comparison.  Only
5576    variants generated within expmed.c are correctly handled, others
5577    could be handled if needed.  */
5578
5579 static void
5580 do_cmp_and_jump (rtx arg1, rtx arg2, enum rtx_code op, enum machine_mode mode,
5581                  rtx label)
5582 {
5583   /* If this mode is an integer too wide to compare properly,
5584      compare word by word.  Rely on cse to optimize constant cases.  */
5585
5586   if (GET_MODE_CLASS (mode) == MODE_INT
5587       && ! can_compare_p (op, mode, ccp_jump))
5588     {
5589       rtx label2 = gen_label_rtx ();
5590
5591       switch (op)
5592         {
5593         case LTU:
5594           do_jump_by_parts_greater_rtx (mode, 1, arg2, arg1, label2, label);
5595           break;
5596
5597         case LEU:
5598           do_jump_by_parts_greater_rtx (mode, 1, arg1, arg2, label, label2);
5599           break;
5600
5601         case LT:
5602           do_jump_by_parts_greater_rtx (mode, 0, arg2, arg1, label2, label);
5603           break;
5604
5605         case GT:
5606           do_jump_by_parts_greater_rtx (mode, 0, arg1, arg2, label2, label);
5607           break;
5608
5609         case GE:
5610           do_jump_by_parts_greater_rtx (mode, 0, arg2, arg1, label, label2);
5611           break;
5612
5613           /* do_jump_by_parts_equality_rtx compares with zero.  Luckily
5614              that's the only equality operations we do */
5615         case EQ:
5616           gcc_assert (arg2 == const0_rtx && mode == GET_MODE(arg1));
5617           do_jump_by_parts_equality_rtx (arg1, label2, label);
5618           break;
5619
5620         case NE:
5621           gcc_assert (arg2 == const0_rtx && mode == GET_MODE(arg1));
5622           do_jump_by_parts_equality_rtx (arg1, label, label2);
5623           break;
5624
5625         default:
5626           gcc_unreachable ();
5627         }
5628
5629       emit_label (label2);
5630     }
5631   else
5632     emit_cmp_and_jump_insns (arg1, arg2, op, NULL_RTX, mode, 0, label);
5633 }