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