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