xref: /openbmc/qemu/tcg/optimize.c (revision 5c62d3779b8b1075782672751165c0e4f716762f)
1 /*
2  * Optimizations for Tiny Code Generator for QEMU
3  *
4  * Copyright (c) 2010 Samsung Electronics.
5  * Contributed by Kirill Batuzov <batuzovk@ispras.ru>
6  *
7  * Permission is hereby granted, free of charge, to any person obtaining a copy
8  * of this software and associated documentation files (the "Software"), to deal
9  * in the Software without restriction, including without limitation the rights
10  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11  * copies of the Software, and to permit persons to whom the Software is
12  * furnished to do so, subject to the following conditions:
13  *
14  * The above copyright notice and this permission notice shall be included in
15  * all copies or substantial portions of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23  * THE SOFTWARE.
24  */
25 
26 #include "qemu/osdep.h"
27 #include "qemu/int128.h"
28 #include "qemu/interval-tree.h"
29 #include "tcg/tcg-op-common.h"
30 #include "tcg-internal.h"
31 #include "tcg-has.h"
32 
33 #define CASE_OP_32_64(x)                        \
34         glue(glue(case INDEX_op_, x), _i32):    \
35         glue(glue(case INDEX_op_, x), _i64)
36 
37 #define CASE_OP_32_64_VEC(x)                    \
38         glue(glue(case INDEX_op_, x), _i32):    \
39         glue(glue(case INDEX_op_, x), _i64):    \
40         glue(glue(case INDEX_op_, x), _vec)
41 
42 typedef struct MemCopyInfo {
43     IntervalTreeNode itree;
44     QSIMPLEQ_ENTRY (MemCopyInfo) next;
45     TCGTemp *ts;
46     TCGType type;
47 } MemCopyInfo;
48 
49 typedef struct TempOptInfo {
50     bool is_const;
51     TCGTemp *prev_copy;
52     TCGTemp *next_copy;
53     QSIMPLEQ_HEAD(, MemCopyInfo) mem_copy;
54     uint64_t val;
55     uint64_t z_mask;  /* mask bit is 0 if and only if value bit is 0 */
56     uint64_t s_mask;  /* mask bit is 1 if value bit matches msb */
57 } TempOptInfo;
58 
59 typedef struct OptContext {
60     TCGContext *tcg;
61     TCGOp *prev_mb;
62     TCGTempSet temps_used;
63 
64     IntervalTreeRoot mem_copy;
65     QSIMPLEQ_HEAD(, MemCopyInfo) mem_free;
66 
67     /* In flight values from optimization. */
68     TCGType type;
69 } OptContext;
70 
71 static inline TempOptInfo *ts_info(TCGTemp *ts)
72 {
73     return ts->state_ptr;
74 }
75 
76 static inline TempOptInfo *arg_info(TCGArg arg)
77 {
78     return ts_info(arg_temp(arg));
79 }
80 
81 static inline bool ti_is_const(TempOptInfo *ti)
82 {
83     return ti->is_const;
84 }
85 
86 static inline uint64_t ti_const_val(TempOptInfo *ti)
87 {
88     return ti->val;
89 }
90 
91 static inline bool ti_is_const_val(TempOptInfo *ti, uint64_t val)
92 {
93     return ti_is_const(ti) && ti_const_val(ti) == val;
94 }
95 
96 static inline bool ts_is_const(TCGTemp *ts)
97 {
98     return ti_is_const(ts_info(ts));
99 }
100 
101 static inline bool ts_is_const_val(TCGTemp *ts, uint64_t val)
102 {
103     return ti_is_const_val(ts_info(ts), val);
104 }
105 
106 static inline bool arg_is_const(TCGArg arg)
107 {
108     return ts_is_const(arg_temp(arg));
109 }
110 
111 static inline bool arg_is_const_val(TCGArg arg, uint64_t val)
112 {
113     return ts_is_const_val(arg_temp(arg), val);
114 }
115 
116 static inline bool ts_is_copy(TCGTemp *ts)
117 {
118     return ts_info(ts)->next_copy != ts;
119 }
120 
121 static TCGTemp *cmp_better_copy(TCGTemp *a, TCGTemp *b)
122 {
123     return a->kind < b->kind ? b : a;
124 }
125 
126 /* Initialize and activate a temporary.  */
127 static void init_ts_info(OptContext *ctx, TCGTemp *ts)
128 {
129     size_t idx = temp_idx(ts);
130     TempOptInfo *ti;
131 
132     if (test_bit(idx, ctx->temps_used.l)) {
133         return;
134     }
135     set_bit(idx, ctx->temps_used.l);
136 
137     ti = ts->state_ptr;
138     if (ti == NULL) {
139         ti = tcg_malloc(sizeof(TempOptInfo));
140         ts->state_ptr = ti;
141     }
142 
143     ti->next_copy = ts;
144     ti->prev_copy = ts;
145     QSIMPLEQ_INIT(&ti->mem_copy);
146     if (ts->kind == TEMP_CONST) {
147         ti->is_const = true;
148         ti->val = ts->val;
149         ti->z_mask = ts->val;
150         ti->s_mask = INT64_MIN >> clrsb64(ts->val);
151     } else {
152         ti->is_const = false;
153         ti->z_mask = -1;
154         ti->s_mask = 0;
155     }
156 }
157 
158 static MemCopyInfo *mem_copy_first(OptContext *ctx, intptr_t s, intptr_t l)
159 {
160     IntervalTreeNode *r = interval_tree_iter_first(&ctx->mem_copy, s, l);
161     return r ? container_of(r, MemCopyInfo, itree) : NULL;
162 }
163 
164 static MemCopyInfo *mem_copy_next(MemCopyInfo *mem, intptr_t s, intptr_t l)
165 {
166     IntervalTreeNode *r = interval_tree_iter_next(&mem->itree, s, l);
167     return r ? container_of(r, MemCopyInfo, itree) : NULL;
168 }
169 
170 static void remove_mem_copy(OptContext *ctx, MemCopyInfo *mc)
171 {
172     TCGTemp *ts = mc->ts;
173     TempOptInfo *ti = ts_info(ts);
174 
175     interval_tree_remove(&mc->itree, &ctx->mem_copy);
176     QSIMPLEQ_REMOVE(&ti->mem_copy, mc, MemCopyInfo, next);
177     QSIMPLEQ_INSERT_TAIL(&ctx->mem_free, mc, next);
178 }
179 
180 static void remove_mem_copy_in(OptContext *ctx, intptr_t s, intptr_t l)
181 {
182     while (true) {
183         MemCopyInfo *mc = mem_copy_first(ctx, s, l);
184         if (!mc) {
185             break;
186         }
187         remove_mem_copy(ctx, mc);
188     }
189 }
190 
191 static void remove_mem_copy_all(OptContext *ctx)
192 {
193     remove_mem_copy_in(ctx, 0, -1);
194     tcg_debug_assert(interval_tree_is_empty(&ctx->mem_copy));
195 }
196 
197 static TCGTemp *find_better_copy(TCGTemp *ts)
198 {
199     TCGTemp *i, *ret;
200 
201     /* If this is already readonly, we can't do better. */
202     if (temp_readonly(ts)) {
203         return ts;
204     }
205 
206     ret = ts;
207     for (i = ts_info(ts)->next_copy; i != ts; i = ts_info(i)->next_copy) {
208         ret = cmp_better_copy(ret, i);
209     }
210     return ret;
211 }
212 
213 static void move_mem_copies(TCGTemp *dst_ts, TCGTemp *src_ts)
214 {
215     TempOptInfo *si = ts_info(src_ts);
216     TempOptInfo *di = ts_info(dst_ts);
217     MemCopyInfo *mc;
218 
219     QSIMPLEQ_FOREACH(mc, &si->mem_copy, next) {
220         tcg_debug_assert(mc->ts == src_ts);
221         mc->ts = dst_ts;
222     }
223     QSIMPLEQ_CONCAT(&di->mem_copy, &si->mem_copy);
224 }
225 
226 /* Reset TEMP's state, possibly removing the temp for the list of copies.  */
227 static void reset_ts(OptContext *ctx, TCGTemp *ts)
228 {
229     TempOptInfo *ti = ts_info(ts);
230     TCGTemp *pts = ti->prev_copy;
231     TCGTemp *nts = ti->next_copy;
232     TempOptInfo *pi = ts_info(pts);
233     TempOptInfo *ni = ts_info(nts);
234 
235     ni->prev_copy = ti->prev_copy;
236     pi->next_copy = ti->next_copy;
237     ti->next_copy = ts;
238     ti->prev_copy = ts;
239     ti->is_const = false;
240     ti->z_mask = -1;
241     ti->s_mask = 0;
242 
243     if (!QSIMPLEQ_EMPTY(&ti->mem_copy)) {
244         if (ts == nts) {
245             /* Last temp copy being removed, the mem copies die. */
246             MemCopyInfo *mc;
247             QSIMPLEQ_FOREACH(mc, &ti->mem_copy, next) {
248                 interval_tree_remove(&mc->itree, &ctx->mem_copy);
249             }
250             QSIMPLEQ_CONCAT(&ctx->mem_free, &ti->mem_copy);
251         } else {
252             move_mem_copies(find_better_copy(nts), ts);
253         }
254     }
255 }
256 
257 static void reset_temp(OptContext *ctx, TCGArg arg)
258 {
259     reset_ts(ctx, arg_temp(arg));
260 }
261 
262 static void record_mem_copy(OptContext *ctx, TCGType type,
263                             TCGTemp *ts, intptr_t start, intptr_t last)
264 {
265     MemCopyInfo *mc;
266     TempOptInfo *ti;
267 
268     mc = QSIMPLEQ_FIRST(&ctx->mem_free);
269     if (mc) {
270         QSIMPLEQ_REMOVE_HEAD(&ctx->mem_free, next);
271     } else {
272         mc = tcg_malloc(sizeof(*mc));
273     }
274 
275     memset(mc, 0, sizeof(*mc));
276     mc->itree.start = start;
277     mc->itree.last = last;
278     mc->type = type;
279     interval_tree_insert(&mc->itree, &ctx->mem_copy);
280 
281     ts = find_better_copy(ts);
282     ti = ts_info(ts);
283     mc->ts = ts;
284     QSIMPLEQ_INSERT_TAIL(&ti->mem_copy, mc, next);
285 }
286 
287 static bool ts_are_copies(TCGTemp *ts1, TCGTemp *ts2)
288 {
289     TCGTemp *i;
290 
291     if (ts1 == ts2) {
292         return true;
293     }
294 
295     if (!ts_is_copy(ts1) || !ts_is_copy(ts2)) {
296         return false;
297     }
298 
299     for (i = ts_info(ts1)->next_copy; i != ts1; i = ts_info(i)->next_copy) {
300         if (i == ts2) {
301             return true;
302         }
303     }
304 
305     return false;
306 }
307 
308 static bool args_are_copies(TCGArg arg1, TCGArg arg2)
309 {
310     return ts_are_copies(arg_temp(arg1), arg_temp(arg2));
311 }
312 
313 static TCGTemp *find_mem_copy_for(OptContext *ctx, TCGType type, intptr_t s)
314 {
315     MemCopyInfo *mc;
316 
317     for (mc = mem_copy_first(ctx, s, s); mc; mc = mem_copy_next(mc, s, s)) {
318         if (mc->itree.start == s && mc->type == type) {
319             return find_better_copy(mc->ts);
320         }
321     }
322     return NULL;
323 }
324 
325 static TCGArg arg_new_constant(OptContext *ctx, uint64_t val)
326 {
327     TCGType type = ctx->type;
328     TCGTemp *ts;
329 
330     if (type == TCG_TYPE_I32) {
331         val = (int32_t)val;
332     }
333 
334     ts = tcg_constant_internal(type, val);
335     init_ts_info(ctx, ts);
336 
337     return temp_arg(ts);
338 }
339 
340 static TCGArg arg_new_temp(OptContext *ctx)
341 {
342     TCGTemp *ts = tcg_temp_new_internal(ctx->type, TEMP_EBB);
343     init_ts_info(ctx, ts);
344     return temp_arg(ts);
345 }
346 
347 static TCGOp *opt_insert_after(OptContext *ctx, TCGOp *op,
348                                TCGOpcode opc, unsigned narg)
349 {
350     return tcg_op_insert_after(ctx->tcg, op, opc, ctx->type, narg);
351 }
352 
353 static TCGOp *opt_insert_before(OptContext *ctx, TCGOp *op,
354                                 TCGOpcode opc, unsigned narg)
355 {
356     return tcg_op_insert_before(ctx->tcg, op, opc, ctx->type, narg);
357 }
358 
359 static bool tcg_opt_gen_mov(OptContext *ctx, TCGOp *op, TCGArg dst, TCGArg src)
360 {
361     TCGTemp *dst_ts = arg_temp(dst);
362     TCGTemp *src_ts = arg_temp(src);
363     TempOptInfo *di;
364     TempOptInfo *si;
365     TCGOpcode new_op;
366 
367     if (ts_are_copies(dst_ts, src_ts)) {
368         tcg_op_remove(ctx->tcg, op);
369         return true;
370     }
371 
372     reset_ts(ctx, dst_ts);
373     di = ts_info(dst_ts);
374     si = ts_info(src_ts);
375 
376     switch (ctx->type) {
377     case TCG_TYPE_I32:
378     case TCG_TYPE_I64:
379         new_op = INDEX_op_mov;
380         break;
381     case TCG_TYPE_V64:
382     case TCG_TYPE_V128:
383     case TCG_TYPE_V256:
384         /* TCGOP_TYPE and TCGOP_VECE remain unchanged.  */
385         new_op = INDEX_op_mov_vec;
386         break;
387     default:
388         g_assert_not_reached();
389     }
390     op->opc = new_op;
391     op->args[0] = dst;
392     op->args[1] = src;
393 
394     di->z_mask = si->z_mask;
395     di->s_mask = si->s_mask;
396 
397     if (src_ts->type == dst_ts->type) {
398         TempOptInfo *ni = ts_info(si->next_copy);
399 
400         di->next_copy = si->next_copy;
401         di->prev_copy = src_ts;
402         ni->prev_copy = dst_ts;
403         si->next_copy = dst_ts;
404         di->is_const = si->is_const;
405         di->val = si->val;
406 
407         if (!QSIMPLEQ_EMPTY(&si->mem_copy)
408             && cmp_better_copy(src_ts, dst_ts) == dst_ts) {
409             move_mem_copies(dst_ts, src_ts);
410         }
411     }
412     return true;
413 }
414 
415 static bool tcg_opt_gen_movi(OptContext *ctx, TCGOp *op,
416                              TCGArg dst, uint64_t val)
417 {
418     /* Convert movi to mov with constant temp. */
419     return tcg_opt_gen_mov(ctx, op, dst, arg_new_constant(ctx, val));
420 }
421 
422 static uint64_t do_constant_folding_2(TCGOpcode op, uint64_t x, uint64_t y)
423 {
424     uint64_t l64, h64;
425 
426     switch (op) {
427     case INDEX_op_add:
428         return x + y;
429 
430     case INDEX_op_sub:
431         return x - y;
432 
433     CASE_OP_32_64(mul):
434         return x * y;
435 
436     case INDEX_op_and:
437     case INDEX_op_and_vec:
438         return x & y;
439 
440     case INDEX_op_or:
441     case INDEX_op_or_vec:
442         return x | y;
443 
444     case INDEX_op_xor:
445     case INDEX_op_xor_vec:
446         return x ^ y;
447 
448     case INDEX_op_shl_i32:
449         return (uint32_t)x << (y & 31);
450 
451     case INDEX_op_shl_i64:
452         return (uint64_t)x << (y & 63);
453 
454     case INDEX_op_shr_i32:
455         return (uint32_t)x >> (y & 31);
456 
457     case INDEX_op_shr_i64:
458         return (uint64_t)x >> (y & 63);
459 
460     case INDEX_op_sar_i32:
461         return (int32_t)x >> (y & 31);
462 
463     case INDEX_op_sar_i64:
464         return (int64_t)x >> (y & 63);
465 
466     case INDEX_op_rotr_i32:
467         return ror32(x, y & 31);
468 
469     case INDEX_op_rotr_i64:
470         return ror64(x, y & 63);
471 
472     case INDEX_op_rotl_i32:
473         return rol32(x, y & 31);
474 
475     case INDEX_op_rotl_i64:
476         return rol64(x, y & 63);
477 
478     case INDEX_op_not:
479     case INDEX_op_not_vec:
480         return ~x;
481 
482     case INDEX_op_neg:
483         return -x;
484 
485     case INDEX_op_andc:
486     case INDEX_op_andc_vec:
487         return x & ~y;
488 
489     case INDEX_op_orc:
490     case INDEX_op_orc_vec:
491         return x | ~y;
492 
493     case INDEX_op_eqv:
494     case INDEX_op_eqv_vec:
495         return ~(x ^ y);
496 
497     case INDEX_op_nand:
498     case INDEX_op_nand_vec:
499         return ~(x & y);
500 
501     case INDEX_op_nor:
502     case INDEX_op_nor_vec:
503         return ~(x | y);
504 
505     case INDEX_op_clz_i32:
506         return (uint32_t)x ? clz32(x) : y;
507 
508     case INDEX_op_clz_i64:
509         return x ? clz64(x) : y;
510 
511     case INDEX_op_ctz_i32:
512         return (uint32_t)x ? ctz32(x) : y;
513 
514     case INDEX_op_ctz_i64:
515         return x ? ctz64(x) : y;
516 
517     case INDEX_op_ctpop_i32:
518         return ctpop32(x);
519 
520     case INDEX_op_ctpop_i64:
521         return ctpop64(x);
522 
523     CASE_OP_32_64(bswap16):
524         x = bswap16(x);
525         return y & TCG_BSWAP_OS ? (int16_t)x : x;
526 
527     CASE_OP_32_64(bswap32):
528         x = bswap32(x);
529         return y & TCG_BSWAP_OS ? (int32_t)x : x;
530 
531     case INDEX_op_bswap64_i64:
532         return bswap64(x);
533 
534     case INDEX_op_ext_i32_i64:
535         return (int32_t)x;
536 
537     case INDEX_op_extu_i32_i64:
538     case INDEX_op_extrl_i64_i32:
539         return (uint32_t)x;
540 
541     case INDEX_op_extrh_i64_i32:
542         return (uint64_t)x >> 32;
543 
544     case INDEX_op_muluh_i32:
545         return ((uint64_t)(uint32_t)x * (uint32_t)y) >> 32;
546     case INDEX_op_mulsh_i32:
547         return ((int64_t)(int32_t)x * (int32_t)y) >> 32;
548 
549     case INDEX_op_muluh_i64:
550         mulu64(&l64, &h64, x, y);
551         return h64;
552     case INDEX_op_mulsh_i64:
553         muls64(&l64, &h64, x, y);
554         return h64;
555 
556     case INDEX_op_div_i32:
557         /* Avoid crashing on divide by zero, otherwise undefined.  */
558         return (int32_t)x / ((int32_t)y ? : 1);
559     case INDEX_op_divu_i32:
560         return (uint32_t)x / ((uint32_t)y ? : 1);
561     case INDEX_op_div_i64:
562         return (int64_t)x / ((int64_t)y ? : 1);
563     case INDEX_op_divu_i64:
564         return (uint64_t)x / ((uint64_t)y ? : 1);
565 
566     case INDEX_op_rem_i32:
567         return (int32_t)x % ((int32_t)y ? : 1);
568     case INDEX_op_remu_i32:
569         return (uint32_t)x % ((uint32_t)y ? : 1);
570     case INDEX_op_rem_i64:
571         return (int64_t)x % ((int64_t)y ? : 1);
572     case INDEX_op_remu_i64:
573         return (uint64_t)x % ((uint64_t)y ? : 1);
574 
575     default:
576         g_assert_not_reached();
577     }
578 }
579 
580 static uint64_t do_constant_folding(TCGOpcode op, TCGType type,
581                                     uint64_t x, uint64_t y)
582 {
583     uint64_t res = do_constant_folding_2(op, x, y);
584     if (type == TCG_TYPE_I32) {
585         res = (int32_t)res;
586     }
587     return res;
588 }
589 
590 static bool do_constant_folding_cond_32(uint32_t x, uint32_t y, TCGCond c)
591 {
592     switch (c) {
593     case TCG_COND_EQ:
594         return x == y;
595     case TCG_COND_NE:
596         return x != y;
597     case TCG_COND_LT:
598         return (int32_t)x < (int32_t)y;
599     case TCG_COND_GE:
600         return (int32_t)x >= (int32_t)y;
601     case TCG_COND_LE:
602         return (int32_t)x <= (int32_t)y;
603     case TCG_COND_GT:
604         return (int32_t)x > (int32_t)y;
605     case TCG_COND_LTU:
606         return x < y;
607     case TCG_COND_GEU:
608         return x >= y;
609     case TCG_COND_LEU:
610         return x <= y;
611     case TCG_COND_GTU:
612         return x > y;
613     case TCG_COND_TSTEQ:
614         return (x & y) == 0;
615     case TCG_COND_TSTNE:
616         return (x & y) != 0;
617     case TCG_COND_ALWAYS:
618     case TCG_COND_NEVER:
619         break;
620     }
621     g_assert_not_reached();
622 }
623 
624 static bool do_constant_folding_cond_64(uint64_t x, uint64_t y, TCGCond c)
625 {
626     switch (c) {
627     case TCG_COND_EQ:
628         return x == y;
629     case TCG_COND_NE:
630         return x != y;
631     case TCG_COND_LT:
632         return (int64_t)x < (int64_t)y;
633     case TCG_COND_GE:
634         return (int64_t)x >= (int64_t)y;
635     case TCG_COND_LE:
636         return (int64_t)x <= (int64_t)y;
637     case TCG_COND_GT:
638         return (int64_t)x > (int64_t)y;
639     case TCG_COND_LTU:
640         return x < y;
641     case TCG_COND_GEU:
642         return x >= y;
643     case TCG_COND_LEU:
644         return x <= y;
645     case TCG_COND_GTU:
646         return x > y;
647     case TCG_COND_TSTEQ:
648         return (x & y) == 0;
649     case TCG_COND_TSTNE:
650         return (x & y) != 0;
651     case TCG_COND_ALWAYS:
652     case TCG_COND_NEVER:
653         break;
654     }
655     g_assert_not_reached();
656 }
657 
658 static int do_constant_folding_cond_eq(TCGCond c)
659 {
660     switch (c) {
661     case TCG_COND_GT:
662     case TCG_COND_LTU:
663     case TCG_COND_LT:
664     case TCG_COND_GTU:
665     case TCG_COND_NE:
666         return 0;
667     case TCG_COND_GE:
668     case TCG_COND_GEU:
669     case TCG_COND_LE:
670     case TCG_COND_LEU:
671     case TCG_COND_EQ:
672         return 1;
673     case TCG_COND_TSTEQ:
674     case TCG_COND_TSTNE:
675         return -1;
676     case TCG_COND_ALWAYS:
677     case TCG_COND_NEVER:
678         break;
679     }
680     g_assert_not_reached();
681 }
682 
683 /*
684  * Return -1 if the condition can't be simplified,
685  * and the result of the condition (0 or 1) if it can.
686  */
687 static int do_constant_folding_cond(TCGType type, TCGArg x,
688                                     TCGArg y, TCGCond c)
689 {
690     if (arg_is_const(x) && arg_is_const(y)) {
691         uint64_t xv = arg_info(x)->val;
692         uint64_t yv = arg_info(y)->val;
693 
694         switch (type) {
695         case TCG_TYPE_I32:
696             return do_constant_folding_cond_32(xv, yv, c);
697         case TCG_TYPE_I64:
698             return do_constant_folding_cond_64(xv, yv, c);
699         default:
700             /* Only scalar comparisons are optimizable */
701             return -1;
702         }
703     } else if (args_are_copies(x, y)) {
704         return do_constant_folding_cond_eq(c);
705     } else if (arg_is_const_val(y, 0)) {
706         switch (c) {
707         case TCG_COND_LTU:
708         case TCG_COND_TSTNE:
709             return 0;
710         case TCG_COND_GEU:
711         case TCG_COND_TSTEQ:
712             return 1;
713         default:
714             return -1;
715         }
716     }
717     return -1;
718 }
719 
720 /**
721  * swap_commutative:
722  * @dest: TCGArg of the destination argument, or NO_DEST.
723  * @p1: first paired argument
724  * @p2: second paired argument
725  *
726  * If *@p1 is a constant and *@p2 is not, swap.
727  * If *@p2 matches @dest, swap.
728  * Return true if a swap was performed.
729  */
730 
731 #define NO_DEST  temp_arg(NULL)
732 
733 static bool swap_commutative(TCGArg dest, TCGArg *p1, TCGArg *p2)
734 {
735     TCGArg a1 = *p1, a2 = *p2;
736     int sum = 0;
737     sum += arg_is_const(a1);
738     sum -= arg_is_const(a2);
739 
740     /* Prefer the constant in second argument, and then the form
741        op a, a, b, which is better handled on non-RISC hosts. */
742     if (sum > 0 || (sum == 0 && dest == a2)) {
743         *p1 = a2;
744         *p2 = a1;
745         return true;
746     }
747     return false;
748 }
749 
750 static bool swap_commutative2(TCGArg *p1, TCGArg *p2)
751 {
752     int sum = 0;
753     sum += arg_is_const(p1[0]);
754     sum += arg_is_const(p1[1]);
755     sum -= arg_is_const(p2[0]);
756     sum -= arg_is_const(p2[1]);
757     if (sum > 0) {
758         TCGArg t;
759         t = p1[0], p1[0] = p2[0], p2[0] = t;
760         t = p1[1], p1[1] = p2[1], p2[1] = t;
761         return true;
762     }
763     return false;
764 }
765 
766 /*
767  * Return -1 if the condition can't be simplified,
768  * and the result of the condition (0 or 1) if it can.
769  */
770 static int do_constant_folding_cond1(OptContext *ctx, TCGOp *op, TCGArg dest,
771                                      TCGArg *p1, TCGArg *p2, TCGArg *pcond)
772 {
773     TCGCond cond;
774     TempOptInfo *i1;
775     bool swap;
776     int r;
777 
778     swap = swap_commutative(dest, p1, p2);
779     cond = *pcond;
780     if (swap) {
781         *pcond = cond = tcg_swap_cond(cond);
782     }
783 
784     r = do_constant_folding_cond(ctx->type, *p1, *p2, cond);
785     if (r >= 0) {
786         return r;
787     }
788     if (!is_tst_cond(cond)) {
789         return -1;
790     }
791 
792     i1 = arg_info(*p1);
793 
794     /*
795      * TSTNE x,x -> NE x,0
796      * TSTNE x,i -> NE x,0 if i includes all nonzero bits of x
797      */
798     if (args_are_copies(*p1, *p2) ||
799         (arg_is_const(*p2) && (i1->z_mask & ~arg_info(*p2)->val) == 0)) {
800         *p2 = arg_new_constant(ctx, 0);
801         *pcond = tcg_tst_eqne_cond(cond);
802         return -1;
803     }
804 
805     /* TSTNE x,i -> LT x,0 if i only includes sign bit copies */
806     if (arg_is_const(*p2) && (arg_info(*p2)->val & ~i1->s_mask) == 0) {
807         *p2 = arg_new_constant(ctx, 0);
808         *pcond = tcg_tst_ltge_cond(cond);
809         return -1;
810     }
811 
812     /* Expand to AND with a temporary if no backend support. */
813     if (!TCG_TARGET_HAS_tst) {
814         TCGOp *op2 = opt_insert_before(ctx, op, INDEX_op_and, 3);
815         TCGArg tmp = arg_new_temp(ctx);
816 
817         op2->args[0] = tmp;
818         op2->args[1] = *p1;
819         op2->args[2] = *p2;
820 
821         *p1 = tmp;
822         *p2 = arg_new_constant(ctx, 0);
823         *pcond = tcg_tst_eqne_cond(cond);
824     }
825     return -1;
826 }
827 
828 static int do_constant_folding_cond2(OptContext *ctx, TCGOp *op, TCGArg *args)
829 {
830     TCGArg al, ah, bl, bh;
831     TCGCond c;
832     bool swap;
833     int r;
834 
835     swap = swap_commutative2(args, args + 2);
836     c = args[4];
837     if (swap) {
838         args[4] = c = tcg_swap_cond(c);
839     }
840 
841     al = args[0];
842     ah = args[1];
843     bl = args[2];
844     bh = args[3];
845 
846     if (arg_is_const(bl) && arg_is_const(bh)) {
847         tcg_target_ulong blv = arg_info(bl)->val;
848         tcg_target_ulong bhv = arg_info(bh)->val;
849         uint64_t b = deposit64(blv, 32, 32, bhv);
850 
851         if (arg_is_const(al) && arg_is_const(ah)) {
852             tcg_target_ulong alv = arg_info(al)->val;
853             tcg_target_ulong ahv = arg_info(ah)->val;
854             uint64_t a = deposit64(alv, 32, 32, ahv);
855 
856             r = do_constant_folding_cond_64(a, b, c);
857             if (r >= 0) {
858                 return r;
859             }
860         }
861 
862         if (b == 0) {
863             switch (c) {
864             case TCG_COND_LTU:
865             case TCG_COND_TSTNE:
866                 return 0;
867             case TCG_COND_GEU:
868             case TCG_COND_TSTEQ:
869                 return 1;
870             default:
871                 break;
872             }
873         }
874 
875         /* TSTNE x,-1 -> NE x,0 */
876         if (b == -1 && is_tst_cond(c)) {
877             args[3] = args[2] = arg_new_constant(ctx, 0);
878             args[4] = tcg_tst_eqne_cond(c);
879             return -1;
880         }
881 
882         /* TSTNE x,sign -> LT x,0 */
883         if (b == INT64_MIN && is_tst_cond(c)) {
884             /* bl must be 0, so copy that to bh */
885             args[3] = bl;
886             args[4] = tcg_tst_ltge_cond(c);
887             return -1;
888         }
889     }
890 
891     if (args_are_copies(al, bl) && args_are_copies(ah, bh)) {
892         r = do_constant_folding_cond_eq(c);
893         if (r >= 0) {
894             return r;
895         }
896 
897         /* TSTNE x,x -> NE x,0 */
898         if (is_tst_cond(c)) {
899             args[3] = args[2] = arg_new_constant(ctx, 0);
900             args[4] = tcg_tst_eqne_cond(c);
901             return -1;
902         }
903     }
904 
905     /* Expand to AND with a temporary if no backend support. */
906     if (!TCG_TARGET_HAS_tst && is_tst_cond(c)) {
907         TCGOp *op1 = opt_insert_before(ctx, op, INDEX_op_and, 3);
908         TCGOp *op2 = opt_insert_before(ctx, op, INDEX_op_and, 3);
909         TCGArg t1 = arg_new_temp(ctx);
910         TCGArg t2 = arg_new_temp(ctx);
911 
912         op1->args[0] = t1;
913         op1->args[1] = al;
914         op1->args[2] = bl;
915         op2->args[0] = t2;
916         op2->args[1] = ah;
917         op2->args[2] = bh;
918 
919         args[0] = t1;
920         args[1] = t2;
921         args[3] = args[2] = arg_new_constant(ctx, 0);
922         args[4] = tcg_tst_eqne_cond(c);
923     }
924     return -1;
925 }
926 
927 static void init_arguments(OptContext *ctx, TCGOp *op, int nb_args)
928 {
929     for (int i = 0; i < nb_args; i++) {
930         TCGTemp *ts = arg_temp(op->args[i]);
931         init_ts_info(ctx, ts);
932     }
933 }
934 
935 static void copy_propagate(OptContext *ctx, TCGOp *op,
936                            int nb_oargs, int nb_iargs)
937 {
938     for (int i = nb_oargs; i < nb_oargs + nb_iargs; i++) {
939         TCGTemp *ts = arg_temp(op->args[i]);
940         if (ts_is_copy(ts)) {
941             op->args[i] = temp_arg(find_better_copy(ts));
942         }
943     }
944 }
945 
946 static void finish_bb(OptContext *ctx)
947 {
948     /* We only optimize memory barriers across basic blocks. */
949     ctx->prev_mb = NULL;
950 }
951 
952 static void finish_ebb(OptContext *ctx)
953 {
954     finish_bb(ctx);
955     /* We only optimize across extended basic blocks. */
956     memset(&ctx->temps_used, 0, sizeof(ctx->temps_used));
957     remove_mem_copy_all(ctx);
958 }
959 
960 static bool finish_folding(OptContext *ctx, TCGOp *op)
961 {
962     const TCGOpDef *def = &tcg_op_defs[op->opc];
963     int i, nb_oargs;
964 
965     nb_oargs = def->nb_oargs;
966     for (i = 0; i < nb_oargs; i++) {
967         TCGTemp *ts = arg_temp(op->args[i]);
968         reset_ts(ctx, ts);
969     }
970     return true;
971 }
972 
973 /*
974  * The fold_* functions return true when processing is complete,
975  * usually by folding the operation to a constant or to a copy,
976  * and calling tcg_opt_gen_{mov,movi}.  They may do other things,
977  * like collect information about the value produced, for use in
978  * optimizing a subsequent operation.
979  *
980  * These first fold_* functions are all helpers, used by other
981  * folders for more specific operations.
982  */
983 
984 static bool fold_const1(OptContext *ctx, TCGOp *op)
985 {
986     if (arg_is_const(op->args[1])) {
987         uint64_t t;
988 
989         t = arg_info(op->args[1])->val;
990         t = do_constant_folding(op->opc, ctx->type, t, 0);
991         return tcg_opt_gen_movi(ctx, op, op->args[0], t);
992     }
993     return false;
994 }
995 
996 static bool fold_const2(OptContext *ctx, TCGOp *op)
997 {
998     if (arg_is_const(op->args[1]) && arg_is_const(op->args[2])) {
999         uint64_t t1 = arg_info(op->args[1])->val;
1000         uint64_t t2 = arg_info(op->args[2])->val;
1001 
1002         t1 = do_constant_folding(op->opc, ctx->type, t1, t2);
1003         return tcg_opt_gen_movi(ctx, op, op->args[0], t1);
1004     }
1005     return false;
1006 }
1007 
1008 static bool fold_commutative(OptContext *ctx, TCGOp *op)
1009 {
1010     swap_commutative(op->args[0], &op->args[1], &op->args[2]);
1011     return false;
1012 }
1013 
1014 static bool fold_const2_commutative(OptContext *ctx, TCGOp *op)
1015 {
1016     swap_commutative(op->args[0], &op->args[1], &op->args[2]);
1017     return fold_const2(ctx, op);
1018 }
1019 
1020 /*
1021  * Record "zero" and "sign" masks for the single output of @op.
1022  * See TempOptInfo definition of z_mask and s_mask.
1023  * If z_mask allows, fold the output to constant zero.
1024  * The passed s_mask may be augmented by z_mask.
1025  */
1026 static bool fold_masks_zs(OptContext *ctx, TCGOp *op,
1027                           uint64_t z_mask, int64_t s_mask)
1028 {
1029     const TCGOpDef *def = &tcg_op_defs[op->opc];
1030     TCGTemp *ts;
1031     TempOptInfo *ti;
1032     int rep;
1033 
1034     /* Only single-output opcodes are supported here. */
1035     tcg_debug_assert(def->nb_oargs == 1);
1036 
1037     /*
1038      * 32-bit ops generate 32-bit results, which for the purpose of
1039      * simplifying tcg are sign-extended.  Certainly that's how we
1040      * represent our constants elsewhere.  Note that the bits will
1041      * be reset properly for a 64-bit value when encountering the
1042      * type changing opcodes.
1043      */
1044     if (ctx->type == TCG_TYPE_I32) {
1045         z_mask = (int32_t)z_mask;
1046         s_mask |= INT32_MIN;
1047     }
1048 
1049     if (z_mask == 0) {
1050         return tcg_opt_gen_movi(ctx, op, op->args[0], 0);
1051     }
1052 
1053     ts = arg_temp(op->args[0]);
1054     reset_ts(ctx, ts);
1055 
1056     ti = ts_info(ts);
1057     ti->z_mask = z_mask;
1058 
1059     /* Canonicalize s_mask and incorporate data from z_mask. */
1060     rep = clz64(~s_mask);
1061     rep = MAX(rep, clz64(z_mask));
1062     rep = MAX(rep - 1, 0);
1063     ti->s_mask = INT64_MIN >> rep;
1064 
1065     return true;
1066 }
1067 
1068 static bool fold_masks_z(OptContext *ctx, TCGOp *op, uint64_t z_mask)
1069 {
1070     return fold_masks_zs(ctx, op, z_mask, 0);
1071 }
1072 
1073 static bool fold_masks_s(OptContext *ctx, TCGOp *op, uint64_t s_mask)
1074 {
1075     return fold_masks_zs(ctx, op, -1, s_mask);
1076 }
1077 
1078 /*
1079  * An "affected" mask bit is 0 if and only if the result is identical
1080  * to the first input.  Thus if the entire mask is 0, the operation
1081  * is equivalent to a copy.
1082  */
1083 static bool fold_affected_mask(OptContext *ctx, TCGOp *op, uint64_t a_mask)
1084 {
1085     if (ctx->type == TCG_TYPE_I32) {
1086         a_mask = (uint32_t)a_mask;
1087     }
1088     if (a_mask == 0) {
1089         return tcg_opt_gen_mov(ctx, op, op->args[0], op->args[1]);
1090     }
1091     return false;
1092 }
1093 
1094 /*
1095  * Convert @op to NOT, if NOT is supported by the host.
1096  * Return true f the conversion is successful, which will still
1097  * indicate that the processing is complete.
1098  */
1099 static bool fold_not(OptContext *ctx, TCGOp *op);
1100 static bool fold_to_not(OptContext *ctx, TCGOp *op, int idx)
1101 {
1102     TCGOpcode not_op;
1103     bool have_not;
1104 
1105     switch (ctx->type) {
1106     case TCG_TYPE_I32:
1107     case TCG_TYPE_I64:
1108         not_op = INDEX_op_not;
1109         have_not = tcg_op_supported(INDEX_op_not, ctx->type, 0);
1110         break;
1111     case TCG_TYPE_V64:
1112     case TCG_TYPE_V128:
1113     case TCG_TYPE_V256:
1114         not_op = INDEX_op_not_vec;
1115         have_not = TCG_TARGET_HAS_not_vec;
1116         break;
1117     default:
1118         g_assert_not_reached();
1119     }
1120     if (have_not) {
1121         op->opc = not_op;
1122         op->args[1] = op->args[idx];
1123         return fold_not(ctx, op);
1124     }
1125     return false;
1126 }
1127 
1128 /* If the binary operation has first argument @i, fold to @i. */
1129 static bool fold_ix_to_i(OptContext *ctx, TCGOp *op, uint64_t i)
1130 {
1131     if (arg_is_const_val(op->args[1], i)) {
1132         return tcg_opt_gen_movi(ctx, op, op->args[0], i);
1133     }
1134     return false;
1135 }
1136 
1137 /* If the binary operation has first argument @i, fold to NOT. */
1138 static bool fold_ix_to_not(OptContext *ctx, TCGOp *op, uint64_t i)
1139 {
1140     if (arg_is_const_val(op->args[1], i)) {
1141         return fold_to_not(ctx, op, 2);
1142     }
1143     return false;
1144 }
1145 
1146 /* If the binary operation has second argument @i, fold to @i. */
1147 static bool fold_xi_to_i(OptContext *ctx, TCGOp *op, uint64_t i)
1148 {
1149     if (arg_is_const_val(op->args[2], i)) {
1150         return tcg_opt_gen_movi(ctx, op, op->args[0], i);
1151     }
1152     return false;
1153 }
1154 
1155 /* If the binary operation has second argument @i, fold to identity. */
1156 static bool fold_xi_to_x(OptContext *ctx, TCGOp *op, uint64_t i)
1157 {
1158     if (arg_is_const_val(op->args[2], i)) {
1159         return tcg_opt_gen_mov(ctx, op, op->args[0], op->args[1]);
1160     }
1161     return false;
1162 }
1163 
1164 /* If the binary operation has second argument @i, fold to NOT. */
1165 static bool fold_xi_to_not(OptContext *ctx, TCGOp *op, uint64_t i)
1166 {
1167     if (arg_is_const_val(op->args[2], i)) {
1168         return fold_to_not(ctx, op, 1);
1169     }
1170     return false;
1171 }
1172 
1173 /* If the binary operation has both arguments equal, fold to @i. */
1174 static bool fold_xx_to_i(OptContext *ctx, TCGOp *op, uint64_t i)
1175 {
1176     if (args_are_copies(op->args[1], op->args[2])) {
1177         return tcg_opt_gen_movi(ctx, op, op->args[0], i);
1178     }
1179     return false;
1180 }
1181 
1182 /* If the binary operation has both arguments equal, fold to identity. */
1183 static bool fold_xx_to_x(OptContext *ctx, TCGOp *op)
1184 {
1185     if (args_are_copies(op->args[1], op->args[2])) {
1186         return tcg_opt_gen_mov(ctx, op, op->args[0], op->args[1]);
1187     }
1188     return false;
1189 }
1190 
1191 /*
1192  * These outermost fold_<op> functions are sorted alphabetically.
1193  *
1194  * The ordering of the transformations should be:
1195  *   1) those that produce a constant
1196  *   2) those that produce a copy
1197  *   3) those that produce information about the result value.
1198  */
1199 
1200 static bool fold_or(OptContext *ctx, TCGOp *op);
1201 static bool fold_orc(OptContext *ctx, TCGOp *op);
1202 static bool fold_xor(OptContext *ctx, TCGOp *op);
1203 
1204 static bool fold_add(OptContext *ctx, TCGOp *op)
1205 {
1206     if (fold_const2_commutative(ctx, op) ||
1207         fold_xi_to_x(ctx, op, 0)) {
1208         return true;
1209     }
1210     return finish_folding(ctx, op);
1211 }
1212 
1213 /* We cannot as yet do_constant_folding with vectors. */
1214 static bool fold_add_vec(OptContext *ctx, TCGOp *op)
1215 {
1216     if (fold_commutative(ctx, op) ||
1217         fold_xi_to_x(ctx, op, 0)) {
1218         return true;
1219     }
1220     return finish_folding(ctx, op);
1221 }
1222 
1223 static bool fold_addsub2(OptContext *ctx, TCGOp *op, bool add)
1224 {
1225     bool a_const = arg_is_const(op->args[2]) && arg_is_const(op->args[3]);
1226     bool b_const = arg_is_const(op->args[4]) && arg_is_const(op->args[5]);
1227 
1228     if (a_const && b_const) {
1229         uint64_t al = arg_info(op->args[2])->val;
1230         uint64_t ah = arg_info(op->args[3])->val;
1231         uint64_t bl = arg_info(op->args[4])->val;
1232         uint64_t bh = arg_info(op->args[5])->val;
1233         TCGArg rl, rh;
1234         TCGOp *op2;
1235 
1236         if (ctx->type == TCG_TYPE_I32) {
1237             uint64_t a = deposit64(al, 32, 32, ah);
1238             uint64_t b = deposit64(bl, 32, 32, bh);
1239 
1240             if (add) {
1241                 a += b;
1242             } else {
1243                 a -= b;
1244             }
1245 
1246             al = sextract64(a, 0, 32);
1247             ah = sextract64(a, 32, 32);
1248         } else {
1249             Int128 a = int128_make128(al, ah);
1250             Int128 b = int128_make128(bl, bh);
1251 
1252             if (add) {
1253                 a = int128_add(a, b);
1254             } else {
1255                 a = int128_sub(a, b);
1256             }
1257 
1258             al = int128_getlo(a);
1259             ah = int128_gethi(a);
1260         }
1261 
1262         rl = op->args[0];
1263         rh = op->args[1];
1264 
1265         /* The proper opcode is supplied by tcg_opt_gen_mov. */
1266         op2 = opt_insert_before(ctx, op, 0, 2);
1267 
1268         tcg_opt_gen_movi(ctx, op, rl, al);
1269         tcg_opt_gen_movi(ctx, op2, rh, ah);
1270         return true;
1271     }
1272 
1273     /* Fold sub2 r,x,i to add2 r,x,-i */
1274     if (!add && b_const) {
1275         uint64_t bl = arg_info(op->args[4])->val;
1276         uint64_t bh = arg_info(op->args[5])->val;
1277 
1278         /* Negate the two parts without assembling and disassembling. */
1279         bl = -bl;
1280         bh = ~bh + !bl;
1281 
1282         op->opc = (ctx->type == TCG_TYPE_I32
1283                    ? INDEX_op_add2_i32 : INDEX_op_add2_i64);
1284         op->args[4] = arg_new_constant(ctx, bl);
1285         op->args[5] = arg_new_constant(ctx, bh);
1286     }
1287     return finish_folding(ctx, op);
1288 }
1289 
1290 static bool fold_add2(OptContext *ctx, TCGOp *op)
1291 {
1292     /* Note that the high and low parts may be independently swapped. */
1293     swap_commutative(op->args[0], &op->args[2], &op->args[4]);
1294     swap_commutative(op->args[1], &op->args[3], &op->args[5]);
1295 
1296     return fold_addsub2(ctx, op, true);
1297 }
1298 
1299 static bool fold_and(OptContext *ctx, TCGOp *op)
1300 {
1301     uint64_t z1, z2, z_mask, s_mask;
1302     TempOptInfo *t1, *t2;
1303 
1304     if (fold_const2_commutative(ctx, op) ||
1305         fold_xi_to_i(ctx, op, 0) ||
1306         fold_xi_to_x(ctx, op, -1) ||
1307         fold_xx_to_x(ctx, op)) {
1308         return true;
1309     }
1310 
1311     t1 = arg_info(op->args[1]);
1312     t2 = arg_info(op->args[2]);
1313     z1 = t1->z_mask;
1314     z2 = t2->z_mask;
1315 
1316     /*
1317      * Known-zeros does not imply known-ones.  Therefore unless
1318      * arg2 is constant, we can't infer affected bits from it.
1319      */
1320     if (ti_is_const(t2) && fold_affected_mask(ctx, op, z1 & ~z2)) {
1321         return true;
1322     }
1323 
1324     z_mask = z1 & z2;
1325 
1326     /*
1327      * Sign repetitions are perforce all identical, whether they are 1 or 0.
1328      * Bitwise operations preserve the relative quantity of the repetitions.
1329      */
1330     s_mask = t1->s_mask & t2->s_mask;
1331 
1332     return fold_masks_zs(ctx, op, z_mask, s_mask);
1333 }
1334 
1335 static bool fold_andc(OptContext *ctx, TCGOp *op)
1336 {
1337     uint64_t z_mask, s_mask;
1338     TempOptInfo *t1, *t2;
1339 
1340     if (fold_const2(ctx, op) ||
1341         fold_xx_to_i(ctx, op, 0) ||
1342         fold_xi_to_x(ctx, op, 0) ||
1343         fold_ix_to_not(ctx, op, -1)) {
1344         return true;
1345     }
1346 
1347     t1 = arg_info(op->args[1]);
1348     t2 = arg_info(op->args[2]);
1349     z_mask = t1->z_mask;
1350 
1351     if (ti_is_const(t2)) {
1352         /* Fold andc r,x,i to and r,x,~i. */
1353         switch (ctx->type) {
1354         case TCG_TYPE_I32:
1355         case TCG_TYPE_I64:
1356             op->opc = INDEX_op_and;
1357             break;
1358         case TCG_TYPE_V64:
1359         case TCG_TYPE_V128:
1360         case TCG_TYPE_V256:
1361             op->opc = INDEX_op_and_vec;
1362             break;
1363         default:
1364             g_assert_not_reached();
1365         }
1366         op->args[2] = arg_new_constant(ctx, ~ti_const_val(t2));
1367         return fold_and(ctx, op);
1368     }
1369 
1370     /*
1371      * Known-zeros does not imply known-ones.  Therefore unless
1372      * arg2 is constant, we can't infer anything from it.
1373      */
1374     if (ti_is_const(t2)) {
1375         uint64_t v2 = ti_const_val(t2);
1376         if (fold_affected_mask(ctx, op, z_mask & v2)) {
1377             return true;
1378         }
1379         z_mask &= ~v2;
1380     }
1381 
1382     s_mask = t1->s_mask & t2->s_mask;
1383     return fold_masks_zs(ctx, op, z_mask, s_mask);
1384 }
1385 
1386 static bool fold_bitsel_vec(OptContext *ctx, TCGOp *op)
1387 {
1388     /* If true and false values are the same, eliminate the cmp. */
1389     if (args_are_copies(op->args[2], op->args[3])) {
1390         return tcg_opt_gen_mov(ctx, op, op->args[0], op->args[2]);
1391     }
1392 
1393     if (arg_is_const(op->args[2]) && arg_is_const(op->args[3])) {
1394         uint64_t tv = arg_info(op->args[2])->val;
1395         uint64_t fv = arg_info(op->args[3])->val;
1396 
1397         if (tv == -1 && fv == 0) {
1398             return tcg_opt_gen_mov(ctx, op, op->args[0], op->args[1]);
1399         }
1400         if (tv == 0 && fv == -1) {
1401             if (TCG_TARGET_HAS_not_vec) {
1402                 op->opc = INDEX_op_not_vec;
1403                 return fold_not(ctx, op);
1404             } else {
1405                 op->opc = INDEX_op_xor_vec;
1406                 op->args[2] = arg_new_constant(ctx, -1);
1407                 return fold_xor(ctx, op);
1408             }
1409         }
1410     }
1411     if (arg_is_const(op->args[2])) {
1412         uint64_t tv = arg_info(op->args[2])->val;
1413         if (tv == -1) {
1414             op->opc = INDEX_op_or_vec;
1415             op->args[2] = op->args[3];
1416             return fold_or(ctx, op);
1417         }
1418         if (tv == 0 && TCG_TARGET_HAS_andc_vec) {
1419             op->opc = INDEX_op_andc_vec;
1420             op->args[2] = op->args[1];
1421             op->args[1] = op->args[3];
1422             return fold_andc(ctx, op);
1423         }
1424     }
1425     if (arg_is_const(op->args[3])) {
1426         uint64_t fv = arg_info(op->args[3])->val;
1427         if (fv == 0) {
1428             op->opc = INDEX_op_and_vec;
1429             return fold_and(ctx, op);
1430         }
1431         if (fv == -1 && TCG_TARGET_HAS_orc_vec) {
1432             op->opc = INDEX_op_orc_vec;
1433             op->args[2] = op->args[1];
1434             op->args[1] = op->args[3];
1435             return fold_orc(ctx, op);
1436         }
1437     }
1438     return finish_folding(ctx, op);
1439 }
1440 
1441 static bool fold_brcond(OptContext *ctx, TCGOp *op)
1442 {
1443     int i = do_constant_folding_cond1(ctx, op, NO_DEST, &op->args[0],
1444                                       &op->args[1], &op->args[2]);
1445     if (i == 0) {
1446         tcg_op_remove(ctx->tcg, op);
1447         return true;
1448     }
1449     if (i > 0) {
1450         op->opc = INDEX_op_br;
1451         op->args[0] = op->args[3];
1452         finish_ebb(ctx);
1453     } else {
1454         finish_bb(ctx);
1455     }
1456     return true;
1457 }
1458 
1459 static bool fold_brcond2(OptContext *ctx, TCGOp *op)
1460 {
1461     TCGCond cond;
1462     TCGArg label;
1463     int i, inv = 0;
1464 
1465     i = do_constant_folding_cond2(ctx, op, &op->args[0]);
1466     cond = op->args[4];
1467     label = op->args[5];
1468     if (i >= 0) {
1469         goto do_brcond_const;
1470     }
1471 
1472     switch (cond) {
1473     case TCG_COND_LT:
1474     case TCG_COND_GE:
1475         /*
1476          * Simplify LT/GE comparisons vs zero to a single compare
1477          * vs the high word of the input.
1478          */
1479         if (arg_is_const_val(op->args[2], 0) &&
1480             arg_is_const_val(op->args[3], 0)) {
1481             goto do_brcond_high;
1482         }
1483         break;
1484 
1485     case TCG_COND_NE:
1486         inv = 1;
1487         QEMU_FALLTHROUGH;
1488     case TCG_COND_EQ:
1489         /*
1490          * Simplify EQ/NE comparisons where one of the pairs
1491          * can be simplified.
1492          */
1493         i = do_constant_folding_cond(TCG_TYPE_I32, op->args[0],
1494                                      op->args[2], cond);
1495         switch (i ^ inv) {
1496         case 0:
1497             goto do_brcond_const;
1498         case 1:
1499             goto do_brcond_high;
1500         }
1501 
1502         i = do_constant_folding_cond(TCG_TYPE_I32, op->args[1],
1503                                      op->args[3], cond);
1504         switch (i ^ inv) {
1505         case 0:
1506             goto do_brcond_const;
1507         case 1:
1508             goto do_brcond_low;
1509         }
1510         break;
1511 
1512     case TCG_COND_TSTEQ:
1513     case TCG_COND_TSTNE:
1514         if (arg_is_const_val(op->args[2], 0)) {
1515             goto do_brcond_high;
1516         }
1517         if (arg_is_const_val(op->args[3], 0)) {
1518             goto do_brcond_low;
1519         }
1520         break;
1521 
1522     default:
1523         break;
1524 
1525     do_brcond_low:
1526         op->opc = INDEX_op_brcond_i32;
1527         op->args[1] = op->args[2];
1528         op->args[2] = cond;
1529         op->args[3] = label;
1530         return fold_brcond(ctx, op);
1531 
1532     do_brcond_high:
1533         op->opc = INDEX_op_brcond_i32;
1534         op->args[0] = op->args[1];
1535         op->args[1] = op->args[3];
1536         op->args[2] = cond;
1537         op->args[3] = label;
1538         return fold_brcond(ctx, op);
1539 
1540     do_brcond_const:
1541         if (i == 0) {
1542             tcg_op_remove(ctx->tcg, op);
1543             return true;
1544         }
1545         op->opc = INDEX_op_br;
1546         op->args[0] = label;
1547         finish_ebb(ctx);
1548         return true;
1549     }
1550 
1551     finish_bb(ctx);
1552     return true;
1553 }
1554 
1555 static bool fold_bswap(OptContext *ctx, TCGOp *op)
1556 {
1557     uint64_t z_mask, s_mask, sign;
1558     TempOptInfo *t1 = arg_info(op->args[1]);
1559 
1560     if (ti_is_const(t1)) {
1561         return tcg_opt_gen_movi(ctx, op, op->args[0],
1562                                 do_constant_folding(op->opc, ctx->type,
1563                                                     ti_const_val(t1),
1564                                                     op->args[2]));
1565     }
1566 
1567     z_mask = t1->z_mask;
1568     switch (op->opc) {
1569     case INDEX_op_bswap16_i32:
1570     case INDEX_op_bswap16_i64:
1571         z_mask = bswap16(z_mask);
1572         sign = INT16_MIN;
1573         break;
1574     case INDEX_op_bswap32_i32:
1575     case INDEX_op_bswap32_i64:
1576         z_mask = bswap32(z_mask);
1577         sign = INT32_MIN;
1578         break;
1579     case INDEX_op_bswap64_i64:
1580         z_mask = bswap64(z_mask);
1581         sign = INT64_MIN;
1582         break;
1583     default:
1584         g_assert_not_reached();
1585     }
1586 
1587     s_mask = 0;
1588     switch (op->args[2] & (TCG_BSWAP_OZ | TCG_BSWAP_OS)) {
1589     case TCG_BSWAP_OZ:
1590         break;
1591     case TCG_BSWAP_OS:
1592         /* If the sign bit may be 1, force all the bits above to 1. */
1593         if (z_mask & sign) {
1594             z_mask |= sign;
1595         }
1596         /* The value and therefore s_mask is explicitly sign-extended. */
1597         s_mask = sign;
1598         break;
1599     default:
1600         /* The high bits are undefined: force all bits above the sign to 1. */
1601         z_mask |= sign << 1;
1602         break;
1603     }
1604 
1605     return fold_masks_zs(ctx, op, z_mask, s_mask);
1606 }
1607 
1608 static bool fold_call(OptContext *ctx, TCGOp *op)
1609 {
1610     TCGContext *s = ctx->tcg;
1611     int nb_oargs = TCGOP_CALLO(op);
1612     int nb_iargs = TCGOP_CALLI(op);
1613     int flags, i;
1614 
1615     init_arguments(ctx, op, nb_oargs + nb_iargs);
1616     copy_propagate(ctx, op, nb_oargs, nb_iargs);
1617 
1618     /* If the function reads or writes globals, reset temp data. */
1619     flags = tcg_call_flags(op);
1620     if (!(flags & (TCG_CALL_NO_READ_GLOBALS | TCG_CALL_NO_WRITE_GLOBALS))) {
1621         int nb_globals = s->nb_globals;
1622 
1623         for (i = 0; i < nb_globals; i++) {
1624             if (test_bit(i, ctx->temps_used.l)) {
1625                 reset_ts(ctx, &ctx->tcg->temps[i]);
1626             }
1627         }
1628     }
1629 
1630     /* If the function has side effects, reset mem data. */
1631     if (!(flags & TCG_CALL_NO_SIDE_EFFECTS)) {
1632         remove_mem_copy_all(ctx);
1633     }
1634 
1635     /* Reset temp data for outputs. */
1636     for (i = 0; i < nb_oargs; i++) {
1637         reset_temp(ctx, op->args[i]);
1638     }
1639 
1640     /* Stop optimizing MB across calls. */
1641     ctx->prev_mb = NULL;
1642     return true;
1643 }
1644 
1645 static bool fold_cmp_vec(OptContext *ctx, TCGOp *op)
1646 {
1647     /* Canonicalize the comparison to put immediate second. */
1648     if (swap_commutative(NO_DEST, &op->args[1], &op->args[2])) {
1649         op->args[3] = tcg_swap_cond(op->args[3]);
1650     }
1651     return finish_folding(ctx, op);
1652 }
1653 
1654 static bool fold_cmpsel_vec(OptContext *ctx, TCGOp *op)
1655 {
1656     /* If true and false values are the same, eliminate the cmp. */
1657     if (args_are_copies(op->args[3], op->args[4])) {
1658         return tcg_opt_gen_mov(ctx, op, op->args[0], op->args[3]);
1659     }
1660 
1661     /* Canonicalize the comparison to put immediate second. */
1662     if (swap_commutative(NO_DEST, &op->args[1], &op->args[2])) {
1663         op->args[5] = tcg_swap_cond(op->args[5]);
1664     }
1665     /*
1666      * Canonicalize the "false" input reg to match the destination,
1667      * so that the tcg backend can implement "move if true".
1668      */
1669     if (swap_commutative(op->args[0], &op->args[4], &op->args[3])) {
1670         op->args[5] = tcg_invert_cond(op->args[5]);
1671     }
1672     return finish_folding(ctx, op);
1673 }
1674 
1675 static bool fold_count_zeros(OptContext *ctx, TCGOp *op)
1676 {
1677     uint64_t z_mask, s_mask;
1678     TempOptInfo *t1 = arg_info(op->args[1]);
1679     TempOptInfo *t2 = arg_info(op->args[2]);
1680 
1681     if (ti_is_const(t1)) {
1682         uint64_t t = ti_const_val(t1);
1683 
1684         if (t != 0) {
1685             t = do_constant_folding(op->opc, ctx->type, t, 0);
1686             return tcg_opt_gen_movi(ctx, op, op->args[0], t);
1687         }
1688         return tcg_opt_gen_mov(ctx, op, op->args[0], op->args[2]);
1689     }
1690 
1691     switch (ctx->type) {
1692     case TCG_TYPE_I32:
1693         z_mask = 31;
1694         break;
1695     case TCG_TYPE_I64:
1696         z_mask = 63;
1697         break;
1698     default:
1699         g_assert_not_reached();
1700     }
1701     s_mask = ~z_mask;
1702     z_mask |= t2->z_mask;
1703     s_mask &= t2->s_mask;
1704 
1705     return fold_masks_zs(ctx, op, z_mask, s_mask);
1706 }
1707 
1708 static bool fold_ctpop(OptContext *ctx, TCGOp *op)
1709 {
1710     uint64_t z_mask;
1711 
1712     if (fold_const1(ctx, op)) {
1713         return true;
1714     }
1715 
1716     switch (ctx->type) {
1717     case TCG_TYPE_I32:
1718         z_mask = 32 | 31;
1719         break;
1720     case TCG_TYPE_I64:
1721         z_mask = 64 | 63;
1722         break;
1723     default:
1724         g_assert_not_reached();
1725     }
1726     return fold_masks_z(ctx, op, z_mask);
1727 }
1728 
1729 static bool fold_deposit(OptContext *ctx, TCGOp *op)
1730 {
1731     TempOptInfo *t1 = arg_info(op->args[1]);
1732     TempOptInfo *t2 = arg_info(op->args[2]);
1733     int ofs = op->args[3];
1734     int len = op->args[4];
1735     int width = 8 * tcg_type_size(ctx->type);
1736     uint64_t z_mask, s_mask;
1737 
1738     if (ti_is_const(t1) && ti_is_const(t2)) {
1739         return tcg_opt_gen_movi(ctx, op, op->args[0],
1740                                 deposit64(ti_const_val(t1), ofs, len,
1741                                           ti_const_val(t2)));
1742     }
1743 
1744     /* Inserting a value into zero at offset 0. */
1745     if (ti_is_const_val(t1, 0) && ofs == 0) {
1746         uint64_t mask = MAKE_64BIT_MASK(0, len);
1747 
1748         op->opc = INDEX_op_and;
1749         op->args[1] = op->args[2];
1750         op->args[2] = arg_new_constant(ctx, mask);
1751         return fold_and(ctx, op);
1752     }
1753 
1754     /* Inserting zero into a value. */
1755     if (ti_is_const_val(t2, 0)) {
1756         uint64_t mask = deposit64(-1, ofs, len, 0);
1757 
1758         op->opc = INDEX_op_and;
1759         op->args[2] = arg_new_constant(ctx, mask);
1760         return fold_and(ctx, op);
1761     }
1762 
1763     /* The s_mask from the top portion of the deposit is still valid. */
1764     if (ofs + len == width) {
1765         s_mask = t2->s_mask << ofs;
1766     } else {
1767         s_mask = t1->s_mask & ~MAKE_64BIT_MASK(0, ofs + len);
1768     }
1769 
1770     z_mask = deposit64(t1->z_mask, ofs, len, t2->z_mask);
1771     return fold_masks_zs(ctx, op, z_mask, s_mask);
1772 }
1773 
1774 static bool fold_divide(OptContext *ctx, TCGOp *op)
1775 {
1776     if (fold_const2(ctx, op) ||
1777         fold_xi_to_x(ctx, op, 1)) {
1778         return true;
1779     }
1780     return finish_folding(ctx, op);
1781 }
1782 
1783 static bool fold_dup(OptContext *ctx, TCGOp *op)
1784 {
1785     if (arg_is_const(op->args[1])) {
1786         uint64_t t = arg_info(op->args[1])->val;
1787         t = dup_const(TCGOP_VECE(op), t);
1788         return tcg_opt_gen_movi(ctx, op, op->args[0], t);
1789     }
1790     return finish_folding(ctx, op);
1791 }
1792 
1793 static bool fold_dup2(OptContext *ctx, TCGOp *op)
1794 {
1795     if (arg_is_const(op->args[1]) && arg_is_const(op->args[2])) {
1796         uint64_t t = deposit64(arg_info(op->args[1])->val, 32, 32,
1797                                arg_info(op->args[2])->val);
1798         return tcg_opt_gen_movi(ctx, op, op->args[0], t);
1799     }
1800 
1801     if (args_are_copies(op->args[1], op->args[2])) {
1802         op->opc = INDEX_op_dup_vec;
1803         TCGOP_VECE(op) = MO_32;
1804     }
1805     return finish_folding(ctx, op);
1806 }
1807 
1808 static bool fold_eqv(OptContext *ctx, TCGOp *op)
1809 {
1810     uint64_t s_mask;
1811     TempOptInfo *t1, *t2;
1812 
1813     if (fold_const2_commutative(ctx, op) ||
1814         fold_xi_to_x(ctx, op, -1) ||
1815         fold_xi_to_not(ctx, op, 0)) {
1816         return true;
1817     }
1818 
1819     t2 = arg_info(op->args[2]);
1820     if (ti_is_const(t2)) {
1821         /* Fold eqv r,x,i to xor r,x,~i. */
1822         switch (ctx->type) {
1823         case TCG_TYPE_I32:
1824         case TCG_TYPE_I64:
1825             op->opc = INDEX_op_xor;
1826             break;
1827         case TCG_TYPE_V64:
1828         case TCG_TYPE_V128:
1829         case TCG_TYPE_V256:
1830             op->opc = INDEX_op_xor_vec;
1831             break;
1832         default:
1833             g_assert_not_reached();
1834         }
1835         op->args[2] = arg_new_constant(ctx, ~ti_const_val(t2));
1836         return fold_xor(ctx, op);
1837     }
1838 
1839     t1 = arg_info(op->args[1]);
1840     s_mask = t1->s_mask & t2->s_mask;
1841     return fold_masks_s(ctx, op, s_mask);
1842 }
1843 
1844 static bool fold_extract(OptContext *ctx, TCGOp *op)
1845 {
1846     uint64_t z_mask_old, z_mask;
1847     TempOptInfo *t1 = arg_info(op->args[1]);
1848     int pos = op->args[2];
1849     int len = op->args[3];
1850 
1851     if (ti_is_const(t1)) {
1852         return tcg_opt_gen_movi(ctx, op, op->args[0],
1853                                 extract64(ti_const_val(t1), pos, len));
1854     }
1855 
1856     z_mask_old = t1->z_mask;
1857     z_mask = extract64(z_mask_old, pos, len);
1858     if (pos == 0 && fold_affected_mask(ctx, op, z_mask_old ^ z_mask)) {
1859         return true;
1860     }
1861 
1862     return fold_masks_z(ctx, op, z_mask);
1863 }
1864 
1865 static bool fold_extract2(OptContext *ctx, TCGOp *op)
1866 {
1867     if (arg_is_const(op->args[1]) && arg_is_const(op->args[2])) {
1868         uint64_t v1 = arg_info(op->args[1])->val;
1869         uint64_t v2 = arg_info(op->args[2])->val;
1870         int shr = op->args[3];
1871 
1872         if (op->opc == INDEX_op_extract2_i64) {
1873             v1 >>= shr;
1874             v2 <<= 64 - shr;
1875         } else {
1876             v1 = (uint32_t)v1 >> shr;
1877             v2 = (uint64_t)((int32_t)v2 << (32 - shr));
1878         }
1879         return tcg_opt_gen_movi(ctx, op, op->args[0], v1 | v2);
1880     }
1881     return finish_folding(ctx, op);
1882 }
1883 
1884 static bool fold_exts(OptContext *ctx, TCGOp *op)
1885 {
1886     uint64_t s_mask, z_mask;
1887     TempOptInfo *t1;
1888 
1889     if (fold_const1(ctx, op)) {
1890         return true;
1891     }
1892 
1893     t1 = arg_info(op->args[1]);
1894     z_mask = t1->z_mask;
1895     s_mask = t1->s_mask;
1896 
1897     switch (op->opc) {
1898     case INDEX_op_ext_i32_i64:
1899         s_mask |= INT32_MIN;
1900         z_mask = (int32_t)z_mask;
1901         break;
1902     default:
1903         g_assert_not_reached();
1904     }
1905     return fold_masks_zs(ctx, op, z_mask, s_mask);
1906 }
1907 
1908 static bool fold_extu(OptContext *ctx, TCGOp *op)
1909 {
1910     uint64_t z_mask;
1911 
1912     if (fold_const1(ctx, op)) {
1913         return true;
1914     }
1915 
1916     z_mask = arg_info(op->args[1])->z_mask;
1917     switch (op->opc) {
1918     case INDEX_op_extrl_i64_i32:
1919     case INDEX_op_extu_i32_i64:
1920         z_mask = (uint32_t)z_mask;
1921         break;
1922     case INDEX_op_extrh_i64_i32:
1923         z_mask >>= 32;
1924         break;
1925     default:
1926         g_assert_not_reached();
1927     }
1928     return fold_masks_z(ctx, op, z_mask);
1929 }
1930 
1931 static bool fold_mb(OptContext *ctx, TCGOp *op)
1932 {
1933     /* Eliminate duplicate and redundant fence instructions.  */
1934     if (ctx->prev_mb) {
1935         /*
1936          * Merge two barriers of the same type into one,
1937          * or a weaker barrier into a stronger one,
1938          * or two weaker barriers into a stronger one.
1939          *   mb X; mb Y => mb X|Y
1940          *   mb; strl => mb; st
1941          *   ldaq; mb => ld; mb
1942          *   ldaq; strl => ld; mb; st
1943          * Other combinations are also merged into a strong
1944          * barrier.  This is stricter than specified but for
1945          * the purposes of TCG is better than not optimizing.
1946          */
1947         ctx->prev_mb->args[0] |= op->args[0];
1948         tcg_op_remove(ctx->tcg, op);
1949     } else {
1950         ctx->prev_mb = op;
1951     }
1952     return true;
1953 }
1954 
1955 static bool fold_mov(OptContext *ctx, TCGOp *op)
1956 {
1957     return tcg_opt_gen_mov(ctx, op, op->args[0], op->args[1]);
1958 }
1959 
1960 static bool fold_movcond(OptContext *ctx, TCGOp *op)
1961 {
1962     uint64_t z_mask, s_mask;
1963     TempOptInfo *tt, *ft;
1964     int i;
1965 
1966     /* If true and false values are the same, eliminate the cmp. */
1967     if (args_are_copies(op->args[3], op->args[4])) {
1968         return tcg_opt_gen_mov(ctx, op, op->args[0], op->args[3]);
1969     }
1970 
1971     /*
1972      * Canonicalize the "false" input reg to match the destination reg so
1973      * that the tcg backend can implement a "move if true" operation.
1974      */
1975     if (swap_commutative(op->args[0], &op->args[4], &op->args[3])) {
1976         op->args[5] = tcg_invert_cond(op->args[5]);
1977     }
1978 
1979     i = do_constant_folding_cond1(ctx, op, NO_DEST, &op->args[1],
1980                                   &op->args[2], &op->args[5]);
1981     if (i >= 0) {
1982         return tcg_opt_gen_mov(ctx, op, op->args[0], op->args[4 - i]);
1983     }
1984 
1985     tt = arg_info(op->args[3]);
1986     ft = arg_info(op->args[4]);
1987     z_mask = tt->z_mask | ft->z_mask;
1988     s_mask = tt->s_mask & ft->s_mask;
1989 
1990     if (ti_is_const(tt) && ti_is_const(ft)) {
1991         uint64_t tv = ti_const_val(tt);
1992         uint64_t fv = ti_const_val(ft);
1993         TCGOpcode opc, negopc = 0;
1994         TCGCond cond = op->args[5];
1995 
1996         switch (ctx->type) {
1997         case TCG_TYPE_I32:
1998             opc = INDEX_op_setcond_i32;
1999             if (TCG_TARGET_HAS_negsetcond_i32) {
2000                 negopc = INDEX_op_negsetcond_i32;
2001             }
2002             tv = (int32_t)tv;
2003             fv = (int32_t)fv;
2004             break;
2005         case TCG_TYPE_I64:
2006             opc = INDEX_op_setcond_i64;
2007             if (TCG_TARGET_HAS_negsetcond_i64) {
2008                 negopc = INDEX_op_negsetcond_i64;
2009             }
2010             break;
2011         default:
2012             g_assert_not_reached();
2013         }
2014 
2015         if (tv == 1 && fv == 0) {
2016             op->opc = opc;
2017             op->args[3] = cond;
2018         } else if (fv == 1 && tv == 0) {
2019             op->opc = opc;
2020             op->args[3] = tcg_invert_cond(cond);
2021         } else if (negopc) {
2022             if (tv == -1 && fv == 0) {
2023                 op->opc = negopc;
2024                 op->args[3] = cond;
2025             } else if (fv == -1 && tv == 0) {
2026                 op->opc = negopc;
2027                 op->args[3] = tcg_invert_cond(cond);
2028             }
2029         }
2030     }
2031 
2032     return fold_masks_zs(ctx, op, z_mask, s_mask);
2033 }
2034 
2035 static bool fold_mul(OptContext *ctx, TCGOp *op)
2036 {
2037     if (fold_const2(ctx, op) ||
2038         fold_xi_to_i(ctx, op, 0) ||
2039         fold_xi_to_x(ctx, op, 1)) {
2040         return true;
2041     }
2042     return finish_folding(ctx, op);
2043 }
2044 
2045 static bool fold_mul_highpart(OptContext *ctx, TCGOp *op)
2046 {
2047     if (fold_const2_commutative(ctx, op) ||
2048         fold_xi_to_i(ctx, op, 0)) {
2049         return true;
2050     }
2051     return finish_folding(ctx, op);
2052 }
2053 
2054 static bool fold_multiply2(OptContext *ctx, TCGOp *op)
2055 {
2056     swap_commutative(op->args[0], &op->args[2], &op->args[3]);
2057 
2058     if (arg_is_const(op->args[2]) && arg_is_const(op->args[3])) {
2059         uint64_t a = arg_info(op->args[2])->val;
2060         uint64_t b = arg_info(op->args[3])->val;
2061         uint64_t h, l;
2062         TCGArg rl, rh;
2063         TCGOp *op2;
2064 
2065         switch (op->opc) {
2066         case INDEX_op_mulu2_i32:
2067             l = (uint64_t)(uint32_t)a * (uint32_t)b;
2068             h = (int32_t)(l >> 32);
2069             l = (int32_t)l;
2070             break;
2071         case INDEX_op_muls2_i32:
2072             l = (int64_t)(int32_t)a * (int32_t)b;
2073             h = l >> 32;
2074             l = (int32_t)l;
2075             break;
2076         case INDEX_op_mulu2_i64:
2077             mulu64(&l, &h, a, b);
2078             break;
2079         case INDEX_op_muls2_i64:
2080             muls64(&l, &h, a, b);
2081             break;
2082         default:
2083             g_assert_not_reached();
2084         }
2085 
2086         rl = op->args[0];
2087         rh = op->args[1];
2088 
2089         /* The proper opcode is supplied by tcg_opt_gen_mov. */
2090         op2 = opt_insert_before(ctx, op, 0, 2);
2091 
2092         tcg_opt_gen_movi(ctx, op, rl, l);
2093         tcg_opt_gen_movi(ctx, op2, rh, h);
2094         return true;
2095     }
2096     return finish_folding(ctx, op);
2097 }
2098 
2099 static bool fold_nand(OptContext *ctx, TCGOp *op)
2100 {
2101     uint64_t s_mask;
2102 
2103     if (fold_const2_commutative(ctx, op) ||
2104         fold_xi_to_not(ctx, op, -1)) {
2105         return true;
2106     }
2107 
2108     s_mask = arg_info(op->args[1])->s_mask
2109            & arg_info(op->args[2])->s_mask;
2110     return fold_masks_s(ctx, op, s_mask);
2111 }
2112 
2113 static bool fold_neg_no_const(OptContext *ctx, TCGOp *op)
2114 {
2115     /* Set to 1 all bits to the left of the rightmost.  */
2116     uint64_t z_mask = arg_info(op->args[1])->z_mask;
2117     z_mask = -(z_mask & -z_mask);
2118 
2119     return fold_masks_z(ctx, op, z_mask);
2120 }
2121 
2122 static bool fold_neg(OptContext *ctx, TCGOp *op)
2123 {
2124     return fold_const1(ctx, op) || fold_neg_no_const(ctx, op);
2125 }
2126 
2127 static bool fold_nor(OptContext *ctx, TCGOp *op)
2128 {
2129     uint64_t s_mask;
2130 
2131     if (fold_const2_commutative(ctx, op) ||
2132         fold_xi_to_not(ctx, op, 0)) {
2133         return true;
2134     }
2135 
2136     s_mask = arg_info(op->args[1])->s_mask
2137            & arg_info(op->args[2])->s_mask;
2138     return fold_masks_s(ctx, op, s_mask);
2139 }
2140 
2141 static bool fold_not(OptContext *ctx, TCGOp *op)
2142 {
2143     if (fold_const1(ctx, op)) {
2144         return true;
2145     }
2146     return fold_masks_s(ctx, op, arg_info(op->args[1])->s_mask);
2147 }
2148 
2149 static bool fold_or(OptContext *ctx, TCGOp *op)
2150 {
2151     uint64_t z_mask, s_mask;
2152     TempOptInfo *t1, *t2;
2153 
2154     if (fold_const2_commutative(ctx, op) ||
2155         fold_xi_to_x(ctx, op, 0) ||
2156         fold_xx_to_x(ctx, op)) {
2157         return true;
2158     }
2159 
2160     t1 = arg_info(op->args[1]);
2161     t2 = arg_info(op->args[2]);
2162     z_mask = t1->z_mask | t2->z_mask;
2163     s_mask = t1->s_mask & t2->s_mask;
2164     return fold_masks_zs(ctx, op, z_mask, s_mask);
2165 }
2166 
2167 static bool fold_orc(OptContext *ctx, TCGOp *op)
2168 {
2169     uint64_t s_mask;
2170     TempOptInfo *t1, *t2;
2171 
2172     if (fold_const2(ctx, op) ||
2173         fold_xx_to_i(ctx, op, -1) ||
2174         fold_xi_to_x(ctx, op, -1) ||
2175         fold_ix_to_not(ctx, op, 0)) {
2176         return true;
2177     }
2178 
2179     t2 = arg_info(op->args[2]);
2180     if (ti_is_const(t2)) {
2181         /* Fold orc r,x,i to or r,x,~i. */
2182         switch (ctx->type) {
2183         case TCG_TYPE_I32:
2184         case TCG_TYPE_I64:
2185             op->opc = INDEX_op_or;
2186             break;
2187         case TCG_TYPE_V64:
2188         case TCG_TYPE_V128:
2189         case TCG_TYPE_V256:
2190             op->opc = INDEX_op_or_vec;
2191             break;
2192         default:
2193             g_assert_not_reached();
2194         }
2195         op->args[2] = arg_new_constant(ctx, ~ti_const_val(t2));
2196         return fold_or(ctx, op);
2197     }
2198 
2199     t1 = arg_info(op->args[1]);
2200     s_mask = t1->s_mask & t2->s_mask;
2201     return fold_masks_s(ctx, op, s_mask);
2202 }
2203 
2204 static bool fold_qemu_ld_1reg(OptContext *ctx, TCGOp *op)
2205 {
2206     const TCGOpDef *def = &tcg_op_defs[op->opc];
2207     MemOpIdx oi = op->args[def->nb_oargs + def->nb_iargs];
2208     MemOp mop = get_memop(oi);
2209     int width = 8 * memop_size(mop);
2210     uint64_t z_mask = -1, s_mask = 0;
2211 
2212     if (width < 64) {
2213         if (mop & MO_SIGN) {
2214             s_mask = MAKE_64BIT_MASK(width - 1, 64 - (width - 1));
2215         } else {
2216             z_mask = MAKE_64BIT_MASK(0, width);
2217         }
2218     }
2219 
2220     /* Opcodes that touch guest memory stop the mb optimization.  */
2221     ctx->prev_mb = NULL;
2222 
2223     return fold_masks_zs(ctx, op, z_mask, s_mask);
2224 }
2225 
2226 static bool fold_qemu_ld_2reg(OptContext *ctx, TCGOp *op)
2227 {
2228     /* Opcodes that touch guest memory stop the mb optimization.  */
2229     ctx->prev_mb = NULL;
2230     return finish_folding(ctx, op);
2231 }
2232 
2233 static bool fold_qemu_st(OptContext *ctx, TCGOp *op)
2234 {
2235     /* Opcodes that touch guest memory stop the mb optimization.  */
2236     ctx->prev_mb = NULL;
2237     return true;
2238 }
2239 
2240 static bool fold_remainder(OptContext *ctx, TCGOp *op)
2241 {
2242     if (fold_const2(ctx, op) ||
2243         fold_xx_to_i(ctx, op, 0)) {
2244         return true;
2245     }
2246     return finish_folding(ctx, op);
2247 }
2248 
2249 /* Return 1 if finished, -1 if simplified, 0 if unchanged. */
2250 static int fold_setcond_zmask(OptContext *ctx, TCGOp *op, bool neg)
2251 {
2252     uint64_t a_zmask, b_val;
2253     TCGCond cond;
2254 
2255     if (!arg_is_const(op->args[2])) {
2256         return false;
2257     }
2258 
2259     a_zmask = arg_info(op->args[1])->z_mask;
2260     b_val = arg_info(op->args[2])->val;
2261     cond = op->args[3];
2262 
2263     if (ctx->type == TCG_TYPE_I32) {
2264         a_zmask = (uint32_t)a_zmask;
2265         b_val = (uint32_t)b_val;
2266     }
2267 
2268     /*
2269      * A with only low bits set vs B with high bits set means that A < B.
2270      */
2271     if (a_zmask < b_val) {
2272         bool inv = false;
2273 
2274         switch (cond) {
2275         case TCG_COND_NE:
2276         case TCG_COND_LEU:
2277         case TCG_COND_LTU:
2278             inv = true;
2279             /* fall through */
2280         case TCG_COND_GTU:
2281         case TCG_COND_GEU:
2282         case TCG_COND_EQ:
2283             return tcg_opt_gen_movi(ctx, op, op->args[0], neg ? -inv : inv);
2284         default:
2285             break;
2286         }
2287     }
2288 
2289     /*
2290      * A with only lsb set is already boolean.
2291      */
2292     if (a_zmask <= 1) {
2293         bool convert = false;
2294         bool inv = false;
2295 
2296         switch (cond) {
2297         case TCG_COND_EQ:
2298             inv = true;
2299             /* fall through */
2300         case TCG_COND_NE:
2301             convert = (b_val == 0);
2302             break;
2303         case TCG_COND_LTU:
2304         case TCG_COND_TSTEQ:
2305             inv = true;
2306             /* fall through */
2307         case TCG_COND_GEU:
2308         case TCG_COND_TSTNE:
2309             convert = (b_val == 1);
2310             break;
2311         default:
2312             break;
2313         }
2314         if (convert) {
2315             if (!inv && !neg) {
2316                 return tcg_opt_gen_mov(ctx, op, op->args[0], op->args[1]);
2317             }
2318 
2319             if (!inv) {
2320                 op->opc = INDEX_op_neg;
2321             } else if (neg) {
2322                 op->opc = INDEX_op_add;
2323                 op->args[2] = arg_new_constant(ctx, -1);
2324             } else {
2325                 op->opc = INDEX_op_xor;
2326                 op->args[2] = arg_new_constant(ctx, 1);
2327             }
2328             return -1;
2329         }
2330     }
2331     return 0;
2332 }
2333 
2334 static void fold_setcond_tst_pow2(OptContext *ctx, TCGOp *op, bool neg)
2335 {
2336     TCGOpcode shr_opc;
2337     TCGOpcode uext_opc = 0, sext_opc = 0;
2338     TCGCond cond = op->args[3];
2339     TCGArg ret, src1, src2;
2340     TCGOp *op2;
2341     uint64_t val;
2342     int sh;
2343     bool inv;
2344 
2345     if (!is_tst_cond(cond) || !arg_is_const(op->args[2])) {
2346         return;
2347     }
2348 
2349     src2 = op->args[2];
2350     val = arg_info(src2)->val;
2351     if (!is_power_of_2(val)) {
2352         return;
2353     }
2354     sh = ctz64(val);
2355 
2356     switch (ctx->type) {
2357     case TCG_TYPE_I32:
2358         shr_opc = INDEX_op_shr_i32;
2359         if (TCG_TARGET_extract_valid(TCG_TYPE_I32, sh, 1)) {
2360             uext_opc = INDEX_op_extract_i32;
2361         }
2362         if (TCG_TARGET_sextract_valid(TCG_TYPE_I32, sh, 1)) {
2363             sext_opc = INDEX_op_sextract_i32;
2364         }
2365         break;
2366     case TCG_TYPE_I64:
2367         shr_opc = INDEX_op_shr_i64;
2368         if (TCG_TARGET_extract_valid(TCG_TYPE_I64, sh, 1)) {
2369             uext_opc = INDEX_op_extract_i64;
2370         }
2371         if (TCG_TARGET_sextract_valid(TCG_TYPE_I64, sh, 1)) {
2372             sext_opc = INDEX_op_sextract_i64;
2373         }
2374         break;
2375     default:
2376         g_assert_not_reached();
2377     }
2378 
2379     ret = op->args[0];
2380     src1 = op->args[1];
2381     inv = cond == TCG_COND_TSTEQ;
2382 
2383     if (sh && sext_opc && neg && !inv) {
2384         op->opc = sext_opc;
2385         op->args[1] = src1;
2386         op->args[2] = sh;
2387         op->args[3] = 1;
2388         return;
2389     } else if (sh && uext_opc) {
2390         op->opc = uext_opc;
2391         op->args[1] = src1;
2392         op->args[2] = sh;
2393         op->args[3] = 1;
2394     } else {
2395         if (sh) {
2396             op2 = opt_insert_before(ctx, op, shr_opc, 3);
2397             op2->args[0] = ret;
2398             op2->args[1] = src1;
2399             op2->args[2] = arg_new_constant(ctx, sh);
2400             src1 = ret;
2401         }
2402         op->opc = INDEX_op_and;
2403         op->args[1] = src1;
2404         op->args[2] = arg_new_constant(ctx, 1);
2405     }
2406 
2407     if (neg && inv) {
2408         op2 = opt_insert_after(ctx, op, INDEX_op_add, 3);
2409         op2->args[0] = ret;
2410         op2->args[1] = ret;
2411         op2->args[2] = arg_new_constant(ctx, -1);
2412     } else if (inv) {
2413         op2 = opt_insert_after(ctx, op, INDEX_op_xor, 3);
2414         op2->args[0] = ret;
2415         op2->args[1] = ret;
2416         op2->args[2] = arg_new_constant(ctx, 1);
2417     } else if (neg) {
2418         op2 = opt_insert_after(ctx, op, INDEX_op_neg, 2);
2419         op2->args[0] = ret;
2420         op2->args[1] = ret;
2421     }
2422 }
2423 
2424 static bool fold_setcond(OptContext *ctx, TCGOp *op)
2425 {
2426     int i = do_constant_folding_cond1(ctx, op, op->args[0], &op->args[1],
2427                                       &op->args[2], &op->args[3]);
2428     if (i >= 0) {
2429         return tcg_opt_gen_movi(ctx, op, op->args[0], i);
2430     }
2431 
2432     i = fold_setcond_zmask(ctx, op, false);
2433     if (i > 0) {
2434         return true;
2435     }
2436     if (i == 0) {
2437         fold_setcond_tst_pow2(ctx, op, false);
2438     }
2439 
2440     return fold_masks_z(ctx, op, 1);
2441 }
2442 
2443 static bool fold_negsetcond(OptContext *ctx, TCGOp *op)
2444 {
2445     int i = do_constant_folding_cond1(ctx, op, op->args[0], &op->args[1],
2446                                       &op->args[2], &op->args[3]);
2447     if (i >= 0) {
2448         return tcg_opt_gen_movi(ctx, op, op->args[0], -i);
2449     }
2450 
2451     i = fold_setcond_zmask(ctx, op, true);
2452     if (i > 0) {
2453         return true;
2454     }
2455     if (i == 0) {
2456         fold_setcond_tst_pow2(ctx, op, true);
2457     }
2458 
2459     /* Value is {0,-1} so all bits are repetitions of the sign. */
2460     return fold_masks_s(ctx, op, -1);
2461 }
2462 
2463 static bool fold_setcond2(OptContext *ctx, TCGOp *op)
2464 {
2465     TCGCond cond;
2466     int i, inv = 0;
2467 
2468     i = do_constant_folding_cond2(ctx, op, &op->args[1]);
2469     cond = op->args[5];
2470     if (i >= 0) {
2471         goto do_setcond_const;
2472     }
2473 
2474     switch (cond) {
2475     case TCG_COND_LT:
2476     case TCG_COND_GE:
2477         /*
2478          * Simplify LT/GE comparisons vs zero to a single compare
2479          * vs the high word of the input.
2480          */
2481         if (arg_is_const_val(op->args[3], 0) &&
2482             arg_is_const_val(op->args[4], 0)) {
2483             goto do_setcond_high;
2484         }
2485         break;
2486 
2487     case TCG_COND_NE:
2488         inv = 1;
2489         QEMU_FALLTHROUGH;
2490     case TCG_COND_EQ:
2491         /*
2492          * Simplify EQ/NE comparisons where one of the pairs
2493          * can be simplified.
2494          */
2495         i = do_constant_folding_cond(TCG_TYPE_I32, op->args[1],
2496                                      op->args[3], cond);
2497         switch (i ^ inv) {
2498         case 0:
2499             goto do_setcond_const;
2500         case 1:
2501             goto do_setcond_high;
2502         }
2503 
2504         i = do_constant_folding_cond(TCG_TYPE_I32, op->args[2],
2505                                      op->args[4], cond);
2506         switch (i ^ inv) {
2507         case 0:
2508             goto do_setcond_const;
2509         case 1:
2510             goto do_setcond_low;
2511         }
2512         break;
2513 
2514     case TCG_COND_TSTEQ:
2515     case TCG_COND_TSTNE:
2516         if (arg_is_const_val(op->args[3], 0)) {
2517             goto do_setcond_high;
2518         }
2519         if (arg_is_const_val(op->args[4], 0)) {
2520             goto do_setcond_low;
2521         }
2522         break;
2523 
2524     default:
2525         break;
2526 
2527     do_setcond_low:
2528         op->args[2] = op->args[3];
2529         op->args[3] = cond;
2530         op->opc = INDEX_op_setcond_i32;
2531         return fold_setcond(ctx, op);
2532 
2533     do_setcond_high:
2534         op->args[1] = op->args[2];
2535         op->args[2] = op->args[4];
2536         op->args[3] = cond;
2537         op->opc = INDEX_op_setcond_i32;
2538         return fold_setcond(ctx, op);
2539     }
2540 
2541     return fold_masks_z(ctx, op, 1);
2542 
2543  do_setcond_const:
2544     return tcg_opt_gen_movi(ctx, op, op->args[0], i);
2545 }
2546 
2547 static bool fold_sextract(OptContext *ctx, TCGOp *op)
2548 {
2549     uint64_t z_mask, s_mask, s_mask_old;
2550     TempOptInfo *t1 = arg_info(op->args[1]);
2551     int pos = op->args[2];
2552     int len = op->args[3];
2553 
2554     if (ti_is_const(t1)) {
2555         return tcg_opt_gen_movi(ctx, op, op->args[0],
2556                                 sextract64(ti_const_val(t1), pos, len));
2557     }
2558 
2559     s_mask_old = t1->s_mask;
2560     s_mask = s_mask_old >> pos;
2561     s_mask |= -1ull << (len - 1);
2562 
2563     if (pos == 0 && fold_affected_mask(ctx, op, s_mask & ~s_mask_old)) {
2564         return true;
2565     }
2566 
2567     z_mask = sextract64(t1->z_mask, pos, len);
2568     return fold_masks_zs(ctx, op, z_mask, s_mask);
2569 }
2570 
2571 static bool fold_shift(OptContext *ctx, TCGOp *op)
2572 {
2573     uint64_t s_mask, z_mask;
2574     TempOptInfo *t1, *t2;
2575 
2576     if (fold_const2(ctx, op) ||
2577         fold_ix_to_i(ctx, op, 0) ||
2578         fold_xi_to_x(ctx, op, 0)) {
2579         return true;
2580     }
2581 
2582     t1 = arg_info(op->args[1]);
2583     t2 = arg_info(op->args[2]);
2584     s_mask = t1->s_mask;
2585     z_mask = t1->z_mask;
2586 
2587     if (ti_is_const(t2)) {
2588         int sh = ti_const_val(t2);
2589 
2590         z_mask = do_constant_folding(op->opc, ctx->type, z_mask, sh);
2591         s_mask = do_constant_folding(op->opc, ctx->type, s_mask, sh);
2592 
2593         return fold_masks_zs(ctx, op, z_mask, s_mask);
2594     }
2595 
2596     switch (op->opc) {
2597     CASE_OP_32_64(sar):
2598         /*
2599          * Arithmetic right shift will not reduce the number of
2600          * input sign repetitions.
2601          */
2602         return fold_masks_s(ctx, op, s_mask);
2603     CASE_OP_32_64(shr):
2604         /*
2605          * If the sign bit is known zero, then logical right shift
2606          * will not reduce the number of input sign repetitions.
2607          */
2608         if (~z_mask & -s_mask) {
2609             return fold_masks_s(ctx, op, s_mask);
2610         }
2611         break;
2612     default:
2613         break;
2614     }
2615 
2616     return finish_folding(ctx, op);
2617 }
2618 
2619 static bool fold_sub_to_neg(OptContext *ctx, TCGOp *op)
2620 {
2621     TCGOpcode neg_op;
2622     bool have_neg;
2623 
2624     if (!arg_is_const(op->args[1]) || arg_info(op->args[1])->val != 0) {
2625         return false;
2626     }
2627 
2628     switch (ctx->type) {
2629     case TCG_TYPE_I32:
2630     case TCG_TYPE_I64:
2631         neg_op = INDEX_op_neg;
2632         have_neg = true;
2633         break;
2634     case TCG_TYPE_V64:
2635     case TCG_TYPE_V128:
2636     case TCG_TYPE_V256:
2637         neg_op = INDEX_op_neg_vec;
2638         have_neg = (TCG_TARGET_HAS_neg_vec &&
2639                     tcg_can_emit_vec_op(neg_op, ctx->type, TCGOP_VECE(op)) > 0);
2640         break;
2641     default:
2642         g_assert_not_reached();
2643     }
2644     if (have_neg) {
2645         op->opc = neg_op;
2646         op->args[1] = op->args[2];
2647         return fold_neg_no_const(ctx, op);
2648     }
2649     return false;
2650 }
2651 
2652 /* We cannot as yet do_constant_folding with vectors. */
2653 static bool fold_sub_vec(OptContext *ctx, TCGOp *op)
2654 {
2655     if (fold_xx_to_i(ctx, op, 0) ||
2656         fold_xi_to_x(ctx, op, 0) ||
2657         fold_sub_to_neg(ctx, op)) {
2658         return true;
2659     }
2660     return finish_folding(ctx, op);
2661 }
2662 
2663 static bool fold_sub(OptContext *ctx, TCGOp *op)
2664 {
2665     if (fold_const2(ctx, op) ||
2666         fold_xx_to_i(ctx, op, 0) ||
2667         fold_xi_to_x(ctx, op, 0) ||
2668         fold_sub_to_neg(ctx, op)) {
2669         return true;
2670     }
2671 
2672     /* Fold sub r,x,i to add r,x,-i */
2673     if (arg_is_const(op->args[2])) {
2674         uint64_t val = arg_info(op->args[2])->val;
2675 
2676         op->opc = INDEX_op_add;
2677         op->args[2] = arg_new_constant(ctx, -val);
2678     }
2679     return finish_folding(ctx, op);
2680 }
2681 
2682 static bool fold_sub2(OptContext *ctx, TCGOp *op)
2683 {
2684     return fold_addsub2(ctx, op, false);
2685 }
2686 
2687 static bool fold_tcg_ld(OptContext *ctx, TCGOp *op)
2688 {
2689     uint64_t z_mask = -1, s_mask = 0;
2690 
2691     /* We can't do any folding with a load, but we can record bits. */
2692     switch (op->opc) {
2693     CASE_OP_32_64(ld8s):
2694         s_mask = INT8_MIN;
2695         break;
2696     CASE_OP_32_64(ld8u):
2697         z_mask = MAKE_64BIT_MASK(0, 8);
2698         break;
2699     CASE_OP_32_64(ld16s):
2700         s_mask = INT16_MIN;
2701         break;
2702     CASE_OP_32_64(ld16u):
2703         z_mask = MAKE_64BIT_MASK(0, 16);
2704         break;
2705     case INDEX_op_ld32s_i64:
2706         s_mask = INT32_MIN;
2707         break;
2708     case INDEX_op_ld32u_i64:
2709         z_mask = MAKE_64BIT_MASK(0, 32);
2710         break;
2711     default:
2712         g_assert_not_reached();
2713     }
2714     return fold_masks_zs(ctx, op, z_mask, s_mask);
2715 }
2716 
2717 static bool fold_tcg_ld_memcopy(OptContext *ctx, TCGOp *op)
2718 {
2719     TCGTemp *dst, *src;
2720     intptr_t ofs;
2721     TCGType type;
2722 
2723     if (op->args[1] != tcgv_ptr_arg(tcg_env)) {
2724         return finish_folding(ctx, op);
2725     }
2726 
2727     type = ctx->type;
2728     ofs = op->args[2];
2729     dst = arg_temp(op->args[0]);
2730     src = find_mem_copy_for(ctx, type, ofs);
2731     if (src && src->base_type == type) {
2732         return tcg_opt_gen_mov(ctx, op, temp_arg(dst), temp_arg(src));
2733     }
2734 
2735     reset_ts(ctx, dst);
2736     record_mem_copy(ctx, type, dst, ofs, ofs + tcg_type_size(type) - 1);
2737     return true;
2738 }
2739 
2740 static bool fold_tcg_st(OptContext *ctx, TCGOp *op)
2741 {
2742     intptr_t ofs = op->args[2];
2743     intptr_t lm1;
2744 
2745     if (op->args[1] != tcgv_ptr_arg(tcg_env)) {
2746         remove_mem_copy_all(ctx);
2747         return true;
2748     }
2749 
2750     switch (op->opc) {
2751     CASE_OP_32_64(st8):
2752         lm1 = 0;
2753         break;
2754     CASE_OP_32_64(st16):
2755         lm1 = 1;
2756         break;
2757     case INDEX_op_st32_i64:
2758     case INDEX_op_st_i32:
2759         lm1 = 3;
2760         break;
2761     case INDEX_op_st_i64:
2762         lm1 = 7;
2763         break;
2764     case INDEX_op_st_vec:
2765         lm1 = tcg_type_size(ctx->type) - 1;
2766         break;
2767     default:
2768         g_assert_not_reached();
2769     }
2770     remove_mem_copy_in(ctx, ofs, ofs + lm1);
2771     return true;
2772 }
2773 
2774 static bool fold_tcg_st_memcopy(OptContext *ctx, TCGOp *op)
2775 {
2776     TCGTemp *src;
2777     intptr_t ofs, last;
2778     TCGType type;
2779 
2780     if (op->args[1] != tcgv_ptr_arg(tcg_env)) {
2781         return fold_tcg_st(ctx, op);
2782     }
2783 
2784     src = arg_temp(op->args[0]);
2785     ofs = op->args[2];
2786     type = ctx->type;
2787 
2788     /*
2789      * Eliminate duplicate stores of a constant.
2790      * This happens frequently when the target ISA zero-extends.
2791      */
2792     if (ts_is_const(src)) {
2793         TCGTemp *prev = find_mem_copy_for(ctx, type, ofs);
2794         if (src == prev) {
2795             tcg_op_remove(ctx->tcg, op);
2796             return true;
2797         }
2798     }
2799 
2800     last = ofs + tcg_type_size(type) - 1;
2801     remove_mem_copy_in(ctx, ofs, last);
2802     record_mem_copy(ctx, type, src, ofs, last);
2803     return true;
2804 }
2805 
2806 static bool fold_xor(OptContext *ctx, TCGOp *op)
2807 {
2808     uint64_t z_mask, s_mask;
2809     TempOptInfo *t1, *t2;
2810 
2811     if (fold_const2_commutative(ctx, op) ||
2812         fold_xx_to_i(ctx, op, 0) ||
2813         fold_xi_to_x(ctx, op, 0) ||
2814         fold_xi_to_not(ctx, op, -1)) {
2815         return true;
2816     }
2817 
2818     t1 = arg_info(op->args[1]);
2819     t2 = arg_info(op->args[2]);
2820     z_mask = t1->z_mask | t2->z_mask;
2821     s_mask = t1->s_mask & t2->s_mask;
2822     return fold_masks_zs(ctx, op, z_mask, s_mask);
2823 }
2824 
2825 /* Propagate constants and copies, fold constant expressions. */
2826 void tcg_optimize(TCGContext *s)
2827 {
2828     int nb_temps, i;
2829     TCGOp *op, *op_next;
2830     OptContext ctx = { .tcg = s };
2831 
2832     QSIMPLEQ_INIT(&ctx.mem_free);
2833 
2834     /* Array VALS has an element for each temp.
2835        If this temp holds a constant then its value is kept in VALS' element.
2836        If this temp is a copy of other ones then the other copies are
2837        available through the doubly linked circular list. */
2838 
2839     nb_temps = s->nb_temps;
2840     for (i = 0; i < nb_temps; ++i) {
2841         s->temps[i].state_ptr = NULL;
2842     }
2843 
2844     QTAILQ_FOREACH_SAFE(op, &s->ops, link, op_next) {
2845         TCGOpcode opc = op->opc;
2846         const TCGOpDef *def;
2847         bool done = false;
2848 
2849         /* Calls are special. */
2850         if (opc == INDEX_op_call) {
2851             fold_call(&ctx, op);
2852             continue;
2853         }
2854 
2855         def = &tcg_op_defs[opc];
2856         init_arguments(&ctx, op, def->nb_oargs + def->nb_iargs);
2857         copy_propagate(&ctx, op, def->nb_oargs, def->nb_iargs);
2858 
2859         /* Pre-compute the type of the operation. */
2860         ctx.type = TCGOP_TYPE(op);
2861 
2862         /*
2863          * Process each opcode.
2864          * Sorted alphabetically by opcode as much as possible.
2865          */
2866         switch (opc) {
2867         case INDEX_op_add:
2868             done = fold_add(&ctx, op);
2869             break;
2870         case INDEX_op_add_vec:
2871             done = fold_add_vec(&ctx, op);
2872             break;
2873         CASE_OP_32_64(add2):
2874             done = fold_add2(&ctx, op);
2875             break;
2876         case INDEX_op_and:
2877         case INDEX_op_and_vec:
2878             done = fold_and(&ctx, op);
2879             break;
2880         case INDEX_op_andc:
2881         case INDEX_op_andc_vec:
2882             done = fold_andc(&ctx, op);
2883             break;
2884         CASE_OP_32_64(brcond):
2885             done = fold_brcond(&ctx, op);
2886             break;
2887         case INDEX_op_brcond2_i32:
2888             done = fold_brcond2(&ctx, op);
2889             break;
2890         CASE_OP_32_64(bswap16):
2891         CASE_OP_32_64(bswap32):
2892         case INDEX_op_bswap64_i64:
2893             done = fold_bswap(&ctx, op);
2894             break;
2895         CASE_OP_32_64(clz):
2896         CASE_OP_32_64(ctz):
2897             done = fold_count_zeros(&ctx, op);
2898             break;
2899         CASE_OP_32_64(ctpop):
2900             done = fold_ctpop(&ctx, op);
2901             break;
2902         CASE_OP_32_64(deposit):
2903             done = fold_deposit(&ctx, op);
2904             break;
2905         CASE_OP_32_64(div):
2906         CASE_OP_32_64(divu):
2907             done = fold_divide(&ctx, op);
2908             break;
2909         case INDEX_op_dup_vec:
2910             done = fold_dup(&ctx, op);
2911             break;
2912         case INDEX_op_dup2_vec:
2913             done = fold_dup2(&ctx, op);
2914             break;
2915         case INDEX_op_eqv:
2916         case INDEX_op_eqv_vec:
2917             done = fold_eqv(&ctx, op);
2918             break;
2919         CASE_OP_32_64(extract):
2920             done = fold_extract(&ctx, op);
2921             break;
2922         CASE_OP_32_64(extract2):
2923             done = fold_extract2(&ctx, op);
2924             break;
2925         case INDEX_op_ext_i32_i64:
2926             done = fold_exts(&ctx, op);
2927             break;
2928         case INDEX_op_extu_i32_i64:
2929         case INDEX_op_extrl_i64_i32:
2930         case INDEX_op_extrh_i64_i32:
2931             done = fold_extu(&ctx, op);
2932             break;
2933         CASE_OP_32_64(ld8s):
2934         CASE_OP_32_64(ld8u):
2935         CASE_OP_32_64(ld16s):
2936         CASE_OP_32_64(ld16u):
2937         case INDEX_op_ld32s_i64:
2938         case INDEX_op_ld32u_i64:
2939             done = fold_tcg_ld(&ctx, op);
2940             break;
2941         case INDEX_op_ld_i32:
2942         case INDEX_op_ld_i64:
2943         case INDEX_op_ld_vec:
2944             done = fold_tcg_ld_memcopy(&ctx, op);
2945             break;
2946         CASE_OP_32_64(st8):
2947         CASE_OP_32_64(st16):
2948         case INDEX_op_st32_i64:
2949             done = fold_tcg_st(&ctx, op);
2950             break;
2951         case INDEX_op_st_i32:
2952         case INDEX_op_st_i64:
2953         case INDEX_op_st_vec:
2954             done = fold_tcg_st_memcopy(&ctx, op);
2955             break;
2956         case INDEX_op_mb:
2957             done = fold_mb(&ctx, op);
2958             break;
2959         case INDEX_op_mov:
2960         case INDEX_op_mov_vec:
2961             done = fold_mov(&ctx, op);
2962             break;
2963         CASE_OP_32_64(movcond):
2964             done = fold_movcond(&ctx, op);
2965             break;
2966         CASE_OP_32_64(mul):
2967             done = fold_mul(&ctx, op);
2968             break;
2969         CASE_OP_32_64(mulsh):
2970         CASE_OP_32_64(muluh):
2971             done = fold_mul_highpart(&ctx, op);
2972             break;
2973         CASE_OP_32_64(muls2):
2974         CASE_OP_32_64(mulu2):
2975             done = fold_multiply2(&ctx, op);
2976             break;
2977         case INDEX_op_nand:
2978         case INDEX_op_nand_vec:
2979             done = fold_nand(&ctx, op);
2980             break;
2981         case INDEX_op_neg:
2982             done = fold_neg(&ctx, op);
2983             break;
2984         case INDEX_op_nor:
2985         case INDEX_op_nor_vec:
2986             done = fold_nor(&ctx, op);
2987             break;
2988         case INDEX_op_not:
2989         case INDEX_op_not_vec:
2990             done = fold_not(&ctx, op);
2991             break;
2992         case INDEX_op_or:
2993         case INDEX_op_or_vec:
2994             done = fold_or(&ctx, op);
2995             break;
2996         case INDEX_op_orc:
2997         case INDEX_op_orc_vec:
2998             done = fold_orc(&ctx, op);
2999             break;
3000         case INDEX_op_qemu_ld_i32:
3001             done = fold_qemu_ld_1reg(&ctx, op);
3002             break;
3003         case INDEX_op_qemu_ld_i64:
3004             if (TCG_TARGET_REG_BITS == 64) {
3005                 done = fold_qemu_ld_1reg(&ctx, op);
3006                 break;
3007             }
3008             QEMU_FALLTHROUGH;
3009         case INDEX_op_qemu_ld_i128:
3010             done = fold_qemu_ld_2reg(&ctx, op);
3011             break;
3012         case INDEX_op_qemu_st8_i32:
3013         case INDEX_op_qemu_st_i32:
3014         case INDEX_op_qemu_st_i64:
3015         case INDEX_op_qemu_st_i128:
3016             done = fold_qemu_st(&ctx, op);
3017             break;
3018         CASE_OP_32_64(rem):
3019         CASE_OP_32_64(remu):
3020             done = fold_remainder(&ctx, op);
3021             break;
3022         CASE_OP_32_64(rotl):
3023         CASE_OP_32_64(rotr):
3024         CASE_OP_32_64(sar):
3025         CASE_OP_32_64(shl):
3026         CASE_OP_32_64(shr):
3027             done = fold_shift(&ctx, op);
3028             break;
3029         CASE_OP_32_64(setcond):
3030             done = fold_setcond(&ctx, op);
3031             break;
3032         CASE_OP_32_64(negsetcond):
3033             done = fold_negsetcond(&ctx, op);
3034             break;
3035         case INDEX_op_setcond2_i32:
3036             done = fold_setcond2(&ctx, op);
3037             break;
3038         case INDEX_op_cmp_vec:
3039             done = fold_cmp_vec(&ctx, op);
3040             break;
3041         case INDEX_op_cmpsel_vec:
3042             done = fold_cmpsel_vec(&ctx, op);
3043             break;
3044         case INDEX_op_bitsel_vec:
3045             done = fold_bitsel_vec(&ctx, op);
3046             break;
3047         CASE_OP_32_64(sextract):
3048             done = fold_sextract(&ctx, op);
3049             break;
3050         case INDEX_op_sub:
3051             done = fold_sub(&ctx, op);
3052             break;
3053         case INDEX_op_sub_vec:
3054             done = fold_sub_vec(&ctx, op);
3055             break;
3056         CASE_OP_32_64(sub2):
3057             done = fold_sub2(&ctx, op);
3058             break;
3059         case INDEX_op_xor:
3060         case INDEX_op_xor_vec:
3061             done = fold_xor(&ctx, op);
3062             break;
3063         case INDEX_op_set_label:
3064         case INDEX_op_br:
3065         case INDEX_op_exit_tb:
3066         case INDEX_op_goto_tb:
3067         case INDEX_op_goto_ptr:
3068             finish_ebb(&ctx);
3069             done = true;
3070             break;
3071         default:
3072             done = finish_folding(&ctx, op);
3073             break;
3074         }
3075         tcg_debug_assert(done);
3076     }
3077 }
3078