OSDN Git Service

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