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