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