OSDN Git Service

* gcc.target/i386/sse-22a.c: New test.
[pf3gnuchains/gcc-fork.git] / gcc / ifcvt.c
1 /* If-conversion support.
2    Copyright (C) 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2010,
3    2011
4    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
9    under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3, or (at your option)
11    any later version.
12
13    GCC is distributed in the hope that it will be useful, but WITHOUT
14    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
15    or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
16    License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with GCC; see the file COPYING3.  If not see
20    <http://www.gnu.org/licenses/>.  */
21
22 #include "config.h"
23 #include "system.h"
24 #include "coretypes.h"
25 #include "tm.h"
26
27 #include "rtl.h"
28 #include "regs.h"
29 #include "function.h"
30 #include "flags.h"
31 #include "insn-config.h"
32 #include "recog.h"
33 #include "except.h"
34 #include "hard-reg-set.h"
35 #include "basic-block.h"
36 #include "expr.h"
37 #include "output.h"
38 #include "optabs.h"
39 #include "diagnostic-core.h"
40 #include "tm_p.h"
41 #include "cfgloop.h"
42 #include "target.h"
43 #include "timevar.h"
44 #include "tree-pass.h"
45 #include "df.h"
46 #include "vec.h"
47 #include "vecprim.h"
48 #include "dbgcnt.h"
49
50 #ifndef HAVE_conditional_move
51 #define HAVE_conditional_move 0
52 #endif
53 #ifndef HAVE_incscc
54 #define HAVE_incscc 0
55 #endif
56 #ifndef HAVE_decscc
57 #define HAVE_decscc 0
58 #endif
59 #ifndef HAVE_trap
60 #define HAVE_trap 0
61 #endif
62
63 #ifndef MAX_CONDITIONAL_EXECUTE
64 #define MAX_CONDITIONAL_EXECUTE \
65   (BRANCH_COST (optimize_function_for_speed_p (cfun), false) \
66    + 1)
67 #endif
68
69 #define IFCVT_MULTIPLE_DUMPS 1
70
71 #define NULL_BLOCK      ((basic_block) NULL)
72
73 /* # of IF-THEN or IF-THEN-ELSE blocks we looked at  */
74 static int num_possible_if_blocks;
75
76 /* # of IF-THEN or IF-THEN-ELSE blocks were converted to conditional
77    execution.  */
78 static int num_updated_if_blocks;
79
80 /* # of changes made.  */
81 static int num_true_changes;
82
83 /* Whether conditional execution changes were made.  */
84 static int cond_exec_changed_p;
85
86 /* Forward references.  */
87 static int count_bb_insns (const_basic_block);
88 static bool cheap_bb_rtx_cost_p (const_basic_block, int);
89 static rtx first_active_insn (basic_block);
90 static rtx last_active_insn (basic_block, int);
91 static rtx find_active_insn_before (basic_block, rtx);
92 static rtx find_active_insn_after (basic_block, rtx);
93 static basic_block block_fallthru (basic_block);
94 static int cond_exec_process_insns (ce_if_block_t *, rtx, rtx, rtx, rtx, int);
95 static rtx cond_exec_get_condition (rtx);
96 static rtx noce_get_condition (rtx, rtx *, bool);
97 static int noce_operand_ok (const_rtx);
98 static void merge_if_block (ce_if_block_t *);
99 static int find_cond_trap (basic_block, edge, edge);
100 static basic_block find_if_header (basic_block, int);
101 static int block_jumps_and_fallthru_p (basic_block, basic_block);
102 static int noce_find_if_block (basic_block, edge, edge, int);
103 static int cond_exec_find_if_block (ce_if_block_t *);
104 static int find_if_case_1 (basic_block, edge, edge);
105 static int find_if_case_2 (basic_block, edge, edge);
106 static int dead_or_predicable (basic_block, basic_block, basic_block,
107                                edge, int);
108 static void noce_emit_move_insn (rtx, rtx);
109 static rtx block_has_only_trap (basic_block);
110 \f
111 /* Count the number of non-jump active insns in BB.  */
112
113 static int
114 count_bb_insns (const_basic_block bb)
115 {
116   int count = 0;
117   rtx insn = BB_HEAD (bb);
118
119   while (1)
120     {
121       if (CALL_P (insn) || NONJUMP_INSN_P (insn))
122         count++;
123
124       if (insn == BB_END (bb))
125         break;
126       insn = NEXT_INSN (insn);
127     }
128
129   return count;
130 }
131
132 /* Determine whether the total insn_rtx_cost on non-jump insns in
133    basic block BB is less than MAX_COST.  This function returns
134    false if the cost of any instruction could not be estimated.  */
135
136 static bool
137 cheap_bb_rtx_cost_p (const_basic_block bb, int max_cost)
138 {
139   int count = 0;
140   rtx insn = BB_HEAD (bb);
141   bool speed = optimize_bb_for_speed_p (bb);
142
143   while (1)
144     {
145       if (NONJUMP_INSN_P (insn))
146         {
147           int cost = insn_rtx_cost (PATTERN (insn), speed);
148           if (cost == 0)
149             return false;
150
151           /* If this instruction is the load or set of a "stack" register,
152              such as a floating point register on x87, then the cost of
153              speculatively executing this insn may need to include
154              the additional cost of popping its result off of the
155              register stack.  Unfortunately, correctly recognizing and
156              accounting for this additional overhead is tricky, so for
157              now we simply prohibit such speculative execution.  */
158 #ifdef STACK_REGS
159           {
160             rtx set = single_set (insn);
161             if (set && STACK_REG_P (SET_DEST (set)))
162               return false;
163           }
164 #endif
165
166           count += cost;
167           if (count >= max_cost)
168             return false;
169         }
170       else if (CALL_P (insn))
171         return false;
172
173       if (insn == BB_END (bb))
174         break;
175       insn = NEXT_INSN (insn);
176     }
177
178   return true;
179 }
180
181 /* Return the first non-jump active insn in the basic block.  */
182
183 static rtx
184 first_active_insn (basic_block bb)
185 {
186   rtx insn = BB_HEAD (bb);
187
188   if (LABEL_P (insn))
189     {
190       if (insn == BB_END (bb))
191         return NULL_RTX;
192       insn = NEXT_INSN (insn);
193     }
194
195   while (NOTE_P (insn) || DEBUG_INSN_P (insn))
196     {
197       if (insn == BB_END (bb))
198         return NULL_RTX;
199       insn = NEXT_INSN (insn);
200     }
201
202   if (JUMP_P (insn))
203     return NULL_RTX;
204
205   return insn;
206 }
207
208 /* Return the last non-jump active (non-jump) insn in the basic block.  */
209
210 static rtx
211 last_active_insn (basic_block bb, int skip_use_p)
212 {
213   rtx insn = BB_END (bb);
214   rtx head = BB_HEAD (bb);
215
216   while (NOTE_P (insn)
217          || JUMP_P (insn)
218          || DEBUG_INSN_P (insn)
219          || (skip_use_p
220              && NONJUMP_INSN_P (insn)
221              && GET_CODE (PATTERN (insn)) == USE))
222     {
223       if (insn == head)
224         return NULL_RTX;
225       insn = PREV_INSN (insn);
226     }
227
228   if (LABEL_P (insn))
229     return NULL_RTX;
230
231   return insn;
232 }
233
234 /* Return the active insn before INSN inside basic block CURR_BB. */
235
236 static rtx
237 find_active_insn_before (basic_block curr_bb, rtx insn)
238 {
239   if (!insn || insn == BB_HEAD (curr_bb))
240     return NULL_RTX;
241
242   while ((insn = PREV_INSN (insn)) != NULL_RTX)
243     {
244       if (NONJUMP_INSN_P (insn) || JUMP_P (insn) || CALL_P (insn))
245         break;
246
247       /* No other active insn all the way to the start of the basic block. */
248       if (insn == BB_HEAD (curr_bb))
249         return NULL_RTX;
250     }
251
252   return insn;
253 }
254
255 /* Return the active insn after INSN inside basic block CURR_BB. */
256
257 static rtx
258 find_active_insn_after (basic_block curr_bb, rtx insn)
259 {
260   if (!insn || insn == BB_END (curr_bb))
261     return NULL_RTX;
262
263   while ((insn = NEXT_INSN (insn)) != NULL_RTX)
264     {
265       if (NONJUMP_INSN_P (insn) || JUMP_P (insn) || CALL_P (insn))
266         break;
267
268       /* No other active insn all the way to the end of the basic block. */
269       if (insn == BB_END (curr_bb))
270         return NULL_RTX;
271     }
272
273   return insn;
274 }
275
276 /* Return the basic block reached by falling though the basic block BB.  */
277
278 static basic_block
279 block_fallthru (basic_block bb)
280 {
281   edge e = find_fallthru_edge (bb->succs);
282
283   return (e) ? e->dest : NULL_BLOCK;
284 }
285 \f
286 /* Go through a bunch of insns, converting them to conditional
287    execution format if possible.  Return TRUE if all of the non-note
288    insns were processed.  */
289
290 static int
291 cond_exec_process_insns (ce_if_block_t *ce_info ATTRIBUTE_UNUSED,
292                          /* if block information */rtx start,
293                          /* first insn to look at */rtx end,
294                          /* last insn to look at */rtx test,
295                          /* conditional execution test */rtx prob_val,
296                          /* probability of branch taken. */int mod_ok)
297 {
298   int must_be_last = FALSE;
299   rtx insn;
300   rtx xtest;
301   rtx pattern;
302
303   if (!start || !end)
304     return FALSE;
305
306   for (insn = start; ; insn = NEXT_INSN (insn))
307     {
308       /* dwarf2out can't cope with conditional prologues.  */
309       if (NOTE_P (insn) && NOTE_KIND (insn) == NOTE_INSN_PROLOGUE_END)
310         return FALSE;
311
312       if (NOTE_P (insn) || DEBUG_INSN_P (insn))
313         goto insn_done;
314
315       gcc_assert(NONJUMP_INSN_P (insn) || CALL_P (insn));
316
317       /* Remove USE insns that get in the way.  */
318       if (reload_completed && GET_CODE (PATTERN (insn)) == USE)
319         {
320           /* ??? Ug.  Actually unlinking the thing is problematic,
321              given what we'd have to coordinate with our callers.  */
322           SET_INSN_DELETED (insn);
323           goto insn_done;
324         }
325
326       /* Last insn wasn't last?  */
327       if (must_be_last)
328         return FALSE;
329
330       if (modified_in_p (test, insn))
331         {
332           if (!mod_ok)
333             return FALSE;
334           must_be_last = TRUE;
335         }
336
337       /* Now build the conditional form of the instruction.  */
338       pattern = PATTERN (insn);
339       xtest = copy_rtx (test);
340
341       /* If this is already a COND_EXEC, rewrite the test to be an AND of the
342          two conditions.  */
343       if (GET_CODE (pattern) == COND_EXEC)
344         {
345           if (GET_MODE (xtest) != GET_MODE (COND_EXEC_TEST (pattern)))
346             return FALSE;
347
348           xtest = gen_rtx_AND (GET_MODE (xtest), xtest,
349                                COND_EXEC_TEST (pattern));
350           pattern = COND_EXEC_CODE (pattern);
351         }
352
353       pattern = gen_rtx_COND_EXEC (VOIDmode, xtest, pattern);
354
355       /* If the machine needs to modify the insn being conditionally executed,
356          say for example to force a constant integer operand into a temp
357          register, do so here.  */
358 #ifdef IFCVT_MODIFY_INSN
359       IFCVT_MODIFY_INSN (ce_info, pattern, insn);
360       if (! pattern)
361         return FALSE;
362 #endif
363
364       validate_change (insn, &PATTERN (insn), pattern, 1);
365
366       if (CALL_P (insn) && prob_val)
367         validate_change (insn, &REG_NOTES (insn),
368                          alloc_EXPR_LIST (REG_BR_PROB, prob_val,
369                                           REG_NOTES (insn)), 1);
370
371     insn_done:
372       if (insn == end)
373         break;
374     }
375
376   return TRUE;
377 }
378
379 /* Return the condition for a jump.  Do not do any special processing.  */
380
381 static rtx
382 cond_exec_get_condition (rtx jump)
383 {
384   rtx test_if, cond;
385
386   if (any_condjump_p (jump))
387     test_if = SET_SRC (pc_set (jump));
388   else
389     return NULL_RTX;
390   cond = XEXP (test_if, 0);
391
392   /* If this branches to JUMP_LABEL when the condition is false,
393      reverse the condition.  */
394   if (GET_CODE (XEXP (test_if, 2)) == LABEL_REF
395       && XEXP (XEXP (test_if, 2), 0) == JUMP_LABEL (jump))
396     {
397       enum rtx_code rev = reversed_comparison_code (cond, jump);
398       if (rev == UNKNOWN)
399         return NULL_RTX;
400
401       cond = gen_rtx_fmt_ee (rev, GET_MODE (cond), XEXP (cond, 0),
402                              XEXP (cond, 1));
403     }
404
405   return cond;
406 }
407
408 /* Given a simple IF-THEN or IF-THEN-ELSE block, attempt to convert it
409    to conditional execution.  Return TRUE if we were successful at
410    converting the block.  */
411
412 static int
413 cond_exec_process_if_block (ce_if_block_t * ce_info,
414                             /* if block information */int do_multiple_p)
415 {
416   basic_block test_bb = ce_info->test_bb;       /* last test block */
417   basic_block then_bb = ce_info->then_bb;       /* THEN */
418   basic_block else_bb = ce_info->else_bb;       /* ELSE or NULL */
419   rtx test_expr;                /* expression in IF_THEN_ELSE that is tested */
420   rtx then_start;               /* first insn in THEN block */
421   rtx then_end;                 /* last insn + 1 in THEN block */
422   rtx else_start = NULL_RTX;    /* first insn in ELSE block or NULL */
423   rtx else_end = NULL_RTX;      /* last insn + 1 in ELSE block */
424   int max;                      /* max # of insns to convert.  */
425   int then_mod_ok;              /* whether conditional mods are ok in THEN */
426   rtx true_expr;                /* test for else block insns */
427   rtx false_expr;               /* test for then block insns */
428   rtx true_prob_val;            /* probability of else block */
429   rtx false_prob_val;           /* probability of then block */
430   rtx then_last_head = NULL_RTX;        /* Last match at the head of THEN */
431   rtx else_last_head = NULL_RTX;        /* Last match at the head of ELSE */
432   rtx then_first_tail = NULL_RTX;       /* First match at the tail of THEN */
433   rtx else_first_tail = NULL_RTX;       /* First match at the tail of ELSE */
434   int then_n_insns, else_n_insns, n_insns;
435   enum rtx_code false_code;
436
437   /* If test is comprised of && or || elements, and we've failed at handling
438      all of them together, just use the last test if it is the special case of
439      && elements without an ELSE block.  */
440   if (!do_multiple_p && ce_info->num_multiple_test_blocks)
441     {
442       if (else_bb || ! ce_info->and_and_p)
443         return FALSE;
444
445       ce_info->test_bb = test_bb = ce_info->last_test_bb;
446       ce_info->num_multiple_test_blocks = 0;
447       ce_info->num_and_and_blocks = 0;
448       ce_info->num_or_or_blocks = 0;
449     }
450
451   /* Find the conditional jump to the ELSE or JOIN part, and isolate
452      the test.  */
453   test_expr = cond_exec_get_condition (BB_END (test_bb));
454   if (! test_expr)
455     return FALSE;
456
457   /* If the conditional jump is more than just a conditional jump,
458      then we can not do conditional execution conversion on this block.  */
459   if (! onlyjump_p (BB_END (test_bb)))
460     return FALSE;
461
462   /* Collect the bounds of where we're to search, skipping any labels, jumps
463      and notes at the beginning and end of the block.  Then count the total
464      number of insns and see if it is small enough to convert.  */
465   then_start = first_active_insn (then_bb);
466   then_end = last_active_insn (then_bb, TRUE);
467   then_n_insns = ce_info->num_then_insns = count_bb_insns (then_bb);
468   n_insns = then_n_insns;
469   max = MAX_CONDITIONAL_EXECUTE;
470
471   if (else_bb)
472     {
473       int n_matching;
474
475       max *= 2;
476       else_start = first_active_insn (else_bb);
477       else_end = last_active_insn (else_bb, TRUE);
478       else_n_insns = ce_info->num_else_insns = count_bb_insns (else_bb);
479       n_insns += else_n_insns;
480
481       /* Look for matching sequences at the head and tail of the two blocks,
482          and limit the range of insns to be converted if possible.  */
483       n_matching = flow_find_cross_jump (then_bb, else_bb,
484                                          &then_first_tail, &else_first_tail,
485                                          NULL);
486       if (then_first_tail == BB_HEAD (then_bb))
487         then_start = then_end = NULL_RTX;
488       if (else_first_tail == BB_HEAD (else_bb))
489         else_start = else_end = NULL_RTX;
490
491       if (n_matching > 0)
492         {
493           if (then_end)
494             then_end = find_active_insn_before (then_bb, then_first_tail);
495           if (else_end)
496             else_end = find_active_insn_before (else_bb, else_first_tail);
497           n_insns -= 2 * n_matching;
498         }
499
500       if (then_start && else_start)
501         {
502           int longest_match = MIN (then_n_insns - n_matching,
503                                    else_n_insns - n_matching);
504           n_matching
505             = flow_find_head_matching_sequence (then_bb, else_bb,
506                                                 &then_last_head,
507                                                 &else_last_head,
508                                                 longest_match);
509
510           if (n_matching > 0)
511             {
512               rtx insn;
513
514               /* We won't pass the insns in the head sequence to
515                  cond_exec_process_insns, so we need to test them here
516                  to make sure that they don't clobber the condition.  */
517               for (insn = BB_HEAD (then_bb);
518                    insn != NEXT_INSN (then_last_head);
519                    insn = NEXT_INSN (insn))
520                 if (!LABEL_P (insn) && !NOTE_P (insn)
521                     && !DEBUG_INSN_P (insn)
522                     && modified_in_p (test_expr, insn))
523                   return FALSE;
524             }
525
526           if (then_last_head == then_end)
527             then_start = then_end = NULL_RTX;
528           if (else_last_head == else_end)
529             else_start = else_end = NULL_RTX;
530
531           if (n_matching > 0)
532             {
533               if (then_start)
534                 then_start = find_active_insn_after (then_bb, then_last_head);
535               if (else_start)
536                 else_start = find_active_insn_after (else_bb, else_last_head);
537               n_insns -= 2 * n_matching;
538             }
539         }
540     }
541
542   if (n_insns > max)
543     return FALSE;
544
545   /* Map test_expr/test_jump into the appropriate MD tests to use on
546      the conditionally executed code.  */
547
548   true_expr = test_expr;
549
550   false_code = reversed_comparison_code (true_expr, BB_END (test_bb));
551   if (false_code != UNKNOWN)
552     false_expr = gen_rtx_fmt_ee (false_code, GET_MODE (true_expr),
553                                  XEXP (true_expr, 0), XEXP (true_expr, 1));
554   else
555     false_expr = NULL_RTX;
556
557 #ifdef IFCVT_MODIFY_TESTS
558   /* If the machine description needs to modify the tests, such as setting a
559      conditional execution register from a comparison, it can do so here.  */
560   IFCVT_MODIFY_TESTS (ce_info, true_expr, false_expr);
561
562   /* See if the conversion failed.  */
563   if (!true_expr || !false_expr)
564     goto fail;
565 #endif
566
567   true_prob_val = find_reg_note (BB_END (test_bb), REG_BR_PROB, NULL_RTX);
568   if (true_prob_val)
569     {
570       true_prob_val = XEXP (true_prob_val, 0);
571       false_prob_val = GEN_INT (REG_BR_PROB_BASE - INTVAL (true_prob_val));
572     }
573   else
574     false_prob_val = NULL_RTX;
575
576   /* If we have && or || tests, do them here.  These tests are in the adjacent
577      blocks after the first block containing the test.  */
578   if (ce_info->num_multiple_test_blocks > 0)
579     {
580       basic_block bb = test_bb;
581       basic_block last_test_bb = ce_info->last_test_bb;
582
583       if (! false_expr)
584         goto fail;
585
586       do
587         {
588           rtx start, end;
589           rtx t, f;
590           enum rtx_code f_code;
591
592           bb = block_fallthru (bb);
593           start = first_active_insn (bb);
594           end = last_active_insn (bb, TRUE);
595           if (start
596               && ! cond_exec_process_insns (ce_info, start, end, false_expr,
597                                             false_prob_val, FALSE))
598             goto fail;
599
600           /* If the conditional jump is more than just a conditional jump, then
601              we can not do conditional execution conversion on this block.  */
602           if (! onlyjump_p (BB_END (bb)))
603             goto fail;
604
605           /* Find the conditional jump and isolate the test.  */
606           t = cond_exec_get_condition (BB_END (bb));
607           if (! t)
608             goto fail;
609
610           f_code = reversed_comparison_code (t, BB_END (bb));
611           if (f_code == UNKNOWN)
612             goto fail;
613
614           f = gen_rtx_fmt_ee (f_code, GET_MODE (t), XEXP (t, 0), XEXP (t, 1));
615           if (ce_info->and_and_p)
616             {
617               t = gen_rtx_AND (GET_MODE (t), true_expr, t);
618               f = gen_rtx_IOR (GET_MODE (t), false_expr, f);
619             }
620           else
621             {
622               t = gen_rtx_IOR (GET_MODE (t), true_expr, t);
623               f = gen_rtx_AND (GET_MODE (t), false_expr, f);
624             }
625
626           /* If the machine description needs to modify the tests, such as
627              setting a conditional execution register from a comparison, it can
628              do so here.  */
629 #ifdef IFCVT_MODIFY_MULTIPLE_TESTS
630           IFCVT_MODIFY_MULTIPLE_TESTS (ce_info, bb, t, f);
631
632           /* See if the conversion failed.  */
633           if (!t || !f)
634             goto fail;
635 #endif
636
637           true_expr = t;
638           false_expr = f;
639         }
640       while (bb != last_test_bb);
641     }
642
643   /* For IF-THEN-ELSE blocks, we don't allow modifications of the test
644      on then THEN block.  */
645   then_mod_ok = (else_bb == NULL_BLOCK);
646
647   /* Go through the THEN and ELSE blocks converting the insns if possible
648      to conditional execution.  */
649
650   if (then_end
651       && (! false_expr
652           || ! cond_exec_process_insns (ce_info, then_start, then_end,
653                                         false_expr, false_prob_val,
654                                         then_mod_ok)))
655     goto fail;
656
657   if (else_bb && else_end
658       && ! cond_exec_process_insns (ce_info, else_start, else_end,
659                                     true_expr, true_prob_val, TRUE))
660     goto fail;
661
662   /* If we cannot apply the changes, fail.  Do not go through the normal fail
663      processing, since apply_change_group will call cancel_changes.  */
664   if (! apply_change_group ())
665     {
666 #ifdef IFCVT_MODIFY_CANCEL
667       /* Cancel any machine dependent changes.  */
668       IFCVT_MODIFY_CANCEL (ce_info);
669 #endif
670       return FALSE;
671     }
672
673 #ifdef IFCVT_MODIFY_FINAL
674   /* Do any machine dependent final modifications.  */
675   IFCVT_MODIFY_FINAL (ce_info);
676 #endif
677
678   /* Conversion succeeded.  */
679   if (dump_file)
680     fprintf (dump_file, "%d insn%s converted to conditional execution.\n",
681              n_insns, (n_insns == 1) ? " was" : "s were");
682
683   /* Merge the blocks!  If we had matching sequences, make sure to delete one
684      copy at the appropriate location first: delete the copy in the THEN branch
685      for a tail sequence so that the remaining one is executed last for both
686      branches, and delete the copy in the ELSE branch for a head sequence so
687      that the remaining one is executed first for both branches.  */
688   if (then_first_tail)
689     {
690       rtx from = then_first_tail;
691       if (!INSN_P (from))
692         from = find_active_insn_after (then_bb, from);
693       delete_insn_chain (from, BB_END (then_bb), false);
694     }
695   if (else_last_head)
696     delete_insn_chain (first_active_insn (else_bb), else_last_head, false);
697
698   merge_if_block (ce_info);
699   cond_exec_changed_p = TRUE;
700   return TRUE;
701
702  fail:
703 #ifdef IFCVT_MODIFY_CANCEL
704   /* Cancel any machine dependent changes.  */
705   IFCVT_MODIFY_CANCEL (ce_info);
706 #endif
707
708   cancel_changes (0);
709   return FALSE;
710 }
711 \f
712 /* Used by noce_process_if_block to communicate with its subroutines.
713
714    The subroutines know that A and B may be evaluated freely.  They
715    know that X is a register.  They should insert new instructions
716    before cond_earliest.  */
717
718 struct noce_if_info
719 {
720   /* The basic blocks that make up the IF-THEN-{ELSE-,}JOIN block.  */
721   basic_block test_bb, then_bb, else_bb, join_bb;
722
723   /* The jump that ends TEST_BB.  */
724   rtx jump;
725
726   /* The jump condition.  */
727   rtx cond;
728
729   /* New insns should be inserted before this one.  */
730   rtx cond_earliest;
731
732   /* Insns in the THEN and ELSE block.  There is always just this
733      one insns in those blocks.  The insns are single_set insns.
734      If there was no ELSE block, INSN_B is the last insn before
735      COND_EARLIEST, or NULL_RTX.  In the former case, the insn
736      operands are still valid, as if INSN_B was moved down below
737      the jump.  */
738   rtx insn_a, insn_b;
739
740   /* The SET_SRC of INSN_A and INSN_B.  */
741   rtx a, b;
742
743   /* The SET_DEST of INSN_A.  */
744   rtx x;
745
746   /* True if this if block is not canonical.  In the canonical form of
747      if blocks, the THEN_BB is the block reached via the fallthru edge
748      from TEST_BB.  For the noce transformations, we allow the symmetric
749      form as well.  */
750   bool then_else_reversed;
751
752   /* Estimated cost of the particular branch instruction.  */
753   int branch_cost;
754 };
755
756 static rtx noce_emit_store_flag (struct noce_if_info *, rtx, int, int);
757 static int noce_try_move (struct noce_if_info *);
758 static int noce_try_store_flag (struct noce_if_info *);
759 static int noce_try_addcc (struct noce_if_info *);
760 static int noce_try_store_flag_constants (struct noce_if_info *);
761 static int noce_try_store_flag_mask (struct noce_if_info *);
762 static rtx noce_emit_cmove (struct noce_if_info *, rtx, enum rtx_code, rtx,
763                             rtx, rtx, rtx);
764 static int noce_try_cmove (struct noce_if_info *);
765 static int noce_try_cmove_arith (struct noce_if_info *);
766 static rtx noce_get_alt_condition (struct noce_if_info *, rtx, rtx *);
767 static int noce_try_minmax (struct noce_if_info *);
768 static int noce_try_abs (struct noce_if_info *);
769 static int noce_try_sign_mask (struct noce_if_info *);
770
771 /* Helper function for noce_try_store_flag*.  */
772
773 static rtx
774 noce_emit_store_flag (struct noce_if_info *if_info, rtx x, int reversep,
775                       int normalize)
776 {
777   rtx cond = if_info->cond;
778   int cond_complex;
779   enum rtx_code code;
780
781   cond_complex = (! general_operand (XEXP (cond, 0), VOIDmode)
782                   || ! general_operand (XEXP (cond, 1), VOIDmode));
783
784   /* If earliest == jump, or when the condition is complex, try to
785      build the store_flag insn directly.  */
786
787   if (cond_complex)
788     {
789       rtx set = pc_set (if_info->jump);
790       cond = XEXP (SET_SRC (set), 0);
791       if (GET_CODE (XEXP (SET_SRC (set), 2)) == LABEL_REF
792           && XEXP (XEXP (SET_SRC (set), 2), 0) == JUMP_LABEL (if_info->jump))
793         reversep = !reversep;
794       if (if_info->then_else_reversed)
795         reversep = !reversep;
796     }
797
798   if (reversep)
799     code = reversed_comparison_code (cond, if_info->jump);
800   else
801     code = GET_CODE (cond);
802
803   if ((if_info->cond_earliest == if_info->jump || cond_complex)
804       && (normalize == 0 || STORE_FLAG_VALUE == normalize))
805     {
806       rtx tmp;
807
808       tmp = gen_rtx_fmt_ee (code, GET_MODE (x), XEXP (cond, 0),
809                             XEXP (cond, 1));
810       tmp = gen_rtx_SET (VOIDmode, x, tmp);
811
812       start_sequence ();
813       tmp = emit_insn (tmp);
814
815       if (recog_memoized (tmp) >= 0)
816         {
817           tmp = get_insns ();
818           end_sequence ();
819           emit_insn (tmp);
820
821           if_info->cond_earliest = if_info->jump;
822
823           return x;
824         }
825
826       end_sequence ();
827     }
828
829   /* Don't even try if the comparison operands or the mode of X are weird.  */
830   if (cond_complex || !SCALAR_INT_MODE_P (GET_MODE (x)))
831     return NULL_RTX;
832
833   return emit_store_flag (x, code, XEXP (cond, 0),
834                           XEXP (cond, 1), VOIDmode,
835                           (code == LTU || code == LEU
836                            || code == GEU || code == GTU), normalize);
837 }
838
839 /* Emit instruction to move an rtx, possibly into STRICT_LOW_PART.
840    X is the destination/target and Y is the value to copy.  */
841
842 static void
843 noce_emit_move_insn (rtx x, rtx y)
844 {
845   enum machine_mode outmode;
846   rtx outer, inner;
847   int bitpos;
848
849   if (GET_CODE (x) != STRICT_LOW_PART)
850     {
851       rtx seq, insn, target;
852       optab ot;
853
854       start_sequence ();
855       /* Check that the SET_SRC is reasonable before calling emit_move_insn,
856          otherwise construct a suitable SET pattern ourselves.  */
857       insn = (OBJECT_P (y) || CONSTANT_P (y) || GET_CODE (y) == SUBREG)
858              ? emit_move_insn (x, y)
859              : emit_insn (gen_rtx_SET (VOIDmode, x, y));
860       seq = get_insns ();
861       end_sequence ();
862
863       if (recog_memoized (insn) <= 0)
864         {
865           if (GET_CODE (x) == ZERO_EXTRACT)
866             {
867               rtx op = XEXP (x, 0);
868               unsigned HOST_WIDE_INT size = INTVAL (XEXP (x, 1));
869               unsigned HOST_WIDE_INT start = INTVAL (XEXP (x, 2));
870
871               /* store_bit_field expects START to be relative to
872                  BYTES_BIG_ENDIAN and adjusts this value for machines with
873                  BITS_BIG_ENDIAN != BYTES_BIG_ENDIAN.  In order to be able to
874                  invoke store_bit_field again it is necessary to have the START
875                  value from the first call.  */
876               if (BITS_BIG_ENDIAN != BYTES_BIG_ENDIAN)
877                 {
878                   if (MEM_P (op))
879                     start = BITS_PER_UNIT - start - size;
880                   else
881                     {
882                       gcc_assert (REG_P (op));
883                       start = BITS_PER_WORD - start - size;
884                     }
885                 }
886
887               gcc_assert (start < (MEM_P (op) ? BITS_PER_UNIT : BITS_PER_WORD));
888               store_bit_field (op, size, start, 0, 0, GET_MODE (x), y);
889               return;
890             }
891
892           switch (GET_RTX_CLASS (GET_CODE (y)))
893             {
894             case RTX_UNARY:
895               ot = code_to_optab[GET_CODE (y)];
896               if (ot)
897                 {
898                   start_sequence ();
899                   target = expand_unop (GET_MODE (y), ot, XEXP (y, 0), x, 0);
900                   if (target != NULL_RTX)
901                     {
902                       if (target != x)
903                         emit_move_insn (x, target);
904                       seq = get_insns ();
905                     }
906                   end_sequence ();
907                 }
908               break;
909
910             case RTX_BIN_ARITH:
911             case RTX_COMM_ARITH:
912               ot = code_to_optab[GET_CODE (y)];
913               if (ot)
914                 {
915                   start_sequence ();
916                   target = expand_binop (GET_MODE (y), ot,
917                                          XEXP (y, 0), XEXP (y, 1),
918                                          x, 0, OPTAB_DIRECT);
919                   if (target != NULL_RTX)
920                     {
921                       if (target != x)
922                           emit_move_insn (x, target);
923                       seq = get_insns ();
924                     }
925                   end_sequence ();
926                 }
927               break;
928
929             default:
930               break;
931             }
932         }
933
934       emit_insn (seq);
935       return;
936     }
937
938   outer = XEXP (x, 0);
939   inner = XEXP (outer, 0);
940   outmode = GET_MODE (outer);
941   bitpos = SUBREG_BYTE (outer) * BITS_PER_UNIT;
942   store_bit_field (inner, GET_MODE_BITSIZE (outmode), bitpos,
943                    0, 0, outmode, y);
944 }
945
946 /* Return sequence of instructions generated by if conversion.  This
947    function calls end_sequence() to end the current stream, ensures
948    that are instructions are unshared, recognizable non-jump insns.
949    On failure, this function returns a NULL_RTX.  */
950
951 static rtx
952 end_ifcvt_sequence (struct noce_if_info *if_info)
953 {
954   rtx insn;
955   rtx seq = get_insns ();
956
957   set_used_flags (if_info->x);
958   set_used_flags (if_info->cond);
959   unshare_all_rtl_in_chain (seq);
960   end_sequence ();
961
962   /* Make sure that all of the instructions emitted are recognizable,
963      and that we haven't introduced a new jump instruction.
964      As an exercise for the reader, build a general mechanism that
965      allows proper placement of required clobbers.  */
966   for (insn = seq; insn; insn = NEXT_INSN (insn))
967     if (JUMP_P (insn)
968         || recog_memoized (insn) == -1)
969       return NULL_RTX;
970
971   return seq;
972 }
973
974 /* Convert "if (a != b) x = a; else x = b" into "x = a" and
975    "if (a == b) x = a; else x = b" into "x = b".  */
976
977 static int
978 noce_try_move (struct noce_if_info *if_info)
979 {
980   rtx cond = if_info->cond;
981   enum rtx_code code = GET_CODE (cond);
982   rtx y, seq;
983
984   if (code != NE && code != EQ)
985     return FALSE;
986
987   /* This optimization isn't valid if either A or B could be a NaN
988      or a signed zero.  */
989   if (HONOR_NANS (GET_MODE (if_info->x))
990       || HONOR_SIGNED_ZEROS (GET_MODE (if_info->x)))
991     return FALSE;
992
993   /* Check whether the operands of the comparison are A and in
994      either order.  */
995   if ((rtx_equal_p (if_info->a, XEXP (cond, 0))
996        && rtx_equal_p (if_info->b, XEXP (cond, 1)))
997       || (rtx_equal_p (if_info->a, XEXP (cond, 1))
998           && rtx_equal_p (if_info->b, XEXP (cond, 0))))
999     {
1000       y = (code == EQ) ? if_info->a : if_info->b;
1001
1002       /* Avoid generating the move if the source is the destination.  */
1003       if (! rtx_equal_p (if_info->x, y))
1004         {
1005           start_sequence ();
1006           noce_emit_move_insn (if_info->x, y);
1007           seq = end_ifcvt_sequence (if_info);
1008           if (!seq)
1009             return FALSE;
1010
1011           emit_insn_before_setloc (seq, if_info->jump,
1012                                    INSN_LOCATOR (if_info->insn_a));
1013         }
1014       return TRUE;
1015     }
1016   return FALSE;
1017 }
1018
1019 /* Convert "if (test) x = 1; else x = 0".
1020
1021    Only try 0 and STORE_FLAG_VALUE here.  Other combinations will be
1022    tried in noce_try_store_flag_constants after noce_try_cmove has had
1023    a go at the conversion.  */
1024
1025 static int
1026 noce_try_store_flag (struct noce_if_info *if_info)
1027 {
1028   int reversep;
1029   rtx target, seq;
1030
1031   if (CONST_INT_P (if_info->b)
1032       && INTVAL (if_info->b) == STORE_FLAG_VALUE
1033       && if_info->a == const0_rtx)
1034     reversep = 0;
1035   else if (if_info->b == const0_rtx
1036            && CONST_INT_P (if_info->a)
1037            && INTVAL (if_info->a) == STORE_FLAG_VALUE
1038            && (reversed_comparison_code (if_info->cond, if_info->jump)
1039                != UNKNOWN))
1040     reversep = 1;
1041   else
1042     return FALSE;
1043
1044   start_sequence ();
1045
1046   target = noce_emit_store_flag (if_info, if_info->x, reversep, 0);
1047   if (target)
1048     {
1049       if (target != if_info->x)
1050         noce_emit_move_insn (if_info->x, target);
1051
1052       seq = end_ifcvt_sequence (if_info);
1053       if (! seq)
1054         return FALSE;
1055
1056       emit_insn_before_setloc (seq, if_info->jump,
1057                                INSN_LOCATOR (if_info->insn_a));
1058       return TRUE;
1059     }
1060   else
1061     {
1062       end_sequence ();
1063       return FALSE;
1064     }
1065 }
1066
1067 /* Convert "if (test) x = a; else x = b", for A and B constant.  */
1068
1069 static int
1070 noce_try_store_flag_constants (struct noce_if_info *if_info)
1071 {
1072   rtx target, seq;
1073   int reversep;
1074   HOST_WIDE_INT itrue, ifalse, diff, tmp;
1075   int normalize, can_reverse;
1076   enum machine_mode mode;
1077
1078   if (CONST_INT_P (if_info->a)
1079       && CONST_INT_P (if_info->b))
1080     {
1081       mode = GET_MODE (if_info->x);
1082       ifalse = INTVAL (if_info->a);
1083       itrue = INTVAL (if_info->b);
1084
1085       /* Make sure we can represent the difference between the two values.  */
1086       if ((itrue - ifalse > 0)
1087           != ((ifalse < 0) != (itrue < 0) ? ifalse < 0 : ifalse < itrue))
1088         return FALSE;
1089
1090       diff = trunc_int_for_mode (itrue - ifalse, mode);
1091
1092       can_reverse = (reversed_comparison_code (if_info->cond, if_info->jump)
1093                      != UNKNOWN);
1094
1095       reversep = 0;
1096       if (diff == STORE_FLAG_VALUE || diff == -STORE_FLAG_VALUE)
1097         normalize = 0;
1098       else if (ifalse == 0 && exact_log2 (itrue) >= 0
1099                && (STORE_FLAG_VALUE == 1
1100                    || if_info->branch_cost >= 2))
1101         normalize = 1;
1102       else if (itrue == 0 && exact_log2 (ifalse) >= 0 && can_reverse
1103                && (STORE_FLAG_VALUE == 1 || if_info->branch_cost >= 2))
1104         normalize = 1, reversep = 1;
1105       else if (itrue == -1
1106                && (STORE_FLAG_VALUE == -1
1107                    || if_info->branch_cost >= 2))
1108         normalize = -1;
1109       else if (ifalse == -1 && can_reverse
1110                && (STORE_FLAG_VALUE == -1 || if_info->branch_cost >= 2))
1111         normalize = -1, reversep = 1;
1112       else if ((if_info->branch_cost >= 2 && STORE_FLAG_VALUE == -1)
1113                || if_info->branch_cost >= 3)
1114         normalize = -1;
1115       else
1116         return FALSE;
1117
1118       if (reversep)
1119         {
1120           tmp = itrue; itrue = ifalse; ifalse = tmp;
1121           diff = trunc_int_for_mode (-diff, mode);
1122         }
1123
1124       start_sequence ();
1125       target = noce_emit_store_flag (if_info, if_info->x, reversep, normalize);
1126       if (! target)
1127         {
1128           end_sequence ();
1129           return FALSE;
1130         }
1131
1132       /* if (test) x = 3; else x = 4;
1133          =>   x = 3 + (test == 0);  */
1134       if (diff == STORE_FLAG_VALUE || diff == -STORE_FLAG_VALUE)
1135         {
1136           target = expand_simple_binop (mode,
1137                                         (diff == STORE_FLAG_VALUE
1138                                          ? PLUS : MINUS),
1139                                         GEN_INT (ifalse), target, if_info->x, 0,
1140                                         OPTAB_WIDEN);
1141         }
1142
1143       /* if (test) x = 8; else x = 0;
1144          =>   x = (test != 0) << 3;  */
1145       else if (ifalse == 0 && (tmp = exact_log2 (itrue)) >= 0)
1146         {
1147           target = expand_simple_binop (mode, ASHIFT,
1148                                         target, GEN_INT (tmp), if_info->x, 0,
1149                                         OPTAB_WIDEN);
1150         }
1151
1152       /* if (test) x = -1; else x = b;
1153          =>   x = -(test != 0) | b;  */
1154       else if (itrue == -1)
1155         {
1156           target = expand_simple_binop (mode, IOR,
1157                                         target, GEN_INT (ifalse), if_info->x, 0,
1158                                         OPTAB_WIDEN);
1159         }
1160
1161       /* if (test) x = a; else x = b;
1162          =>   x = (-(test != 0) & (b - a)) + a;  */
1163       else
1164         {
1165           target = expand_simple_binop (mode, AND,
1166                                         target, GEN_INT (diff), if_info->x, 0,
1167                                         OPTAB_WIDEN);
1168           if (target)
1169             target = expand_simple_binop (mode, PLUS,
1170                                           target, GEN_INT (ifalse),
1171                                           if_info->x, 0, OPTAB_WIDEN);
1172         }
1173
1174       if (! target)
1175         {
1176           end_sequence ();
1177           return FALSE;
1178         }
1179
1180       if (target != if_info->x)
1181         noce_emit_move_insn (if_info->x, target);
1182
1183       seq = end_ifcvt_sequence (if_info);
1184       if (!seq)
1185         return FALSE;
1186
1187       emit_insn_before_setloc (seq, if_info->jump,
1188                                INSN_LOCATOR (if_info->insn_a));
1189       return TRUE;
1190     }
1191
1192   return FALSE;
1193 }
1194
1195 /* Convert "if (test) foo++" into "foo += (test != 0)", and
1196    similarly for "foo--".  */
1197
1198 static int
1199 noce_try_addcc (struct noce_if_info *if_info)
1200 {
1201   rtx target, seq;
1202   int subtract, normalize;
1203
1204   if (GET_CODE (if_info->a) == PLUS
1205       && rtx_equal_p (XEXP (if_info->a, 0), if_info->b)
1206       && (reversed_comparison_code (if_info->cond, if_info->jump)
1207           != UNKNOWN))
1208     {
1209       rtx cond = if_info->cond;
1210       enum rtx_code code = reversed_comparison_code (cond, if_info->jump);
1211
1212       /* First try to use addcc pattern.  */
1213       if (general_operand (XEXP (cond, 0), VOIDmode)
1214           && general_operand (XEXP (cond, 1), VOIDmode))
1215         {
1216           start_sequence ();
1217           target = emit_conditional_add (if_info->x, code,
1218                                          XEXP (cond, 0),
1219                                          XEXP (cond, 1),
1220                                          VOIDmode,
1221                                          if_info->b,
1222                                          XEXP (if_info->a, 1),
1223                                          GET_MODE (if_info->x),
1224                                          (code == LTU || code == GEU
1225                                           || code == LEU || code == GTU));
1226           if (target)
1227             {
1228               if (target != if_info->x)
1229                 noce_emit_move_insn (if_info->x, target);
1230
1231               seq = end_ifcvt_sequence (if_info);
1232               if (!seq)
1233                 return FALSE;
1234
1235               emit_insn_before_setloc (seq, if_info->jump,
1236                                        INSN_LOCATOR (if_info->insn_a));
1237               return TRUE;
1238             }
1239           end_sequence ();
1240         }
1241
1242       /* If that fails, construct conditional increment or decrement using
1243          setcc.  */
1244       if (if_info->branch_cost >= 2
1245           && (XEXP (if_info->a, 1) == const1_rtx
1246               || XEXP (if_info->a, 1) == constm1_rtx))
1247         {
1248           start_sequence ();
1249           if (STORE_FLAG_VALUE == INTVAL (XEXP (if_info->a, 1)))
1250             subtract = 0, normalize = 0;
1251           else if (-STORE_FLAG_VALUE == INTVAL (XEXP (if_info->a, 1)))
1252             subtract = 1, normalize = 0;
1253           else
1254             subtract = 0, normalize = INTVAL (XEXP (if_info->a, 1));
1255
1256
1257           target = noce_emit_store_flag (if_info,
1258                                          gen_reg_rtx (GET_MODE (if_info->x)),
1259                                          1, normalize);
1260
1261           if (target)
1262             target = expand_simple_binop (GET_MODE (if_info->x),
1263                                           subtract ? MINUS : PLUS,
1264                                           if_info->b, target, if_info->x,
1265                                           0, OPTAB_WIDEN);
1266           if (target)
1267             {
1268               if (target != if_info->x)
1269                 noce_emit_move_insn (if_info->x, target);
1270
1271               seq = end_ifcvt_sequence (if_info);
1272               if (!seq)
1273                 return FALSE;
1274
1275               emit_insn_before_setloc (seq, if_info->jump,
1276                                        INSN_LOCATOR (if_info->insn_a));
1277               return TRUE;
1278             }
1279           end_sequence ();
1280         }
1281     }
1282
1283   return FALSE;
1284 }
1285
1286 /* Convert "if (test) x = 0;" to "x &= -(test == 0);"  */
1287
1288 static int
1289 noce_try_store_flag_mask (struct noce_if_info *if_info)
1290 {
1291   rtx target, seq;
1292   int reversep;
1293
1294   reversep = 0;
1295   if ((if_info->branch_cost >= 2
1296        || STORE_FLAG_VALUE == -1)
1297       && ((if_info->a == const0_rtx
1298            && rtx_equal_p (if_info->b, if_info->x))
1299           || ((reversep = (reversed_comparison_code (if_info->cond,
1300                                                      if_info->jump)
1301                            != UNKNOWN))
1302               && if_info->b == const0_rtx
1303               && rtx_equal_p (if_info->a, if_info->x))))
1304     {
1305       start_sequence ();
1306       target = noce_emit_store_flag (if_info,
1307                                      gen_reg_rtx (GET_MODE (if_info->x)),
1308                                      reversep, -1);
1309       if (target)
1310         target = expand_simple_binop (GET_MODE (if_info->x), AND,
1311                                       if_info->x,
1312                                       target, if_info->x, 0,
1313                                       OPTAB_WIDEN);
1314
1315       if (target)
1316         {
1317           if (target != if_info->x)
1318             noce_emit_move_insn (if_info->x, target);
1319
1320           seq = end_ifcvt_sequence (if_info);
1321           if (!seq)
1322             return FALSE;
1323
1324           emit_insn_before_setloc (seq, if_info->jump,
1325                                    INSN_LOCATOR (if_info->insn_a));
1326           return TRUE;
1327         }
1328
1329       end_sequence ();
1330     }
1331
1332   return FALSE;
1333 }
1334
1335 /* Helper function for noce_try_cmove and noce_try_cmove_arith.  */
1336
1337 static rtx
1338 noce_emit_cmove (struct noce_if_info *if_info, rtx x, enum rtx_code code,
1339                  rtx cmp_a, rtx cmp_b, rtx vfalse, rtx vtrue)
1340 {
1341   rtx target ATTRIBUTE_UNUSED;
1342   int unsignedp ATTRIBUTE_UNUSED;
1343
1344   /* If earliest == jump, try to build the cmove insn directly.
1345      This is helpful when combine has created some complex condition
1346      (like for alpha's cmovlbs) that we can't hope to regenerate
1347      through the normal interface.  */
1348
1349   if (if_info->cond_earliest == if_info->jump)
1350     {
1351       rtx tmp;
1352
1353       tmp = gen_rtx_fmt_ee (code, GET_MODE (if_info->cond), cmp_a, cmp_b);
1354       tmp = gen_rtx_IF_THEN_ELSE (GET_MODE (x), tmp, vtrue, vfalse);
1355       tmp = gen_rtx_SET (VOIDmode, x, tmp);
1356
1357       start_sequence ();
1358       tmp = emit_insn (tmp);
1359
1360       if (recog_memoized (tmp) >= 0)
1361         {
1362           tmp = get_insns ();
1363           end_sequence ();
1364           emit_insn (tmp);
1365
1366           return x;
1367         }
1368
1369       end_sequence ();
1370     }
1371
1372   /* Don't even try if the comparison operands are weird.  */
1373   if (! general_operand (cmp_a, GET_MODE (cmp_a))
1374       || ! general_operand (cmp_b, GET_MODE (cmp_b)))
1375     return NULL_RTX;
1376
1377 #if HAVE_conditional_move
1378   unsignedp = (code == LTU || code == GEU
1379                || code == LEU || code == GTU);
1380
1381   target = emit_conditional_move (x, code, cmp_a, cmp_b, VOIDmode,
1382                                   vtrue, vfalse, GET_MODE (x),
1383                                   unsignedp);
1384   if (target)
1385     return target;
1386
1387   /* We might be faced with a situation like:
1388
1389      x = (reg:M TARGET)
1390      vtrue = (subreg:M (reg:N VTRUE) BYTE)
1391      vfalse = (subreg:M (reg:N VFALSE) BYTE)
1392
1393      We can't do a conditional move in mode M, but it's possible that we
1394      could do a conditional move in mode N instead and take a subreg of
1395      the result.
1396
1397      If we can't create new pseudos, though, don't bother.  */
1398   if (reload_completed)
1399     return NULL_RTX;
1400
1401   if (GET_CODE (vtrue) == SUBREG && GET_CODE (vfalse) == SUBREG)
1402     {
1403       rtx reg_vtrue = SUBREG_REG (vtrue);
1404       rtx reg_vfalse = SUBREG_REG (vfalse);
1405       unsigned int byte_vtrue = SUBREG_BYTE (vtrue);
1406       unsigned int byte_vfalse = SUBREG_BYTE (vfalse);
1407       rtx promoted_target;
1408
1409       if (GET_MODE (reg_vtrue) != GET_MODE (reg_vfalse)
1410           || byte_vtrue != byte_vfalse
1411           || (SUBREG_PROMOTED_VAR_P (vtrue)
1412               != SUBREG_PROMOTED_VAR_P (vfalse))
1413           || (SUBREG_PROMOTED_UNSIGNED_P (vtrue)
1414               != SUBREG_PROMOTED_UNSIGNED_P (vfalse)))
1415         return NULL_RTX;
1416
1417       promoted_target = gen_reg_rtx (GET_MODE (reg_vtrue));
1418
1419       target = emit_conditional_move (promoted_target, code, cmp_a, cmp_b,
1420                                       VOIDmode, reg_vtrue, reg_vfalse,
1421                                       GET_MODE (reg_vtrue), unsignedp);
1422       /* Nope, couldn't do it in that mode either.  */
1423       if (!target)
1424         return NULL_RTX;
1425
1426       target = gen_rtx_SUBREG (GET_MODE (vtrue), promoted_target, byte_vtrue);
1427       SUBREG_PROMOTED_VAR_P (target) = SUBREG_PROMOTED_VAR_P (vtrue);
1428       SUBREG_PROMOTED_UNSIGNED_SET (target, SUBREG_PROMOTED_UNSIGNED_P (vtrue));
1429       emit_move_insn (x, target);
1430       return x;
1431     }
1432   else
1433     return NULL_RTX;
1434 #else
1435   /* We'll never get here, as noce_process_if_block doesn't call the
1436      functions involved.  Ifdef code, however, should be discouraged
1437      because it leads to typos in the code not selected.  However,
1438      emit_conditional_move won't exist either.  */
1439   return NULL_RTX;
1440 #endif
1441 }
1442
1443 /* Try only simple constants and registers here.  More complex cases
1444    are handled in noce_try_cmove_arith after noce_try_store_flag_arith
1445    has had a go at it.  */
1446
1447 static int
1448 noce_try_cmove (struct noce_if_info *if_info)
1449 {
1450   enum rtx_code code;
1451   rtx target, seq;
1452
1453   if ((CONSTANT_P (if_info->a) || register_operand (if_info->a, VOIDmode))
1454       && (CONSTANT_P (if_info->b) || register_operand (if_info->b, VOIDmode)))
1455     {
1456       start_sequence ();
1457
1458       code = GET_CODE (if_info->cond);
1459       target = noce_emit_cmove (if_info, if_info->x, code,
1460                                 XEXP (if_info->cond, 0),
1461                                 XEXP (if_info->cond, 1),
1462                                 if_info->a, if_info->b);
1463
1464       if (target)
1465         {
1466           if (target != if_info->x)
1467             noce_emit_move_insn (if_info->x, target);
1468
1469           seq = end_ifcvt_sequence (if_info);
1470           if (!seq)
1471             return FALSE;
1472
1473           emit_insn_before_setloc (seq, if_info->jump,
1474                                    INSN_LOCATOR (if_info->insn_a));
1475           return TRUE;
1476         }
1477       else
1478         {
1479           end_sequence ();
1480           return FALSE;
1481         }
1482     }
1483
1484   return FALSE;
1485 }
1486
1487 /* Try more complex cases involving conditional_move.  */
1488
1489 static int
1490 noce_try_cmove_arith (struct noce_if_info *if_info)
1491 {
1492   rtx a = if_info->a;
1493   rtx b = if_info->b;
1494   rtx x = if_info->x;
1495   rtx orig_a, orig_b;
1496   rtx insn_a, insn_b;
1497   rtx tmp, target;
1498   int is_mem = 0;
1499   int insn_cost;
1500   enum rtx_code code;
1501
1502   /* A conditional move from two memory sources is equivalent to a
1503      conditional on their addresses followed by a load.  Don't do this
1504      early because it'll screw alias analysis.  Note that we've
1505      already checked for no side effects.  */
1506   /* ??? FIXME: Magic number 5.  */
1507   if (cse_not_expected
1508       && MEM_P (a) && MEM_P (b)
1509       && MEM_ADDR_SPACE (a) == MEM_ADDR_SPACE (b)
1510       && if_info->branch_cost >= 5)
1511     {
1512       enum machine_mode address_mode
1513         = targetm.addr_space.address_mode (MEM_ADDR_SPACE (a));
1514
1515       a = XEXP (a, 0);
1516       b = XEXP (b, 0);
1517       x = gen_reg_rtx (address_mode);
1518       is_mem = 1;
1519     }
1520
1521   /* ??? We could handle this if we knew that a load from A or B could
1522      not fault.  This is also true if we've already loaded
1523      from the address along the path from ENTRY.  */
1524   else if (may_trap_p (a) || may_trap_p (b))
1525     return FALSE;
1526
1527   /* if (test) x = a + b; else x = c - d;
1528      => y = a + b;
1529         x = c - d;
1530         if (test)
1531           x = y;
1532   */
1533
1534   code = GET_CODE (if_info->cond);
1535   insn_a = if_info->insn_a;
1536   insn_b = if_info->insn_b;
1537
1538   /* Total insn_rtx_cost should be smaller than branch cost.  Exit
1539      if insn_rtx_cost can't be estimated.  */
1540   if (insn_a)
1541     {
1542       insn_cost
1543         = insn_rtx_cost (PATTERN (insn_a),
1544                          optimize_bb_for_speed_p (BLOCK_FOR_INSN (insn_a)));
1545       if (insn_cost == 0 || insn_cost > COSTS_N_INSNS (if_info->branch_cost))
1546         return FALSE;
1547     }
1548   else
1549     insn_cost = 0;
1550
1551   if (insn_b)
1552     {
1553       insn_cost
1554         += insn_rtx_cost (PATTERN (insn_b),
1555                           optimize_bb_for_speed_p (BLOCK_FOR_INSN (insn_b)));
1556       if (insn_cost == 0 || insn_cost > COSTS_N_INSNS (if_info->branch_cost))
1557         return FALSE;
1558     }
1559
1560   /* Possibly rearrange operands to make things come out more natural.  */
1561   if (reversed_comparison_code (if_info->cond, if_info->jump) != UNKNOWN)
1562     {
1563       int reversep = 0;
1564       if (rtx_equal_p (b, x))
1565         reversep = 1;
1566       else if (general_operand (b, GET_MODE (b)))
1567         reversep = 1;
1568
1569       if (reversep)
1570         {
1571           code = reversed_comparison_code (if_info->cond, if_info->jump);
1572           tmp = a, a = b, b = tmp;
1573           tmp = insn_a, insn_a = insn_b, insn_b = tmp;
1574         }
1575     }
1576
1577   start_sequence ();
1578
1579   orig_a = a;
1580   orig_b = b;
1581
1582   /* If either operand is complex, load it into a register first.
1583      The best way to do this is to copy the original insn.  In this
1584      way we preserve any clobbers etc that the insn may have had.
1585      This is of course not possible in the IS_MEM case.  */
1586   if (! general_operand (a, GET_MODE (a)))
1587     {
1588       rtx set;
1589
1590       if (is_mem)
1591         {
1592           tmp = gen_reg_rtx (GET_MODE (a));
1593           tmp = emit_insn (gen_rtx_SET (VOIDmode, tmp, a));
1594         }
1595       else if (! insn_a)
1596         goto end_seq_and_fail;
1597       else
1598         {
1599           a = gen_reg_rtx (GET_MODE (a));
1600           tmp = copy_rtx (insn_a);
1601           set = single_set (tmp);
1602           SET_DEST (set) = a;
1603           tmp = emit_insn (PATTERN (tmp));
1604         }
1605       if (recog_memoized (tmp) < 0)
1606         goto end_seq_and_fail;
1607     }
1608   if (! general_operand (b, GET_MODE (b)))
1609     {
1610       rtx set, last;
1611
1612       if (is_mem)
1613         {
1614           tmp = gen_reg_rtx (GET_MODE (b));
1615           tmp = gen_rtx_SET (VOIDmode, tmp, b);
1616         }
1617       else if (! insn_b)
1618         goto end_seq_and_fail;
1619       else
1620         {
1621           b = gen_reg_rtx (GET_MODE (b));
1622           tmp = copy_rtx (insn_b);
1623           set = single_set (tmp);
1624           SET_DEST (set) = b;
1625           tmp = PATTERN (tmp);
1626         }
1627
1628       /* If insn to set up A clobbers any registers B depends on, try to
1629          swap insn that sets up A with the one that sets up B.  If even
1630          that doesn't help, punt.  */
1631       last = get_last_insn ();
1632       if (last && modified_in_p (orig_b, last))
1633         {
1634           tmp = emit_insn_before (tmp, get_insns ());
1635           if (modified_in_p (orig_a, tmp))
1636             goto end_seq_and_fail;
1637         }
1638       else
1639         tmp = emit_insn (tmp);
1640
1641       if (recog_memoized (tmp) < 0)
1642         goto end_seq_and_fail;
1643     }
1644
1645   target = noce_emit_cmove (if_info, x, code, XEXP (if_info->cond, 0),
1646                             XEXP (if_info->cond, 1), a, b);
1647
1648   if (! target)
1649     goto end_seq_and_fail;
1650
1651   /* If we're handling a memory for above, emit the load now.  */
1652   if (is_mem)
1653     {
1654       tmp = gen_rtx_MEM (GET_MODE (if_info->x), target);
1655
1656       /* Copy over flags as appropriate.  */
1657       if (MEM_VOLATILE_P (if_info->a) || MEM_VOLATILE_P (if_info->b))
1658         MEM_VOLATILE_P (tmp) = 1;
1659       if (MEM_IN_STRUCT_P (if_info->a) && MEM_IN_STRUCT_P (if_info->b))
1660         MEM_IN_STRUCT_P (tmp) = 1;
1661       if (MEM_SCALAR_P (if_info->a) && MEM_SCALAR_P (if_info->b))
1662         MEM_SCALAR_P (tmp) = 1;
1663       if (MEM_ALIAS_SET (if_info->a) == MEM_ALIAS_SET (if_info->b))
1664         set_mem_alias_set (tmp, MEM_ALIAS_SET (if_info->a));
1665       set_mem_align (tmp,
1666                      MIN (MEM_ALIGN (if_info->a), MEM_ALIGN (if_info->b)));
1667
1668       gcc_assert (MEM_ADDR_SPACE (if_info->a) == MEM_ADDR_SPACE (if_info->b));
1669       set_mem_addr_space (tmp, MEM_ADDR_SPACE (if_info->a));
1670
1671       noce_emit_move_insn (if_info->x, tmp);
1672     }
1673   else if (target != x)
1674     noce_emit_move_insn (x, target);
1675
1676   tmp = end_ifcvt_sequence (if_info);
1677   if (!tmp)
1678     return FALSE;
1679
1680   emit_insn_before_setloc (tmp, if_info->jump, INSN_LOCATOR (if_info->insn_a));
1681   return TRUE;
1682
1683  end_seq_and_fail:
1684   end_sequence ();
1685   return FALSE;
1686 }
1687
1688 /* For most cases, the simplified condition we found is the best
1689    choice, but this is not the case for the min/max/abs transforms.
1690    For these we wish to know that it is A or B in the condition.  */
1691
1692 static rtx
1693 noce_get_alt_condition (struct noce_if_info *if_info, rtx target,
1694                         rtx *earliest)
1695 {
1696   rtx cond, set, insn;
1697   int reverse;
1698
1699   /* If target is already mentioned in the known condition, return it.  */
1700   if (reg_mentioned_p (target, if_info->cond))
1701     {
1702       *earliest = if_info->cond_earliest;
1703       return if_info->cond;
1704     }
1705
1706   set = pc_set (if_info->jump);
1707   cond = XEXP (SET_SRC (set), 0);
1708   reverse
1709     = GET_CODE (XEXP (SET_SRC (set), 2)) == LABEL_REF
1710       && XEXP (XEXP (SET_SRC (set), 2), 0) == JUMP_LABEL (if_info->jump);
1711   if (if_info->then_else_reversed)
1712     reverse = !reverse;
1713
1714   /* If we're looking for a constant, try to make the conditional
1715      have that constant in it.  There are two reasons why it may
1716      not have the constant we want:
1717
1718      1. GCC may have needed to put the constant in a register, because
1719         the target can't compare directly against that constant.  For
1720         this case, we look for a SET immediately before the comparison
1721         that puts a constant in that register.
1722
1723      2. GCC may have canonicalized the conditional, for example
1724         replacing "if x < 4" with "if x <= 3".  We can undo that (or
1725         make equivalent types of changes) to get the constants we need
1726         if they're off by one in the right direction.  */
1727
1728   if (CONST_INT_P (target))
1729     {
1730       enum rtx_code code = GET_CODE (if_info->cond);
1731       rtx op_a = XEXP (if_info->cond, 0);
1732       rtx op_b = XEXP (if_info->cond, 1);
1733       rtx prev_insn;
1734
1735       /* First, look to see if we put a constant in a register.  */
1736       prev_insn = prev_nonnote_insn (if_info->cond_earliest);
1737       if (prev_insn
1738           && BLOCK_FOR_INSN (prev_insn)
1739              == BLOCK_FOR_INSN (if_info->cond_earliest)
1740           && INSN_P (prev_insn)
1741           && GET_CODE (PATTERN (prev_insn)) == SET)
1742         {
1743           rtx src = find_reg_equal_equiv_note (prev_insn);
1744           if (!src)
1745             src = SET_SRC (PATTERN (prev_insn));
1746           if (CONST_INT_P (src))
1747             {
1748               if (rtx_equal_p (op_a, SET_DEST (PATTERN (prev_insn))))
1749                 op_a = src;
1750               else if (rtx_equal_p (op_b, SET_DEST (PATTERN (prev_insn))))
1751                 op_b = src;
1752
1753               if (CONST_INT_P (op_a))
1754                 {
1755                   rtx tmp = op_a;
1756                   op_a = op_b;
1757                   op_b = tmp;
1758                   code = swap_condition (code);
1759                 }
1760             }
1761         }
1762
1763       /* Now, look to see if we can get the right constant by
1764          adjusting the conditional.  */
1765       if (CONST_INT_P (op_b))
1766         {
1767           HOST_WIDE_INT desired_val = INTVAL (target);
1768           HOST_WIDE_INT actual_val = INTVAL (op_b);
1769
1770           switch (code)
1771             {
1772             case LT:
1773               if (actual_val == desired_val + 1)
1774                 {
1775                   code = LE;
1776                   op_b = GEN_INT (desired_val);
1777                 }
1778               break;
1779             case LE:
1780               if (actual_val == desired_val - 1)
1781                 {
1782                   code = LT;
1783                   op_b = GEN_INT (desired_val);
1784                 }
1785               break;
1786             case GT:
1787               if (actual_val == desired_val - 1)
1788                 {
1789                   code = GE;
1790                   op_b = GEN_INT (desired_val);
1791                 }
1792               break;
1793             case GE:
1794               if (actual_val == desired_val + 1)
1795                 {
1796                   code = GT;
1797                   op_b = GEN_INT (desired_val);
1798                 }
1799               break;
1800             default:
1801               break;
1802             }
1803         }
1804
1805       /* If we made any changes, generate a new conditional that is
1806          equivalent to what we started with, but has the right
1807          constants in it.  */
1808       if (code != GET_CODE (if_info->cond)
1809           || op_a != XEXP (if_info->cond, 0)
1810           || op_b != XEXP (if_info->cond, 1))
1811         {
1812           cond = gen_rtx_fmt_ee (code, GET_MODE (cond), op_a, op_b);
1813           *earliest = if_info->cond_earliest;
1814           return cond;
1815         }
1816     }
1817
1818   cond = canonicalize_condition (if_info->jump, cond, reverse,
1819                                  earliest, target, false, true);
1820   if (! cond || ! reg_mentioned_p (target, cond))
1821     return NULL;
1822
1823   /* We almost certainly searched back to a different place.
1824      Need to re-verify correct lifetimes.  */
1825
1826   /* X may not be mentioned in the range (cond_earliest, jump].  */
1827   for (insn = if_info->jump; insn != *earliest; insn = PREV_INSN (insn))
1828     if (INSN_P (insn) && reg_overlap_mentioned_p (if_info->x, PATTERN (insn)))
1829       return NULL;
1830
1831   /* A and B may not be modified in the range [cond_earliest, jump).  */
1832   for (insn = *earliest; insn != if_info->jump; insn = NEXT_INSN (insn))
1833     if (INSN_P (insn)
1834         && (modified_in_p (if_info->a, insn)
1835             || modified_in_p (if_info->b, insn)))
1836       return NULL;
1837
1838   return cond;
1839 }
1840
1841 /* Convert "if (a < b) x = a; else x = b;" to "x = min(a, b);", etc.  */
1842
1843 static int
1844 noce_try_minmax (struct noce_if_info *if_info)
1845 {
1846   rtx cond, earliest, target, seq;
1847   enum rtx_code code, op;
1848   int unsignedp;
1849
1850   /* ??? Reject modes with NaNs or signed zeros since we don't know how
1851      they will be resolved with an SMIN/SMAX.  It wouldn't be too hard
1852      to get the target to tell us...  */
1853   if (HONOR_SIGNED_ZEROS (GET_MODE (if_info->x))
1854       || HONOR_NANS (GET_MODE (if_info->x)))
1855     return FALSE;
1856
1857   cond = noce_get_alt_condition (if_info, if_info->a, &earliest);
1858   if (!cond)
1859     return FALSE;
1860
1861   /* Verify the condition is of the form we expect, and canonicalize
1862      the comparison code.  */
1863   code = GET_CODE (cond);
1864   if (rtx_equal_p (XEXP (cond, 0), if_info->a))
1865     {
1866       if (! rtx_equal_p (XEXP (cond, 1), if_info->b))
1867         return FALSE;
1868     }
1869   else if (rtx_equal_p (XEXP (cond, 1), if_info->a))
1870     {
1871       if (! rtx_equal_p (XEXP (cond, 0), if_info->b))
1872         return FALSE;
1873       code = swap_condition (code);
1874     }
1875   else
1876     return FALSE;
1877
1878   /* Determine what sort of operation this is.  Note that the code is for
1879      a taken branch, so the code->operation mapping appears backwards.  */
1880   switch (code)
1881     {
1882     case LT:
1883     case LE:
1884     case UNLT:
1885     case UNLE:
1886       op = SMAX;
1887       unsignedp = 0;
1888       break;
1889     case GT:
1890     case GE:
1891     case UNGT:
1892     case UNGE:
1893       op = SMIN;
1894       unsignedp = 0;
1895       break;
1896     case LTU:
1897     case LEU:
1898       op = UMAX;
1899       unsignedp = 1;
1900       break;
1901     case GTU:
1902     case GEU:
1903       op = UMIN;
1904       unsignedp = 1;
1905       break;
1906     default:
1907       return FALSE;
1908     }
1909
1910   start_sequence ();
1911
1912   target = expand_simple_binop (GET_MODE (if_info->x), op,
1913                                 if_info->a, if_info->b,
1914                                 if_info->x, unsignedp, OPTAB_WIDEN);
1915   if (! target)
1916     {
1917       end_sequence ();
1918       return FALSE;
1919     }
1920   if (target != if_info->x)
1921     noce_emit_move_insn (if_info->x, target);
1922
1923   seq = end_ifcvt_sequence (if_info);
1924   if (!seq)
1925     return FALSE;
1926
1927   emit_insn_before_setloc (seq, if_info->jump, INSN_LOCATOR (if_info->insn_a));
1928   if_info->cond = cond;
1929   if_info->cond_earliest = earliest;
1930
1931   return TRUE;
1932 }
1933
1934 /* Convert "if (a < 0) x = -a; else x = a;" to "x = abs(a);",
1935    "if (a < 0) x = ~a; else x = a;" to "x = one_cmpl_abs(a);",
1936    etc.  */
1937
1938 static int
1939 noce_try_abs (struct noce_if_info *if_info)
1940 {
1941   rtx cond, earliest, target, seq, a, b, c;
1942   int negate;
1943   bool one_cmpl = false;
1944
1945   /* Reject modes with signed zeros.  */
1946   if (HONOR_SIGNED_ZEROS (GET_MODE (if_info->x)))
1947     return FALSE;
1948
1949   /* Recognize A and B as constituting an ABS or NABS.  The canonical
1950      form is a branch around the negation, taken when the object is the
1951      first operand of a comparison against 0 that evaluates to true.  */
1952   a = if_info->a;
1953   b = if_info->b;
1954   if (GET_CODE (a) == NEG && rtx_equal_p (XEXP (a, 0), b))
1955     negate = 0;
1956   else if (GET_CODE (b) == NEG && rtx_equal_p (XEXP (b, 0), a))
1957     {
1958       c = a; a = b; b = c;
1959       negate = 1;
1960     }
1961   else if (GET_CODE (a) == NOT && rtx_equal_p (XEXP (a, 0), b))
1962     {
1963       negate = 0;
1964       one_cmpl = true;
1965     }
1966   else if (GET_CODE (b) == NOT && rtx_equal_p (XEXP (b, 0), a))
1967     {
1968       c = a; a = b; b = c;
1969       negate = 1;
1970       one_cmpl = true;
1971     }
1972   else
1973     return FALSE;
1974
1975   cond = noce_get_alt_condition (if_info, b, &earliest);
1976   if (!cond)
1977     return FALSE;
1978
1979   /* Verify the condition is of the form we expect.  */
1980   if (rtx_equal_p (XEXP (cond, 0), b))
1981     c = XEXP (cond, 1);
1982   else if (rtx_equal_p (XEXP (cond, 1), b))
1983     {
1984       c = XEXP (cond, 0);
1985       negate = !negate;
1986     }
1987   else
1988     return FALSE;
1989
1990   /* Verify that C is zero.  Search one step backward for a
1991      REG_EQUAL note or a simple source if necessary.  */
1992   if (REG_P (c))
1993     {
1994       rtx set, insn = prev_nonnote_insn (earliest);
1995       if (insn
1996           && BLOCK_FOR_INSN (insn) == BLOCK_FOR_INSN (earliest)
1997           && (set = single_set (insn))
1998           && rtx_equal_p (SET_DEST (set), c))
1999         {
2000           rtx note = find_reg_equal_equiv_note (insn);
2001           if (note)
2002             c = XEXP (note, 0);
2003           else
2004             c = SET_SRC (set);
2005         }
2006       else
2007         return FALSE;
2008     }
2009   if (MEM_P (c)
2010       && GET_CODE (XEXP (c, 0)) == SYMBOL_REF
2011       && CONSTANT_POOL_ADDRESS_P (XEXP (c, 0)))
2012     c = get_pool_constant (XEXP (c, 0));
2013
2014   /* Work around funny ideas get_condition has wrt canonicalization.
2015      Note that these rtx constants are known to be CONST_INT, and
2016      therefore imply integer comparisons.  */
2017   if (c == constm1_rtx && GET_CODE (cond) == GT)
2018     ;
2019   else if (c == const1_rtx && GET_CODE (cond) == LT)
2020     ;
2021   else if (c != CONST0_RTX (GET_MODE (b)))
2022     return FALSE;
2023
2024   /* Determine what sort of operation this is.  */
2025   switch (GET_CODE (cond))
2026     {
2027     case LT:
2028     case LE:
2029     case UNLT:
2030     case UNLE:
2031       negate = !negate;
2032       break;
2033     case GT:
2034     case GE:
2035     case UNGT:
2036     case UNGE:
2037       break;
2038     default:
2039       return FALSE;
2040     }
2041
2042   start_sequence ();
2043   if (one_cmpl)
2044     target = expand_one_cmpl_abs_nojump (GET_MODE (if_info->x), b,
2045                                          if_info->x);
2046   else
2047     target = expand_abs_nojump (GET_MODE (if_info->x), b, if_info->x, 1);
2048
2049   /* ??? It's a quandary whether cmove would be better here, especially
2050      for integers.  Perhaps combine will clean things up.  */
2051   if (target && negate)
2052     {
2053       if (one_cmpl)
2054         target = expand_simple_unop (GET_MODE (target), NOT, target,
2055                                      if_info->x, 0);
2056       else
2057         target = expand_simple_unop (GET_MODE (target), NEG, target,
2058                                      if_info->x, 0);
2059     }
2060
2061   if (! target)
2062     {
2063       end_sequence ();
2064       return FALSE;
2065     }
2066
2067   if (target != if_info->x)
2068     noce_emit_move_insn (if_info->x, target);
2069
2070   seq = end_ifcvt_sequence (if_info);
2071   if (!seq)
2072     return FALSE;
2073
2074   emit_insn_before_setloc (seq, if_info->jump, INSN_LOCATOR (if_info->insn_a));
2075   if_info->cond = cond;
2076   if_info->cond_earliest = earliest;
2077
2078   return TRUE;
2079 }
2080
2081 /* Convert "if (m < 0) x = b; else x = 0;" to "x = (m >> C) & b;".  */
2082
2083 static int
2084 noce_try_sign_mask (struct noce_if_info *if_info)
2085 {
2086   rtx cond, t, m, c, seq;
2087   enum machine_mode mode;
2088   enum rtx_code code;
2089   bool t_unconditional;
2090
2091   cond = if_info->cond;
2092   code = GET_CODE (cond);
2093   m = XEXP (cond, 0);
2094   c = XEXP (cond, 1);
2095
2096   t = NULL_RTX;
2097   if (if_info->a == const0_rtx)
2098     {
2099       if ((code == LT && c == const0_rtx)
2100           || (code == LE && c == constm1_rtx))
2101         t = if_info->b;
2102     }
2103   else if (if_info->b == const0_rtx)
2104     {
2105       if ((code == GE && c == const0_rtx)
2106           || (code == GT && c == constm1_rtx))
2107         t = if_info->a;
2108     }
2109
2110   if (! t || side_effects_p (t))
2111     return FALSE;
2112
2113   /* We currently don't handle different modes.  */
2114   mode = GET_MODE (t);
2115   if (GET_MODE (m) != mode)
2116     return FALSE;
2117
2118   /* This is only profitable if T is unconditionally executed/evaluated in the
2119      original insn sequence or T is cheap.  The former happens if B is the
2120      non-zero (T) value and if INSN_B was taken from TEST_BB, or there was no
2121      INSN_B which can happen for e.g. conditional stores to memory.  For the
2122      cost computation use the block TEST_BB where the evaluation will end up
2123      after the transformation.  */
2124   t_unconditional =
2125     (t == if_info->b
2126      && (if_info->insn_b == NULL_RTX
2127          || BLOCK_FOR_INSN (if_info->insn_b) == if_info->test_bb));
2128   if (!(t_unconditional
2129         || (rtx_cost (t, SET, optimize_bb_for_speed_p (if_info->test_bb))
2130             < COSTS_N_INSNS (2))))
2131     return FALSE;
2132
2133   start_sequence ();
2134   /* Use emit_store_flag to generate "m < 0 ? -1 : 0" instead of expanding
2135      "(signed) m >> 31" directly.  This benefits targets with specialized
2136      insns to obtain the signmask, but still uses ashr_optab otherwise.  */
2137   m = emit_store_flag (gen_reg_rtx (mode), LT, m, const0_rtx, mode, 0, -1);
2138   t = m ? expand_binop (mode, and_optab, m, t, NULL_RTX, 0, OPTAB_DIRECT)
2139         : NULL_RTX;
2140
2141   if (!t)
2142     {
2143       end_sequence ();
2144       return FALSE;
2145     }
2146
2147   noce_emit_move_insn (if_info->x, t);
2148
2149   seq = end_ifcvt_sequence (if_info);
2150   if (!seq)
2151     return FALSE;
2152
2153   emit_insn_before_setloc (seq, if_info->jump, INSN_LOCATOR (if_info->insn_a));
2154   return TRUE;
2155 }
2156
2157
2158 /* Optimize away "if (x & C) x |= C" and similar bit manipulation
2159    transformations.  */
2160
2161 static int
2162 noce_try_bitop (struct noce_if_info *if_info)
2163 {
2164   rtx cond, x, a, result, seq;
2165   enum machine_mode mode;
2166   enum rtx_code code;
2167   int bitnum;
2168
2169   x = if_info->x;
2170   cond = if_info->cond;
2171   code = GET_CODE (cond);
2172
2173   /* Check for no else condition.  */
2174   if (! rtx_equal_p (x, if_info->b))
2175     return FALSE;
2176
2177   /* Check for a suitable condition.  */
2178   if (code != NE && code != EQ)
2179     return FALSE;
2180   if (XEXP (cond, 1) != const0_rtx)
2181     return FALSE;
2182   cond = XEXP (cond, 0);
2183
2184   /* ??? We could also handle AND here.  */
2185   if (GET_CODE (cond) == ZERO_EXTRACT)
2186     {
2187       if (XEXP (cond, 1) != const1_rtx
2188           || !CONST_INT_P (XEXP (cond, 2))
2189           || ! rtx_equal_p (x, XEXP (cond, 0)))
2190         return FALSE;
2191       bitnum = INTVAL (XEXP (cond, 2));
2192       mode = GET_MODE (x);
2193       if (BITS_BIG_ENDIAN)
2194         bitnum = GET_MODE_BITSIZE (mode) - 1 - bitnum;
2195       if (bitnum < 0 || bitnum >= HOST_BITS_PER_WIDE_INT)
2196         return FALSE;
2197     }
2198   else
2199     return FALSE;
2200
2201   a = if_info->a;
2202   if (GET_CODE (a) == IOR || GET_CODE (a) == XOR)
2203     {
2204       /* Check for "if (X & C) x = x op C".  */
2205       if (! rtx_equal_p (x, XEXP (a, 0))
2206           || !CONST_INT_P (XEXP (a, 1))
2207           || (INTVAL (XEXP (a, 1)) & GET_MODE_MASK (mode))
2208              != (unsigned HOST_WIDE_INT) 1 << bitnum)
2209         return FALSE;
2210
2211       /* if ((x & C) == 0) x |= C; is transformed to x |= C.   */
2212       /* if ((x & C) != 0) x |= C; is transformed to nothing.  */
2213       if (GET_CODE (a) == IOR)
2214         result = (code == NE) ? a : NULL_RTX;
2215       else if (code == NE)
2216         {
2217           /* if ((x & C) == 0) x ^= C; is transformed to x |= C.   */
2218           result = gen_int_mode ((HOST_WIDE_INT) 1 << bitnum, mode);
2219           result = simplify_gen_binary (IOR, mode, x, result);
2220         }
2221       else
2222         {
2223           /* if ((x & C) != 0) x ^= C; is transformed to x &= ~C.  */
2224           result = gen_int_mode (~((HOST_WIDE_INT) 1 << bitnum), mode);
2225           result = simplify_gen_binary (AND, mode, x, result);
2226         }
2227     }
2228   else if (GET_CODE (a) == AND)
2229     {
2230       /* Check for "if (X & C) x &= ~C".  */
2231       if (! rtx_equal_p (x, XEXP (a, 0))
2232           || !CONST_INT_P (XEXP (a, 1))
2233           || (INTVAL (XEXP (a, 1)) & GET_MODE_MASK (mode))
2234              != (~((HOST_WIDE_INT) 1 << bitnum) & GET_MODE_MASK (mode)))
2235         return FALSE;
2236
2237       /* if ((x & C) == 0) x &= ~C; is transformed to nothing.  */
2238       /* if ((x & C) != 0) x &= ~C; is transformed to x &= ~C.  */
2239       result = (code == EQ) ? a : NULL_RTX;
2240     }
2241   else
2242     return FALSE;
2243
2244   if (result)
2245     {
2246       start_sequence ();
2247       noce_emit_move_insn (x, result);
2248       seq = end_ifcvt_sequence (if_info);
2249       if (!seq)
2250         return FALSE;
2251
2252       emit_insn_before_setloc (seq, if_info->jump,
2253                                INSN_LOCATOR (if_info->insn_a));
2254     }
2255   return TRUE;
2256 }
2257
2258
2259 /* Similar to get_condition, only the resulting condition must be
2260    valid at JUMP, instead of at EARLIEST.
2261
2262    If THEN_ELSE_REVERSED is true, the fallthrough does not go to the
2263    THEN block of the caller, and we have to reverse the condition.  */
2264
2265 static rtx
2266 noce_get_condition (rtx jump, rtx *earliest, bool then_else_reversed)
2267 {
2268   rtx cond, set, tmp;
2269   bool reverse;
2270
2271   if (! any_condjump_p (jump))
2272     return NULL_RTX;
2273
2274   set = pc_set (jump);
2275
2276   /* If this branches to JUMP_LABEL when the condition is false,
2277      reverse the condition.  */
2278   reverse = (GET_CODE (XEXP (SET_SRC (set), 2)) == LABEL_REF
2279              && XEXP (XEXP (SET_SRC (set), 2), 0) == JUMP_LABEL (jump));
2280
2281   /* We may have to reverse because the caller's if block is not canonical,
2282      i.e. the THEN block isn't the fallthrough block for the TEST block
2283      (see find_if_header).  */
2284   if (then_else_reversed)
2285     reverse = !reverse;
2286
2287   /* If the condition variable is a register and is MODE_INT, accept it.  */
2288
2289   cond = XEXP (SET_SRC (set), 0);
2290   tmp = XEXP (cond, 0);
2291   if (REG_P (tmp) && GET_MODE_CLASS (GET_MODE (tmp)) == MODE_INT)
2292     {
2293       *earliest = jump;
2294
2295       if (reverse)
2296         cond = gen_rtx_fmt_ee (reverse_condition (GET_CODE (cond)),
2297                                GET_MODE (cond), tmp, XEXP (cond, 1));
2298       return cond;
2299     }
2300
2301   /* Otherwise, fall back on canonicalize_condition to do the dirty
2302      work of manipulating MODE_CC values and COMPARE rtx codes.  */
2303   tmp = canonicalize_condition (jump, cond, reverse, earliest,
2304                                 NULL_RTX, false, true);
2305
2306   /* We don't handle side-effects in the condition, like handling
2307      REG_INC notes and making sure no duplicate conditions are emitted.  */
2308   if (tmp != NULL_RTX && side_effects_p (tmp))
2309     return NULL_RTX;
2310
2311   return tmp;
2312 }
2313
2314 /* Return true if OP is ok for if-then-else processing.  */
2315
2316 static int
2317 noce_operand_ok (const_rtx op)
2318 {
2319   /* We special-case memories, so handle any of them with
2320      no address side effects.  */
2321   if (MEM_P (op))
2322     return ! side_effects_p (XEXP (op, 0));
2323
2324   if (side_effects_p (op))
2325     return FALSE;
2326
2327   return ! may_trap_p (op);
2328 }
2329
2330 /* Return true if a write into MEM may trap or fault.  */
2331
2332 static bool
2333 noce_mem_write_may_trap_or_fault_p (const_rtx mem)
2334 {
2335   rtx addr;
2336
2337   if (MEM_READONLY_P (mem))
2338     return true;
2339
2340   if (may_trap_or_fault_p (mem))
2341     return true;
2342
2343   addr = XEXP (mem, 0);
2344
2345   /* Call target hook to avoid the effects of -fpic etc....  */
2346   addr = targetm.delegitimize_address (addr);
2347
2348   while (addr)
2349     switch (GET_CODE (addr))
2350       {
2351       case CONST:
2352       case PRE_DEC:
2353       case PRE_INC:
2354       case POST_DEC:
2355       case POST_INC:
2356       case POST_MODIFY:
2357         addr = XEXP (addr, 0);
2358         break;
2359       case LO_SUM:
2360       case PRE_MODIFY:
2361         addr = XEXP (addr, 1);
2362         break;
2363       case PLUS:
2364         if (CONST_INT_P (XEXP (addr, 1)))
2365           addr = XEXP (addr, 0);
2366         else
2367           return false;
2368         break;
2369       case LABEL_REF:
2370         return true;
2371       case SYMBOL_REF:
2372         if (SYMBOL_REF_DECL (addr)
2373             && decl_readonly_section (SYMBOL_REF_DECL (addr), 0))
2374           return true;
2375         return false;
2376       default:
2377         return false;
2378       }
2379
2380   return false;
2381 }
2382
2383 /* Return whether we can use store speculation for MEM.  TOP_BB is the
2384    basic block above the conditional block where we are considering
2385    doing the speculative store.  We look for whether MEM is set
2386    unconditionally later in the function.  */
2387
2388 static bool
2389 noce_can_store_speculate_p (basic_block top_bb, const_rtx mem)
2390 {
2391   basic_block dominator;
2392
2393   for (dominator = get_immediate_dominator (CDI_POST_DOMINATORS, top_bb);
2394        dominator != NULL;
2395        dominator = get_immediate_dominator (CDI_POST_DOMINATORS, dominator))
2396     {
2397       rtx insn;
2398
2399       FOR_BB_INSNS (dominator, insn)
2400         {
2401           /* If we see something that might be a memory barrier, we
2402              have to stop looking.  Even if the MEM is set later in
2403              the function, we still don't want to set it
2404              unconditionally before the barrier.  */
2405           if (INSN_P (insn)
2406               && (volatile_insn_p (PATTERN (insn))
2407                   || (CALL_P (insn) && (!RTL_CONST_CALL_P (insn)))))
2408             return false;
2409
2410           if (memory_modified_in_insn_p (mem, insn))
2411             return true;
2412           if (modified_in_p (XEXP (mem, 0), insn))
2413             return false;
2414
2415         }
2416     }
2417
2418   return false;
2419 }
2420
2421 /* Given a simple IF-THEN-JOIN or IF-THEN-ELSE-JOIN block, attempt to convert
2422    it without using conditional execution.  Return TRUE if we were successful
2423    at converting the block.  */
2424
2425 static int
2426 noce_process_if_block (struct noce_if_info *if_info)
2427 {
2428   basic_block test_bb = if_info->test_bb;       /* test block */
2429   basic_block then_bb = if_info->then_bb;       /* THEN */
2430   basic_block else_bb = if_info->else_bb;       /* ELSE or NULL */
2431   basic_block join_bb = if_info->join_bb;       /* JOIN */
2432   rtx jump = if_info->jump;
2433   rtx cond = if_info->cond;
2434   rtx insn_a, insn_b;
2435   rtx set_a, set_b;
2436   rtx orig_x, x, a, b;
2437
2438   /* We're looking for patterns of the form
2439
2440      (1) if (...) x = a; else x = b;
2441      (2) x = b; if (...) x = a;
2442      (3) if (...) x = a;   // as if with an initial x = x.
2443
2444      The later patterns require jumps to be more expensive.
2445
2446      ??? For future expansion, look for multiple X in such patterns.  */
2447
2448   /* Look for one of the potential sets.  */
2449   insn_a = first_active_insn (then_bb);
2450   if (! insn_a
2451       || insn_a != last_active_insn (then_bb, FALSE)
2452       || (set_a = single_set (insn_a)) == NULL_RTX)
2453     return FALSE;
2454
2455   x = SET_DEST (set_a);
2456   a = SET_SRC (set_a);
2457
2458   /* Look for the other potential set.  Make sure we've got equivalent
2459      destinations.  */
2460   /* ??? This is overconservative.  Storing to two different mems is
2461      as easy as conditionally computing the address.  Storing to a
2462      single mem merely requires a scratch memory to use as one of the
2463      destination addresses; often the memory immediately below the
2464      stack pointer is available for this.  */
2465   set_b = NULL_RTX;
2466   if (else_bb)
2467     {
2468       insn_b = first_active_insn (else_bb);
2469       if (! insn_b
2470           || insn_b != last_active_insn (else_bb, FALSE)
2471           || (set_b = single_set (insn_b)) == NULL_RTX
2472           || ! rtx_equal_p (x, SET_DEST (set_b)))
2473         return FALSE;
2474     }
2475   else
2476     {
2477       insn_b = prev_nonnote_nondebug_insn (if_info->cond_earliest);
2478       /* We're going to be moving the evaluation of B down from above
2479          COND_EARLIEST to JUMP.  Make sure the relevant data is still
2480          intact.  */
2481       if (! insn_b
2482           || BLOCK_FOR_INSN (insn_b) != BLOCK_FOR_INSN (if_info->cond_earliest)
2483           || !NONJUMP_INSN_P (insn_b)
2484           || (set_b = single_set (insn_b)) == NULL_RTX
2485           || ! rtx_equal_p (x, SET_DEST (set_b))
2486           || ! noce_operand_ok (SET_SRC (set_b))
2487           || reg_overlap_mentioned_p (x, SET_SRC (set_b))
2488           || modified_between_p (SET_SRC (set_b), insn_b, jump)
2489           /* Likewise with X.  In particular this can happen when
2490              noce_get_condition looks farther back in the instruction
2491              stream than one might expect.  */
2492           || reg_overlap_mentioned_p (x, cond)
2493           || reg_overlap_mentioned_p (x, a)
2494           || modified_between_p (x, insn_b, jump))
2495         insn_b = set_b = NULL_RTX;
2496     }
2497
2498   /* If x has side effects then only the if-then-else form is safe to
2499      convert.  But even in that case we would need to restore any notes
2500      (such as REG_INC) at then end.  That can be tricky if
2501      noce_emit_move_insn expands to more than one insn, so disable the
2502      optimization entirely for now if there are side effects.  */
2503   if (side_effects_p (x))
2504     return FALSE;
2505
2506   b = (set_b ? SET_SRC (set_b) : x);
2507
2508   /* Only operate on register destinations, and even then avoid extending
2509      the lifetime of hard registers on small register class machines.  */
2510   orig_x = x;
2511   if (!REG_P (x)
2512       || (HARD_REGISTER_P (x)
2513           && targetm.small_register_classes_for_mode_p (GET_MODE (x))))
2514     {
2515       if (GET_MODE (x) == BLKmode)
2516         return FALSE;
2517
2518       if (GET_CODE (x) == ZERO_EXTRACT
2519           && (!CONST_INT_P (XEXP (x, 1))
2520               || !CONST_INT_P (XEXP (x, 2))))
2521         return FALSE;
2522
2523       x = gen_reg_rtx (GET_MODE (GET_CODE (x) == STRICT_LOW_PART
2524                                  ? XEXP (x, 0) : x));
2525     }
2526
2527   /* Don't operate on sources that may trap or are volatile.  */
2528   if (! noce_operand_ok (a) || ! noce_operand_ok (b))
2529     return FALSE;
2530
2531  retry:
2532   /* Set up the info block for our subroutines.  */
2533   if_info->insn_a = insn_a;
2534   if_info->insn_b = insn_b;
2535   if_info->x = x;
2536   if_info->a = a;
2537   if_info->b = b;
2538
2539   /* Try optimizations in some approximation of a useful order.  */
2540   /* ??? Should first look to see if X is live incoming at all.  If it
2541      isn't, we don't need anything but an unconditional set.  */
2542
2543   /* Look and see if A and B are really the same.  Avoid creating silly
2544      cmove constructs that no one will fix up later.  */
2545   if (rtx_equal_p (a, b))
2546     {
2547       /* If we have an INSN_B, we don't have to create any new rtl.  Just
2548          move the instruction that we already have.  If we don't have an
2549          INSN_B, that means that A == X, and we've got a noop move.  In
2550          that case don't do anything and let the code below delete INSN_A.  */
2551       if (insn_b && else_bb)
2552         {
2553           rtx note;
2554
2555           if (else_bb && insn_b == BB_END (else_bb))
2556             BB_END (else_bb) = PREV_INSN (insn_b);
2557           reorder_insns (insn_b, insn_b, PREV_INSN (jump));
2558
2559           /* If there was a REG_EQUAL note, delete it since it may have been
2560              true due to this insn being after a jump.  */
2561           if ((note = find_reg_note (insn_b, REG_EQUAL, NULL_RTX)) != 0)
2562             remove_note (insn_b, note);
2563
2564           insn_b = NULL_RTX;
2565         }
2566       /* If we have "x = b; if (...) x = a;", and x has side-effects, then
2567          x must be executed twice.  */
2568       else if (insn_b && side_effects_p (orig_x))
2569         return FALSE;
2570
2571       x = orig_x;
2572       goto success;
2573     }
2574
2575   if (!set_b && MEM_P (orig_x))
2576     {
2577       /* Disallow the "if (...) x = a;" form (implicit "else x = x;")
2578          for optimizations if writing to x may trap or fault,
2579          i.e. it's a memory other than a static var or a stack slot,
2580          is misaligned on strict aligned machines or is read-only.  If
2581          x is a read-only memory, then the program is valid only if we
2582          avoid the store into it.  If there are stores on both the
2583          THEN and ELSE arms, then we can go ahead with the conversion;
2584          either the program is broken, or the condition is always
2585          false such that the other memory is selected.  */
2586       if (noce_mem_write_may_trap_or_fault_p (orig_x))
2587         return FALSE;
2588
2589       /* Avoid store speculation: given "if (...) x = a" where x is a
2590          MEM, we only want to do the store if x is always set
2591          somewhere in the function.  This avoids cases like
2592            if (pthread_mutex_trylock(mutex))
2593              ++global_variable;
2594          where we only want global_variable to be changed if the mutex
2595          is held.  FIXME: This should ideally be expressed directly in
2596          RTL somehow.  */
2597       if (!noce_can_store_speculate_p (test_bb, orig_x))
2598         return FALSE;
2599     }
2600
2601   if (noce_try_move (if_info))
2602     goto success;
2603   if (noce_try_store_flag (if_info))
2604     goto success;
2605   if (noce_try_bitop (if_info))
2606     goto success;
2607   if (noce_try_minmax (if_info))
2608     goto success;
2609   if (noce_try_abs (if_info))
2610     goto success;
2611   if (HAVE_conditional_move
2612       && noce_try_cmove (if_info))
2613     goto success;
2614   if (! targetm.have_conditional_execution ())
2615     {
2616       if (noce_try_store_flag_constants (if_info))
2617         goto success;
2618       if (noce_try_addcc (if_info))
2619         goto success;
2620       if (noce_try_store_flag_mask (if_info))
2621         goto success;
2622       if (HAVE_conditional_move
2623           && noce_try_cmove_arith (if_info))
2624         goto success;
2625       if (noce_try_sign_mask (if_info))
2626         goto success;
2627     }
2628
2629   if (!else_bb && set_b)
2630     {
2631       insn_b = set_b = NULL_RTX;
2632       b = orig_x;
2633       goto retry;
2634     }
2635
2636   return FALSE;
2637
2638  success:
2639
2640   /* If we used a temporary, fix it up now.  */
2641   if (orig_x != x)
2642     {
2643       rtx seq;
2644
2645       start_sequence ();
2646       noce_emit_move_insn (orig_x, x);
2647       seq = get_insns ();
2648       set_used_flags (orig_x);
2649       unshare_all_rtl_in_chain (seq);
2650       end_sequence ();
2651
2652       emit_insn_before_setloc (seq, BB_END (test_bb), INSN_LOCATOR (insn_a));
2653     }
2654
2655   /* The original THEN and ELSE blocks may now be removed.  The test block
2656      must now jump to the join block.  If the test block and the join block
2657      can be merged, do so.  */
2658   if (else_bb)
2659     {
2660       delete_basic_block (else_bb);
2661       num_true_changes++;
2662     }
2663   else
2664     remove_edge (find_edge (test_bb, join_bb));
2665
2666   remove_edge (find_edge (then_bb, join_bb));
2667   redirect_edge_and_branch_force (single_succ_edge (test_bb), join_bb);
2668   delete_basic_block (then_bb);
2669   num_true_changes++;
2670
2671   if (can_merge_blocks_p (test_bb, join_bb))
2672     {
2673       merge_blocks (test_bb, join_bb);
2674       num_true_changes++;
2675     }
2676
2677   num_updated_if_blocks++;
2678   return TRUE;
2679 }
2680
2681 /* Check whether a block is suitable for conditional move conversion.
2682    Every insn must be a simple set of a register to a constant or a
2683    register.  For each assignment, store the value in the array VALS,
2684    indexed by register number, then store the register number in
2685    REGS.  COND is the condition we will test.  */
2686
2687 static int
2688 check_cond_move_block (basic_block bb, rtx *vals, VEC (int, heap) **regs,
2689                        rtx cond)
2690 {
2691   rtx insn;
2692
2693    /* We can only handle simple jumps at the end of the basic block.
2694       It is almost impossible to update the CFG otherwise.  */
2695   insn = BB_END (bb);
2696   if (JUMP_P (insn) && !onlyjump_p (insn))
2697     return FALSE;
2698
2699   FOR_BB_INSNS (bb, insn)
2700     {
2701       rtx set, dest, src;
2702
2703       if (!NONDEBUG_INSN_P (insn) || JUMP_P (insn))
2704         continue;
2705       set = single_set (insn);
2706       if (!set)
2707         return FALSE;
2708
2709       dest = SET_DEST (set);
2710       src = SET_SRC (set);
2711       if (!REG_P (dest)
2712           || (HARD_REGISTER_P (dest)
2713               && targetm.small_register_classes_for_mode_p (GET_MODE (dest))))
2714         return FALSE;
2715
2716       if (!CONSTANT_P (src) && !register_operand (src, VOIDmode))
2717         return FALSE;
2718
2719       if (side_effects_p (src) || side_effects_p (dest))
2720         return FALSE;
2721
2722       if (may_trap_p (src) || may_trap_p (dest))
2723         return FALSE;
2724
2725       /* Don't try to handle this if the source register was
2726          modified earlier in the block.  */
2727       if ((REG_P (src)
2728            && vals[REGNO (src)] != NULL)
2729           || (GET_CODE (src) == SUBREG && REG_P (SUBREG_REG (src))
2730               && vals[REGNO (SUBREG_REG (src))] != NULL))
2731         return FALSE;
2732
2733       /* Don't try to handle this if the destination register was
2734          modified earlier in the block.  */
2735       if (vals[REGNO (dest)] != NULL)
2736         return FALSE;
2737
2738       /* Don't try to handle this if the condition uses the
2739          destination register.  */
2740       if (reg_overlap_mentioned_p (dest, cond))
2741         return FALSE;
2742
2743       /* Don't try to handle this if the source register is modified
2744          later in the block.  */
2745       if (!CONSTANT_P (src)
2746           && modified_between_p (src, insn, NEXT_INSN (BB_END (bb))))
2747         return FALSE;
2748
2749       vals[REGNO (dest)] = src;
2750
2751       VEC_safe_push (int, heap, *regs, REGNO (dest));
2752     }
2753
2754   return TRUE;
2755 }
2756
2757 /* Given a basic block BB suitable for conditional move conversion,
2758    a condition COND, and arrays THEN_VALS and ELSE_VALS containing the
2759    register values depending on COND, emit the insns in the block as
2760    conditional moves.  If ELSE_BLOCK is true, THEN_BB was already
2761    processed.  The caller has started a sequence for the conversion.
2762    Return true if successful, false if something goes wrong.  */
2763
2764 static bool
2765 cond_move_convert_if_block (struct noce_if_info *if_infop,
2766                             basic_block bb, rtx cond,
2767                             rtx *then_vals, rtx *else_vals,
2768                             bool else_block_p)
2769 {
2770   enum rtx_code code;
2771   rtx insn, cond_arg0, cond_arg1;
2772
2773   code = GET_CODE (cond);
2774   cond_arg0 = XEXP (cond, 0);
2775   cond_arg1 = XEXP (cond, 1);
2776
2777   FOR_BB_INSNS (bb, insn)
2778     {
2779       rtx set, target, dest, t, e;
2780       unsigned int regno;
2781
2782       /* ??? Maybe emit conditional debug insn?  */
2783       if (!NONDEBUG_INSN_P (insn) || JUMP_P (insn))
2784         continue;
2785       set = single_set (insn);
2786       gcc_assert (set && REG_P (SET_DEST (set)));
2787
2788       dest = SET_DEST (set);
2789       regno = REGNO (dest);
2790
2791       t = then_vals[regno];
2792       e = else_vals[regno];
2793
2794       if (else_block_p)
2795         {
2796           /* If this register was set in the then block, we already
2797              handled this case there.  */
2798           if (t)
2799             continue;
2800           t = dest;
2801           gcc_assert (e);
2802         }
2803       else
2804         {
2805           gcc_assert (t);
2806           if (!e)
2807             e = dest;
2808         }
2809
2810       target = noce_emit_cmove (if_infop, dest, code, cond_arg0, cond_arg1,
2811                                 t, e);
2812       if (!target)
2813         return false;
2814
2815       if (target != dest)
2816         noce_emit_move_insn (dest, target);
2817     }
2818
2819   return true;
2820 }
2821
2822 /* Given a simple IF-THEN-JOIN or IF-THEN-ELSE-JOIN block, attempt to convert
2823    it using only conditional moves.  Return TRUE if we were successful at
2824    converting the block.  */
2825
2826 static int
2827 cond_move_process_if_block (struct noce_if_info *if_info)
2828 {
2829   basic_block test_bb = if_info->test_bb;
2830   basic_block then_bb = if_info->then_bb;
2831   basic_block else_bb = if_info->else_bb;
2832   basic_block join_bb = if_info->join_bb;
2833   rtx jump = if_info->jump;
2834   rtx cond = if_info->cond;
2835   rtx seq, loc_insn;
2836   int max_reg, size, c, reg;
2837   rtx *then_vals;
2838   rtx *else_vals;
2839   VEC (int, heap) *then_regs = NULL;
2840   VEC (int, heap) *else_regs = NULL;
2841   unsigned int i;
2842
2843   /* Build a mapping for each block to the value used for each
2844      register.  */
2845   max_reg = max_reg_num ();
2846   size = (max_reg + 1) * sizeof (rtx);
2847   then_vals = (rtx *) alloca (size);
2848   else_vals = (rtx *) alloca (size);
2849   memset (then_vals, 0, size);
2850   memset (else_vals, 0, size);
2851
2852   /* Make sure the blocks are suitable.  */
2853   if (!check_cond_move_block (then_bb, then_vals, &then_regs, cond)
2854       || (else_bb
2855           && !check_cond_move_block (else_bb, else_vals, &else_regs, cond)))
2856     {
2857       VEC_free (int, heap, then_regs);
2858       VEC_free (int, heap, else_regs);
2859       return FALSE;
2860     }
2861
2862   /* Make sure the blocks can be used together.  If the same register
2863      is set in both blocks, and is not set to a constant in both
2864      cases, then both blocks must set it to the same register.  We
2865      have already verified that if it is set to a register, that the
2866      source register does not change after the assignment.  Also count
2867      the number of registers set in only one of the blocks.  */
2868   c = 0;
2869   FOR_EACH_VEC_ELT (int, then_regs, i, reg)
2870     {
2871       if (!then_vals[reg] && !else_vals[reg])
2872         continue;
2873
2874       if (!else_vals[reg])
2875         ++c;
2876       else
2877         {
2878           if (!CONSTANT_P (then_vals[reg])
2879               && !CONSTANT_P (else_vals[reg])
2880               && !rtx_equal_p (then_vals[reg], else_vals[reg]))
2881             {
2882               VEC_free (int, heap, then_regs);
2883               VEC_free (int, heap, else_regs);
2884               return FALSE;
2885             }
2886         }
2887     }
2888
2889   /* Finish off c for MAX_CONDITIONAL_EXECUTE.  */
2890   FOR_EACH_VEC_ELT (int, else_regs, i, reg)
2891     if (!then_vals[reg])
2892       ++c;
2893
2894   /* Make sure it is reasonable to convert this block.  What matters
2895      is the number of assignments currently made in only one of the
2896      branches, since if we convert we are going to always execute
2897      them.  */
2898   if (c > MAX_CONDITIONAL_EXECUTE)
2899     {
2900       VEC_free (int, heap, then_regs);
2901       VEC_free (int, heap, else_regs);
2902       return FALSE;
2903     }
2904
2905   /* Try to emit the conditional moves.  First do the then block,
2906      then do anything left in the else blocks.  */
2907   start_sequence ();
2908   if (!cond_move_convert_if_block (if_info, then_bb, cond,
2909                                    then_vals, else_vals, false)
2910       || (else_bb
2911           && !cond_move_convert_if_block (if_info, else_bb, cond,
2912                                           then_vals, else_vals, true)))
2913     {
2914       end_sequence ();
2915       VEC_free (int, heap, then_regs);
2916       VEC_free (int, heap, else_regs);
2917       return FALSE;
2918     }
2919   seq = end_ifcvt_sequence (if_info);
2920   if (!seq)
2921     {
2922       VEC_free (int, heap, then_regs);
2923       VEC_free (int, heap, else_regs);
2924       return FALSE;
2925     }
2926
2927   loc_insn = first_active_insn (then_bb);
2928   if (!loc_insn)
2929     {
2930       loc_insn = first_active_insn (else_bb);
2931       gcc_assert (loc_insn);
2932     }
2933   emit_insn_before_setloc (seq, jump, INSN_LOCATOR (loc_insn));
2934
2935   if (else_bb)
2936     {
2937       delete_basic_block (else_bb);
2938       num_true_changes++;
2939     }
2940   else
2941     remove_edge (find_edge (test_bb, join_bb));
2942
2943   remove_edge (find_edge (then_bb, join_bb));
2944   redirect_edge_and_branch_force (single_succ_edge (test_bb), join_bb);
2945   delete_basic_block (then_bb);
2946   num_true_changes++;
2947
2948   if (can_merge_blocks_p (test_bb, join_bb))
2949     {
2950       merge_blocks (test_bb, join_bb);
2951       num_true_changes++;
2952     }
2953
2954   num_updated_if_blocks++;
2955
2956   VEC_free (int, heap, then_regs);
2957   VEC_free (int, heap, else_regs);
2958   return TRUE;
2959 }
2960
2961 \f
2962 /* Determine if a given basic block heads a simple IF-THEN-JOIN or an
2963    IF-THEN-ELSE-JOIN block.
2964
2965    If so, we'll try to convert the insns to not require the branch,
2966    using only transformations that do not require conditional execution.
2967
2968    Return TRUE if we were successful at converting the block.  */
2969
2970 static int
2971 noce_find_if_block (basic_block test_bb, edge then_edge, edge else_edge,
2972                     int pass)
2973 {
2974   basic_block then_bb, else_bb, join_bb;
2975   bool then_else_reversed = false;
2976   rtx jump, cond;
2977   rtx cond_earliest;
2978   struct noce_if_info if_info;
2979
2980   /* We only ever should get here before reload.  */
2981   gcc_assert (!reload_completed);
2982
2983   /* Recognize an IF-THEN-ELSE-JOIN block.  */
2984   if (single_pred_p (then_edge->dest)
2985       && single_succ_p (then_edge->dest)
2986       && single_pred_p (else_edge->dest)
2987       && single_succ_p (else_edge->dest)
2988       && single_succ (then_edge->dest) == single_succ (else_edge->dest))
2989     {
2990       then_bb = then_edge->dest;
2991       else_bb = else_edge->dest;
2992       join_bb = single_succ (then_bb);
2993     }
2994   /* Recognize an IF-THEN-JOIN block.  */
2995   else if (single_pred_p (then_edge->dest)
2996            && single_succ_p (then_edge->dest)
2997            && single_succ (then_edge->dest) == else_edge->dest)
2998     {
2999       then_bb = then_edge->dest;
3000       else_bb = NULL_BLOCK;
3001       join_bb = else_edge->dest;
3002     }
3003   /* Recognize an IF-ELSE-JOIN block.  We can have those because the order
3004      of basic blocks in cfglayout mode does not matter, so the fallthrough
3005      edge can go to any basic block (and not just to bb->next_bb, like in
3006      cfgrtl mode).  */
3007   else if (single_pred_p (else_edge->dest)
3008            && single_succ_p (else_edge->dest)
3009            && single_succ (else_edge->dest) == then_edge->dest)
3010     {
3011       /* The noce transformations do not apply to IF-ELSE-JOIN blocks.
3012          To make this work, we have to invert the THEN and ELSE blocks
3013          and reverse the jump condition.  */
3014       then_bb = else_edge->dest;
3015       else_bb = NULL_BLOCK;
3016       join_bb = single_succ (then_bb);
3017       then_else_reversed = true;
3018     }
3019   else
3020     /* Not a form we can handle.  */
3021     return FALSE;
3022
3023   /* The edges of the THEN and ELSE blocks cannot have complex edges.  */
3024   if (single_succ_edge (then_bb)->flags & EDGE_COMPLEX)
3025     return FALSE;
3026   if (else_bb
3027       && single_succ_edge (else_bb)->flags & EDGE_COMPLEX)
3028     return FALSE;
3029
3030   num_possible_if_blocks++;
3031
3032   if (dump_file)
3033     {
3034       fprintf (dump_file,
3035                "\nIF-THEN%s-JOIN block found, pass %d, test %d, then %d",
3036                (else_bb) ? "-ELSE" : "",
3037                pass, test_bb->index, then_bb->index);
3038
3039       if (else_bb)
3040         fprintf (dump_file, ", else %d", else_bb->index);
3041
3042       fprintf (dump_file, ", join %d\n", join_bb->index);
3043     }
3044
3045   /* If the conditional jump is more than just a conditional
3046      jump, then we can not do if-conversion on this block.  */
3047   jump = BB_END (test_bb);
3048   if (! onlyjump_p (jump))
3049     return FALSE;
3050
3051   /* If this is not a standard conditional jump, we can't parse it.  */
3052   cond = noce_get_condition (jump, &cond_earliest, then_else_reversed);
3053   if (!cond)
3054     return FALSE;
3055
3056   /* We must be comparing objects whose modes imply the size.  */
3057   if (GET_MODE (XEXP (cond, 0)) == BLKmode)
3058     return FALSE;
3059
3060   /* Initialize an IF_INFO struct to pass around.  */
3061   memset (&if_info, 0, sizeof if_info);
3062   if_info.test_bb = test_bb;
3063   if_info.then_bb = then_bb;
3064   if_info.else_bb = else_bb;
3065   if_info.join_bb = join_bb;
3066   if_info.cond = cond;
3067   if_info.cond_earliest = cond_earliest;
3068   if_info.jump = jump;
3069   if_info.then_else_reversed = then_else_reversed;
3070   if_info.branch_cost = BRANCH_COST (optimize_bb_for_speed_p (test_bb),
3071                                      predictable_edge_p (then_edge));
3072
3073   /* Do the real work.  */
3074
3075   if (noce_process_if_block (&if_info))
3076     return TRUE;
3077
3078   if (HAVE_conditional_move
3079       && cond_move_process_if_block (&if_info))
3080     return TRUE;
3081
3082   return FALSE;
3083 }
3084 \f
3085
3086 /* Merge the blocks and mark for local life update.  */
3087
3088 static void
3089 merge_if_block (struct ce_if_block * ce_info)
3090 {
3091   basic_block test_bb = ce_info->test_bb;       /* last test block */
3092   basic_block then_bb = ce_info->then_bb;       /* THEN */
3093   basic_block else_bb = ce_info->else_bb;       /* ELSE or NULL */
3094   basic_block join_bb = ce_info->join_bb;       /* join block */
3095   basic_block combo_bb;
3096
3097   /* All block merging is done into the lower block numbers.  */
3098
3099   combo_bb = test_bb;
3100   df_set_bb_dirty (test_bb);
3101
3102   /* Merge any basic blocks to handle && and || subtests.  Each of
3103      the blocks are on the fallthru path from the predecessor block.  */
3104   if (ce_info->num_multiple_test_blocks > 0)
3105     {
3106       basic_block bb = test_bb;
3107       basic_block last_test_bb = ce_info->last_test_bb;
3108       basic_block fallthru = block_fallthru (bb);
3109
3110       do
3111         {
3112           bb = fallthru;
3113           fallthru = block_fallthru (bb);
3114           merge_blocks (combo_bb, bb);
3115           num_true_changes++;
3116         }
3117       while (bb != last_test_bb);
3118     }
3119
3120   /* Merge TEST block into THEN block.  Normally the THEN block won't have a
3121      label, but it might if there were || tests.  That label's count should be
3122      zero, and it normally should be removed.  */
3123
3124   if (then_bb)
3125     {
3126       merge_blocks (combo_bb, then_bb);
3127       num_true_changes++;
3128     }
3129
3130   /* The ELSE block, if it existed, had a label.  That label count
3131      will almost always be zero, but odd things can happen when labels
3132      get their addresses taken.  */
3133   if (else_bb)
3134     {
3135       merge_blocks (combo_bb, else_bb);
3136       num_true_changes++;
3137     }
3138
3139   /* If there was no join block reported, that means it was not adjacent
3140      to the others, and so we cannot merge them.  */
3141
3142   if (! join_bb)
3143     {
3144       rtx last = BB_END (combo_bb);
3145
3146       /* The outgoing edge for the current COMBO block should already
3147          be correct.  Verify this.  */
3148       if (EDGE_COUNT (combo_bb->succs) == 0)
3149         gcc_assert (find_reg_note (last, REG_NORETURN, NULL)
3150                     || (NONJUMP_INSN_P (last)
3151                         && GET_CODE (PATTERN (last)) == TRAP_IF
3152                         && (TRAP_CONDITION (PATTERN (last))
3153                             == const_true_rtx)));
3154
3155       else
3156       /* There should still be something at the end of the THEN or ELSE
3157          blocks taking us to our final destination.  */
3158         gcc_assert (JUMP_P (last)
3159                     || (EDGE_SUCC (combo_bb, 0)->dest == EXIT_BLOCK_PTR
3160                         && CALL_P (last)
3161                         && SIBLING_CALL_P (last))
3162                     || ((EDGE_SUCC (combo_bb, 0)->flags & EDGE_EH)
3163                         && can_throw_internal (last)));
3164     }
3165
3166   /* The JOIN block may have had quite a number of other predecessors too.
3167      Since we've already merged the TEST, THEN and ELSE blocks, we should
3168      have only one remaining edge from our if-then-else diamond.  If there
3169      is more than one remaining edge, it must come from elsewhere.  There
3170      may be zero incoming edges if the THEN block didn't actually join
3171      back up (as with a call to a non-return function).  */
3172   else if (EDGE_COUNT (join_bb->preds) < 2
3173            && join_bb != EXIT_BLOCK_PTR)
3174     {
3175       /* We can merge the JOIN cleanly and update the dataflow try
3176          again on this pass.*/
3177       merge_blocks (combo_bb, join_bb);
3178       num_true_changes++;
3179     }
3180   else
3181     {
3182       /* We cannot merge the JOIN.  */
3183
3184       /* The outgoing edge for the current COMBO block should already
3185          be correct.  Verify this.  */
3186       gcc_assert (single_succ_p (combo_bb)
3187                   && single_succ (combo_bb) == join_bb);
3188
3189       /* Remove the jump and cruft from the end of the COMBO block.  */
3190       if (join_bb != EXIT_BLOCK_PTR)
3191         tidy_fallthru_edge (single_succ_edge (combo_bb));
3192     }
3193
3194   num_updated_if_blocks++;
3195 }
3196 \f
3197 /* Find a block ending in a simple IF condition and try to transform it
3198    in some way.  When converting a multi-block condition, put the new code
3199    in the first such block and delete the rest.  Return a pointer to this
3200    first block if some transformation was done.  Return NULL otherwise.  */
3201
3202 static basic_block
3203 find_if_header (basic_block test_bb, int pass)
3204 {
3205   ce_if_block_t ce_info;
3206   edge then_edge;
3207   edge else_edge;
3208
3209   /* The kind of block we're looking for has exactly two successors.  */
3210   if (EDGE_COUNT (test_bb->succs) != 2)
3211     return NULL;
3212
3213   then_edge = EDGE_SUCC (test_bb, 0);
3214   else_edge = EDGE_SUCC (test_bb, 1);
3215
3216   if (df_get_bb_dirty (then_edge->dest))
3217     return NULL;
3218   if (df_get_bb_dirty (else_edge->dest))
3219     return NULL;
3220
3221   /* Neither edge should be abnormal.  */
3222   if ((then_edge->flags & EDGE_COMPLEX)
3223       || (else_edge->flags & EDGE_COMPLEX))
3224     return NULL;
3225
3226   /* Nor exit the loop.  */
3227   if ((then_edge->flags & EDGE_LOOP_EXIT)
3228       || (else_edge->flags & EDGE_LOOP_EXIT))
3229     return NULL;
3230
3231   /* The THEN edge is canonically the one that falls through.  */
3232   if (then_edge->flags & EDGE_FALLTHRU)
3233     ;
3234   else if (else_edge->flags & EDGE_FALLTHRU)
3235     {
3236       edge e = else_edge;
3237       else_edge = then_edge;
3238       then_edge = e;
3239     }
3240   else
3241     /* Otherwise this must be a multiway branch of some sort.  */
3242     return NULL;
3243
3244   memset (&ce_info, 0, sizeof (ce_info));
3245   ce_info.test_bb = test_bb;
3246   ce_info.then_bb = then_edge->dest;
3247   ce_info.else_bb = else_edge->dest;
3248   ce_info.pass = pass;
3249
3250 #ifdef IFCVT_INIT_EXTRA_FIELDS
3251   IFCVT_INIT_EXTRA_FIELDS (&ce_info);
3252 #endif
3253
3254   if (!reload_completed
3255       && noce_find_if_block (test_bb, then_edge, else_edge, pass))
3256     goto success;
3257
3258   if (reload_completed
3259       && targetm.have_conditional_execution ()
3260       && cond_exec_find_if_block (&ce_info))
3261     goto success;
3262
3263   if (HAVE_trap
3264       && optab_handler (ctrap_optab, word_mode) != CODE_FOR_nothing
3265       && find_cond_trap (test_bb, then_edge, else_edge))
3266     goto success;
3267
3268   if (dom_info_state (CDI_POST_DOMINATORS) >= DOM_NO_FAST_QUERY
3269       && (reload_completed || !targetm.have_conditional_execution ()))
3270     {
3271       if (find_if_case_1 (test_bb, then_edge, else_edge))
3272         goto success;
3273       if (find_if_case_2 (test_bb, then_edge, else_edge))
3274         goto success;
3275     }
3276
3277   return NULL;
3278
3279  success:
3280   if (dump_file)
3281     fprintf (dump_file, "Conversion succeeded on pass %d.\n", pass);
3282   /* Set this so we continue looking.  */
3283   cond_exec_changed_p = TRUE;
3284   return ce_info.test_bb;
3285 }
3286
3287 /* Return true if a block has two edges, one of which falls through to the next
3288    block, and the other jumps to a specific block, so that we can tell if the
3289    block is part of an && test or an || test.  Returns either -1 or the number
3290    of non-note, non-jump, non-USE/CLOBBER insns in the block.  */
3291
3292 static int
3293 block_jumps_and_fallthru_p (basic_block cur_bb, basic_block target_bb)
3294 {
3295   edge cur_edge;
3296   int fallthru_p = FALSE;
3297   int jump_p = FALSE;
3298   rtx insn;
3299   rtx end;
3300   int n_insns = 0;
3301   edge_iterator ei;
3302
3303   if (!cur_bb || !target_bb)
3304     return -1;
3305
3306   /* If no edges, obviously it doesn't jump or fallthru.  */
3307   if (EDGE_COUNT (cur_bb->succs) == 0)
3308     return FALSE;
3309
3310   FOR_EACH_EDGE (cur_edge, ei, cur_bb->succs)
3311     {
3312       if (cur_edge->flags & EDGE_COMPLEX)
3313         /* Anything complex isn't what we want.  */
3314         return -1;
3315
3316       else if (cur_edge->flags & EDGE_FALLTHRU)
3317         fallthru_p = TRUE;
3318
3319       else if (cur_edge->dest == target_bb)
3320         jump_p = TRUE;
3321
3322       else
3323         return -1;
3324     }
3325
3326   if ((jump_p & fallthru_p) == 0)
3327     return -1;
3328
3329   /* Don't allow calls in the block, since this is used to group && and ||
3330      together for conditional execution support.  ??? we should support
3331      conditional execution support across calls for IA-64 some day, but
3332      for now it makes the code simpler.  */
3333   end = BB_END (cur_bb);
3334   insn = BB_HEAD (cur_bb);
3335
3336   while (insn != NULL_RTX)
3337     {
3338       if (CALL_P (insn))
3339         return -1;
3340
3341       if (INSN_P (insn)
3342           && !JUMP_P (insn)
3343           && !DEBUG_INSN_P (insn)
3344           && GET_CODE (PATTERN (insn)) != USE
3345           && GET_CODE (PATTERN (insn)) != CLOBBER)
3346         n_insns++;
3347
3348       if (insn == end)
3349         break;
3350
3351       insn = NEXT_INSN (insn);
3352     }
3353
3354   return n_insns;
3355 }
3356
3357 /* Determine if a given basic block heads a simple IF-THEN or IF-THEN-ELSE
3358    block.  If so, we'll try to convert the insns to not require the branch.
3359    Return TRUE if we were successful at converting the block.  */
3360
3361 static int
3362 cond_exec_find_if_block (struct ce_if_block * ce_info)
3363 {
3364   basic_block test_bb = ce_info->test_bb;
3365   basic_block then_bb = ce_info->then_bb;
3366   basic_block else_bb = ce_info->else_bb;
3367   basic_block join_bb = NULL_BLOCK;
3368   edge cur_edge;
3369   basic_block next;
3370   edge_iterator ei;
3371
3372   ce_info->last_test_bb = test_bb;
3373
3374   /* We only ever should get here after reload,
3375      and if we have conditional execution.  */
3376   gcc_assert (reload_completed && targetm.have_conditional_execution ());
3377
3378   /* Discover if any fall through predecessors of the current test basic block
3379      were && tests (which jump to the else block) or || tests (which jump to
3380      the then block).  */
3381   if (single_pred_p (test_bb)
3382       && single_pred_edge (test_bb)->flags == EDGE_FALLTHRU)
3383     {
3384       basic_block bb = single_pred (test_bb);
3385       basic_block target_bb;
3386       int max_insns = MAX_CONDITIONAL_EXECUTE;
3387       int n_insns;
3388
3389       /* Determine if the preceding block is an && or || block.  */
3390       if ((n_insns = block_jumps_and_fallthru_p (bb, else_bb)) >= 0)
3391         {
3392           ce_info->and_and_p = TRUE;
3393           target_bb = else_bb;
3394         }
3395       else if ((n_insns = block_jumps_and_fallthru_p (bb, then_bb)) >= 0)
3396         {
3397           ce_info->and_and_p = FALSE;
3398           target_bb = then_bb;
3399         }
3400       else
3401         target_bb = NULL_BLOCK;
3402
3403       if (target_bb && n_insns <= max_insns)
3404         {
3405           int total_insns = 0;
3406           int blocks = 0;
3407
3408           ce_info->last_test_bb = test_bb;
3409
3410           /* Found at least one && or || block, look for more.  */
3411           do
3412             {
3413               ce_info->test_bb = test_bb = bb;
3414               total_insns += n_insns;
3415               blocks++;
3416
3417               if (!single_pred_p (bb))
3418                 break;
3419
3420               bb = single_pred (bb);
3421               n_insns = block_jumps_and_fallthru_p (bb, target_bb);
3422             }
3423           while (n_insns >= 0 && (total_insns + n_insns) <= max_insns);
3424
3425           ce_info->num_multiple_test_blocks = blocks;
3426           ce_info->num_multiple_test_insns = total_insns;
3427
3428           if (ce_info->and_and_p)
3429             ce_info->num_and_and_blocks = blocks;
3430           else
3431             ce_info->num_or_or_blocks = blocks;
3432         }
3433     }
3434
3435   /* The THEN block of an IF-THEN combo must have exactly one predecessor,
3436      other than any || blocks which jump to the THEN block.  */
3437   if ((EDGE_COUNT (then_bb->preds) - ce_info->num_or_or_blocks) != 1)
3438     return FALSE;
3439
3440   /* The edges of the THEN and ELSE blocks cannot have complex edges.  */
3441   FOR_EACH_EDGE (cur_edge, ei, then_bb->preds)
3442     {
3443       if (cur_edge->flags & EDGE_COMPLEX)
3444         return FALSE;
3445     }
3446
3447   FOR_EACH_EDGE (cur_edge, ei, else_bb->preds)
3448     {
3449       if (cur_edge->flags & EDGE_COMPLEX)
3450         return FALSE;
3451     }
3452
3453   /* The THEN block of an IF-THEN combo must have zero or one successors.  */
3454   if (EDGE_COUNT (then_bb->succs) > 0
3455       && (!single_succ_p (then_bb)
3456           || (single_succ_edge (then_bb)->flags & EDGE_COMPLEX)
3457           || (epilogue_completed
3458               && tablejump_p (BB_END (then_bb), NULL, NULL))))
3459     return FALSE;
3460
3461   /* If the THEN block has no successors, conditional execution can still
3462      make a conditional call.  Don't do this unless the ELSE block has
3463      only one incoming edge -- the CFG manipulation is too ugly otherwise.
3464      Check for the last insn of the THEN block being an indirect jump, which
3465      is listed as not having any successors, but confuses the rest of the CE
3466      code processing.  ??? we should fix this in the future.  */
3467   if (EDGE_COUNT (then_bb->succs) == 0)
3468     {
3469       if (single_pred_p (else_bb))
3470         {
3471           rtx last_insn = BB_END (then_bb);
3472
3473           while (last_insn
3474                  && NOTE_P (last_insn)
3475                  && last_insn != BB_HEAD (then_bb))
3476             last_insn = PREV_INSN (last_insn);
3477
3478           if (last_insn
3479               && JUMP_P (last_insn)
3480               && ! simplejump_p (last_insn))
3481             return FALSE;
3482
3483           join_bb = else_bb;
3484           else_bb = NULL_BLOCK;
3485         }
3486       else
3487         return FALSE;
3488     }
3489
3490   /* If the THEN block's successor is the other edge out of the TEST block,
3491      then we have an IF-THEN combo without an ELSE.  */
3492   else if (single_succ (then_bb) == else_bb)
3493     {
3494       join_bb = else_bb;
3495       else_bb = NULL_BLOCK;
3496     }
3497
3498   /* If the THEN and ELSE block meet in a subsequent block, and the ELSE
3499      has exactly one predecessor and one successor, and the outgoing edge
3500      is not complex, then we have an IF-THEN-ELSE combo.  */
3501   else if (single_succ_p (else_bb)
3502            && single_succ (then_bb) == single_succ (else_bb)
3503            && single_pred_p (else_bb)
3504            && !(single_succ_edge (else_bb)->flags & EDGE_COMPLEX)
3505            && !(epilogue_completed
3506                 && tablejump_p (BB_END (else_bb), NULL, NULL)))
3507     join_bb = single_succ (else_bb);
3508
3509   /* Otherwise it is not an IF-THEN or IF-THEN-ELSE combination.  */
3510   else
3511     return FALSE;
3512
3513   num_possible_if_blocks++;
3514
3515   if (dump_file)
3516     {
3517       fprintf (dump_file,
3518                "\nIF-THEN%s block found, pass %d, start block %d "
3519                "[insn %d], then %d [%d]",
3520                (else_bb) ? "-ELSE" : "",
3521                ce_info->pass,
3522                test_bb->index,
3523                BB_HEAD (test_bb) ? (int)INSN_UID (BB_HEAD (test_bb)) : -1,
3524                then_bb->index,
3525                BB_HEAD (then_bb) ? (int)INSN_UID (BB_HEAD (then_bb)) : -1);
3526
3527       if (else_bb)
3528         fprintf (dump_file, ", else %d [%d]",
3529                  else_bb->index,
3530                  BB_HEAD (else_bb) ? (int)INSN_UID (BB_HEAD (else_bb)) : -1);
3531
3532       fprintf (dump_file, ", join %d [%d]",
3533                join_bb->index,
3534                BB_HEAD (join_bb) ? (int)INSN_UID (BB_HEAD (join_bb)) : -1);
3535
3536       if (ce_info->num_multiple_test_blocks > 0)
3537         fprintf (dump_file, ", %d %s block%s last test %d [%d]",
3538                  ce_info->num_multiple_test_blocks,
3539                  (ce_info->and_and_p) ? "&&" : "||",
3540                  (ce_info->num_multiple_test_blocks == 1) ? "" : "s",
3541                  ce_info->last_test_bb->index,
3542                  ((BB_HEAD (ce_info->last_test_bb))
3543                   ? (int)INSN_UID (BB_HEAD (ce_info->last_test_bb))
3544                   : -1));
3545
3546       fputc ('\n', dump_file);
3547     }
3548
3549   /* Make sure IF, THEN, and ELSE, blocks are adjacent.  Actually, we get the
3550      first condition for free, since we've already asserted that there's a
3551      fallthru edge from IF to THEN.  Likewise for the && and || blocks, since
3552      we checked the FALLTHRU flag, those are already adjacent to the last IF
3553      block.  */
3554   /* ??? As an enhancement, move the ELSE block.  Have to deal with
3555      BLOCK notes, if by no other means than backing out the merge if they
3556      exist.  Sticky enough I don't want to think about it now.  */
3557   next = then_bb;
3558   if (else_bb && (next = next->next_bb) != else_bb)
3559     return FALSE;
3560   if ((next = next->next_bb) != join_bb && join_bb != EXIT_BLOCK_PTR)
3561     {
3562       if (else_bb)
3563         join_bb = NULL;
3564       else
3565         return FALSE;
3566     }
3567
3568   /* Do the real work.  */
3569
3570   ce_info->else_bb = else_bb;
3571   ce_info->join_bb = join_bb;
3572
3573   /* If we have && and || tests, try to first handle combining the && and ||
3574      tests into the conditional code, and if that fails, go back and handle
3575      it without the && and ||, which at present handles the && case if there
3576      was no ELSE block.  */
3577   if (cond_exec_process_if_block (ce_info, TRUE))
3578     return TRUE;
3579
3580   if (ce_info->num_multiple_test_blocks)
3581     {
3582       cancel_changes (0);
3583
3584       if (cond_exec_process_if_block (ce_info, FALSE))
3585         return TRUE;
3586     }
3587
3588   return FALSE;
3589 }
3590
3591 /* Convert a branch over a trap, or a branch
3592    to a trap, into a conditional trap.  */
3593
3594 static int
3595 find_cond_trap (basic_block test_bb, edge then_edge, edge else_edge)
3596 {
3597   basic_block then_bb = then_edge->dest;
3598   basic_block else_bb = else_edge->dest;
3599   basic_block other_bb, trap_bb;
3600   rtx trap, jump, cond, cond_earliest, seq;
3601   enum rtx_code code;
3602
3603   /* Locate the block with the trap instruction.  */
3604   /* ??? While we look for no successors, we really ought to allow
3605      EH successors.  Need to fix merge_if_block for that to work.  */
3606   if ((trap = block_has_only_trap (then_bb)) != NULL)
3607     trap_bb = then_bb, other_bb = else_bb;
3608   else if ((trap = block_has_only_trap (else_bb)) != NULL)
3609     trap_bb = else_bb, other_bb = then_bb;
3610   else
3611     return FALSE;
3612
3613   if (dump_file)
3614     {
3615       fprintf (dump_file, "\nTRAP-IF block found, start %d, trap %d\n",
3616                test_bb->index, trap_bb->index);
3617     }
3618
3619   /* If this is not a standard conditional jump, we can't parse it.  */
3620   jump = BB_END (test_bb);
3621   cond = noce_get_condition (jump, &cond_earliest, false);
3622   if (! cond)
3623     return FALSE;
3624
3625   /* If the conditional jump is more than just a conditional jump, then
3626      we can not do if-conversion on this block.  */
3627   if (! onlyjump_p (jump))
3628     return FALSE;
3629
3630   /* We must be comparing objects whose modes imply the size.  */
3631   if (GET_MODE (XEXP (cond, 0)) == BLKmode)
3632     return FALSE;
3633
3634   /* Reverse the comparison code, if necessary.  */
3635   code = GET_CODE (cond);
3636   if (then_bb == trap_bb)
3637     {
3638       code = reversed_comparison_code (cond, jump);
3639       if (code == UNKNOWN)
3640         return FALSE;
3641     }
3642
3643   /* Attempt to generate the conditional trap.  */
3644   seq = gen_cond_trap (code, copy_rtx (XEXP (cond, 0)),
3645                        copy_rtx (XEXP (cond, 1)),
3646                        TRAP_CODE (PATTERN (trap)));
3647   if (seq == NULL)
3648     return FALSE;
3649
3650   /* Emit the new insns before cond_earliest.  */
3651   emit_insn_before_setloc (seq, cond_earliest, INSN_LOCATOR (trap));
3652
3653   /* Delete the trap block if possible.  */
3654   remove_edge (trap_bb == then_bb ? then_edge : else_edge);
3655   df_set_bb_dirty (test_bb);
3656   df_set_bb_dirty (then_bb);
3657   df_set_bb_dirty (else_bb);
3658
3659   if (EDGE_COUNT (trap_bb->preds) == 0)
3660     {
3661       delete_basic_block (trap_bb);
3662       num_true_changes++;
3663     }
3664
3665   /* Wire together the blocks again.  */
3666   if (current_ir_type () == IR_RTL_CFGLAYOUT)
3667     single_succ_edge (test_bb)->flags |= EDGE_FALLTHRU;
3668   else
3669     {
3670       rtx lab, newjump;
3671
3672       lab = JUMP_LABEL (jump);
3673       newjump = emit_jump_insn_after (gen_jump (lab), jump);
3674       LABEL_NUSES (lab) += 1;
3675       JUMP_LABEL (newjump) = lab;
3676       emit_barrier_after (newjump);
3677     }
3678   delete_insn (jump);
3679
3680   if (can_merge_blocks_p (test_bb, other_bb))
3681     {
3682       merge_blocks (test_bb, other_bb);
3683       num_true_changes++;
3684     }
3685
3686   num_updated_if_blocks++;
3687   return TRUE;
3688 }
3689
3690 /* Subroutine of find_cond_trap: if BB contains only a trap insn,
3691    return it.  */
3692
3693 static rtx
3694 block_has_only_trap (basic_block bb)
3695 {
3696   rtx trap;
3697
3698   /* We're not the exit block.  */
3699   if (bb == EXIT_BLOCK_PTR)
3700     return NULL_RTX;
3701
3702   /* The block must have no successors.  */
3703   if (EDGE_COUNT (bb->succs) > 0)
3704     return NULL_RTX;
3705
3706   /* The only instruction in the THEN block must be the trap.  */
3707   trap = first_active_insn (bb);
3708   if (! (trap == BB_END (bb)
3709          && GET_CODE (PATTERN (trap)) == TRAP_IF
3710          && TRAP_CONDITION (PATTERN (trap)) == const_true_rtx))
3711     return NULL_RTX;
3712
3713   return trap;
3714 }
3715
3716 /* Look for IF-THEN-ELSE cases in which one of THEN or ELSE is
3717    transformable, but not necessarily the other.  There need be no
3718    JOIN block.
3719
3720    Return TRUE if we were successful at converting the block.
3721
3722    Cases we'd like to look at:
3723
3724    (1)
3725         if (test) goto over; // x not live
3726         x = a;
3727         goto label;
3728         over:
3729
3730    becomes
3731
3732         x = a;
3733         if (! test) goto label;
3734
3735    (2)
3736         if (test) goto E; // x not live
3737         x = big();
3738         goto L;
3739         E:
3740         x = b;
3741         goto M;
3742
3743    becomes
3744
3745         x = b;
3746         if (test) goto M;
3747         x = big();
3748         goto L;
3749
3750    (3) // This one's really only interesting for targets that can do
3751        // multiway branching, e.g. IA-64 BBB bundles.  For other targets
3752        // it results in multiple branches on a cache line, which often
3753        // does not sit well with predictors.
3754
3755         if (test1) goto E; // predicted not taken
3756         x = a;
3757         if (test2) goto F;
3758         ...
3759         E:
3760         x = b;
3761         J:
3762
3763    becomes
3764
3765         x = a;
3766         if (test1) goto E;
3767         if (test2) goto F;
3768
3769    Notes:
3770
3771    (A) Don't do (2) if the branch is predicted against the block we're
3772    eliminating.  Do it anyway if we can eliminate a branch; this requires
3773    that the sole successor of the eliminated block postdominate the other
3774    side of the if.
3775
3776    (B) With CE, on (3) we can steal from both sides of the if, creating
3777
3778         if (test1) x = a;
3779         if (!test1) x = b;
3780         if (test1) goto J;
3781         if (test2) goto F;
3782         ...
3783         J:
3784
3785    Again, this is most useful if J postdominates.
3786
3787    (C) CE substitutes for helpful life information.
3788
3789    (D) These heuristics need a lot of work.  */
3790
3791 /* Tests for case 1 above.  */
3792
3793 static int
3794 find_if_case_1 (basic_block test_bb, edge then_edge, edge else_edge)
3795 {
3796   basic_block then_bb = then_edge->dest;
3797   basic_block else_bb = else_edge->dest;
3798   basic_block new_bb;
3799   int then_bb_index;
3800
3801   /* If we are partitioning hot/cold basic blocks, we don't want to
3802      mess up unconditional or indirect jumps that cross between hot
3803      and cold sections.
3804
3805      Basic block partitioning may result in some jumps that appear to
3806      be optimizable (or blocks that appear to be mergeable), but which really
3807      must be left untouched (they are required to make it safely across
3808      partition boundaries).  See  the comments at the top of
3809      bb-reorder.c:partition_hot_cold_basic_blocks for complete details.  */
3810
3811   if ((BB_END (then_bb)
3812        && find_reg_note (BB_END (then_bb), REG_CROSSING_JUMP, NULL_RTX))
3813       || (BB_END (test_bb)
3814           && find_reg_note (BB_END (test_bb), REG_CROSSING_JUMP, NULL_RTX))
3815       || (BB_END (else_bb)
3816           && find_reg_note (BB_END (else_bb), REG_CROSSING_JUMP,
3817                             NULL_RTX)))
3818     return FALSE;
3819
3820   /* THEN has one successor.  */
3821   if (!single_succ_p (then_bb))
3822     return FALSE;
3823
3824   /* THEN does not fall through, but is not strange either.  */
3825   if (single_succ_edge (then_bb)->flags & (EDGE_COMPLEX | EDGE_FALLTHRU))
3826     return FALSE;
3827
3828   /* THEN has one predecessor.  */
3829   if (!single_pred_p (then_bb))
3830     return FALSE;
3831
3832   /* THEN must do something.  */
3833   if (forwarder_block_p (then_bb))
3834     return FALSE;
3835
3836   num_possible_if_blocks++;
3837   if (dump_file)
3838     fprintf (dump_file,
3839              "\nIF-CASE-1 found, start %d, then %d\n",
3840              test_bb->index, then_bb->index);
3841
3842   /* THEN is small.  */
3843   if (! cheap_bb_rtx_cost_p (then_bb,
3844         COSTS_N_INSNS (BRANCH_COST (optimize_bb_for_speed_p (then_edge->src),
3845                                     predictable_edge_p (then_edge)))))
3846     return FALSE;
3847
3848   /* Registers set are dead, or are predicable.  */
3849   if (! dead_or_predicable (test_bb, then_bb, else_bb,
3850                             single_succ_edge (then_bb), 1))
3851     return FALSE;
3852
3853   /* Conversion went ok, including moving the insns and fixing up the
3854      jump.  Adjust the CFG to match.  */
3855
3856   /* We can avoid creating a new basic block if then_bb is immediately
3857      followed by else_bb, i.e. deleting then_bb allows test_bb to fall
3858      thru to else_bb.  */
3859
3860   if (then_bb->next_bb == else_bb
3861       && then_bb->prev_bb == test_bb
3862       && else_bb != EXIT_BLOCK_PTR)
3863     {
3864       redirect_edge_succ (FALLTHRU_EDGE (test_bb), else_bb);
3865       new_bb = 0;
3866     }
3867   else
3868     new_bb = redirect_edge_and_branch_force (FALLTHRU_EDGE (test_bb),
3869                                              else_bb);
3870
3871   df_set_bb_dirty (test_bb);
3872   df_set_bb_dirty (else_bb);
3873
3874   then_bb_index = then_bb->index;
3875   delete_basic_block (then_bb);
3876
3877   /* Make rest of code believe that the newly created block is the THEN_BB
3878      block we removed.  */
3879   if (new_bb)
3880     {
3881       df_bb_replace (then_bb_index, new_bb);
3882       /* Since the fallthru edge was redirected from test_bb to new_bb,
3883          we need to ensure that new_bb is in the same partition as
3884          test bb (you can not fall through across section boundaries).  */
3885       BB_COPY_PARTITION (new_bb, test_bb);
3886     }
3887
3888   num_true_changes++;
3889   num_updated_if_blocks++;
3890
3891   return TRUE;
3892 }
3893
3894 /* Test for case 2 above.  */
3895
3896 static int
3897 find_if_case_2 (basic_block test_bb, edge then_edge, edge else_edge)
3898 {
3899   basic_block then_bb = then_edge->dest;
3900   basic_block else_bb = else_edge->dest;
3901   edge else_succ;
3902   rtx note;
3903
3904   /* If we are partitioning hot/cold basic blocks, we don't want to
3905      mess up unconditional or indirect jumps that cross between hot
3906      and cold sections.
3907
3908      Basic block partitioning may result in some jumps that appear to
3909      be optimizable (or blocks that appear to be mergeable), but which really
3910      must be left untouched (they are required to make it safely across
3911      partition boundaries).  See  the comments at the top of
3912      bb-reorder.c:partition_hot_cold_basic_blocks for complete details.  */
3913
3914   if ((BB_END (then_bb)
3915        && find_reg_note (BB_END (then_bb), REG_CROSSING_JUMP, NULL_RTX))
3916       || (BB_END (test_bb)
3917           && find_reg_note (BB_END (test_bb), REG_CROSSING_JUMP, NULL_RTX))
3918       || (BB_END (else_bb)
3919           && find_reg_note (BB_END (else_bb), REG_CROSSING_JUMP,
3920                             NULL_RTX)))
3921     return FALSE;
3922
3923   /* ELSE has one successor.  */
3924   if (!single_succ_p (else_bb))
3925     return FALSE;
3926   else
3927     else_succ = single_succ_edge (else_bb);
3928
3929   /* ELSE outgoing edge is not complex.  */
3930   if (else_succ->flags & EDGE_COMPLEX)
3931     return FALSE;
3932
3933   /* ELSE has one predecessor.  */
3934   if (!single_pred_p (else_bb))
3935     return FALSE;
3936
3937   /* THEN is not EXIT.  */
3938   if (then_bb->index < NUM_FIXED_BLOCKS)
3939     return FALSE;
3940
3941   /* ELSE is predicted or SUCC(ELSE) postdominates THEN.  */
3942   note = find_reg_note (BB_END (test_bb), REG_BR_PROB, NULL_RTX);
3943   if (note && INTVAL (XEXP (note, 0)) >= REG_BR_PROB_BASE / 2)
3944     ;
3945   else if (else_succ->dest->index < NUM_FIXED_BLOCKS
3946            || dominated_by_p (CDI_POST_DOMINATORS, then_bb,
3947                               else_succ->dest))
3948     ;
3949   else
3950     return FALSE;
3951
3952   num_possible_if_blocks++;
3953   if (dump_file)
3954     fprintf (dump_file,
3955              "\nIF-CASE-2 found, start %d, else %d\n",
3956              test_bb->index, else_bb->index);
3957
3958   /* ELSE is small.  */
3959   if (! cheap_bb_rtx_cost_p (else_bb,
3960         COSTS_N_INSNS (BRANCH_COST (optimize_bb_for_speed_p (else_edge->src),
3961                                     predictable_edge_p (else_edge)))))
3962     return FALSE;
3963
3964   /* Registers set are dead, or are predicable.  */
3965   if (! dead_or_predicable (test_bb, else_bb, then_bb, else_succ, 0))
3966     return FALSE;
3967
3968   /* Conversion went ok, including moving the insns and fixing up the
3969      jump.  Adjust the CFG to match.  */
3970
3971   df_set_bb_dirty (test_bb);
3972   df_set_bb_dirty (then_bb);
3973   delete_basic_block (else_bb);
3974
3975   num_true_changes++;
3976   num_updated_if_blocks++;
3977
3978   /* ??? We may now fallthru from one of THEN's successors into a join
3979      block.  Rerun cleanup_cfg?  Examine things manually?  Wait?  */
3980
3981   return TRUE;
3982 }
3983
3984 /* Used by the code above to perform the actual rtl transformations.
3985    Return TRUE if successful.
3986
3987    TEST_BB is the block containing the conditional branch.  MERGE_BB
3988    is the block containing the code to manipulate.  DEST_EDGE is an
3989    edge representing a jump to the join block; after the conversion,
3990    TEST_BB should be branching to its destination.
3991    REVERSEP is true if the sense of the branch should be reversed.  */
3992
3993 static int
3994 dead_or_predicable (basic_block test_bb, basic_block merge_bb,
3995                     basic_block other_bb, edge dest_edge, int reversep)
3996 {
3997   basic_block new_dest = dest_edge->dest;
3998   rtx head, end, jump, earliest = NULL_RTX, old_dest;
3999   bitmap merge_set = NULL;
4000   /* Number of pending changes.  */
4001   int n_validated_changes = 0;
4002   rtx new_dest_label = NULL_RTX;
4003
4004   jump = BB_END (test_bb);
4005
4006   /* Find the extent of the real code in the merge block.  */
4007   head = BB_HEAD (merge_bb);
4008   end = BB_END (merge_bb);
4009
4010   while (DEBUG_INSN_P (end) && end != head)
4011     end = PREV_INSN (end);
4012
4013   /* If merge_bb ends with a tablejump, predicating/moving insn's
4014      into test_bb and then deleting merge_bb will result in the jumptable
4015      that follows merge_bb being removed along with merge_bb and then we
4016      get an unresolved reference to the jumptable.  */
4017   if (tablejump_p (end, NULL, NULL))
4018     return FALSE;
4019
4020   if (LABEL_P (head))
4021     head = NEXT_INSN (head);
4022   while (DEBUG_INSN_P (head) && head != end)
4023     head = NEXT_INSN (head);
4024   if (NOTE_P (head))
4025     {
4026       if (head == end)
4027         {
4028           head = end = NULL_RTX;
4029           goto no_body;
4030         }
4031       head = NEXT_INSN (head);
4032       while (DEBUG_INSN_P (head) && head != end)
4033         head = NEXT_INSN (head);
4034     }
4035
4036   if (JUMP_P (end))
4037     {
4038       if (head == end)
4039         {
4040           head = end = NULL_RTX;
4041           goto no_body;
4042         }
4043       end = PREV_INSN (end);
4044       while (DEBUG_INSN_P (end) && end != head)
4045         end = PREV_INSN (end);
4046     }
4047
4048   /* Disable handling dead code by conditional execution if the machine needs
4049      to do anything funny with the tests, etc.  */
4050 #ifndef IFCVT_MODIFY_TESTS
4051   if (targetm.have_conditional_execution ())
4052     {
4053       /* In the conditional execution case, we have things easy.  We know
4054          the condition is reversible.  We don't have to check life info
4055          because we're going to conditionally execute the code anyway.
4056          All that's left is making sure the insns involved can actually
4057          be predicated.  */
4058
4059       rtx cond, prob_val;
4060
4061       cond = cond_exec_get_condition (jump);
4062       if (! cond)
4063         return FALSE;
4064
4065       prob_val = find_reg_note (jump, REG_BR_PROB, NULL_RTX);
4066       if (prob_val)
4067         prob_val = XEXP (prob_val, 0);
4068
4069       if (reversep)
4070         {
4071           enum rtx_code rev = reversed_comparison_code (cond, jump);
4072           if (rev == UNKNOWN)
4073             return FALSE;
4074           cond = gen_rtx_fmt_ee (rev, GET_MODE (cond), XEXP (cond, 0),
4075                                  XEXP (cond, 1));
4076           if (prob_val)
4077             prob_val = GEN_INT (REG_BR_PROB_BASE - INTVAL (prob_val));
4078         }
4079
4080       if (cond_exec_process_insns (NULL, head, end, cond, prob_val, 0)
4081           && verify_changes (0))
4082         n_validated_changes = num_validated_changes ();
4083       else
4084         cancel_changes (0);
4085
4086       earliest = jump;
4087     }
4088 #endif
4089
4090   /* If we allocated new pseudos (e.g. in the conditional move
4091      expander called from noce_emit_cmove), we must resize the
4092      array first.  */
4093   if (max_regno < max_reg_num ())
4094     max_regno = max_reg_num ();
4095
4096   /* Try the NCE path if the CE path did not result in any changes.  */
4097   if (n_validated_changes == 0)
4098     {
4099       rtx cond, insn;
4100       regset live;
4101       bool success;
4102
4103       /* In the non-conditional execution case, we have to verify that there
4104          are no trapping operations, no calls, no references to memory, and
4105          that any registers modified are dead at the branch site.  */
4106
4107       if (!any_condjump_p (jump))
4108         return FALSE;
4109
4110       /* Find the extent of the conditional.  */
4111       cond = noce_get_condition (jump, &earliest, false);
4112       if (!cond)
4113         return FALSE;
4114
4115       live = BITMAP_ALLOC (&reg_obstack);
4116       simulate_backwards_to_point (merge_bb, live, end);
4117       success = can_move_insns_across (head, end, earliest, jump,
4118                                        merge_bb, live,
4119                                        df_get_live_in (other_bb), NULL);
4120       BITMAP_FREE (live);
4121       if (!success)
4122         return FALSE;
4123
4124       /* Collect the set of registers set in MERGE_BB.  */
4125       merge_set = BITMAP_ALLOC (&reg_obstack);
4126
4127       FOR_BB_INSNS (merge_bb, insn)
4128         if (NONDEBUG_INSN_P (insn))
4129           df_simulate_find_defs (insn, merge_set);
4130     }
4131
4132  no_body:
4133   /* We don't want to use normal invert_jump or redirect_jump because
4134      we don't want to delete_insn called.  Also, we want to do our own
4135      change group management.  */
4136
4137   old_dest = JUMP_LABEL (jump);
4138   if (other_bb != new_dest)
4139     {
4140       if (JUMP_P (BB_END (dest_edge->src)))
4141         new_dest_label = JUMP_LABEL (BB_END (dest_edge->src));
4142       else if (new_dest == EXIT_BLOCK_PTR)
4143         new_dest_label = ret_rtx;
4144       else
4145         new_dest_label = block_label (new_dest);
4146
4147       if (reversep
4148           ? ! invert_jump_1 (jump, new_dest_label)
4149           : ! redirect_jump_1 (jump, new_dest_label))
4150         goto cancel;
4151     }
4152
4153   if (verify_changes (n_validated_changes))
4154     confirm_change_group ();
4155   else
4156     goto cancel;
4157
4158   if (other_bb != new_dest)
4159     {
4160       redirect_jump_2 (jump, old_dest, new_dest_label, 0, reversep);
4161
4162       redirect_edge_succ (BRANCH_EDGE (test_bb), new_dest);
4163       if (reversep)
4164         {
4165           gcov_type count, probability;
4166           count = BRANCH_EDGE (test_bb)->count;
4167           BRANCH_EDGE (test_bb)->count = FALLTHRU_EDGE (test_bb)->count;
4168           FALLTHRU_EDGE (test_bb)->count = count;
4169           probability = BRANCH_EDGE (test_bb)->probability;
4170           BRANCH_EDGE (test_bb)->probability
4171             = FALLTHRU_EDGE (test_bb)->probability;
4172           FALLTHRU_EDGE (test_bb)->probability = probability;
4173           update_br_prob_note (test_bb);
4174         }
4175     }
4176
4177   /* Move the insns out of MERGE_BB to before the branch.  */
4178   if (head != NULL)
4179     {
4180       rtx insn;
4181
4182       if (end == BB_END (merge_bb))
4183         BB_END (merge_bb) = PREV_INSN (head);
4184
4185       /* PR 21767: when moving insns above a conditional branch, the REG_EQUAL
4186          notes being moved might become invalid.  */
4187       insn = head;
4188       do
4189         {
4190           rtx note, set;
4191
4192           if (! INSN_P (insn))
4193             continue;
4194           note = find_reg_note (insn, REG_EQUAL, NULL_RTX);
4195           if (! note)
4196             continue;
4197           set = single_set (insn);
4198           if (!set || !function_invariant_p (SET_SRC (set))
4199               || !function_invariant_p (XEXP (note, 0)))
4200             remove_note (insn, note);
4201         } while (insn != end && (insn = NEXT_INSN (insn)));
4202
4203       /* PR46315: when moving insns above a conditional branch, the REG_EQUAL
4204          notes referring to the registers being set might become invalid.  */
4205       if (merge_set)
4206         {
4207           unsigned i;
4208           bitmap_iterator bi;
4209
4210           EXECUTE_IF_SET_IN_BITMAP (merge_set, 0, i, bi)
4211             remove_reg_equal_equiv_notes_for_regno (i);
4212
4213           BITMAP_FREE (merge_set);
4214         }
4215
4216       reorder_insns (head, end, PREV_INSN (earliest));
4217     }
4218
4219   /* Remove the jump and edge if we can.  */
4220   if (other_bb == new_dest)
4221     {
4222       delete_insn (jump);
4223       remove_edge (BRANCH_EDGE (test_bb));
4224       /* ??? Can't merge blocks here, as then_bb is still in use.
4225          At minimum, the merge will get done just before bb-reorder.  */
4226     }
4227
4228   return TRUE;
4229
4230  cancel:
4231   cancel_changes (0);
4232
4233   if (merge_set)
4234     BITMAP_FREE (merge_set);
4235
4236   return FALSE;
4237 }
4238 \f
4239 /* Main entry point for all if-conversion.  */
4240
4241 static void
4242 if_convert (void)
4243 {
4244   basic_block bb;
4245   int pass;
4246
4247   if (optimize == 1)
4248     {
4249       df_live_add_problem ();
4250       df_live_set_all_dirty ();
4251     }
4252
4253   num_possible_if_blocks = 0;
4254   num_updated_if_blocks = 0;
4255   num_true_changes = 0;
4256
4257   loop_optimizer_init (AVOID_CFG_MODIFICATIONS);
4258   mark_loop_exit_edges ();
4259   loop_optimizer_finalize ();
4260   free_dominance_info (CDI_DOMINATORS);
4261
4262   /* Compute postdominators.  */
4263   calculate_dominance_info (CDI_POST_DOMINATORS);
4264
4265   df_set_flags (DF_LR_RUN_DCE);
4266
4267   /* Go through each of the basic blocks looking for things to convert.  If we
4268      have conditional execution, we make multiple passes to allow us to handle
4269      IF-THEN{-ELSE} blocks within other IF-THEN{-ELSE} blocks.  */
4270   pass = 0;
4271   do
4272     {
4273       df_analyze ();
4274       /* Only need to do dce on the first pass.  */
4275       df_clear_flags (DF_LR_RUN_DCE);
4276       cond_exec_changed_p = FALSE;
4277       pass++;
4278
4279 #ifdef IFCVT_MULTIPLE_DUMPS
4280       if (dump_file && pass > 1)
4281         fprintf (dump_file, "\n\n========== Pass %d ==========\n", pass);
4282 #endif
4283
4284       FOR_EACH_BB (bb)
4285         {
4286           basic_block new_bb;
4287           while (!df_get_bb_dirty (bb)
4288                  && (new_bb = find_if_header (bb, pass)) != NULL)
4289             bb = new_bb;
4290         }
4291
4292 #ifdef IFCVT_MULTIPLE_DUMPS
4293       if (dump_file && cond_exec_changed_p)
4294         {
4295           if (dump_flags & TDF_SLIM)
4296             print_rtl_slim_with_bb (dump_file, get_insns (), dump_flags);
4297           else
4298             print_rtl_with_bb (dump_file, get_insns ());
4299         }
4300 #endif
4301     }
4302   while (cond_exec_changed_p);
4303
4304 #ifdef IFCVT_MULTIPLE_DUMPS
4305   if (dump_file)
4306     fprintf (dump_file, "\n\n========== no more changes\n");
4307 #endif
4308
4309   free_dominance_info (CDI_POST_DOMINATORS);
4310
4311   if (dump_file)
4312     fflush (dump_file);
4313
4314   clear_aux_for_blocks ();
4315
4316   /* If we allocated new pseudos, we must resize the array for sched1.  */
4317   if (max_regno < max_reg_num ())
4318     max_regno = max_reg_num ();
4319
4320   /* Write the final stats.  */
4321   if (dump_file && num_possible_if_blocks > 0)
4322     {
4323       fprintf (dump_file,
4324                "\n%d possible IF blocks searched.\n",
4325                num_possible_if_blocks);
4326       fprintf (dump_file,
4327                "%d IF blocks converted.\n",
4328                num_updated_if_blocks);
4329       fprintf (dump_file,
4330                "%d true changes made.\n\n\n",
4331                num_true_changes);
4332     }
4333
4334   if (optimize == 1)
4335     df_remove_problem (df_live);
4336
4337 #ifdef ENABLE_CHECKING
4338   verify_flow_info ();
4339 #endif
4340 }
4341 \f
4342 static bool
4343 gate_handle_if_conversion (void)
4344 {
4345   return (optimize > 0)
4346     && dbg_cnt (if_conversion);
4347 }
4348
4349 /* If-conversion and CFG cleanup.  */
4350 static unsigned int
4351 rest_of_handle_if_conversion (void)
4352 {
4353   if (flag_if_conversion)
4354     {
4355       if (dump_file)
4356         dump_flow_info (dump_file, dump_flags);
4357       cleanup_cfg (CLEANUP_EXPENSIVE);
4358       if_convert ();
4359     }
4360
4361   cleanup_cfg (0);
4362   return 0;
4363 }
4364
4365 struct rtl_opt_pass pass_rtl_ifcvt =
4366 {
4367  {
4368   RTL_PASS,
4369   "ce1",                                /* name */
4370   gate_handle_if_conversion,            /* gate */
4371   rest_of_handle_if_conversion,         /* execute */
4372   NULL,                                 /* sub */
4373   NULL,                                 /* next */
4374   0,                                    /* static_pass_number */
4375   TV_IFCVT,                             /* tv_id */
4376   0,                                    /* properties_required */
4377   0,                                    /* properties_provided */
4378   0,                                    /* properties_destroyed */
4379   0,                                    /* todo_flags_start */
4380   TODO_df_finish | TODO_verify_rtl_sharing |
4381   0                                     /* todo_flags_finish */
4382  }
4383 };
4384
4385 static bool
4386 gate_handle_if_after_combine (void)
4387 {
4388   return optimize > 0 && flag_if_conversion
4389     && dbg_cnt (if_after_combine);
4390 }
4391
4392
4393 /* Rerun if-conversion, as combine may have simplified things enough
4394    to now meet sequence length restrictions.  */
4395 static unsigned int
4396 rest_of_handle_if_after_combine (void)
4397 {
4398   if_convert ();
4399   return 0;
4400 }
4401
4402 struct rtl_opt_pass pass_if_after_combine =
4403 {
4404  {
4405   RTL_PASS,
4406   "ce2",                                /* name */
4407   gate_handle_if_after_combine,         /* gate */
4408   rest_of_handle_if_after_combine,      /* execute */
4409   NULL,                                 /* sub */
4410   NULL,                                 /* next */
4411   0,                                    /* static_pass_number */
4412   TV_IFCVT,                             /* tv_id */
4413   0,                                    /* properties_required */
4414   0,                                    /* properties_provided */
4415   0,                                    /* properties_destroyed */
4416   0,                                    /* todo_flags_start */
4417   TODO_df_finish | TODO_verify_rtl_sharing |
4418   TODO_ggc_collect                      /* todo_flags_finish */
4419  }
4420 };
4421
4422
4423 static bool
4424 gate_handle_if_after_reload (void)
4425 {
4426   return optimize > 0 && flag_if_conversion2
4427     && dbg_cnt (if_after_reload);
4428 }
4429
4430 static unsigned int
4431 rest_of_handle_if_after_reload (void)
4432 {
4433   if_convert ();
4434   return 0;
4435 }
4436
4437
4438 struct rtl_opt_pass pass_if_after_reload =
4439 {
4440  {
4441   RTL_PASS,
4442   "ce3",                                /* name */
4443   gate_handle_if_after_reload,          /* gate */
4444   rest_of_handle_if_after_reload,       /* execute */
4445   NULL,                                 /* sub */
4446   NULL,                                 /* next */
4447   0,                                    /* static_pass_number */
4448   TV_IFCVT2,                            /* tv_id */
4449   0,                                    /* properties_required */
4450   0,                                    /* properties_provided */
4451   0,                                    /* properties_destroyed */
4452   0,                                    /* todo_flags_start */
4453   TODO_df_finish | TODO_verify_rtl_sharing |
4454   TODO_ggc_collect                      /* todo_flags_finish */
4455  }
4456 };