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