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