OSDN Git Service

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