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