xref: /openbmc/qemu/include/tcg/tcg.h (revision be3fc97a)
1 /*
2  * Tiny Code Generator for QEMU
3  *
4  * Copyright (c) 2008 Fabrice Bellard
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  */
24 
25 #ifndef TCG_H
26 #define TCG_H
27 
28 #include "exec/memop.h"
29 #include "exec/memopidx.h"
30 #include "qemu/bitops.h"
31 #include "qemu/plugin.h"
32 #include "qemu/queue.h"
33 #include "tcg/tcg-mo.h"
34 #include "tcg-target-reg-bits.h"
35 #include "tcg-target.h"
36 #include "tcg/tcg-cond.h"
37 #include "tcg/debug-assert.h"
38 
39 /* XXX: make safe guess about sizes */
40 #define MAX_OP_PER_INSTR 266
41 
42 #define CPU_TEMP_BUF_NLONGS 128
43 #define TCG_STATIC_FRAME_SIZE  (CPU_TEMP_BUF_NLONGS * sizeof(long))
44 
45 #if TCG_TARGET_REG_BITS == 32
46 typedef int32_t tcg_target_long;
47 typedef uint32_t tcg_target_ulong;
48 #define TCG_PRIlx PRIx32
49 #define TCG_PRIld PRId32
50 #elif TCG_TARGET_REG_BITS == 64
51 typedef int64_t tcg_target_long;
52 typedef uint64_t tcg_target_ulong;
53 #define TCG_PRIlx PRIx64
54 #define TCG_PRIld PRId64
55 #else
56 #error unsupported
57 #endif
58 
59 #if TCG_TARGET_NB_REGS <= 32
60 typedef uint32_t TCGRegSet;
61 #elif TCG_TARGET_NB_REGS <= 64
62 typedef uint64_t TCGRegSet;
63 #else
64 #error unsupported
65 #endif
66 
67 #if TCG_TARGET_REG_BITS == 32
68 /* Turn some undef macros into false macros.  */
69 #define TCG_TARGET_HAS_extr_i64_i32     0
70 #define TCG_TARGET_HAS_div_i64          0
71 #define TCG_TARGET_HAS_rem_i64          0
72 #define TCG_TARGET_HAS_div2_i64         0
73 #define TCG_TARGET_HAS_rot_i64          0
74 #define TCG_TARGET_HAS_ext8s_i64        0
75 #define TCG_TARGET_HAS_ext16s_i64       0
76 #define TCG_TARGET_HAS_ext32s_i64       0
77 #define TCG_TARGET_HAS_ext8u_i64        0
78 #define TCG_TARGET_HAS_ext16u_i64       0
79 #define TCG_TARGET_HAS_ext32u_i64       0
80 #define TCG_TARGET_HAS_bswap16_i64      0
81 #define TCG_TARGET_HAS_bswap32_i64      0
82 #define TCG_TARGET_HAS_bswap64_i64      0
83 #define TCG_TARGET_HAS_not_i64          0
84 #define TCG_TARGET_HAS_andc_i64         0
85 #define TCG_TARGET_HAS_orc_i64          0
86 #define TCG_TARGET_HAS_eqv_i64          0
87 #define TCG_TARGET_HAS_nand_i64         0
88 #define TCG_TARGET_HAS_nor_i64          0
89 #define TCG_TARGET_HAS_clz_i64          0
90 #define TCG_TARGET_HAS_ctz_i64          0
91 #define TCG_TARGET_HAS_ctpop_i64        0
92 #define TCG_TARGET_HAS_deposit_i64      0
93 #define TCG_TARGET_HAS_extract_i64      0
94 #define TCG_TARGET_HAS_sextract_i64     0
95 #define TCG_TARGET_HAS_extract2_i64     0
96 #define TCG_TARGET_HAS_negsetcond_i64   0
97 #define TCG_TARGET_HAS_add2_i64         0
98 #define TCG_TARGET_HAS_sub2_i64         0
99 #define TCG_TARGET_HAS_mulu2_i64        0
100 #define TCG_TARGET_HAS_muls2_i64        0
101 #define TCG_TARGET_HAS_muluh_i64        0
102 #define TCG_TARGET_HAS_mulsh_i64        0
103 /* Turn some undef macros into true macros.  */
104 #define TCG_TARGET_HAS_add2_i32         1
105 #define TCG_TARGET_HAS_sub2_i32         1
106 #endif
107 
108 #ifndef TCG_TARGET_deposit_i32_valid
109 #define TCG_TARGET_deposit_i32_valid(ofs, len) 1
110 #endif
111 #ifndef TCG_TARGET_deposit_i64_valid
112 #define TCG_TARGET_deposit_i64_valid(ofs, len) 1
113 #endif
114 #ifndef TCG_TARGET_extract_i32_valid
115 #define TCG_TARGET_extract_i32_valid(ofs, len) 1
116 #endif
117 #ifndef TCG_TARGET_extract_i64_valid
118 #define TCG_TARGET_extract_i64_valid(ofs, len) 1
119 #endif
120 
121 /* Only one of DIV or DIV2 should be defined.  */
122 #if defined(TCG_TARGET_HAS_div_i32)
123 #define TCG_TARGET_HAS_div2_i32         0
124 #elif defined(TCG_TARGET_HAS_div2_i32)
125 #define TCG_TARGET_HAS_div_i32          0
126 #define TCG_TARGET_HAS_rem_i32          0
127 #endif
128 #if defined(TCG_TARGET_HAS_div_i64)
129 #define TCG_TARGET_HAS_div2_i64         0
130 #elif defined(TCG_TARGET_HAS_div2_i64)
131 #define TCG_TARGET_HAS_div_i64          0
132 #define TCG_TARGET_HAS_rem_i64          0
133 #endif
134 
135 #if !defined(TCG_TARGET_HAS_v64) \
136     && !defined(TCG_TARGET_HAS_v128) \
137     && !defined(TCG_TARGET_HAS_v256)
138 #define TCG_TARGET_MAYBE_vec            0
139 #define TCG_TARGET_HAS_abs_vec          0
140 #define TCG_TARGET_HAS_neg_vec          0
141 #define TCG_TARGET_HAS_not_vec          0
142 #define TCG_TARGET_HAS_andc_vec         0
143 #define TCG_TARGET_HAS_orc_vec          0
144 #define TCG_TARGET_HAS_nand_vec         0
145 #define TCG_TARGET_HAS_nor_vec          0
146 #define TCG_TARGET_HAS_eqv_vec          0
147 #define TCG_TARGET_HAS_roti_vec         0
148 #define TCG_TARGET_HAS_rots_vec         0
149 #define TCG_TARGET_HAS_rotv_vec         0
150 #define TCG_TARGET_HAS_shi_vec          0
151 #define TCG_TARGET_HAS_shs_vec          0
152 #define TCG_TARGET_HAS_shv_vec          0
153 #define TCG_TARGET_HAS_mul_vec          0
154 #define TCG_TARGET_HAS_sat_vec          0
155 #define TCG_TARGET_HAS_minmax_vec       0
156 #define TCG_TARGET_HAS_bitsel_vec       0
157 #define TCG_TARGET_HAS_cmpsel_vec       0
158 #define TCG_TARGET_HAS_tst_vec          0
159 #else
160 #define TCG_TARGET_MAYBE_vec            1
161 #endif
162 #ifndef TCG_TARGET_HAS_v64
163 #define TCG_TARGET_HAS_v64              0
164 #endif
165 #ifndef TCG_TARGET_HAS_v128
166 #define TCG_TARGET_HAS_v128             0
167 #endif
168 #ifndef TCG_TARGET_HAS_v256
169 #define TCG_TARGET_HAS_v256             0
170 #endif
171 
172 typedef enum TCGOpcode {
173 #define DEF(name, oargs, iargs, cargs, flags) INDEX_op_ ## name,
174 #include "tcg/tcg-opc.h"
175 #undef DEF
176     NB_OPS,
177 } TCGOpcode;
178 
179 #define tcg_regset_set_reg(d, r)   ((d) |= (TCGRegSet)1 << (r))
180 #define tcg_regset_reset_reg(d, r) ((d) &= ~((TCGRegSet)1 << (r)))
181 #define tcg_regset_test_reg(d, r)  (((d) >> (r)) & 1)
182 
183 #ifndef TCG_TARGET_INSN_UNIT_SIZE
184 # error "Missing TCG_TARGET_INSN_UNIT_SIZE"
185 #elif TCG_TARGET_INSN_UNIT_SIZE == 1
186 typedef uint8_t tcg_insn_unit;
187 #elif TCG_TARGET_INSN_UNIT_SIZE == 2
188 typedef uint16_t tcg_insn_unit;
189 #elif TCG_TARGET_INSN_UNIT_SIZE == 4
190 typedef uint32_t tcg_insn_unit;
191 #elif TCG_TARGET_INSN_UNIT_SIZE == 8
192 typedef uint64_t tcg_insn_unit;
193 #else
194 /* The port better have done this.  */
195 #endif
196 
197 typedef struct TCGRelocation TCGRelocation;
198 struct TCGRelocation {
199     QSIMPLEQ_ENTRY(TCGRelocation) next;
200     tcg_insn_unit *ptr;
201     intptr_t addend;
202     int type;
203 };
204 
205 typedef struct TCGOp TCGOp;
206 typedef struct TCGLabelUse TCGLabelUse;
207 struct TCGLabelUse {
208     QSIMPLEQ_ENTRY(TCGLabelUse) next;
209     TCGOp *op;
210 };
211 
212 typedef struct TCGLabel TCGLabel;
213 struct TCGLabel {
214     bool present;
215     bool has_value;
216     uint16_t id;
217     union {
218         uintptr_t value;
219         const tcg_insn_unit *value_ptr;
220     } u;
221     QSIMPLEQ_HEAD(, TCGLabelUse) branches;
222     QSIMPLEQ_HEAD(, TCGRelocation) relocs;
223     QSIMPLEQ_ENTRY(TCGLabel) next;
224 };
225 
226 typedef struct TCGPool {
227     struct TCGPool *next;
228     int size;
229     uint8_t data[] __attribute__ ((aligned));
230 } TCGPool;
231 
232 #define TCG_POOL_CHUNK_SIZE 32768
233 
234 #define TCG_MAX_TEMPS 512
235 #define TCG_MAX_INSNS 512
236 
237 /* when the size of the arguments of a called function is smaller than
238    this value, they are statically allocated in the TB stack frame */
239 #define TCG_STATIC_CALL_ARGS_SIZE 128
240 
241 typedef enum TCGType {
242     TCG_TYPE_I32,
243     TCG_TYPE_I64,
244     TCG_TYPE_I128,
245 
246     TCG_TYPE_V64,
247     TCG_TYPE_V128,
248     TCG_TYPE_V256,
249 
250     /* Number of different types (integer not enum) */
251 #define TCG_TYPE_COUNT  (TCG_TYPE_V256 + 1)
252 
253     /* An alias for the size of the host register.  */
254 #if TCG_TARGET_REG_BITS == 32
255     TCG_TYPE_REG = TCG_TYPE_I32,
256 #else
257     TCG_TYPE_REG = TCG_TYPE_I64,
258 #endif
259 
260     /* An alias for the size of the native pointer.  */
261 #if UINTPTR_MAX == UINT32_MAX
262     TCG_TYPE_PTR = TCG_TYPE_I32,
263 #else
264     TCG_TYPE_PTR = TCG_TYPE_I64,
265 #endif
266 } TCGType;
267 
268 /**
269  * tcg_type_size
270  * @t: type
271  *
272  * Return the size of the type in bytes.
273  */
274 static inline int tcg_type_size(TCGType t)
275 {
276     unsigned i = t;
277     if (i >= TCG_TYPE_V64) {
278         tcg_debug_assert(i < TCG_TYPE_COUNT);
279         i -= TCG_TYPE_V64 - 1;
280     }
281     return 4 << i;
282 }
283 
284 typedef tcg_target_ulong TCGArg;
285 
286 /* Define type and accessor macros for TCG variables.
287 
288    TCG variables are the inputs and outputs of TCG ops, as described
289    in tcg/README. Target CPU front-end code uses these types to deal
290    with TCG variables as it emits TCG code via the tcg_gen_* functions.
291    They come in several flavours:
292     * TCGv_i32  : 32 bit integer type
293     * TCGv_i64  : 64 bit integer type
294     * TCGv_i128 : 128 bit integer type
295     * TCGv_ptr  : a host pointer type
296     * TCGv_vec  : a host vector type; the exact size is not exposed
297                   to the CPU front-end code.
298     * TCGv      : an integer type the same size as target_ulong
299                   (an alias for either TCGv_i32 or TCGv_i64)
300    The compiler's type checking will complain if you mix them
301    up and pass the wrong sized TCGv to a function.
302 
303    Users of tcg_gen_* don't need to know about any of the internal
304    details of these, and should treat them as opaque types.
305    You won't be able to look inside them in a debugger either.
306 
307    Internal implementation details follow:
308 
309    Note that there is no definition of the structs TCGv_i32_d etc anywhere.
310    This is deliberate, because the values we store in variables of type
311    TCGv_i32 are not really pointers-to-structures. They're just small
312    integers, but keeping them in pointer types like this means that the
313    compiler will complain if you accidentally pass a TCGv_i32 to a
314    function which takes a TCGv_i64, and so on. Only the internals of
315    TCG need to care about the actual contents of the types.  */
316 
317 typedef struct TCGv_i32_d *TCGv_i32;
318 typedef struct TCGv_i64_d *TCGv_i64;
319 typedef struct TCGv_i128_d *TCGv_i128;
320 typedef struct TCGv_ptr_d *TCGv_ptr;
321 typedef struct TCGv_vec_d *TCGv_vec;
322 typedef TCGv_ptr TCGv_env;
323 
324 /* call flags */
325 /* Helper does not read globals (either directly or through an exception). It
326    implies TCG_CALL_NO_WRITE_GLOBALS. */
327 #define TCG_CALL_NO_READ_GLOBALS    0x0001
328 /* Helper does not write globals */
329 #define TCG_CALL_NO_WRITE_GLOBALS   0x0002
330 /* Helper can be safely suppressed if the return value is not used. */
331 #define TCG_CALL_NO_SIDE_EFFECTS    0x0004
332 /* Helper is G_NORETURN.  */
333 #define TCG_CALL_NO_RETURN          0x0008
334 
335 /* convenience version of most used call flags */
336 #define TCG_CALL_NO_RWG         TCG_CALL_NO_READ_GLOBALS
337 #define TCG_CALL_NO_WG          TCG_CALL_NO_WRITE_GLOBALS
338 #define TCG_CALL_NO_SE          TCG_CALL_NO_SIDE_EFFECTS
339 #define TCG_CALL_NO_RWG_SE      (TCG_CALL_NO_RWG | TCG_CALL_NO_SE)
340 #define TCG_CALL_NO_WG_SE       (TCG_CALL_NO_WG | TCG_CALL_NO_SE)
341 
342 /*
343  * Flags for the bswap opcodes.
344  * If IZ, the input is zero-extended, otherwise unknown.
345  * If OZ or OS, the output is zero- or sign-extended respectively,
346  * otherwise the high bits are undefined.
347  */
348 enum {
349     TCG_BSWAP_IZ = 1,
350     TCG_BSWAP_OZ = 2,
351     TCG_BSWAP_OS = 4,
352 };
353 
354 typedef enum TCGTempVal {
355     TEMP_VAL_DEAD,
356     TEMP_VAL_REG,
357     TEMP_VAL_MEM,
358     TEMP_VAL_CONST,
359 } TCGTempVal;
360 
361 typedef enum TCGTempKind {
362     /*
363      * Temp is dead at the end of the extended basic block (EBB),
364      * the single-entry multiple-exit region that falls through
365      * conditional branches.
366      */
367     TEMP_EBB,
368     /* Temp is live across the entire translation block, but dead at end. */
369     TEMP_TB,
370     /* Temp is live across the entire translation block, and between them. */
371     TEMP_GLOBAL,
372     /* Temp is in a fixed register. */
373     TEMP_FIXED,
374     /* Temp is a fixed constant. */
375     TEMP_CONST,
376 } TCGTempKind;
377 
378 typedef struct TCGTemp {
379     TCGReg reg:8;
380     TCGTempVal val_type:8;
381     TCGType base_type:8;
382     TCGType type:8;
383     TCGTempKind kind:3;
384     unsigned int indirect_reg:1;
385     unsigned int indirect_base:1;
386     unsigned int mem_coherent:1;
387     unsigned int mem_allocated:1;
388     unsigned int temp_allocated:1;
389     unsigned int temp_subindex:2;
390 
391     int64_t val;
392     struct TCGTemp *mem_base;
393     intptr_t mem_offset;
394     const char *name;
395 
396     /* Pass-specific information that can be stored for a temporary.
397        One word worth of integer data, and one pointer to data
398        allocated separately.  */
399     uintptr_t state;
400     void *state_ptr;
401 } TCGTemp;
402 
403 typedef struct TCGContext TCGContext;
404 
405 typedef struct TCGTempSet {
406     unsigned long l[BITS_TO_LONGS(TCG_MAX_TEMPS)];
407 } TCGTempSet;
408 
409 /*
410  * With 1 128-bit output, a 32-bit host requires 4 output parameters,
411  * which leaves a maximum of 28 other slots.  Which is enough for 7
412  * 128-bit operands.
413  */
414 #define DEAD_ARG  (1 << 4)
415 #define SYNC_ARG  (1 << 0)
416 typedef uint32_t TCGLifeData;
417 
418 struct TCGOp {
419     TCGOpcode opc   : 8;
420     unsigned nargs  : 8;
421 
422     /* Parameters for this opcode.  See below.  */
423     unsigned param1 : 8;
424     unsigned param2 : 8;
425 
426     /* Lifetime data of the operands.  */
427     TCGLifeData life;
428 
429     /* Next and previous opcodes.  */
430     QTAILQ_ENTRY(TCGOp) link;
431 
432     /* Register preferences for the output(s).  */
433     TCGRegSet output_pref[2];
434 
435     /* Arguments for the opcode.  */
436     TCGArg args[];
437 };
438 
439 #define TCGOP_CALLI(X)    (X)->param1
440 #define TCGOP_CALLO(X)    (X)->param2
441 
442 #define TCGOP_VECL(X)     (X)->param1
443 #define TCGOP_VECE(X)     (X)->param2
444 
445 /* Make sure operands fit in the bitfields above.  */
446 QEMU_BUILD_BUG_ON(NB_OPS > (1 << 8));
447 
448 static inline TCGRegSet output_pref(const TCGOp *op, unsigned i)
449 {
450     return i < ARRAY_SIZE(op->output_pref) ? op->output_pref[i] : 0;
451 }
452 
453 struct TCGContext {
454     uint8_t *pool_cur, *pool_end;
455     TCGPool *pool_first, *pool_current, *pool_first_large;
456     int nb_labels;
457     int nb_globals;
458     int nb_temps;
459     int nb_indirects;
460     int nb_ops;
461     TCGType addr_type;            /* TCG_TYPE_I32 or TCG_TYPE_I64 */
462 
463     int page_mask;
464     uint8_t page_bits;
465     uint8_t tlb_dyn_max_bits;
466     uint8_t insn_start_words;
467     TCGBar guest_mo;
468 
469     TCGRegSet reserved_regs;
470     intptr_t current_frame_offset;
471     intptr_t frame_start;
472     intptr_t frame_end;
473     TCGTemp *frame_temp;
474 
475     TranslationBlock *gen_tb;     /* tb for which code is being generated */
476     tcg_insn_unit *code_buf;      /* pointer for start of tb */
477     tcg_insn_unit *code_ptr;      /* pointer for running end of tb */
478 
479 #ifdef CONFIG_DEBUG_TCG
480     int goto_tb_issue_mask;
481     const TCGOpcode *vecop_list;
482 #endif
483 
484     /* Code generation.  Note that we specifically do not use tcg_insn_unit
485        here, because there's too much arithmetic throughout that relies
486        on addition and subtraction working on bytes.  Rely on the GCC
487        extension that allows arithmetic on void*.  */
488     void *code_gen_buffer;
489     size_t code_gen_buffer_size;
490     void *code_gen_ptr;
491     void *data_gen_ptr;
492 
493     /* Threshold to flush the translated code buffer.  */
494     void *code_gen_highwater;
495 
496     /* Track which vCPU triggers events */
497     CPUState *cpu;                      /* *_trans */
498 
499     /* These structures are private to tcg-target.c.inc.  */
500 #ifdef TCG_TARGET_NEED_LDST_LABELS
501     QSIMPLEQ_HEAD(, TCGLabelQemuLdst) ldst_labels;
502 #endif
503 #ifdef TCG_TARGET_NEED_POOL_LABELS
504     struct TCGLabelPoolData *pool_labels;
505 #endif
506 
507     TCGLabel *exitreq_label;
508 
509 #ifdef CONFIG_PLUGIN
510     /*
511      * We keep one plugin_tb struct per TCGContext. Note that on every TB
512      * translation we clear but do not free its contents; this way we
513      * avoid a lot of malloc/free churn, since after a few TB's it's
514      * unlikely that we'll need to allocate either more instructions or more
515      * space for instructions (for variable-instruction-length ISAs).
516      */
517     struct qemu_plugin_tb *plugin_tb;
518     const struct DisasContextBase *plugin_db;
519 
520     /* descriptor of the instruction being translated */
521     struct qemu_plugin_insn *plugin_insn;
522 #endif
523 
524     /* For host-specific values. */
525 #ifdef __riscv
526     MemOp riscv_cur_vsew;
527     TCGType riscv_cur_type;
528 #endif
529 
530     GHashTable *const_table[TCG_TYPE_COUNT];
531     TCGTempSet free_temps[TCG_TYPE_COUNT];
532     TCGTemp temps[TCG_MAX_TEMPS]; /* globals first, temps after */
533 
534     QTAILQ_HEAD(, TCGOp) ops, free_ops;
535     QSIMPLEQ_HEAD(, TCGLabel) labels;
536 
537     /*
538      * When clear, new ops are added to the tail of @ops.
539      * When set, new ops are added in front of @emit_before_op.
540      */
541     TCGOp *emit_before_op;
542 
543     /* Tells which temporary holds a given register.
544        It does not take into account fixed registers */
545     TCGTemp *reg_to_temp[TCG_TARGET_NB_REGS];
546 
547     uint16_t gen_insn_end_off[TCG_MAX_INSNS];
548     uint64_t *gen_insn_data;
549 
550     /* Exit to translator on overflow. */
551     sigjmp_buf jmp_trans;
552 };
553 
554 static inline bool temp_readonly(TCGTemp *ts)
555 {
556     return ts->kind >= TEMP_FIXED;
557 }
558 
559 #ifdef CONFIG_USER_ONLY
560 extern bool tcg_use_softmmu;
561 #else
562 #define tcg_use_softmmu  true
563 #endif
564 
565 extern __thread TCGContext *tcg_ctx;
566 extern const void *tcg_code_gen_epilogue;
567 extern uintptr_t tcg_splitwx_diff;
568 extern TCGv_env tcg_env;
569 
570 bool in_code_gen_buffer(const void *p);
571 
572 #ifdef CONFIG_DEBUG_TCG
573 const void *tcg_splitwx_to_rx(void *rw);
574 void *tcg_splitwx_to_rw(const void *rx);
575 #else
576 static inline const void *tcg_splitwx_to_rx(void *rw)
577 {
578     return rw ? rw + tcg_splitwx_diff : NULL;
579 }
580 
581 static inline void *tcg_splitwx_to_rw(const void *rx)
582 {
583     return rx ? (void *)rx - tcg_splitwx_diff : NULL;
584 }
585 #endif
586 
587 static inline TCGArg temp_arg(TCGTemp *ts)
588 {
589     return (uintptr_t)ts;
590 }
591 
592 static inline TCGTemp *arg_temp(TCGArg a)
593 {
594     return (TCGTemp *)(uintptr_t)a;
595 }
596 
597 #ifdef CONFIG_DEBUG_TCG
598 size_t temp_idx(TCGTemp *ts);
599 TCGTemp *tcgv_i32_temp(TCGv_i32 v);
600 #else
601 static inline size_t temp_idx(TCGTemp *ts)
602 {
603     return ts - tcg_ctx->temps;
604 }
605 
606 /*
607  * Using the offset of a temporary, relative to TCGContext, rather than
608  * its index means that we don't use 0.  That leaves offset 0 free for
609  * a NULL representation without having to leave index 0 unused.
610  */
611 static inline TCGTemp *tcgv_i32_temp(TCGv_i32 v)
612 {
613     return (void *)tcg_ctx + (uintptr_t)v;
614 }
615 #endif
616 
617 static inline TCGTemp *tcgv_i64_temp(TCGv_i64 v)
618 {
619     return tcgv_i32_temp((TCGv_i32)v);
620 }
621 
622 static inline TCGTemp *tcgv_i128_temp(TCGv_i128 v)
623 {
624     return tcgv_i32_temp((TCGv_i32)v);
625 }
626 
627 static inline TCGTemp *tcgv_ptr_temp(TCGv_ptr v)
628 {
629     return tcgv_i32_temp((TCGv_i32)v);
630 }
631 
632 static inline TCGTemp *tcgv_vec_temp(TCGv_vec v)
633 {
634     return tcgv_i32_temp((TCGv_i32)v);
635 }
636 
637 static inline TCGArg tcgv_i32_arg(TCGv_i32 v)
638 {
639     return temp_arg(tcgv_i32_temp(v));
640 }
641 
642 static inline TCGArg tcgv_i64_arg(TCGv_i64 v)
643 {
644     return temp_arg(tcgv_i64_temp(v));
645 }
646 
647 static inline TCGArg tcgv_i128_arg(TCGv_i128 v)
648 {
649     return temp_arg(tcgv_i128_temp(v));
650 }
651 
652 static inline TCGArg tcgv_ptr_arg(TCGv_ptr v)
653 {
654     return temp_arg(tcgv_ptr_temp(v));
655 }
656 
657 static inline TCGArg tcgv_vec_arg(TCGv_vec v)
658 {
659     return temp_arg(tcgv_vec_temp(v));
660 }
661 
662 static inline TCGv_i32 temp_tcgv_i32(TCGTemp *t)
663 {
664     (void)temp_idx(t); /* trigger embedded assert */
665     return (TCGv_i32)((void *)t - (void *)tcg_ctx);
666 }
667 
668 static inline TCGv_i64 temp_tcgv_i64(TCGTemp *t)
669 {
670     return (TCGv_i64)temp_tcgv_i32(t);
671 }
672 
673 static inline TCGv_i128 temp_tcgv_i128(TCGTemp *t)
674 {
675     return (TCGv_i128)temp_tcgv_i32(t);
676 }
677 
678 static inline TCGv_ptr temp_tcgv_ptr(TCGTemp *t)
679 {
680     return (TCGv_ptr)temp_tcgv_i32(t);
681 }
682 
683 static inline TCGv_vec temp_tcgv_vec(TCGTemp *t)
684 {
685     return (TCGv_vec)temp_tcgv_i32(t);
686 }
687 
688 static inline TCGArg tcg_get_insn_param(TCGOp *op, int arg)
689 {
690     return op->args[arg];
691 }
692 
693 static inline void tcg_set_insn_param(TCGOp *op, int arg, TCGArg v)
694 {
695     op->args[arg] = v;
696 }
697 
698 static inline uint64_t tcg_get_insn_start_param(TCGOp *op, int arg)
699 {
700     if (TCG_TARGET_REG_BITS == 64) {
701         return tcg_get_insn_param(op, arg);
702     } else {
703         return deposit64(tcg_get_insn_param(op, arg * 2), 32, 32,
704                          tcg_get_insn_param(op, arg * 2 + 1));
705     }
706 }
707 
708 static inline void tcg_set_insn_start_param(TCGOp *op, int arg, uint64_t v)
709 {
710     if (TCG_TARGET_REG_BITS == 64) {
711         tcg_set_insn_param(op, arg, v);
712     } else {
713         tcg_set_insn_param(op, arg * 2, v);
714         tcg_set_insn_param(op, arg * 2 + 1, v >> 32);
715     }
716 }
717 
718 /* The last op that was emitted.  */
719 static inline TCGOp *tcg_last_op(void)
720 {
721     return QTAILQ_LAST(&tcg_ctx->ops);
722 }
723 
724 /* Test for whether to terminate the TB for using too many opcodes.  */
725 static inline bool tcg_op_buf_full(void)
726 {
727     /* This is not a hard limit, it merely stops translation when
728      * we have produced "enough" opcodes.  We want to limit TB size
729      * such that a RISC host can reasonably use a 16-bit signed
730      * branch within the TB.  We also need to be mindful of the
731      * 16-bit unsigned offsets, TranslationBlock.jmp_reset_offset[]
732      * and TCGContext.gen_insn_end_off[].
733      */
734     return tcg_ctx->nb_ops >= 4000;
735 }
736 
737 /* pool based memory allocation */
738 
739 /* user-mode: mmap_lock must be held for tcg_malloc_internal. */
740 void *tcg_malloc_internal(TCGContext *s, int size);
741 void tcg_pool_reset(TCGContext *s);
742 TranslationBlock *tcg_tb_alloc(TCGContext *s);
743 
744 void tcg_region_reset_all(void);
745 
746 size_t tcg_code_size(void);
747 size_t tcg_code_capacity(void);
748 
749 void tcg_tb_insert(TranslationBlock *tb);
750 void tcg_tb_remove(TranslationBlock *tb);
751 TranslationBlock *tcg_tb_lookup(uintptr_t tc_ptr);
752 void tcg_tb_foreach(GTraverseFunc func, gpointer user_data);
753 size_t tcg_nb_tbs(void);
754 
755 /* user-mode: Called with mmap_lock held.  */
756 static inline void *tcg_malloc(int size)
757 {
758     TCGContext *s = tcg_ctx;
759     uint8_t *ptr, *ptr_end;
760 
761     /* ??? This is a weak placeholder for minimum malloc alignment.  */
762     size = QEMU_ALIGN_UP(size, 8);
763 
764     ptr = s->pool_cur;
765     ptr_end = ptr + size;
766     if (unlikely(ptr_end > s->pool_end)) {
767         return tcg_malloc_internal(tcg_ctx, size);
768     } else {
769         s->pool_cur = ptr_end;
770         return ptr;
771     }
772 }
773 
774 void tcg_func_start(TCGContext *s);
775 
776 int tcg_gen_code(TCGContext *s, TranslationBlock *tb, uint64_t pc_start);
777 
778 void tb_target_set_jmp_target(const TranslationBlock *, int,
779                               uintptr_t, uintptr_t);
780 
781 void tcg_set_frame(TCGContext *s, TCGReg reg, intptr_t start, intptr_t size);
782 
783 #define TCG_CT_CONST  1 /* any constant of register size */
784 
785 typedef struct TCGArgConstraint {
786     unsigned ct : 16;
787     unsigned alias_index : 4;
788     unsigned sort_index : 4;
789     unsigned pair_index : 4;
790     unsigned pair : 2;  /* 0: none, 1: first, 2: second, 3: second alias */
791     bool oalias : 1;
792     bool ialias : 1;
793     bool newreg : 1;
794     TCGRegSet regs;
795 } TCGArgConstraint;
796 
797 #define TCG_MAX_OP_ARGS 16
798 
799 /* Bits for TCGOpDef->flags, 8 bits available, all used.  */
800 enum {
801     /* Instruction exits the translation block.  */
802     TCG_OPF_BB_EXIT      = 0x01,
803     /* Instruction defines the end of a basic block.  */
804     TCG_OPF_BB_END       = 0x02,
805     /* Instruction clobbers call registers and potentially update globals.  */
806     TCG_OPF_CALL_CLOBBER = 0x04,
807     /* Instruction has side effects: it cannot be removed if its outputs
808        are not used, and might trigger exceptions.  */
809     TCG_OPF_SIDE_EFFECTS = 0x08,
810     /* Instruction operands are 64-bits (otherwise 32-bits).  */
811     TCG_OPF_64BIT        = 0x10,
812     /* Instruction is optional and not implemented by the host, or insn
813        is generic and should not be implemented by the host.  */
814     TCG_OPF_NOT_PRESENT  = 0x20,
815     /* Instruction operands are vectors.  */
816     TCG_OPF_VECTOR       = 0x40,
817     /* Instruction is a conditional branch. */
818     TCG_OPF_COND_BRANCH  = 0x80
819 };
820 
821 typedef struct TCGOpDef {
822     const char *name;
823     uint8_t nb_oargs, nb_iargs, nb_cargs, nb_args;
824     uint8_t flags;
825     TCGArgConstraint *args_ct;
826 } TCGOpDef;
827 
828 extern TCGOpDef tcg_op_defs[];
829 extern const size_t tcg_op_defs_max;
830 
831 typedef struct TCGTargetOpDef {
832     TCGOpcode op;
833     const char *args_ct_str[TCG_MAX_OP_ARGS];
834 } TCGTargetOpDef;
835 
836 bool tcg_op_supported(TCGOpcode op);
837 
838 void tcg_gen_call0(void *func, TCGHelperInfo *, TCGTemp *ret);
839 void tcg_gen_call1(void *func, TCGHelperInfo *, TCGTemp *ret, TCGTemp *);
840 void tcg_gen_call2(void *func, TCGHelperInfo *, TCGTemp *ret,
841                    TCGTemp *, TCGTemp *);
842 void tcg_gen_call3(void *func, TCGHelperInfo *, TCGTemp *ret,
843                    TCGTemp *, TCGTemp *, TCGTemp *);
844 void tcg_gen_call4(void *func, TCGHelperInfo *, TCGTemp *ret,
845                    TCGTemp *, TCGTemp *, TCGTemp *, TCGTemp *);
846 void tcg_gen_call5(void *func, TCGHelperInfo *, TCGTemp *ret,
847                    TCGTemp *, TCGTemp *, TCGTemp *, TCGTemp *, TCGTemp *);
848 void tcg_gen_call6(void *func, TCGHelperInfo *, TCGTemp *ret,
849                    TCGTemp *, TCGTemp *, TCGTemp *, TCGTemp *,
850                    TCGTemp *, TCGTemp *);
851 void tcg_gen_call7(void *func, TCGHelperInfo *, TCGTemp *ret,
852                    TCGTemp *, TCGTemp *, TCGTemp *, TCGTemp *,
853                    TCGTemp *, TCGTemp *, TCGTemp *);
854 
855 TCGOp *tcg_emit_op(TCGOpcode opc, unsigned nargs);
856 void tcg_op_remove(TCGContext *s, TCGOp *op);
857 TCGOp *tcg_op_insert_before(TCGContext *s, TCGOp *op,
858                             TCGOpcode opc, unsigned nargs);
859 TCGOp *tcg_op_insert_after(TCGContext *s, TCGOp *op,
860                            TCGOpcode opc, unsigned nargs);
861 
862 /**
863  * tcg_remove_ops_after:
864  * @op: target operation
865  *
866  * Discard any opcodes emitted since @op.  Expected usage is to save
867  * a starting point with tcg_last_op(), speculatively emit opcodes,
868  * then decide whether or not to keep those opcodes after the fact.
869  */
870 void tcg_remove_ops_after(TCGOp *op);
871 
872 void tcg_optimize(TCGContext *s);
873 
874 TCGLabel *gen_new_label(void);
875 
876 /**
877  * label_arg
878  * @l: label
879  *
880  * Encode a label for storage in the TCG opcode stream.
881  */
882 
883 static inline TCGArg label_arg(TCGLabel *l)
884 {
885     return (uintptr_t)l;
886 }
887 
888 /**
889  * arg_label
890  * @i: value
891  *
892  * The opposite of label_arg.  Retrieve a label from the
893  * encoding of the TCG opcode stream.
894  */
895 
896 static inline TCGLabel *arg_label(TCGArg i)
897 {
898     return (TCGLabel *)(uintptr_t)i;
899 }
900 
901 /**
902  * tcg_ptr_byte_diff
903  * @a, @b: addresses to be differenced
904  *
905  * There are many places within the TCG backends where we need a byte
906  * difference between two pointers.  While this can be accomplished
907  * with local casting, it's easy to get wrong -- especially if one is
908  * concerned with the signedness of the result.
909  *
910  * This version relies on GCC's void pointer arithmetic to get the
911  * correct result.
912  */
913 
914 static inline ptrdiff_t tcg_ptr_byte_diff(const void *a, const void *b)
915 {
916     return a - b;
917 }
918 
919 /**
920  * tcg_pcrel_diff
921  * @s: the tcg context
922  * @target: address of the target
923  *
924  * Produce a pc-relative difference, from the current code_ptr
925  * to the destination address.
926  */
927 
928 static inline ptrdiff_t tcg_pcrel_diff(TCGContext *s, const void *target)
929 {
930     return tcg_ptr_byte_diff(target, tcg_splitwx_to_rx(s->code_ptr));
931 }
932 
933 /**
934  * tcg_tbrel_diff
935  * @s: the tcg context
936  * @target: address of the target
937  *
938  * Produce a difference, from the beginning of the current TB code
939  * to the destination address.
940  */
941 static inline ptrdiff_t tcg_tbrel_diff(TCGContext *s, const void *target)
942 {
943     return tcg_ptr_byte_diff(target, tcg_splitwx_to_rx(s->code_buf));
944 }
945 
946 /**
947  * tcg_current_code_size
948  * @s: the tcg context
949  *
950  * Compute the current code size within the translation block.
951  * This is used to fill in qemu's data structures for goto_tb.
952  */
953 
954 static inline size_t tcg_current_code_size(TCGContext *s)
955 {
956     return tcg_ptr_byte_diff(s->code_ptr, s->code_buf);
957 }
958 
959 /**
960  * tcg_qemu_tb_exec:
961  * @env: pointer to CPUArchState for the CPU
962  * @tb_ptr: address of generated code for the TB to execute
963  *
964  * Start executing code from a given translation block.
965  * Where translation blocks have been linked, execution
966  * may proceed from the given TB into successive ones.
967  * Control eventually returns only when some action is needed
968  * from the top-level loop: either control must pass to a TB
969  * which has not yet been directly linked, or an asynchronous
970  * event such as an interrupt needs handling.
971  *
972  * Return: The return value is the value passed to the corresponding
973  * tcg_gen_exit_tb() at translation time of the last TB attempted to execute.
974  * The value is either zero or a 4-byte aligned pointer to that TB combined
975  * with additional information in its two least significant bits. The
976  * additional information is encoded as follows:
977  *  0, 1: the link between this TB and the next is via the specified
978  *        TB index (0 or 1). That is, we left the TB via (the equivalent
979  *        of) "goto_tb <index>". The main loop uses this to determine
980  *        how to link the TB just executed to the next.
981  *  2:    we are using instruction counting code generation, and we
982  *        did not start executing this TB because the instruction counter
983  *        would hit zero midway through it. In this case the pointer
984  *        returned is the TB we were about to execute, and the caller must
985  *        arrange to execute the remaining count of instructions.
986  *  3:    we stopped because the CPU's exit_request flag was set
987  *        (usually meaning that there is an interrupt that needs to be
988  *        handled). The pointer returned is the TB we were about to execute
989  *        when we noticed the pending exit request.
990  *
991  * If the bottom two bits indicate an exit-via-index then the CPU
992  * state is correctly synchronised and ready for execution of the next
993  * TB (and in particular the guest PC is the address to execute next).
994  * Otherwise, we gave up on execution of this TB before it started, and
995  * the caller must fix up the CPU state by calling the CPU's
996  * synchronize_from_tb() method with the TB pointer we return (falling
997  * back to calling the CPU's set_pc method with tb->pb if no
998  * synchronize_from_tb() method exists).
999  *
1000  * Note that TCG targets may use a different definition of tcg_qemu_tb_exec
1001  * to this default (which just calls the prologue.code emitted by
1002  * tcg_target_qemu_prologue()).
1003  */
1004 #define TB_EXIT_MASK      3
1005 #define TB_EXIT_IDX0      0
1006 #define TB_EXIT_IDX1      1
1007 #define TB_EXIT_IDXMAX    1
1008 #define TB_EXIT_REQUESTED 3
1009 
1010 #ifdef CONFIG_TCG_INTERPRETER
1011 uintptr_t tcg_qemu_tb_exec(CPUArchState *env, const void *tb_ptr);
1012 #else
1013 typedef uintptr_t tcg_prologue_fn(CPUArchState *env, const void *tb_ptr);
1014 extern tcg_prologue_fn *tcg_qemu_tb_exec;
1015 #endif
1016 
1017 void tcg_register_jit(const void *buf, size_t buf_size);
1018 
1019 #if TCG_TARGET_MAYBE_vec
1020 /* Return zero if the tuple (opc, type, vece) is unsupportable;
1021    return > 0 if it is directly supportable;
1022    return < 0 if we must call tcg_expand_vec_op.  */
1023 int tcg_can_emit_vec_op(TCGOpcode, TCGType, unsigned);
1024 #else
1025 static inline int tcg_can_emit_vec_op(TCGOpcode o, TCGType t, unsigned ve)
1026 {
1027     return 0;
1028 }
1029 #endif
1030 
1031 /* Expand the tuple (opc, type, vece) on the given arguments.  */
1032 void tcg_expand_vec_op(TCGOpcode, TCGType, unsigned, TCGArg, ...);
1033 
1034 /* Replicate a constant C according to the log2 of the element size.  */
1035 uint64_t dup_const(unsigned vece, uint64_t c);
1036 
1037 #define dup_const(VECE, C)                                         \
1038     (__builtin_constant_p(VECE)                                    \
1039      ? (  (VECE) == MO_8  ? 0x0101010101010101ull * (uint8_t)(C)   \
1040         : (VECE) == MO_16 ? 0x0001000100010001ull * (uint16_t)(C)  \
1041         : (VECE) == MO_32 ? 0x0000000100000001ull * (uint32_t)(C)  \
1042         : (VECE) == MO_64 ? (uint64_t)(C)                          \
1043         : (qemu_build_not_reached_always(), 0))                    \
1044      : dup_const(VECE, C))
1045 
1046 static inline const TCGOpcode *tcg_swap_vecop_list(const TCGOpcode *n)
1047 {
1048 #ifdef CONFIG_DEBUG_TCG
1049     const TCGOpcode *o = tcg_ctx->vecop_list;
1050     tcg_ctx->vecop_list = n;
1051     return o;
1052 #else
1053     return NULL;
1054 #endif
1055 }
1056 
1057 bool tcg_can_emit_vecop_list(const TCGOpcode *, TCGType, unsigned);
1058 void tcg_dump_ops(TCGContext *s, FILE *f, bool have_prefs);
1059 
1060 #endif /* TCG_H */
1061