]> Git Repo - qemu.git/blob - tcg/tcg.c
tcg: Remove tcg_get_arg_str_i32/64
[qemu.git] / tcg / tcg.c
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 /* define it to use liveness analysis (better code) */
26 #define USE_LIVENESS_ANALYSIS
27 #define USE_TCG_OPTIMIZATIONS
28
29 #include "qemu/osdep.h"
30
31 /* Define to jump the ELF file used to communicate with GDB.  */
32 #undef DEBUG_JIT
33
34 #if !defined(CONFIG_DEBUG_TCG) && !defined(NDEBUG)
35 /* define it to suppress various consistency checks (faster) */
36 #define NDEBUG
37 #endif
38
39 #include "qemu-common.h"
40 #include "qemu/host-utils.h"
41 #include "qemu/timer.h"
42
43 /* Note: the long term plan is to reduce the dependencies on the QEMU
44    CPU definitions. Currently they are used for qemu_ld/st
45    instructions */
46 #define NO_CPU_IO_DEFS
47 #include "cpu.h"
48
49 #include "tcg-op.h"
50
51 #if UINTPTR_MAX == UINT32_MAX
52 # define ELF_CLASS  ELFCLASS32
53 #else
54 # define ELF_CLASS  ELFCLASS64
55 #endif
56 #ifdef HOST_WORDS_BIGENDIAN
57 # define ELF_DATA   ELFDATA2MSB
58 #else
59 # define ELF_DATA   ELFDATA2LSB
60 #endif
61
62 #include "elf.h"
63 #include "exec/log.h"
64
65 /* Forward declarations for functions declared in tcg-target.c and used here. */
66 static void tcg_target_init(TCGContext *s);
67 static void tcg_target_qemu_prologue(TCGContext *s);
68 static void patch_reloc(tcg_insn_unit *code_ptr, int type,
69                         intptr_t value, intptr_t addend);
70
71 /* The CIE and FDE header definitions will be common to all hosts.  */
72 typedef struct {
73     uint32_t len __attribute__((aligned((sizeof(void *)))));
74     uint32_t id;
75     uint8_t version;
76     char augmentation[1];
77     uint8_t code_align;
78     uint8_t data_align;
79     uint8_t return_column;
80 } DebugFrameCIE;
81
82 typedef struct QEMU_PACKED {
83     uint32_t len __attribute__((aligned((sizeof(void *)))));
84     uint32_t cie_offset;
85     uintptr_t func_start;
86     uintptr_t func_len;
87 } DebugFrameFDEHeader;
88
89 typedef struct QEMU_PACKED {
90     DebugFrameCIE cie;
91     DebugFrameFDEHeader fde;
92 } DebugFrameHeader;
93
94 static void tcg_register_jit_int(void *buf, size_t size,
95                                  const void *debug_frame,
96                                  size_t debug_frame_size)
97     __attribute__((unused));
98
99 /* Forward declarations for functions declared and used in tcg-target.c. */
100 static int target_parse_constraint(TCGArgConstraint *ct, const char **pct_str);
101 static void tcg_out_ld(TCGContext *s, TCGType type, TCGReg ret, TCGReg arg1,
102                        intptr_t arg2);
103 static void tcg_out_mov(TCGContext *s, TCGType type, TCGReg ret, TCGReg arg);
104 static void tcg_out_movi(TCGContext *s, TCGType type,
105                          TCGReg ret, tcg_target_long arg);
106 static void tcg_out_op(TCGContext *s, TCGOpcode opc, const TCGArg *args,
107                        const int *const_args);
108 static void tcg_out_st(TCGContext *s, TCGType type, TCGReg arg, TCGReg arg1,
109                        intptr_t arg2);
110 static void tcg_out_call(TCGContext *s, tcg_insn_unit *target);
111 static int tcg_target_const_match(tcg_target_long val, TCGType type,
112                                   const TCGArgConstraint *arg_ct);
113 static void tcg_out_tb_init(TCGContext *s);
114 static bool tcg_out_tb_finalize(TCGContext *s);
115
116
117
118 static TCGRegSet tcg_target_available_regs[2];
119 static TCGRegSet tcg_target_call_clobber_regs;
120
121 #if TCG_TARGET_INSN_UNIT_SIZE == 1
122 static __attribute__((unused)) inline void tcg_out8(TCGContext *s, uint8_t v)
123 {
124     *s->code_ptr++ = v;
125 }
126
127 static __attribute__((unused)) inline void tcg_patch8(tcg_insn_unit *p,
128                                                       uint8_t v)
129 {
130     *p = v;
131 }
132 #endif
133
134 #if TCG_TARGET_INSN_UNIT_SIZE <= 2
135 static __attribute__((unused)) inline void tcg_out16(TCGContext *s, uint16_t v)
136 {
137     if (TCG_TARGET_INSN_UNIT_SIZE == 2) {
138         *s->code_ptr++ = v;
139     } else {
140         tcg_insn_unit *p = s->code_ptr;
141         memcpy(p, &v, sizeof(v));
142         s->code_ptr = p + (2 / TCG_TARGET_INSN_UNIT_SIZE);
143     }
144 }
145
146 static __attribute__((unused)) inline void tcg_patch16(tcg_insn_unit *p,
147                                                        uint16_t v)
148 {
149     if (TCG_TARGET_INSN_UNIT_SIZE == 2) {
150         *p = v;
151     } else {
152         memcpy(p, &v, sizeof(v));
153     }
154 }
155 #endif
156
157 #if TCG_TARGET_INSN_UNIT_SIZE <= 4
158 static __attribute__((unused)) inline void tcg_out32(TCGContext *s, uint32_t v)
159 {
160     if (TCG_TARGET_INSN_UNIT_SIZE == 4) {
161         *s->code_ptr++ = v;
162     } else {
163         tcg_insn_unit *p = s->code_ptr;
164         memcpy(p, &v, sizeof(v));
165         s->code_ptr = p + (4 / TCG_TARGET_INSN_UNIT_SIZE);
166     }
167 }
168
169 static __attribute__((unused)) inline void tcg_patch32(tcg_insn_unit *p,
170                                                        uint32_t v)
171 {
172     if (TCG_TARGET_INSN_UNIT_SIZE == 4) {
173         *p = v;
174     } else {
175         memcpy(p, &v, sizeof(v));
176     }
177 }
178 #endif
179
180 #if TCG_TARGET_INSN_UNIT_SIZE <= 8
181 static __attribute__((unused)) inline void tcg_out64(TCGContext *s, uint64_t v)
182 {
183     if (TCG_TARGET_INSN_UNIT_SIZE == 8) {
184         *s->code_ptr++ = v;
185     } else {
186         tcg_insn_unit *p = s->code_ptr;
187         memcpy(p, &v, sizeof(v));
188         s->code_ptr = p + (8 / TCG_TARGET_INSN_UNIT_SIZE);
189     }
190 }
191
192 static __attribute__((unused)) inline void tcg_patch64(tcg_insn_unit *p,
193                                                        uint64_t v)
194 {
195     if (TCG_TARGET_INSN_UNIT_SIZE == 8) {
196         *p = v;
197     } else {
198         memcpy(p, &v, sizeof(v));
199     }
200 }
201 #endif
202
203 /* label relocation processing */
204
205 static void tcg_out_reloc(TCGContext *s, tcg_insn_unit *code_ptr, int type,
206                           TCGLabel *l, intptr_t addend)
207 {
208     TCGRelocation *r;
209
210     if (l->has_value) {
211         /* FIXME: This may break relocations on RISC targets that
212            modify instruction fields in place.  The caller may not have 
213            written the initial value.  */
214         patch_reloc(code_ptr, type, l->u.value, addend);
215     } else {
216         /* add a new relocation entry */
217         r = tcg_malloc(sizeof(TCGRelocation));
218         r->type = type;
219         r->ptr = code_ptr;
220         r->addend = addend;
221         r->next = l->u.first_reloc;
222         l->u.first_reloc = r;
223     }
224 }
225
226 static void tcg_out_label(TCGContext *s, TCGLabel *l, tcg_insn_unit *ptr)
227 {
228     intptr_t value = (intptr_t)ptr;
229     TCGRelocation *r;
230
231     assert(!l->has_value);
232
233     for (r = l->u.first_reloc; r != NULL; r = r->next) {
234         patch_reloc(r->ptr, r->type, value, r->addend);
235     }
236
237     l->has_value = 1;
238     l->u.value_ptr = ptr;
239 }
240
241 TCGLabel *gen_new_label(void)
242 {
243     TCGContext *s = &tcg_ctx;
244     TCGLabel *l = tcg_malloc(sizeof(TCGLabel));
245
246     *l = (TCGLabel){
247         .id = s->nb_labels++
248     };
249
250     return l;
251 }
252
253 #include "tcg-target.c"
254
255 /* pool based memory allocation */
256 void *tcg_malloc_internal(TCGContext *s, int size)
257 {
258     TCGPool *p;
259     int pool_size;
260     
261     if (size > TCG_POOL_CHUNK_SIZE) {
262         /* big malloc: insert a new pool (XXX: could optimize) */
263         p = g_malloc(sizeof(TCGPool) + size);
264         p->size = size;
265         p->next = s->pool_first_large;
266         s->pool_first_large = p;
267         return p->data;
268     } else {
269         p = s->pool_current;
270         if (!p) {
271             p = s->pool_first;
272             if (!p)
273                 goto new_pool;
274         } else {
275             if (!p->next) {
276             new_pool:
277                 pool_size = TCG_POOL_CHUNK_SIZE;
278                 p = g_malloc(sizeof(TCGPool) + pool_size);
279                 p->size = pool_size;
280                 p->next = NULL;
281                 if (s->pool_current) 
282                     s->pool_current->next = p;
283                 else
284                     s->pool_first = p;
285             } else {
286                 p = p->next;
287             }
288         }
289     }
290     s->pool_current = p;
291     s->pool_cur = p->data + size;
292     s->pool_end = p->data + p->size;
293     return p->data;
294 }
295
296 void tcg_pool_reset(TCGContext *s)
297 {
298     TCGPool *p, *t;
299     for (p = s->pool_first_large; p; p = t) {
300         t = p->next;
301         g_free(p);
302     }
303     s->pool_first_large = NULL;
304     s->pool_cur = s->pool_end = NULL;
305     s->pool_current = NULL;
306 }
307
308 typedef struct TCGHelperInfo {
309     void *func;
310     const char *name;
311     unsigned flags;
312     unsigned sizemask;
313 } TCGHelperInfo;
314
315 #include "exec/helper-proto.h"
316
317 static const TCGHelperInfo all_helpers[] = {
318 #include "exec/helper-tcg.h"
319 };
320
321 void tcg_context_init(TCGContext *s)
322 {
323     int op, total_args, n, i;
324     TCGOpDef *def;
325     TCGArgConstraint *args_ct;
326     int *sorted_args;
327     GHashTable *helper_table;
328
329     memset(s, 0, sizeof(*s));
330     s->nb_globals = 0;
331     
332     /* Count total number of arguments and allocate the corresponding
333        space */
334     total_args = 0;
335     for(op = 0; op < NB_OPS; op++) {
336         def = &tcg_op_defs[op];
337         n = def->nb_iargs + def->nb_oargs;
338         total_args += n;
339     }
340
341     args_ct = g_malloc(sizeof(TCGArgConstraint) * total_args);
342     sorted_args = g_malloc(sizeof(int) * total_args);
343
344     for(op = 0; op < NB_OPS; op++) {
345         def = &tcg_op_defs[op];
346         def->args_ct = args_ct;
347         def->sorted_args = sorted_args;
348         n = def->nb_iargs + def->nb_oargs;
349         sorted_args += n;
350         args_ct += n;
351     }
352
353     /* Register helpers.  */
354     /* Use g_direct_hash/equal for direct pointer comparisons on func.  */
355     s->helpers = helper_table = g_hash_table_new(NULL, NULL);
356
357     for (i = 0; i < ARRAY_SIZE(all_helpers); ++i) {
358         g_hash_table_insert(helper_table, (gpointer)all_helpers[i].func,
359                             (gpointer)&all_helpers[i]);
360     }
361
362     tcg_target_init(s);
363 }
364
365 void tcg_prologue_init(TCGContext *s)
366 {
367     size_t prologue_size, total_size;
368     void *buf0, *buf1;
369
370     /* Put the prologue at the beginning of code_gen_buffer.  */
371     buf0 = s->code_gen_buffer;
372     s->code_ptr = buf0;
373     s->code_buf = buf0;
374     s->code_gen_prologue = buf0;
375
376     /* Generate the prologue.  */
377     tcg_target_qemu_prologue(s);
378     buf1 = s->code_ptr;
379     flush_icache_range((uintptr_t)buf0, (uintptr_t)buf1);
380
381     /* Deduct the prologue from the buffer.  */
382     prologue_size = tcg_current_code_size(s);
383     s->code_gen_ptr = buf1;
384     s->code_gen_buffer = buf1;
385     s->code_buf = buf1;
386     total_size = s->code_gen_buffer_size - prologue_size;
387     s->code_gen_buffer_size = total_size;
388
389     /* Compute a high-water mark, at which we voluntarily flush the buffer
390        and start over.  The size here is arbitrary, significantly larger
391        than we expect the code generation for any one opcode to require.  */
392     s->code_gen_highwater = s->code_gen_buffer + (total_size - 1024);
393
394     tcg_register_jit(s->code_gen_buffer, total_size);
395
396 #ifdef DEBUG_DISAS
397     if (qemu_loglevel_mask(CPU_LOG_TB_OUT_ASM)) {
398         qemu_log("PROLOGUE: [size=%zu]\n", prologue_size);
399         log_disas(buf0, prologue_size);
400         qemu_log("\n");
401         qemu_log_flush();
402     }
403 #endif
404 }
405
406 void tcg_func_start(TCGContext *s)
407 {
408     tcg_pool_reset(s);
409     s->nb_temps = s->nb_globals;
410
411     /* No temps have been previously allocated for size or locality.  */
412     memset(s->free_temps, 0, sizeof(s->free_temps));
413
414     s->nb_labels = 0;
415     s->current_frame_offset = s->frame_start;
416
417 #ifdef CONFIG_DEBUG_TCG
418     s->goto_tb_issue_mask = 0;
419 #endif
420
421     s->gen_first_op_idx = 0;
422     s->gen_last_op_idx = -1;
423     s->gen_next_op_idx = 0;
424     s->gen_next_parm_idx = 0;
425
426     s->be = tcg_malloc(sizeof(TCGBackendData));
427 }
428
429 static inline int temp_idx(TCGContext *s, TCGTemp *ts)
430 {
431     ptrdiff_t n = ts - s->temps;
432     tcg_debug_assert(n >= 0 && n < s->nb_temps);
433     return n;
434 }
435
436 static inline TCGTemp *tcg_temp_alloc(TCGContext *s)
437 {
438     int n = s->nb_temps++;
439     tcg_debug_assert(n < TCG_MAX_TEMPS);
440     return memset(&s->temps[n], 0, sizeof(TCGTemp));
441 }
442
443 static inline TCGTemp *tcg_global_alloc(TCGContext *s)
444 {
445     tcg_debug_assert(s->nb_globals == s->nb_temps);
446     s->nb_globals++;
447     return tcg_temp_alloc(s);
448 }
449
450 static int tcg_global_reg_new_internal(TCGContext *s, TCGType type,
451                                        TCGReg reg, const char *name)
452 {
453     TCGTemp *ts;
454
455     if (TCG_TARGET_REG_BITS == 32 && type != TCG_TYPE_I32) {
456         tcg_abort();
457     }
458
459     ts = tcg_global_alloc(s);
460     ts->base_type = type;
461     ts->type = type;
462     ts->fixed_reg = 1;
463     ts->reg = reg;
464     ts->name = name;
465     tcg_regset_set_reg(s->reserved_regs, reg);
466
467     return temp_idx(s, ts);
468 }
469
470 void tcg_set_frame(TCGContext *s, TCGReg reg, intptr_t start, intptr_t size)
471 {
472     int idx;
473     s->frame_start = start;
474     s->frame_end = start + size;
475     idx = tcg_global_reg_new_internal(s, TCG_TYPE_PTR, reg, "_frame");
476     s->frame_temp = &s->temps[idx];
477 }
478
479 TCGv_i32 tcg_global_reg_new_i32(TCGReg reg, const char *name)
480 {
481     TCGContext *s = &tcg_ctx;
482     int idx;
483
484     if (tcg_regset_test_reg(s->reserved_regs, reg)) {
485         tcg_abort();
486     }
487     idx = tcg_global_reg_new_internal(s, TCG_TYPE_I32, reg, name);
488     return MAKE_TCGV_I32(idx);
489 }
490
491 TCGv_i64 tcg_global_reg_new_i64(TCGReg reg, const char *name)
492 {
493     TCGContext *s = &tcg_ctx;
494     int idx;
495
496     if (tcg_regset_test_reg(s->reserved_regs, reg)) {
497         tcg_abort();
498     }
499     idx = tcg_global_reg_new_internal(s, TCG_TYPE_I64, reg, name);
500     return MAKE_TCGV_I64(idx);
501 }
502
503 int tcg_global_mem_new_internal(TCGType type, TCGv_ptr base,
504                                 intptr_t offset, const char *name)
505 {
506     TCGContext *s = &tcg_ctx;
507     TCGTemp *base_ts = &s->temps[GET_TCGV_PTR(base)];
508     TCGTemp *ts = tcg_global_alloc(s);
509     int bigendian = 0;
510 #ifdef HOST_WORDS_BIGENDIAN
511     bigendian = 1;
512 #endif
513
514     if (TCG_TARGET_REG_BITS == 32 && type == TCG_TYPE_I64) {
515         TCGTemp *ts2 = tcg_global_alloc(s);
516         char buf[64];
517
518         ts->base_type = TCG_TYPE_I64;
519         ts->type = TCG_TYPE_I32;
520         ts->mem_allocated = 1;
521         ts->mem_base = base_ts;
522         ts->mem_offset = offset + bigendian * 4;
523         pstrcpy(buf, sizeof(buf), name);
524         pstrcat(buf, sizeof(buf), "_0");
525         ts->name = strdup(buf);
526
527         tcg_debug_assert(ts2 == ts + 1);
528         ts2->base_type = TCG_TYPE_I64;
529         ts2->type = TCG_TYPE_I32;
530         ts2->mem_allocated = 1;
531         ts2->mem_base = base_ts;
532         ts2->mem_offset = offset + (1 - bigendian) * 4;
533         pstrcpy(buf, sizeof(buf), name);
534         pstrcat(buf, sizeof(buf), "_1");
535         ts->name = strdup(buf);
536     } else {
537         ts->base_type = type;
538         ts->type = type;
539         ts->mem_allocated = 1;
540         ts->mem_base = base_ts;
541         ts->mem_offset = offset;
542         ts->name = name;
543     }
544     return temp_idx(s, ts);
545 }
546
547 static int tcg_temp_new_internal(TCGType type, int temp_local)
548 {
549     TCGContext *s = &tcg_ctx;
550     TCGTemp *ts;
551     int idx, k;
552
553     k = type + (temp_local ? TCG_TYPE_COUNT : 0);
554     idx = find_first_bit(s->free_temps[k].l, TCG_MAX_TEMPS);
555     if (idx < TCG_MAX_TEMPS) {
556         /* There is already an available temp with the right type.  */
557         clear_bit(idx, s->free_temps[k].l);
558
559         ts = &s->temps[idx];
560         ts->temp_allocated = 1;
561         tcg_debug_assert(ts->base_type == type);
562         tcg_debug_assert(ts->temp_local == temp_local);
563     } else {
564         ts = tcg_temp_alloc(s);
565         if (TCG_TARGET_REG_BITS == 32 && type == TCG_TYPE_I64) {
566             TCGTemp *ts2 = tcg_temp_alloc(s);
567
568             ts->base_type = type;
569             ts->type = TCG_TYPE_I32;
570             ts->temp_allocated = 1;
571             ts->temp_local = temp_local;
572
573             tcg_debug_assert(ts2 == ts + 1);
574             ts2->base_type = TCG_TYPE_I64;
575             ts2->type = TCG_TYPE_I32;
576             ts2->temp_allocated = 1;
577             ts2->temp_local = temp_local;
578         } else {
579             ts->base_type = type;
580             ts->type = type;
581             ts->temp_allocated = 1;
582             ts->temp_local = temp_local;
583         }
584         idx = temp_idx(s, ts);
585     }
586
587 #if defined(CONFIG_DEBUG_TCG)
588     s->temps_in_use++;
589 #endif
590     return idx;
591 }
592
593 TCGv_i32 tcg_temp_new_internal_i32(int temp_local)
594 {
595     int idx;
596
597     idx = tcg_temp_new_internal(TCG_TYPE_I32, temp_local);
598     return MAKE_TCGV_I32(idx);
599 }
600
601 TCGv_i64 tcg_temp_new_internal_i64(int temp_local)
602 {
603     int idx;
604
605     idx = tcg_temp_new_internal(TCG_TYPE_I64, temp_local);
606     return MAKE_TCGV_I64(idx);
607 }
608
609 static void tcg_temp_free_internal(int idx)
610 {
611     TCGContext *s = &tcg_ctx;
612     TCGTemp *ts;
613     int k;
614
615 #if defined(CONFIG_DEBUG_TCG)
616     s->temps_in_use--;
617     if (s->temps_in_use < 0) {
618         fprintf(stderr, "More temporaries freed than allocated!\n");
619     }
620 #endif
621
622     assert(idx >= s->nb_globals && idx < s->nb_temps);
623     ts = &s->temps[idx];
624     assert(ts->temp_allocated != 0);
625     ts->temp_allocated = 0;
626
627     k = ts->base_type + (ts->temp_local ? TCG_TYPE_COUNT : 0);
628     set_bit(idx, s->free_temps[k].l);
629 }
630
631 void tcg_temp_free_i32(TCGv_i32 arg)
632 {
633     tcg_temp_free_internal(GET_TCGV_I32(arg));
634 }
635
636 void tcg_temp_free_i64(TCGv_i64 arg)
637 {
638     tcg_temp_free_internal(GET_TCGV_I64(arg));
639 }
640
641 TCGv_i32 tcg_const_i32(int32_t val)
642 {
643     TCGv_i32 t0;
644     t0 = tcg_temp_new_i32();
645     tcg_gen_movi_i32(t0, val);
646     return t0;
647 }
648
649 TCGv_i64 tcg_const_i64(int64_t val)
650 {
651     TCGv_i64 t0;
652     t0 = tcg_temp_new_i64();
653     tcg_gen_movi_i64(t0, val);
654     return t0;
655 }
656
657 TCGv_i32 tcg_const_local_i32(int32_t val)
658 {
659     TCGv_i32 t0;
660     t0 = tcg_temp_local_new_i32();
661     tcg_gen_movi_i32(t0, val);
662     return t0;
663 }
664
665 TCGv_i64 tcg_const_local_i64(int64_t val)
666 {
667     TCGv_i64 t0;
668     t0 = tcg_temp_local_new_i64();
669     tcg_gen_movi_i64(t0, val);
670     return t0;
671 }
672
673 #if defined(CONFIG_DEBUG_TCG)
674 void tcg_clear_temp_count(void)
675 {
676     TCGContext *s = &tcg_ctx;
677     s->temps_in_use = 0;
678 }
679
680 int tcg_check_temp_count(void)
681 {
682     TCGContext *s = &tcg_ctx;
683     if (s->temps_in_use) {
684         /* Clear the count so that we don't give another
685          * warning immediately next time around.
686          */
687         s->temps_in_use = 0;
688         return 1;
689     }
690     return 0;
691 }
692 #endif
693
694 /* Note: we convert the 64 bit args to 32 bit and do some alignment
695    and endian swap. Maybe it would be better to do the alignment
696    and endian swap in tcg_reg_alloc_call(). */
697 void tcg_gen_callN(TCGContext *s, void *func, TCGArg ret,
698                    int nargs, TCGArg *args)
699 {
700     int i, real_args, nb_rets, pi, pi_first;
701     unsigned sizemask, flags;
702     TCGHelperInfo *info;
703
704     info = g_hash_table_lookup(s->helpers, (gpointer)func);
705     flags = info->flags;
706     sizemask = info->sizemask;
707
708 #if defined(__sparc__) && !defined(__arch64__) \
709     && !defined(CONFIG_TCG_INTERPRETER)
710     /* We have 64-bit values in one register, but need to pass as two
711        separate parameters.  Split them.  */
712     int orig_sizemask = sizemask;
713     int orig_nargs = nargs;
714     TCGv_i64 retl, reth;
715
716     TCGV_UNUSED_I64(retl);
717     TCGV_UNUSED_I64(reth);
718     if (sizemask != 0) {
719         TCGArg *split_args = __builtin_alloca(sizeof(TCGArg) * nargs * 2);
720         for (i = real_args = 0; i < nargs; ++i) {
721             int is_64bit = sizemask & (1 << (i+1)*2);
722             if (is_64bit) {
723                 TCGv_i64 orig = MAKE_TCGV_I64(args[i]);
724                 TCGv_i32 h = tcg_temp_new_i32();
725                 TCGv_i32 l = tcg_temp_new_i32();
726                 tcg_gen_extr_i64_i32(l, h, orig);
727                 split_args[real_args++] = GET_TCGV_I32(h);
728                 split_args[real_args++] = GET_TCGV_I32(l);
729             } else {
730                 split_args[real_args++] = args[i];
731             }
732         }
733         nargs = real_args;
734         args = split_args;
735         sizemask = 0;
736     }
737 #elif defined(TCG_TARGET_EXTEND_ARGS) && TCG_TARGET_REG_BITS == 64
738     for (i = 0; i < nargs; ++i) {
739         int is_64bit = sizemask & (1 << (i+1)*2);
740         int is_signed = sizemask & (2 << (i+1)*2);
741         if (!is_64bit) {
742             TCGv_i64 temp = tcg_temp_new_i64();
743             TCGv_i64 orig = MAKE_TCGV_I64(args[i]);
744             if (is_signed) {
745                 tcg_gen_ext32s_i64(temp, orig);
746             } else {
747                 tcg_gen_ext32u_i64(temp, orig);
748             }
749             args[i] = GET_TCGV_I64(temp);
750         }
751     }
752 #endif /* TCG_TARGET_EXTEND_ARGS */
753
754     pi_first = pi = s->gen_next_parm_idx;
755     if (ret != TCG_CALL_DUMMY_ARG) {
756 #if defined(__sparc__) && !defined(__arch64__) \
757     && !defined(CONFIG_TCG_INTERPRETER)
758         if (orig_sizemask & 1) {
759             /* The 32-bit ABI is going to return the 64-bit value in
760                the %o0/%o1 register pair.  Prepare for this by using
761                two return temporaries, and reassemble below.  */
762             retl = tcg_temp_new_i64();
763             reth = tcg_temp_new_i64();
764             s->gen_opparam_buf[pi++] = GET_TCGV_I64(reth);
765             s->gen_opparam_buf[pi++] = GET_TCGV_I64(retl);
766             nb_rets = 2;
767         } else {
768             s->gen_opparam_buf[pi++] = ret;
769             nb_rets = 1;
770         }
771 #else
772         if (TCG_TARGET_REG_BITS < 64 && (sizemask & 1)) {
773 #ifdef HOST_WORDS_BIGENDIAN
774             s->gen_opparam_buf[pi++] = ret + 1;
775             s->gen_opparam_buf[pi++] = ret;
776 #else
777             s->gen_opparam_buf[pi++] = ret;
778             s->gen_opparam_buf[pi++] = ret + 1;
779 #endif
780             nb_rets = 2;
781         } else {
782             s->gen_opparam_buf[pi++] = ret;
783             nb_rets = 1;
784         }
785 #endif
786     } else {
787         nb_rets = 0;
788     }
789     real_args = 0;
790     for (i = 0; i < nargs; i++) {
791         int is_64bit = sizemask & (1 << (i+1)*2);
792         if (TCG_TARGET_REG_BITS < 64 && is_64bit) {
793 #ifdef TCG_TARGET_CALL_ALIGN_ARGS
794             /* some targets want aligned 64 bit args */
795             if (real_args & 1) {
796                 s->gen_opparam_buf[pi++] = TCG_CALL_DUMMY_ARG;
797                 real_args++;
798             }
799 #endif
800             /* If stack grows up, then we will be placing successive
801                arguments at lower addresses, which means we need to
802                reverse the order compared to how we would normally
803                treat either big or little-endian.  For those arguments
804                that will wind up in registers, this still works for
805                HPPA (the only current STACK_GROWSUP target) since the
806                argument registers are *also* allocated in decreasing
807                order.  If another such target is added, this logic may
808                have to get more complicated to differentiate between
809                stack arguments and register arguments.  */
810 #if defined(HOST_WORDS_BIGENDIAN) != defined(TCG_TARGET_STACK_GROWSUP)
811             s->gen_opparam_buf[pi++] = args[i] + 1;
812             s->gen_opparam_buf[pi++] = args[i];
813 #else
814             s->gen_opparam_buf[pi++] = args[i];
815             s->gen_opparam_buf[pi++] = args[i] + 1;
816 #endif
817             real_args += 2;
818             continue;
819         }
820
821         s->gen_opparam_buf[pi++] = args[i];
822         real_args++;
823     }
824     s->gen_opparam_buf[pi++] = (uintptr_t)func;
825     s->gen_opparam_buf[pi++] = flags;
826
827     i = s->gen_next_op_idx;
828     tcg_debug_assert(i < OPC_BUF_SIZE);
829     tcg_debug_assert(pi <= OPPARAM_BUF_SIZE);
830
831     /* Set links for sequential allocation during translation.  */
832     s->gen_op_buf[i] = (TCGOp){
833         .opc = INDEX_op_call,
834         .callo = nb_rets,
835         .calli = real_args,
836         .args = pi_first,
837         .prev = i - 1,
838         .next = i + 1
839     };
840
841     /* Make sure the calli field didn't overflow.  */
842     tcg_debug_assert(s->gen_op_buf[i].calli == real_args);
843
844     s->gen_last_op_idx = i;
845     s->gen_next_op_idx = i + 1;
846     s->gen_next_parm_idx = pi;
847
848 #if defined(__sparc__) && !defined(__arch64__) \
849     && !defined(CONFIG_TCG_INTERPRETER)
850     /* Free all of the parts we allocated above.  */
851     for (i = real_args = 0; i < orig_nargs; ++i) {
852         int is_64bit = orig_sizemask & (1 << (i+1)*2);
853         if (is_64bit) {
854             TCGv_i32 h = MAKE_TCGV_I32(args[real_args++]);
855             TCGv_i32 l = MAKE_TCGV_I32(args[real_args++]);
856             tcg_temp_free_i32(h);
857             tcg_temp_free_i32(l);
858         } else {
859             real_args++;
860         }
861     }
862     if (orig_sizemask & 1) {
863         /* The 32-bit ABI returned two 32-bit pieces.  Re-assemble them.
864            Note that describing these as TCGv_i64 eliminates an unnecessary
865            zero-extension that tcg_gen_concat_i32_i64 would create.  */
866         tcg_gen_concat32_i64(MAKE_TCGV_I64(ret), retl, reth);
867         tcg_temp_free_i64(retl);
868         tcg_temp_free_i64(reth);
869     }
870 #elif defined(TCG_TARGET_EXTEND_ARGS) && TCG_TARGET_REG_BITS == 64
871     for (i = 0; i < nargs; ++i) {
872         int is_64bit = sizemask & (1 << (i+1)*2);
873         if (!is_64bit) {
874             TCGv_i64 temp = MAKE_TCGV_I64(args[i]);
875             tcg_temp_free_i64(temp);
876         }
877     }
878 #endif /* TCG_TARGET_EXTEND_ARGS */
879 }
880
881 static void tcg_reg_alloc_start(TCGContext *s)
882 {
883     int i;
884     TCGTemp *ts;
885     for(i = 0; i < s->nb_globals; i++) {
886         ts = &s->temps[i];
887         if (ts->fixed_reg) {
888             ts->val_type = TEMP_VAL_REG;
889         } else {
890             ts->val_type = TEMP_VAL_MEM;
891         }
892     }
893     for(i = s->nb_globals; i < s->nb_temps; i++) {
894         ts = &s->temps[i];
895         if (ts->temp_local) {
896             ts->val_type = TEMP_VAL_MEM;
897         } else {
898             ts->val_type = TEMP_VAL_DEAD;
899         }
900         ts->mem_allocated = 0;
901         ts->fixed_reg = 0;
902     }
903     for(i = 0; i < TCG_TARGET_NB_REGS; i++) {
904         s->reg_to_temp[i] = -1;
905     }
906 }
907
908 static char *tcg_get_arg_str_idx(TCGContext *s, char *buf, int buf_size,
909                                  int idx)
910 {
911     TCGTemp *ts;
912
913     assert(idx >= 0 && idx < s->nb_temps);
914     ts = &s->temps[idx];
915     if (idx < s->nb_globals) {
916         pstrcpy(buf, buf_size, ts->name);
917     } else {
918         if (ts->temp_local) 
919             snprintf(buf, buf_size, "loc%d", idx - s->nb_globals);
920         else
921             snprintf(buf, buf_size, "tmp%d", idx - s->nb_globals);
922     }
923     return buf;
924 }
925
926 /* Find helper name.  */
927 static inline const char *tcg_find_helper(TCGContext *s, uintptr_t val)
928 {
929     const char *ret = NULL;
930     if (s->helpers) {
931         TCGHelperInfo *info = g_hash_table_lookup(s->helpers, (gpointer)val);
932         if (info) {
933             ret = info->name;
934         }
935     }
936     return ret;
937 }
938
939 static const char * const cond_name[] =
940 {
941     [TCG_COND_NEVER] = "never",
942     [TCG_COND_ALWAYS] = "always",
943     [TCG_COND_EQ] = "eq",
944     [TCG_COND_NE] = "ne",
945     [TCG_COND_LT] = "lt",
946     [TCG_COND_GE] = "ge",
947     [TCG_COND_LE] = "le",
948     [TCG_COND_GT] = "gt",
949     [TCG_COND_LTU] = "ltu",
950     [TCG_COND_GEU] = "geu",
951     [TCG_COND_LEU] = "leu",
952     [TCG_COND_GTU] = "gtu"
953 };
954
955 static const char * const ldst_name[] =
956 {
957     [MO_UB]   = "ub",
958     [MO_SB]   = "sb",
959     [MO_LEUW] = "leuw",
960     [MO_LESW] = "lesw",
961     [MO_LEUL] = "leul",
962     [MO_LESL] = "lesl",
963     [MO_LEQ]  = "leq",
964     [MO_BEUW] = "beuw",
965     [MO_BESW] = "besw",
966     [MO_BEUL] = "beul",
967     [MO_BESL] = "besl",
968     [MO_BEQ]  = "beq",
969 };
970
971 void tcg_dump_ops(TCGContext *s)
972 {
973     char buf[128];
974     TCGOp *op;
975     int oi;
976
977     for (oi = s->gen_first_op_idx; oi >= 0; oi = op->next) {
978         int i, k, nb_oargs, nb_iargs, nb_cargs;
979         const TCGOpDef *def;
980         const TCGArg *args;
981         TCGOpcode c;
982
983         op = &s->gen_op_buf[oi];
984         c = op->opc;
985         def = &tcg_op_defs[c];
986         args = &s->gen_opparam_buf[op->args];
987
988         if (c == INDEX_op_insn_start) {
989             qemu_log("%s ----", oi != s->gen_first_op_idx ? "\n" : "");
990
991             for (i = 0; i < TARGET_INSN_START_WORDS; ++i) {
992                 target_ulong a;
993 #if TARGET_LONG_BITS > TCG_TARGET_REG_BITS
994                 a = ((target_ulong)args[i * 2 + 1] << 32) | args[i * 2];
995 #else
996                 a = args[i];
997 #endif
998                 qemu_log(" " TARGET_FMT_lx, a);
999             }
1000         } else if (c == INDEX_op_call) {
1001             /* variable number of arguments */
1002             nb_oargs = op->callo;
1003             nb_iargs = op->calli;
1004             nb_cargs = def->nb_cargs;
1005
1006             /* function name, flags, out args */
1007             qemu_log(" %s %s,$0x%" TCG_PRIlx ",$%d", def->name,
1008                      tcg_find_helper(s, args[nb_oargs + nb_iargs]),
1009                      args[nb_oargs + nb_iargs + 1], nb_oargs);
1010             for (i = 0; i < nb_oargs; i++) {
1011                 qemu_log(",%s", tcg_get_arg_str_idx(s, buf, sizeof(buf),
1012                                                    args[i]));
1013             }
1014             for (i = 0; i < nb_iargs; i++) {
1015                 TCGArg arg = args[nb_oargs + i];
1016                 const char *t = "<dummy>";
1017                 if (arg != TCG_CALL_DUMMY_ARG) {
1018                     t = tcg_get_arg_str_idx(s, buf, sizeof(buf), arg);
1019                 }
1020                 qemu_log(",%s", t);
1021             }
1022         } else {
1023             qemu_log(" %s ", def->name);
1024
1025             nb_oargs = def->nb_oargs;
1026             nb_iargs = def->nb_iargs;
1027             nb_cargs = def->nb_cargs;
1028
1029             k = 0;
1030             for (i = 0; i < nb_oargs; i++) {
1031                 if (k != 0) {
1032                     qemu_log(",");
1033                 }
1034                 qemu_log("%s", tcg_get_arg_str_idx(s, buf, sizeof(buf),
1035                                                    args[k++]));
1036             }
1037             for (i = 0; i < nb_iargs; i++) {
1038                 if (k != 0) {
1039                     qemu_log(",");
1040                 }
1041                 qemu_log("%s", tcg_get_arg_str_idx(s, buf, sizeof(buf),
1042                                                    args[k++]));
1043             }
1044             switch (c) {
1045             case INDEX_op_brcond_i32:
1046             case INDEX_op_setcond_i32:
1047             case INDEX_op_movcond_i32:
1048             case INDEX_op_brcond2_i32:
1049             case INDEX_op_setcond2_i32:
1050             case INDEX_op_brcond_i64:
1051             case INDEX_op_setcond_i64:
1052             case INDEX_op_movcond_i64:
1053                 if (args[k] < ARRAY_SIZE(cond_name) && cond_name[args[k]]) {
1054                     qemu_log(",%s", cond_name[args[k++]]);
1055                 } else {
1056                     qemu_log(",$0x%" TCG_PRIlx, args[k++]);
1057                 }
1058                 i = 1;
1059                 break;
1060             case INDEX_op_qemu_ld_i32:
1061             case INDEX_op_qemu_st_i32:
1062             case INDEX_op_qemu_ld_i64:
1063             case INDEX_op_qemu_st_i64:
1064                 {
1065                     TCGMemOpIdx oi = args[k++];
1066                     TCGMemOp op = get_memop(oi);
1067                     unsigned ix = get_mmuidx(oi);
1068
1069                     if (op & ~(MO_AMASK | MO_BSWAP | MO_SSIZE)) {
1070                         qemu_log(",$0x%x,%u", op, ix);
1071                     } else {
1072                         const char *s_al = "", *s_op;
1073                         if (op & MO_AMASK) {
1074                             if ((op & MO_AMASK) == MO_ALIGN) {
1075                                 s_al = "al+";
1076                             } else {
1077                                 s_al = "un+";
1078                             }
1079                         }
1080                         s_op = ldst_name[op & (MO_BSWAP | MO_SSIZE)];
1081                         qemu_log(",%s%s,%u", s_al, s_op, ix);
1082                     }
1083                     i = 1;
1084                 }
1085                 break;
1086             default:
1087                 i = 0;
1088                 break;
1089             }
1090             switch (c) {
1091             case INDEX_op_set_label:
1092             case INDEX_op_br:
1093             case INDEX_op_brcond_i32:
1094             case INDEX_op_brcond_i64:
1095             case INDEX_op_brcond2_i32:
1096                 qemu_log("%s$L%d", k ? "," : "", arg_label(args[k])->id);
1097                 i++, k++;
1098                 break;
1099             default:
1100                 break;
1101             }
1102             for (; i < nb_cargs; i++, k++) {
1103                 qemu_log("%s$0x%" TCG_PRIlx, k ? "," : "", args[k]);
1104             }
1105         }
1106         qemu_log("\n");
1107     }
1108 }
1109
1110 /* we give more priority to constraints with less registers */
1111 static int get_constraint_priority(const TCGOpDef *def, int k)
1112 {
1113     const TCGArgConstraint *arg_ct;
1114
1115     int i, n;
1116     arg_ct = &def->args_ct[k];
1117     if (arg_ct->ct & TCG_CT_ALIAS) {
1118         /* an alias is equivalent to a single register */
1119         n = 1;
1120     } else {
1121         if (!(arg_ct->ct & TCG_CT_REG))
1122             return 0;
1123         n = 0;
1124         for(i = 0; i < TCG_TARGET_NB_REGS; i++) {
1125             if (tcg_regset_test_reg(arg_ct->u.regs, i))
1126                 n++;
1127         }
1128     }
1129     return TCG_TARGET_NB_REGS - n + 1;
1130 }
1131
1132 /* sort from highest priority to lowest */
1133 static void sort_constraints(TCGOpDef *def, int start, int n)
1134 {
1135     int i, j, p1, p2, tmp;
1136
1137     for(i = 0; i < n; i++)
1138         def->sorted_args[start + i] = start + i;
1139     if (n <= 1)
1140         return;
1141     for(i = 0; i < n - 1; i++) {
1142         for(j = i + 1; j < n; j++) {
1143             p1 = get_constraint_priority(def, def->sorted_args[start + i]);
1144             p2 = get_constraint_priority(def, def->sorted_args[start + j]);
1145             if (p1 < p2) {
1146                 tmp = def->sorted_args[start + i];
1147                 def->sorted_args[start + i] = def->sorted_args[start + j];
1148                 def->sorted_args[start + j] = tmp;
1149             }
1150         }
1151     }
1152 }
1153
1154 void tcg_add_target_add_op_defs(const TCGTargetOpDef *tdefs)
1155 {
1156     TCGOpcode op;
1157     TCGOpDef *def;
1158     const char *ct_str;
1159     int i, nb_args;
1160
1161     for(;;) {
1162         if (tdefs->op == (TCGOpcode)-1)
1163             break;
1164         op = tdefs->op;
1165         assert((unsigned)op < NB_OPS);
1166         def = &tcg_op_defs[op];
1167 #if defined(CONFIG_DEBUG_TCG)
1168         /* Duplicate entry in op definitions? */
1169         assert(!def->used);
1170         def->used = 1;
1171 #endif
1172         nb_args = def->nb_iargs + def->nb_oargs;
1173         for(i = 0; i < nb_args; i++) {
1174             ct_str = tdefs->args_ct_str[i];
1175             /* Incomplete TCGTargetOpDef entry? */
1176             assert(ct_str != NULL);
1177             tcg_regset_clear(def->args_ct[i].u.regs);
1178             def->args_ct[i].ct = 0;
1179             if (ct_str[0] >= '0' && ct_str[0] <= '9') {
1180                 int oarg;
1181                 oarg = ct_str[0] - '0';
1182                 assert(oarg < def->nb_oargs);
1183                 assert(def->args_ct[oarg].ct & TCG_CT_REG);
1184                 /* TCG_CT_ALIAS is for the output arguments. The input
1185                    argument is tagged with TCG_CT_IALIAS. */
1186                 def->args_ct[i] = def->args_ct[oarg];
1187                 def->args_ct[oarg].ct = TCG_CT_ALIAS;
1188                 def->args_ct[oarg].alias_index = i;
1189                 def->args_ct[i].ct |= TCG_CT_IALIAS;
1190                 def->args_ct[i].alias_index = oarg;
1191             } else {
1192                 for(;;) {
1193                     if (*ct_str == '\0')
1194                         break;
1195                     switch(*ct_str) {
1196                     case 'i':
1197                         def->args_ct[i].ct |= TCG_CT_CONST;
1198                         ct_str++;
1199                         break;
1200                     default:
1201                         if (target_parse_constraint(&def->args_ct[i], &ct_str) < 0) {
1202                             fprintf(stderr, "Invalid constraint '%s' for arg %d of operation '%s'\n",
1203                                     ct_str, i, def->name);
1204                             exit(1);
1205                         }
1206                     }
1207                 }
1208             }
1209         }
1210
1211         /* TCGTargetOpDef entry with too much information? */
1212         assert(i == TCG_MAX_OP_ARGS || tdefs->args_ct_str[i] == NULL);
1213
1214         /* sort the constraints (XXX: this is just an heuristic) */
1215         sort_constraints(def, 0, def->nb_oargs);
1216         sort_constraints(def, def->nb_oargs, def->nb_iargs);
1217
1218 #if 0
1219         {
1220             int i;
1221
1222             printf("%s: sorted=", def->name);
1223             for(i = 0; i < def->nb_oargs + def->nb_iargs; i++)
1224                 printf(" %d", def->sorted_args[i]);
1225             printf("\n");
1226         }
1227 #endif
1228         tdefs++;
1229     }
1230
1231 #if defined(CONFIG_DEBUG_TCG)
1232     i = 0;
1233     for (op = 0; op < tcg_op_defs_max; op++) {
1234         const TCGOpDef *def = &tcg_op_defs[op];
1235         if (def->flags & TCG_OPF_NOT_PRESENT) {
1236             /* Wrong entry in op definitions? */
1237             if (def->used) {
1238                 fprintf(stderr, "Invalid op definition for %s\n", def->name);
1239                 i = 1;
1240             }
1241         } else {
1242             /* Missing entry in op definitions? */
1243             if (!def->used) {
1244                 fprintf(stderr, "Missing op definition for %s\n", def->name);
1245                 i = 1;
1246             }
1247         }
1248     }
1249     if (i == 1) {
1250         tcg_abort();
1251     }
1252 #endif
1253 }
1254
1255 void tcg_op_remove(TCGContext *s, TCGOp *op)
1256 {
1257     int next = op->next;
1258     int prev = op->prev;
1259
1260     if (next >= 0) {
1261         s->gen_op_buf[next].prev = prev;
1262     } else {
1263         s->gen_last_op_idx = prev;
1264     }
1265     if (prev >= 0) {
1266         s->gen_op_buf[prev].next = next;
1267     } else {
1268         s->gen_first_op_idx = next;
1269     }
1270
1271     memset(op, -1, sizeof(*op));
1272
1273 #ifdef CONFIG_PROFILER
1274     s->del_op_count++;
1275 #endif
1276 }
1277
1278 #ifdef USE_LIVENESS_ANALYSIS
1279 /* liveness analysis: end of function: all temps are dead, and globals
1280    should be in memory. */
1281 static inline void tcg_la_func_end(TCGContext *s, uint8_t *dead_temps,
1282                                    uint8_t *mem_temps)
1283 {
1284     memset(dead_temps, 1, s->nb_temps);
1285     memset(mem_temps, 1, s->nb_globals);
1286     memset(mem_temps + s->nb_globals, 0, s->nb_temps - s->nb_globals);
1287 }
1288
1289 /* liveness analysis: end of basic block: all temps are dead, globals
1290    and local temps should be in memory. */
1291 static inline void tcg_la_bb_end(TCGContext *s, uint8_t *dead_temps,
1292                                  uint8_t *mem_temps)
1293 {
1294     int i;
1295
1296     memset(dead_temps, 1, s->nb_temps);
1297     memset(mem_temps, 1, s->nb_globals);
1298     for(i = s->nb_globals; i < s->nb_temps; i++) {
1299         mem_temps[i] = s->temps[i].temp_local;
1300     }
1301 }
1302
1303 /* Liveness analysis : update the opc_dead_args array to tell if a
1304    given input arguments is dead. Instructions updating dead
1305    temporaries are removed. */
1306 static void tcg_liveness_analysis(TCGContext *s)
1307 {
1308     uint8_t *dead_temps, *mem_temps;
1309     int oi, oi_prev, nb_ops;
1310
1311     nb_ops = s->gen_next_op_idx;
1312     s->op_dead_args = tcg_malloc(nb_ops * sizeof(uint16_t));
1313     s->op_sync_args = tcg_malloc(nb_ops * sizeof(uint8_t));
1314     
1315     dead_temps = tcg_malloc(s->nb_temps);
1316     mem_temps = tcg_malloc(s->nb_temps);
1317     tcg_la_func_end(s, dead_temps, mem_temps);
1318
1319     for (oi = s->gen_last_op_idx; oi >= 0; oi = oi_prev) {
1320         int i, nb_iargs, nb_oargs;
1321         TCGOpcode opc_new, opc_new2;
1322         bool have_opc_new2;
1323         uint16_t dead_args;
1324         uint8_t sync_args;
1325         TCGArg arg;
1326
1327         TCGOp * const op = &s->gen_op_buf[oi];
1328         TCGArg * const args = &s->gen_opparam_buf[op->args];
1329         TCGOpcode opc = op->opc;
1330         const TCGOpDef *def = &tcg_op_defs[opc];
1331
1332         oi_prev = op->prev;
1333
1334         switch (opc) {
1335         case INDEX_op_call:
1336             {
1337                 int call_flags;
1338
1339                 nb_oargs = op->callo;
1340                 nb_iargs = op->calli;
1341                 call_flags = args[nb_oargs + nb_iargs + 1];
1342
1343                 /* pure functions can be removed if their result is unused */
1344                 if (call_flags & TCG_CALL_NO_SIDE_EFFECTS) {
1345                     for (i = 0; i < nb_oargs; i++) {
1346                         arg = args[i];
1347                         if (!dead_temps[arg] || mem_temps[arg]) {
1348                             goto do_not_remove_call;
1349                         }
1350                     }
1351                     goto do_remove;
1352                 } else {
1353                 do_not_remove_call:
1354
1355                     /* output args are dead */
1356                     dead_args = 0;
1357                     sync_args = 0;
1358                     for (i = 0; i < nb_oargs; i++) {
1359                         arg = args[i];
1360                         if (dead_temps[arg]) {
1361                             dead_args |= (1 << i);
1362                         }
1363                         if (mem_temps[arg]) {
1364                             sync_args |= (1 << i);
1365                         }
1366                         dead_temps[arg] = 1;
1367                         mem_temps[arg] = 0;
1368                     }
1369
1370                     if (!(call_flags & TCG_CALL_NO_READ_GLOBALS)) {
1371                         /* globals should be synced to memory */
1372                         memset(mem_temps, 1, s->nb_globals);
1373                     }
1374                     if (!(call_flags & (TCG_CALL_NO_WRITE_GLOBALS |
1375                                         TCG_CALL_NO_READ_GLOBALS))) {
1376                         /* globals should go back to memory */
1377                         memset(dead_temps, 1, s->nb_globals);
1378                     }
1379
1380                     /* record arguments that die in this helper */
1381                     for (i = nb_oargs; i < nb_iargs + nb_oargs; i++) {
1382                         arg = args[i];
1383                         if (arg != TCG_CALL_DUMMY_ARG) {
1384                             if (dead_temps[arg]) {
1385                                 dead_args |= (1 << i);
1386                             }
1387                         }
1388                     }
1389                     /* input arguments are live for preceding opcodes */
1390                     for (i = nb_oargs; i < nb_oargs + nb_iargs; i++) {
1391                         arg = args[i];
1392                         dead_temps[arg] = 0;
1393                     }
1394                     s->op_dead_args[oi] = dead_args;
1395                     s->op_sync_args[oi] = sync_args;
1396                 }
1397             }
1398             break;
1399         case INDEX_op_insn_start:
1400             break;
1401         case INDEX_op_discard:
1402             /* mark the temporary as dead */
1403             dead_temps[args[0]] = 1;
1404             mem_temps[args[0]] = 0;
1405             break;
1406
1407         case INDEX_op_add2_i32:
1408             opc_new = INDEX_op_add_i32;
1409             goto do_addsub2;
1410         case INDEX_op_sub2_i32:
1411             opc_new = INDEX_op_sub_i32;
1412             goto do_addsub2;
1413         case INDEX_op_add2_i64:
1414             opc_new = INDEX_op_add_i64;
1415             goto do_addsub2;
1416         case INDEX_op_sub2_i64:
1417             opc_new = INDEX_op_sub_i64;
1418         do_addsub2:
1419             nb_iargs = 4;
1420             nb_oargs = 2;
1421             /* Test if the high part of the operation is dead, but not
1422                the low part.  The result can be optimized to a simple
1423                add or sub.  This happens often for x86_64 guest when the
1424                cpu mode is set to 32 bit.  */
1425             if (dead_temps[args[1]] && !mem_temps[args[1]]) {
1426                 if (dead_temps[args[0]] && !mem_temps[args[0]]) {
1427                     goto do_remove;
1428                 }
1429                 /* Replace the opcode and adjust the args in place,
1430                    leaving 3 unused args at the end.  */
1431                 op->opc = opc = opc_new;
1432                 args[1] = args[2];
1433                 args[2] = args[4];
1434                 /* Fall through and mark the single-word operation live.  */
1435                 nb_iargs = 2;
1436                 nb_oargs = 1;
1437             }
1438             goto do_not_remove;
1439
1440         case INDEX_op_mulu2_i32:
1441             opc_new = INDEX_op_mul_i32;
1442             opc_new2 = INDEX_op_muluh_i32;
1443             have_opc_new2 = TCG_TARGET_HAS_muluh_i32;
1444             goto do_mul2;
1445         case INDEX_op_muls2_i32:
1446             opc_new = INDEX_op_mul_i32;
1447             opc_new2 = INDEX_op_mulsh_i32;
1448             have_opc_new2 = TCG_TARGET_HAS_mulsh_i32;
1449             goto do_mul2;
1450         case INDEX_op_mulu2_i64:
1451             opc_new = INDEX_op_mul_i64;
1452             opc_new2 = INDEX_op_muluh_i64;
1453             have_opc_new2 = TCG_TARGET_HAS_muluh_i64;
1454             goto do_mul2;
1455         case INDEX_op_muls2_i64:
1456             opc_new = INDEX_op_mul_i64;
1457             opc_new2 = INDEX_op_mulsh_i64;
1458             have_opc_new2 = TCG_TARGET_HAS_mulsh_i64;
1459             goto do_mul2;
1460         do_mul2:
1461             nb_iargs = 2;
1462             nb_oargs = 2;
1463             if (dead_temps[args[1]] && !mem_temps[args[1]]) {
1464                 if (dead_temps[args[0]] && !mem_temps[args[0]]) {
1465                     /* Both parts of the operation are dead.  */
1466                     goto do_remove;
1467                 }
1468                 /* The high part of the operation is dead; generate the low. */
1469                 op->opc = opc = opc_new;
1470                 args[1] = args[2];
1471                 args[2] = args[3];
1472             } else if (have_opc_new2 && dead_temps[args[0]]
1473                        && !mem_temps[args[0]]) {
1474                 /* The low part of the operation is dead; generate the high. */
1475                 op->opc = opc = opc_new2;
1476                 args[0] = args[1];
1477                 args[1] = args[2];
1478                 args[2] = args[3];
1479             } else {
1480                 goto do_not_remove;
1481             }
1482             /* Mark the single-word operation live.  */
1483             nb_oargs = 1;
1484             goto do_not_remove;
1485
1486         default:
1487             /* XXX: optimize by hardcoding common cases (e.g. triadic ops) */
1488             nb_iargs = def->nb_iargs;
1489             nb_oargs = def->nb_oargs;
1490
1491             /* Test if the operation can be removed because all
1492                its outputs are dead. We assume that nb_oargs == 0
1493                implies side effects */
1494             if (!(def->flags & TCG_OPF_SIDE_EFFECTS) && nb_oargs != 0) {
1495                 for (i = 0; i < nb_oargs; i++) {
1496                     arg = args[i];
1497                     if (!dead_temps[arg] || mem_temps[arg]) {
1498                         goto do_not_remove;
1499                     }
1500                 }
1501             do_remove:
1502                 tcg_op_remove(s, op);
1503             } else {
1504             do_not_remove:
1505                 /* output args are dead */
1506                 dead_args = 0;
1507                 sync_args = 0;
1508                 for (i = 0; i < nb_oargs; i++) {
1509                     arg = args[i];
1510                     if (dead_temps[arg]) {
1511                         dead_args |= (1 << i);
1512                     }
1513                     if (mem_temps[arg]) {
1514                         sync_args |= (1 << i);
1515                     }
1516                     dead_temps[arg] = 1;
1517                     mem_temps[arg] = 0;
1518                 }
1519
1520                 /* if end of basic block, update */
1521                 if (def->flags & TCG_OPF_BB_END) {
1522                     tcg_la_bb_end(s, dead_temps, mem_temps);
1523                 } else if (def->flags & TCG_OPF_SIDE_EFFECTS) {
1524                     /* globals should be synced to memory */
1525                     memset(mem_temps, 1, s->nb_globals);
1526                 }
1527
1528                 /* record arguments that die in this opcode */
1529                 for (i = nb_oargs; i < nb_oargs + nb_iargs; i++) {
1530                     arg = args[i];
1531                     if (dead_temps[arg]) {
1532                         dead_args |= (1 << i);
1533                     }
1534                 }
1535                 /* input arguments are live for preceding opcodes */
1536                 for (i = nb_oargs; i < nb_oargs + nb_iargs; i++) {
1537                     arg = args[i];
1538                     dead_temps[arg] = 0;
1539                 }
1540                 s->op_dead_args[oi] = dead_args;
1541                 s->op_sync_args[oi] = sync_args;
1542             }
1543             break;
1544         }
1545     }
1546 }
1547 #else
1548 /* dummy liveness analysis */
1549 static void tcg_liveness_analysis(TCGContext *s)
1550 {
1551     int nb_ops = s->gen_next_op_idx;
1552
1553     s->op_dead_args = tcg_malloc(nb_ops * sizeof(uint16_t));
1554     memset(s->op_dead_args, 0, nb_ops * sizeof(uint16_t));
1555     s->op_sync_args = tcg_malloc(nb_ops * sizeof(uint8_t));
1556     memset(s->op_sync_args, 0, nb_ops * sizeof(uint8_t));
1557 }
1558 #endif
1559
1560 #ifndef NDEBUG
1561 static void dump_regs(TCGContext *s)
1562 {
1563     TCGTemp *ts;
1564     int i;
1565     char buf[64];
1566
1567     for(i = 0; i < s->nb_temps; i++) {
1568         ts = &s->temps[i];
1569         printf("  %10s: ", tcg_get_arg_str_idx(s, buf, sizeof(buf), i));
1570         switch(ts->val_type) {
1571         case TEMP_VAL_REG:
1572             printf("%s", tcg_target_reg_names[ts->reg]);
1573             break;
1574         case TEMP_VAL_MEM:
1575             printf("%d(%s)", (int)ts->mem_offset,
1576                    tcg_target_reg_names[ts->mem_base->reg]);
1577             break;
1578         case TEMP_VAL_CONST:
1579             printf("$0x%" TCG_PRIlx, ts->val);
1580             break;
1581         case TEMP_VAL_DEAD:
1582             printf("D");
1583             break;
1584         default:
1585             printf("???");
1586             break;
1587         }
1588         printf("\n");
1589     }
1590
1591     for(i = 0; i < TCG_TARGET_NB_REGS; i++) {
1592         if (s->reg_to_temp[i] >= 0) {
1593             printf("%s: %s\n", 
1594                    tcg_target_reg_names[i], 
1595                    tcg_get_arg_str_idx(s, buf, sizeof(buf), s->reg_to_temp[i]));
1596         }
1597     }
1598 }
1599
1600 static void check_regs(TCGContext *s)
1601 {
1602     TCGReg reg;
1603     int k;
1604     TCGTemp *ts;
1605     char buf[64];
1606
1607     for(reg = 0; reg < TCG_TARGET_NB_REGS; reg++) {
1608         k = s->reg_to_temp[reg];
1609         if (k >= 0) {
1610             ts = &s->temps[k];
1611             if (ts->val_type != TEMP_VAL_REG ||
1612                 ts->reg != reg) {
1613                 printf("Inconsistency for register %s:\n", 
1614                        tcg_target_reg_names[reg]);
1615                 goto fail;
1616             }
1617         }
1618     }
1619     for(k = 0; k < s->nb_temps; k++) {
1620         ts = &s->temps[k];
1621         if (ts->val_type == TEMP_VAL_REG &&
1622             !ts->fixed_reg &&
1623             s->reg_to_temp[ts->reg] != k) {
1624                 printf("Inconsistency for temp %s:\n", 
1625                        tcg_get_arg_str_idx(s, buf, sizeof(buf), k));
1626         fail:
1627                 printf("reg state:\n");
1628                 dump_regs(s);
1629                 tcg_abort();
1630         }
1631     }
1632 }
1633 #endif
1634
1635 static void temp_allocate_frame(TCGContext *s, int temp)
1636 {
1637     TCGTemp *ts;
1638     ts = &s->temps[temp];
1639 #if !(defined(__sparc__) && TCG_TARGET_REG_BITS == 64)
1640     /* Sparc64 stack is accessed with offset of 2047 */
1641     s->current_frame_offset = (s->current_frame_offset +
1642                                (tcg_target_long)sizeof(tcg_target_long) - 1) &
1643         ~(sizeof(tcg_target_long) - 1);
1644 #endif
1645     if (s->current_frame_offset + (tcg_target_long)sizeof(tcg_target_long) >
1646         s->frame_end) {
1647         tcg_abort();
1648     }
1649     ts->mem_offset = s->current_frame_offset;
1650     ts->mem_base = s->frame_temp;
1651     ts->mem_allocated = 1;
1652     s->current_frame_offset += sizeof(tcg_target_long);
1653 }
1654
1655 /* sync register 'reg' by saving it to the corresponding temporary */
1656 static inline void tcg_reg_sync(TCGContext *s, TCGReg reg)
1657 {
1658     TCGTemp *ts;
1659     int temp;
1660
1661     temp = s->reg_to_temp[reg];
1662     ts = &s->temps[temp];
1663     assert(ts->val_type == TEMP_VAL_REG);
1664     if (!ts->mem_coherent && !ts->fixed_reg) {
1665         if (!ts->mem_allocated) {
1666             temp_allocate_frame(s, temp);
1667         }
1668         tcg_out_st(s, ts->type, reg, ts->mem_base->reg, ts->mem_offset);
1669     }
1670     ts->mem_coherent = 1;
1671 }
1672
1673 /* free register 'reg' by spilling the corresponding temporary if necessary */
1674 static void tcg_reg_free(TCGContext *s, TCGReg reg)
1675 {
1676     int temp;
1677
1678     temp = s->reg_to_temp[reg];
1679     if (temp != -1) {
1680         tcg_reg_sync(s, reg);
1681         s->temps[temp].val_type = TEMP_VAL_MEM;
1682         s->reg_to_temp[reg] = -1;
1683     }
1684 }
1685
1686 /* Allocate a register belonging to reg1 & ~reg2 */
1687 static TCGReg tcg_reg_alloc(TCGContext *s, TCGRegSet reg1, TCGRegSet reg2)
1688 {
1689     int i;
1690     TCGReg reg;
1691     TCGRegSet reg_ct;
1692
1693     tcg_regset_andnot(reg_ct, reg1, reg2);
1694
1695     /* first try free registers */
1696     for(i = 0; i < ARRAY_SIZE(tcg_target_reg_alloc_order); i++) {
1697         reg = tcg_target_reg_alloc_order[i];
1698         if (tcg_regset_test_reg(reg_ct, reg) && s->reg_to_temp[reg] == -1)
1699             return reg;
1700     }
1701
1702     /* XXX: do better spill choice */
1703     for(i = 0; i < ARRAY_SIZE(tcg_target_reg_alloc_order); i++) {
1704         reg = tcg_target_reg_alloc_order[i];
1705         if (tcg_regset_test_reg(reg_ct, reg)) {
1706             tcg_reg_free(s, reg);
1707             return reg;
1708         }
1709     }
1710
1711     tcg_abort();
1712 }
1713
1714 /* mark a temporary as dead. */
1715 static inline void temp_dead(TCGContext *s, int temp)
1716 {
1717     TCGTemp *ts;
1718
1719     ts = &s->temps[temp];
1720     if (!ts->fixed_reg) {
1721         if (ts->val_type == TEMP_VAL_REG) {
1722             s->reg_to_temp[ts->reg] = -1;
1723         }
1724         if (temp < s->nb_globals || ts->temp_local) {
1725             ts->val_type = TEMP_VAL_MEM;
1726         } else {
1727             ts->val_type = TEMP_VAL_DEAD;
1728         }
1729     }
1730 }
1731
1732 /* sync a temporary to memory. 'allocated_regs' is used in case a
1733    temporary registers needs to be allocated to store a constant. */
1734 static inline void temp_sync(TCGContext *s, int temp, TCGRegSet allocated_regs)
1735 {
1736     TCGTemp *ts;
1737
1738     ts = &s->temps[temp];
1739     if (!ts->fixed_reg) {
1740         switch(ts->val_type) {
1741         case TEMP_VAL_CONST:
1742             ts->reg = tcg_reg_alloc(s, tcg_target_available_regs[ts->type],
1743                                     allocated_regs);
1744             ts->val_type = TEMP_VAL_REG;
1745             s->reg_to_temp[ts->reg] = temp;
1746             ts->mem_coherent = 0;
1747             tcg_out_movi(s, ts->type, ts->reg, ts->val);
1748             /* fallthrough*/
1749         case TEMP_VAL_REG:
1750             tcg_reg_sync(s, ts->reg);
1751             break;
1752         case TEMP_VAL_DEAD:
1753         case TEMP_VAL_MEM:
1754             break;
1755         default:
1756             tcg_abort();
1757         }
1758     }
1759 }
1760
1761 /* save a temporary to memory. 'allocated_regs' is used in case a
1762    temporary registers needs to be allocated to store a constant. */
1763 static inline void temp_save(TCGContext *s, int temp, TCGRegSet allocated_regs)
1764 {
1765 #ifdef USE_LIVENESS_ANALYSIS
1766     /* The liveness analysis already ensures that globals are back
1767        in memory. Keep an assert for safety. */
1768     assert(s->temps[temp].val_type == TEMP_VAL_MEM || s->temps[temp].fixed_reg);
1769 #else
1770     temp_sync(s, temp, allocated_regs);
1771     temp_dead(s, temp);
1772 #endif
1773 }
1774
1775 /* save globals to their canonical location and assume they can be
1776    modified be the following code. 'allocated_regs' is used in case a
1777    temporary registers needs to be allocated to store a constant. */
1778 static void save_globals(TCGContext *s, TCGRegSet allocated_regs)
1779 {
1780     int i;
1781
1782     for(i = 0; i < s->nb_globals; i++) {
1783         temp_save(s, i, allocated_regs);
1784     }
1785 }
1786
1787 /* sync globals to their canonical location and assume they can be
1788    read by the following code. 'allocated_regs' is used in case a
1789    temporary registers needs to be allocated to store a constant. */
1790 static void sync_globals(TCGContext *s, TCGRegSet allocated_regs)
1791 {
1792     int i;
1793
1794     for (i = 0; i < s->nb_globals; i++) {
1795 #ifdef USE_LIVENESS_ANALYSIS
1796         assert(s->temps[i].val_type != TEMP_VAL_REG || s->temps[i].fixed_reg ||
1797                s->temps[i].mem_coherent);
1798 #else
1799         temp_sync(s, i, allocated_regs);
1800 #endif
1801     }
1802 }
1803
1804 /* at the end of a basic block, we assume all temporaries are dead and
1805    all globals are stored at their canonical location. */
1806 static void tcg_reg_alloc_bb_end(TCGContext *s, TCGRegSet allocated_regs)
1807 {
1808     TCGTemp *ts;
1809     int i;
1810
1811     for(i = s->nb_globals; i < s->nb_temps; i++) {
1812         ts = &s->temps[i];
1813         if (ts->temp_local) {
1814             temp_save(s, i, allocated_regs);
1815         } else {
1816 #ifdef USE_LIVENESS_ANALYSIS
1817             /* The liveness analysis already ensures that temps are dead.
1818                Keep an assert for safety. */
1819             assert(ts->val_type == TEMP_VAL_DEAD);
1820 #else
1821             temp_dead(s, i);
1822 #endif
1823         }
1824     }
1825
1826     save_globals(s, allocated_regs);
1827 }
1828
1829 #define IS_DEAD_ARG(n) ((dead_args >> (n)) & 1)
1830 #define NEED_SYNC_ARG(n) ((sync_args >> (n)) & 1)
1831
1832 static void tcg_reg_alloc_movi(TCGContext *s, const TCGArg *args,
1833                                uint16_t dead_args, uint8_t sync_args)
1834 {
1835     TCGTemp *ots;
1836     tcg_target_ulong val;
1837
1838     ots = &s->temps[args[0]];
1839     val = args[1];
1840
1841     if (ots->fixed_reg) {
1842         /* for fixed registers, we do not do any constant
1843            propagation */
1844         tcg_out_movi(s, ots->type, ots->reg, val);
1845     } else {
1846         /* The movi is not explicitly generated here */
1847         if (ots->val_type == TEMP_VAL_REG)
1848             s->reg_to_temp[ots->reg] = -1;
1849         ots->val_type = TEMP_VAL_CONST;
1850         ots->val = val;
1851     }
1852     if (NEED_SYNC_ARG(0)) {
1853         temp_sync(s, args[0], s->reserved_regs);
1854     }
1855     if (IS_DEAD_ARG(0)) {
1856         temp_dead(s, args[0]);
1857     }
1858 }
1859
1860 static void tcg_reg_alloc_mov(TCGContext *s, const TCGOpDef *def,
1861                               const TCGArg *args, uint16_t dead_args,
1862                               uint8_t sync_args)
1863 {
1864     TCGRegSet allocated_regs;
1865     TCGTemp *ts, *ots;
1866     TCGType otype, itype;
1867
1868     tcg_regset_set(allocated_regs, s->reserved_regs);
1869     ots = &s->temps[args[0]];
1870     ts = &s->temps[args[1]];
1871
1872     /* Note that otype != itype for no-op truncation.  */
1873     otype = ots->type;
1874     itype = ts->type;
1875
1876     /* If the source value is not in a register, and we're going to be
1877        forced to have it in a register in order to perform the copy,
1878        then copy the SOURCE value into its own register first.  That way
1879        we don't have to reload SOURCE the next time it is used. */
1880     if (((NEED_SYNC_ARG(0) || ots->fixed_reg) && ts->val_type != TEMP_VAL_REG)
1881         || ts->val_type == TEMP_VAL_MEM) {
1882         ts->reg = tcg_reg_alloc(s, tcg_target_available_regs[itype],
1883                                 allocated_regs);
1884         if (ts->val_type == TEMP_VAL_MEM) {
1885             tcg_out_ld(s, itype, ts->reg, ts->mem_base->reg, ts->mem_offset);
1886             ts->mem_coherent = 1;
1887         } else if (ts->val_type == TEMP_VAL_CONST) {
1888             tcg_out_movi(s, itype, ts->reg, ts->val);
1889             ts->mem_coherent = 0;
1890         }
1891         s->reg_to_temp[ts->reg] = args[1];
1892         ts->val_type = TEMP_VAL_REG;
1893     }
1894
1895     if (IS_DEAD_ARG(0) && !ots->fixed_reg) {
1896         /* mov to a non-saved dead register makes no sense (even with
1897            liveness analysis disabled). */
1898         assert(NEED_SYNC_ARG(0));
1899         /* The code above should have moved the temp to a register. */
1900         assert(ts->val_type == TEMP_VAL_REG);
1901         if (!ots->mem_allocated) {
1902             temp_allocate_frame(s, args[0]);
1903         }
1904         tcg_out_st(s, otype, ts->reg, ots->mem_base->reg, ots->mem_offset);
1905         if (IS_DEAD_ARG(1)) {
1906             temp_dead(s, args[1]);
1907         }
1908         temp_dead(s, args[0]);
1909     } else if (ts->val_type == TEMP_VAL_CONST) {
1910         /* propagate constant */
1911         if (ots->val_type == TEMP_VAL_REG) {
1912             s->reg_to_temp[ots->reg] = -1;
1913         }
1914         ots->val_type = TEMP_VAL_CONST;
1915         ots->val = ts->val;
1916         if (IS_DEAD_ARG(1)) {
1917             temp_dead(s, args[1]);
1918         }
1919     } else {
1920         /* The code in the first if block should have moved the
1921            temp to a register. */
1922         assert(ts->val_type == TEMP_VAL_REG);
1923         if (IS_DEAD_ARG(1) && !ts->fixed_reg && !ots->fixed_reg) {
1924             /* the mov can be suppressed */
1925             if (ots->val_type == TEMP_VAL_REG) {
1926                 s->reg_to_temp[ots->reg] = -1;
1927             }
1928             ots->reg = ts->reg;
1929             temp_dead(s, args[1]);
1930         } else {
1931             if (ots->val_type != TEMP_VAL_REG) {
1932                 /* When allocating a new register, make sure to not spill the
1933                    input one. */
1934                 tcg_regset_set_reg(allocated_regs, ts->reg);
1935                 ots->reg = tcg_reg_alloc(s, tcg_target_available_regs[otype],
1936                                          allocated_regs);
1937             }
1938             tcg_out_mov(s, otype, ots->reg, ts->reg);
1939         }
1940         ots->val_type = TEMP_VAL_REG;
1941         ots->mem_coherent = 0;
1942         s->reg_to_temp[ots->reg] = args[0];
1943         if (NEED_SYNC_ARG(0)) {
1944             tcg_reg_sync(s, ots->reg);
1945         }
1946     }
1947 }
1948
1949 static void tcg_reg_alloc_op(TCGContext *s, 
1950                              const TCGOpDef *def, TCGOpcode opc,
1951                              const TCGArg *args, uint16_t dead_args,
1952                              uint8_t sync_args)
1953 {
1954     TCGRegSet allocated_regs;
1955     int i, k, nb_iargs, nb_oargs;
1956     TCGReg reg;
1957     TCGArg arg;
1958     const TCGArgConstraint *arg_ct;
1959     TCGTemp *ts;
1960     TCGArg new_args[TCG_MAX_OP_ARGS];
1961     int const_args[TCG_MAX_OP_ARGS];
1962
1963     nb_oargs = def->nb_oargs;
1964     nb_iargs = def->nb_iargs;
1965
1966     /* copy constants */
1967     memcpy(new_args + nb_oargs + nb_iargs, 
1968            args + nb_oargs + nb_iargs, 
1969            sizeof(TCGArg) * def->nb_cargs);
1970
1971     /* satisfy input constraints */ 
1972     tcg_regset_set(allocated_regs, s->reserved_regs);
1973     for(k = 0; k < nb_iargs; k++) {
1974         i = def->sorted_args[nb_oargs + k];
1975         arg = args[i];
1976         arg_ct = &def->args_ct[i];
1977         ts = &s->temps[arg];
1978         if (ts->val_type == TEMP_VAL_MEM) {
1979             reg = tcg_reg_alloc(s, arg_ct->u.regs, allocated_regs);
1980             tcg_out_ld(s, ts->type, reg, ts->mem_base->reg, ts->mem_offset);
1981             ts->val_type = TEMP_VAL_REG;
1982             ts->reg = reg;
1983             ts->mem_coherent = 1;
1984             s->reg_to_temp[reg] = arg;
1985         } else if (ts->val_type == TEMP_VAL_CONST) {
1986             if (tcg_target_const_match(ts->val, ts->type, arg_ct)) {
1987                 /* constant is OK for instruction */
1988                 const_args[i] = 1;
1989                 new_args[i] = ts->val;
1990                 goto iarg_end;
1991             } else {
1992                 /* need to move to a register */
1993                 reg = tcg_reg_alloc(s, arg_ct->u.regs, allocated_regs);
1994                 tcg_out_movi(s, ts->type, reg, ts->val);
1995                 ts->val_type = TEMP_VAL_REG;
1996                 ts->reg = reg;
1997                 ts->mem_coherent = 0;
1998                 s->reg_to_temp[reg] = arg;
1999             }
2000         }
2001         assert(ts->val_type == TEMP_VAL_REG);
2002         if (arg_ct->ct & TCG_CT_IALIAS) {
2003             if (ts->fixed_reg) {
2004                 /* if fixed register, we must allocate a new register
2005                    if the alias is not the same register */
2006                 if (arg != args[arg_ct->alias_index])
2007                     goto allocate_in_reg;
2008             } else {
2009                 /* if the input is aliased to an output and if it is
2010                    not dead after the instruction, we must allocate
2011                    a new register and move it */
2012                 if (!IS_DEAD_ARG(i)) {
2013                     goto allocate_in_reg;
2014                 }
2015                 /* check if the current register has already been allocated
2016                    for another input aliased to an output */
2017                 int k2, i2;
2018                 for (k2 = 0 ; k2 < k ; k2++) {
2019                     i2 = def->sorted_args[nb_oargs + k2];
2020                     if ((def->args_ct[i2].ct & TCG_CT_IALIAS) &&
2021                         (new_args[i2] == ts->reg)) {
2022                         goto allocate_in_reg;
2023                     }
2024                 }
2025             }
2026         }
2027         reg = ts->reg;
2028         if (tcg_regset_test_reg(arg_ct->u.regs, reg)) {
2029             /* nothing to do : the constraint is satisfied */
2030         } else {
2031         allocate_in_reg:
2032             /* allocate a new register matching the constraint 
2033                and move the temporary register into it */
2034             reg = tcg_reg_alloc(s, arg_ct->u.regs, allocated_regs);
2035             tcg_out_mov(s, ts->type, reg, ts->reg);
2036         }
2037         new_args[i] = reg;
2038         const_args[i] = 0;
2039         tcg_regset_set_reg(allocated_regs, reg);
2040     iarg_end: ;
2041     }
2042     
2043     /* mark dead temporaries and free the associated registers */
2044     for (i = nb_oargs; i < nb_oargs + nb_iargs; i++) {
2045         if (IS_DEAD_ARG(i)) {
2046             temp_dead(s, args[i]);
2047         }
2048     }
2049
2050     if (def->flags & TCG_OPF_BB_END) {
2051         tcg_reg_alloc_bb_end(s, allocated_regs);
2052     } else {
2053         if (def->flags & TCG_OPF_CALL_CLOBBER) {
2054             /* XXX: permit generic clobber register list ? */ 
2055             for (i = 0; i < TCG_TARGET_NB_REGS; i++) {
2056                 if (tcg_regset_test_reg(tcg_target_call_clobber_regs, i)) {
2057                     tcg_reg_free(s, i);
2058                 }
2059             }
2060         }
2061         if (def->flags & TCG_OPF_SIDE_EFFECTS) {
2062             /* sync globals if the op has side effects and might trigger
2063                an exception. */
2064             sync_globals(s, allocated_regs);
2065         }
2066         
2067         /* satisfy the output constraints */
2068         tcg_regset_set(allocated_regs, s->reserved_regs);
2069         for(k = 0; k < nb_oargs; k++) {
2070             i = def->sorted_args[k];
2071             arg = args[i];
2072             arg_ct = &def->args_ct[i];
2073             ts = &s->temps[arg];
2074             if (arg_ct->ct & TCG_CT_ALIAS) {
2075                 reg = new_args[arg_ct->alias_index];
2076             } else {
2077                 /* if fixed register, we try to use it */
2078                 reg = ts->reg;
2079                 if (ts->fixed_reg &&
2080                     tcg_regset_test_reg(arg_ct->u.regs, reg)) {
2081                     goto oarg_end;
2082                 }
2083                 reg = tcg_reg_alloc(s, arg_ct->u.regs, allocated_regs);
2084             }
2085             tcg_regset_set_reg(allocated_regs, reg);
2086             /* if a fixed register is used, then a move will be done afterwards */
2087             if (!ts->fixed_reg) {
2088                 if (ts->val_type == TEMP_VAL_REG) {
2089                     s->reg_to_temp[ts->reg] = -1;
2090                 }
2091                 ts->val_type = TEMP_VAL_REG;
2092                 ts->reg = reg;
2093                 /* temp value is modified, so the value kept in memory is
2094                    potentially not the same */
2095                 ts->mem_coherent = 0;
2096                 s->reg_to_temp[reg] = arg;
2097             }
2098         oarg_end:
2099             new_args[i] = reg;
2100         }
2101     }
2102
2103     /* emit instruction */
2104     tcg_out_op(s, opc, new_args, const_args);
2105     
2106     /* move the outputs in the correct register if needed */
2107     for(i = 0; i < nb_oargs; i++) {
2108         ts = &s->temps[args[i]];
2109         reg = new_args[i];
2110         if (ts->fixed_reg && ts->reg != reg) {
2111             tcg_out_mov(s, ts->type, ts->reg, reg);
2112         }
2113         if (NEED_SYNC_ARG(i)) {
2114             tcg_reg_sync(s, reg);
2115         }
2116         if (IS_DEAD_ARG(i)) {
2117             temp_dead(s, args[i]);
2118         }
2119     }
2120 }
2121
2122 #ifdef TCG_TARGET_STACK_GROWSUP
2123 #define STACK_DIR(x) (-(x))
2124 #else
2125 #define STACK_DIR(x) (x)
2126 #endif
2127
2128 static void tcg_reg_alloc_call(TCGContext *s, int nb_oargs, int nb_iargs,
2129                                const TCGArg * const args, uint16_t dead_args,
2130                                uint8_t sync_args)
2131 {
2132     int flags, nb_regs, i;
2133     TCGReg reg;
2134     TCGArg arg;
2135     TCGTemp *ts;
2136     intptr_t stack_offset;
2137     size_t call_stack_size;
2138     tcg_insn_unit *func_addr;
2139     int allocate_args;
2140     TCGRegSet allocated_regs;
2141
2142     func_addr = (tcg_insn_unit *)(intptr_t)args[nb_oargs + nb_iargs];
2143     flags = args[nb_oargs + nb_iargs + 1];
2144
2145     nb_regs = ARRAY_SIZE(tcg_target_call_iarg_regs);
2146     if (nb_regs > nb_iargs) {
2147         nb_regs = nb_iargs;
2148     }
2149
2150     /* assign stack slots first */
2151     call_stack_size = (nb_iargs - nb_regs) * sizeof(tcg_target_long);
2152     call_stack_size = (call_stack_size + TCG_TARGET_STACK_ALIGN - 1) & 
2153         ~(TCG_TARGET_STACK_ALIGN - 1);
2154     allocate_args = (call_stack_size > TCG_STATIC_CALL_ARGS_SIZE);
2155     if (allocate_args) {
2156         /* XXX: if more than TCG_STATIC_CALL_ARGS_SIZE is needed,
2157            preallocate call stack */
2158         tcg_abort();
2159     }
2160
2161     stack_offset = TCG_TARGET_CALL_STACK_OFFSET;
2162     for(i = nb_regs; i < nb_iargs; i++) {
2163         arg = args[nb_oargs + i];
2164 #ifdef TCG_TARGET_STACK_GROWSUP
2165         stack_offset -= sizeof(tcg_target_long);
2166 #endif
2167         if (arg != TCG_CALL_DUMMY_ARG) {
2168             ts = &s->temps[arg];
2169             if (ts->val_type == TEMP_VAL_REG) {
2170                 tcg_out_st(s, ts->type, ts->reg, TCG_REG_CALL_STACK, stack_offset);
2171             } else if (ts->val_type == TEMP_VAL_MEM) {
2172                 reg = tcg_reg_alloc(s, tcg_target_available_regs[ts->type], 
2173                                     s->reserved_regs);
2174                 /* XXX: not correct if reading values from the stack */
2175                 tcg_out_ld(s, ts->type, reg, ts->mem_base->reg, ts->mem_offset);
2176                 tcg_out_st(s, ts->type, reg, TCG_REG_CALL_STACK, stack_offset);
2177             } else if (ts->val_type == TEMP_VAL_CONST) {
2178                 reg = tcg_reg_alloc(s, tcg_target_available_regs[ts->type], 
2179                                     s->reserved_regs);
2180                 /* XXX: sign extend may be needed on some targets */
2181                 tcg_out_movi(s, ts->type, reg, ts->val);
2182                 tcg_out_st(s, ts->type, reg, TCG_REG_CALL_STACK, stack_offset);
2183             } else {
2184                 tcg_abort();
2185             }
2186         }
2187 #ifndef TCG_TARGET_STACK_GROWSUP
2188         stack_offset += sizeof(tcg_target_long);
2189 #endif
2190     }
2191     
2192     /* assign input registers */
2193     tcg_regset_set(allocated_regs, s->reserved_regs);
2194     for(i = 0; i < nb_regs; i++) {
2195         arg = args[nb_oargs + i];
2196         if (arg != TCG_CALL_DUMMY_ARG) {
2197             ts = &s->temps[arg];
2198             reg = tcg_target_call_iarg_regs[i];
2199             tcg_reg_free(s, reg);
2200             if (ts->val_type == TEMP_VAL_REG) {
2201                 if (ts->reg != reg) {
2202                     tcg_out_mov(s, ts->type, reg, ts->reg);
2203                 }
2204             } else if (ts->val_type == TEMP_VAL_MEM) {
2205                 tcg_out_ld(s, ts->type, reg, ts->mem_base->reg, ts->mem_offset);
2206             } else if (ts->val_type == TEMP_VAL_CONST) {
2207                 /* XXX: sign extend ? */
2208                 tcg_out_movi(s, ts->type, reg, ts->val);
2209             } else {
2210                 tcg_abort();
2211             }
2212             tcg_regset_set_reg(allocated_regs, reg);
2213         }
2214     }
2215     
2216     /* mark dead temporaries and free the associated registers */
2217     for(i = nb_oargs; i < nb_iargs + nb_oargs; i++) {
2218         if (IS_DEAD_ARG(i)) {
2219             temp_dead(s, args[i]);
2220         }
2221     }
2222     
2223     /* clobber call registers */
2224     for (i = 0; i < TCG_TARGET_NB_REGS; i++) {
2225         if (tcg_regset_test_reg(tcg_target_call_clobber_regs, i)) {
2226             tcg_reg_free(s, i);
2227         }
2228     }
2229
2230     /* Save globals if they might be written by the helper, sync them if
2231        they might be read. */
2232     if (flags & TCG_CALL_NO_READ_GLOBALS) {
2233         /* Nothing to do */
2234     } else if (flags & TCG_CALL_NO_WRITE_GLOBALS) {
2235         sync_globals(s, allocated_regs);
2236     } else {
2237         save_globals(s, allocated_regs);
2238     }
2239
2240     tcg_out_call(s, func_addr);
2241
2242     /* assign output registers and emit moves if needed */
2243     for(i = 0; i < nb_oargs; i++) {
2244         arg = args[i];
2245         ts = &s->temps[arg];
2246         reg = tcg_target_call_oarg_regs[i];
2247         assert(s->reg_to_temp[reg] == -1);
2248
2249         if (ts->fixed_reg) {
2250             if (ts->reg != reg) {
2251                 tcg_out_mov(s, ts->type, ts->reg, reg);
2252             }
2253         } else {
2254             if (ts->val_type == TEMP_VAL_REG) {
2255                 s->reg_to_temp[ts->reg] = -1;
2256             }
2257             ts->val_type = TEMP_VAL_REG;
2258             ts->reg = reg;
2259             ts->mem_coherent = 0;
2260             s->reg_to_temp[reg] = arg;
2261             if (NEED_SYNC_ARG(i)) {
2262                 tcg_reg_sync(s, reg);
2263             }
2264             if (IS_DEAD_ARG(i)) {
2265                 temp_dead(s, args[i]);
2266             }
2267         }
2268     }
2269 }
2270
2271 #ifdef CONFIG_PROFILER
2272
2273 static int64_t tcg_table_op_count[NB_OPS];
2274
2275 void tcg_dump_op_count(FILE *f, fprintf_function cpu_fprintf)
2276 {
2277     int i;
2278
2279     for (i = 0; i < NB_OPS; i++) {
2280         cpu_fprintf(f, "%s %" PRId64 "\n", tcg_op_defs[i].name,
2281                     tcg_table_op_count[i]);
2282     }
2283 }
2284 #else
2285 void tcg_dump_op_count(FILE *f, fprintf_function cpu_fprintf)
2286 {
2287     cpu_fprintf(f, "[TCG profiler not compiled]\n");
2288 }
2289 #endif
2290
2291
2292 int tcg_gen_code(TCGContext *s, tcg_insn_unit *gen_code_buf)
2293 {
2294     int i, oi, oi_next, num_insns;
2295
2296 #ifdef CONFIG_PROFILER
2297     {
2298         int n;
2299
2300         n = s->gen_last_op_idx + 1;
2301         s->op_count += n;
2302         if (n > s->op_count_max) {
2303             s->op_count_max = n;
2304         }
2305
2306         n = s->nb_temps;
2307         s->temp_count += n;
2308         if (n > s->temp_count_max) {
2309             s->temp_count_max = n;
2310         }
2311     }
2312 #endif
2313
2314 #ifdef DEBUG_DISAS
2315     if (unlikely(qemu_loglevel_mask(CPU_LOG_TB_OP))) {
2316         qemu_log("OP:\n");
2317         tcg_dump_ops(s);
2318         qemu_log("\n");
2319     }
2320 #endif
2321
2322 #ifdef CONFIG_PROFILER
2323     s->opt_time -= profile_getclock();
2324 #endif
2325
2326 #ifdef USE_TCG_OPTIMIZATIONS
2327     tcg_optimize(s);
2328 #endif
2329
2330 #ifdef CONFIG_PROFILER
2331     s->opt_time += profile_getclock();
2332     s->la_time -= profile_getclock();
2333 #endif
2334
2335     tcg_liveness_analysis(s);
2336
2337 #ifdef CONFIG_PROFILER
2338     s->la_time += profile_getclock();
2339 #endif
2340
2341 #ifdef DEBUG_DISAS
2342     if (unlikely(qemu_loglevel_mask(CPU_LOG_TB_OP_OPT))) {
2343         qemu_log("OP after optimization and liveness analysis:\n");
2344         tcg_dump_ops(s);
2345         qemu_log("\n");
2346     }
2347 #endif
2348
2349     tcg_reg_alloc_start(s);
2350
2351     s->code_buf = gen_code_buf;
2352     s->code_ptr = gen_code_buf;
2353
2354     tcg_out_tb_init(s);
2355
2356     num_insns = -1;
2357     for (oi = s->gen_first_op_idx; oi >= 0; oi = oi_next) {
2358         TCGOp * const op = &s->gen_op_buf[oi];
2359         TCGArg * const args = &s->gen_opparam_buf[op->args];
2360         TCGOpcode opc = op->opc;
2361         const TCGOpDef *def = &tcg_op_defs[opc];
2362         uint16_t dead_args = s->op_dead_args[oi];
2363         uint8_t sync_args = s->op_sync_args[oi];
2364
2365         oi_next = op->next;
2366 #ifdef CONFIG_PROFILER
2367         tcg_table_op_count[opc]++;
2368 #endif
2369
2370         switch (opc) {
2371         case INDEX_op_mov_i32:
2372         case INDEX_op_mov_i64:
2373             tcg_reg_alloc_mov(s, def, args, dead_args, sync_args);
2374             break;
2375         case INDEX_op_movi_i32:
2376         case INDEX_op_movi_i64:
2377             tcg_reg_alloc_movi(s, args, dead_args, sync_args);
2378             break;
2379         case INDEX_op_insn_start:
2380             if (num_insns >= 0) {
2381                 s->gen_insn_end_off[num_insns] = tcg_current_code_size(s);
2382             }
2383             num_insns++;
2384             for (i = 0; i < TARGET_INSN_START_WORDS; ++i) {
2385                 target_ulong a;
2386 #if TARGET_LONG_BITS > TCG_TARGET_REG_BITS
2387                 a = ((target_ulong)args[i * 2 + 1] << 32) | args[i * 2];
2388 #else
2389                 a = args[i];
2390 #endif
2391                 s->gen_insn_data[num_insns][i] = a;
2392             }
2393             break;
2394         case INDEX_op_discard:
2395             temp_dead(s, args[0]);
2396             break;
2397         case INDEX_op_set_label:
2398             tcg_reg_alloc_bb_end(s, s->reserved_regs);
2399             tcg_out_label(s, arg_label(args[0]), s->code_ptr);
2400             break;
2401         case INDEX_op_call:
2402             tcg_reg_alloc_call(s, op->callo, op->calli, args,
2403                                dead_args, sync_args);
2404             break;
2405         default:
2406             /* Sanity check that we've not introduced any unhandled opcodes. */
2407             if (def->flags & TCG_OPF_NOT_PRESENT) {
2408                 tcg_abort();
2409             }
2410             /* Note: in order to speed up the code, it would be much
2411                faster to have specialized register allocator functions for
2412                some common argument patterns */
2413             tcg_reg_alloc_op(s, def, opc, args, dead_args, sync_args);
2414             break;
2415         }
2416 #ifndef NDEBUG
2417         check_regs(s);
2418 #endif
2419         /* Test for (pending) buffer overflow.  The assumption is that any
2420            one operation beginning below the high water mark cannot overrun
2421            the buffer completely.  Thus we can test for overflow after
2422            generating code without having to check during generation.  */
2423         if (unlikely((void *)s->code_ptr > s->code_gen_highwater)) {
2424             return -1;
2425         }
2426     }
2427     tcg_debug_assert(num_insns >= 0);
2428     s->gen_insn_end_off[num_insns] = tcg_current_code_size(s);
2429
2430     /* Generate TB finalization at the end of block */
2431     if (!tcg_out_tb_finalize(s)) {
2432         return -1;
2433     }
2434
2435     /* flush instruction cache */
2436     flush_icache_range((uintptr_t)s->code_buf, (uintptr_t)s->code_ptr);
2437
2438     return tcg_current_code_size(s);
2439 }
2440
2441 #ifdef CONFIG_PROFILER
2442 void tcg_dump_info(FILE *f, fprintf_function cpu_fprintf)
2443 {
2444     TCGContext *s = &tcg_ctx;
2445     int64_t tb_count = s->tb_count;
2446     int64_t tb_div_count = tb_count ? tb_count : 1;
2447     int64_t tot = s->interm_time + s->code_time;
2448
2449     cpu_fprintf(f, "JIT cycles          %" PRId64 " (%0.3f s at 2.4 GHz)\n",
2450                 tot, tot / 2.4e9);
2451     cpu_fprintf(f, "translated TBs      %" PRId64 " (aborted=%" PRId64 " %0.1f%%)\n", 
2452                 tb_count, s->tb_count1 - tb_count,
2453                 (double)(s->tb_count1 - s->tb_count)
2454                 / (s->tb_count1 ? s->tb_count1 : 1) * 100.0);
2455     cpu_fprintf(f, "avg ops/TB          %0.1f max=%d\n", 
2456                 (double)s->op_count / tb_div_count, s->op_count_max);
2457     cpu_fprintf(f, "deleted ops/TB      %0.2f\n",
2458                 (double)s->del_op_count / tb_div_count);
2459     cpu_fprintf(f, "avg temps/TB        %0.2f max=%d\n",
2460                 (double)s->temp_count / tb_div_count, s->temp_count_max);
2461     cpu_fprintf(f, "avg host code/TB    %0.1f\n",
2462                 (double)s->code_out_len / tb_div_count);
2463     cpu_fprintf(f, "avg search data/TB  %0.1f\n",
2464                 (double)s->search_out_len / tb_div_count);
2465     
2466     cpu_fprintf(f, "cycles/op           %0.1f\n", 
2467                 s->op_count ? (double)tot / s->op_count : 0);
2468     cpu_fprintf(f, "cycles/in byte      %0.1f\n", 
2469                 s->code_in_len ? (double)tot / s->code_in_len : 0);
2470     cpu_fprintf(f, "cycles/out byte     %0.1f\n", 
2471                 s->code_out_len ? (double)tot / s->code_out_len : 0);
2472     cpu_fprintf(f, "cycles/search byte     %0.1f\n",
2473                 s->search_out_len ? (double)tot / s->search_out_len : 0);
2474     if (tot == 0) {
2475         tot = 1;
2476     }
2477     cpu_fprintf(f, "  gen_interm time   %0.1f%%\n", 
2478                 (double)s->interm_time / tot * 100.0);
2479     cpu_fprintf(f, "  gen_code time     %0.1f%%\n", 
2480                 (double)s->code_time / tot * 100.0);
2481     cpu_fprintf(f, "optim./code time    %0.1f%%\n",
2482                 (double)s->opt_time / (s->code_time ? s->code_time : 1)
2483                 * 100.0);
2484     cpu_fprintf(f, "liveness/code time  %0.1f%%\n", 
2485                 (double)s->la_time / (s->code_time ? s->code_time : 1) * 100.0);
2486     cpu_fprintf(f, "cpu_restore count   %" PRId64 "\n",
2487                 s->restore_count);
2488     cpu_fprintf(f, "  avg cycles        %0.1f\n",
2489                 s->restore_count ? (double)s->restore_time / s->restore_count : 0);
2490 }
2491 #else
2492 void tcg_dump_info(FILE *f, fprintf_function cpu_fprintf)
2493 {
2494     cpu_fprintf(f, "[TCG profiler not compiled]\n");
2495 }
2496 #endif
2497
2498 #ifdef ELF_HOST_MACHINE
2499 /* In order to use this feature, the backend needs to do three things:
2500
2501    (1) Define ELF_HOST_MACHINE to indicate both what value to
2502        put into the ELF image and to indicate support for the feature.
2503
2504    (2) Define tcg_register_jit.  This should create a buffer containing
2505        the contents of a .debug_frame section that describes the post-
2506        prologue unwind info for the tcg machine.
2507
2508    (3) Call tcg_register_jit_int, with the constructed .debug_frame.
2509 */
2510
2511 /* Begin GDB interface.  THE FOLLOWING MUST MATCH GDB DOCS.  */
2512 typedef enum {
2513     JIT_NOACTION = 0,
2514     JIT_REGISTER_FN,
2515     JIT_UNREGISTER_FN
2516 } jit_actions_t;
2517
2518 struct jit_code_entry {
2519     struct jit_code_entry *next_entry;
2520     struct jit_code_entry *prev_entry;
2521     const void *symfile_addr;
2522     uint64_t symfile_size;
2523 };
2524
2525 struct jit_descriptor {
2526     uint32_t version;
2527     uint32_t action_flag;
2528     struct jit_code_entry *relevant_entry;
2529     struct jit_code_entry *first_entry;
2530 };
2531
2532 void __jit_debug_register_code(void) __attribute__((noinline));
2533 void __jit_debug_register_code(void)
2534 {
2535     asm("");
2536 }
2537
2538 /* Must statically initialize the version, because GDB may check
2539    the version before we can set it.  */
2540 struct jit_descriptor __jit_debug_descriptor = { 1, 0, 0, 0 };
2541
2542 /* End GDB interface.  */
2543
2544 static int find_string(const char *strtab, const char *str)
2545 {
2546     const char *p = strtab + 1;
2547
2548     while (1) {
2549         if (strcmp(p, str) == 0) {
2550             return p - strtab;
2551         }
2552         p += strlen(p) + 1;
2553     }
2554 }
2555
2556 static void tcg_register_jit_int(void *buf_ptr, size_t buf_size,
2557                                  const void *debug_frame,
2558                                  size_t debug_frame_size)
2559 {
2560     struct __attribute__((packed)) DebugInfo {
2561         uint32_t  len;
2562         uint16_t  version;
2563         uint32_t  abbrev;
2564         uint8_t   ptr_size;
2565         uint8_t   cu_die;
2566         uint16_t  cu_lang;
2567         uintptr_t cu_low_pc;
2568         uintptr_t cu_high_pc;
2569         uint8_t   fn_die;
2570         char      fn_name[16];
2571         uintptr_t fn_low_pc;
2572         uintptr_t fn_high_pc;
2573         uint8_t   cu_eoc;
2574     };
2575
2576     struct ElfImage {
2577         ElfW(Ehdr) ehdr;
2578         ElfW(Phdr) phdr;
2579         ElfW(Shdr) shdr[7];
2580         ElfW(Sym)  sym[2];
2581         struct DebugInfo di;
2582         uint8_t    da[24];
2583         char       str[80];
2584     };
2585
2586     struct ElfImage *img;
2587
2588     static const struct ElfImage img_template = {
2589         .ehdr = {
2590             .e_ident[EI_MAG0] = ELFMAG0,
2591             .e_ident[EI_MAG1] = ELFMAG1,
2592             .e_ident[EI_MAG2] = ELFMAG2,
2593             .e_ident[EI_MAG3] = ELFMAG3,
2594             .e_ident[EI_CLASS] = ELF_CLASS,
2595             .e_ident[EI_DATA] = ELF_DATA,
2596             .e_ident[EI_VERSION] = EV_CURRENT,
2597             .e_type = ET_EXEC,
2598             .e_machine = ELF_HOST_MACHINE,
2599             .e_version = EV_CURRENT,
2600             .e_phoff = offsetof(struct ElfImage, phdr),
2601             .e_shoff = offsetof(struct ElfImage, shdr),
2602             .e_ehsize = sizeof(ElfW(Shdr)),
2603             .e_phentsize = sizeof(ElfW(Phdr)),
2604             .e_phnum = 1,
2605             .e_shentsize = sizeof(ElfW(Shdr)),
2606             .e_shnum = ARRAY_SIZE(img->shdr),
2607             .e_shstrndx = ARRAY_SIZE(img->shdr) - 1,
2608 #ifdef ELF_HOST_FLAGS
2609             .e_flags = ELF_HOST_FLAGS,
2610 #endif
2611 #ifdef ELF_OSABI
2612             .e_ident[EI_OSABI] = ELF_OSABI,
2613 #endif
2614         },
2615         .phdr = {
2616             .p_type = PT_LOAD,
2617             .p_flags = PF_X,
2618         },
2619         .shdr = {
2620             [0] = { .sh_type = SHT_NULL },
2621             /* Trick: The contents of code_gen_buffer are not present in
2622                this fake ELF file; that got allocated elsewhere.  Therefore
2623                we mark .text as SHT_NOBITS (similar to .bss) so that readers
2624                will not look for contents.  We can record any address.  */
2625             [1] = { /* .text */
2626                 .sh_type = SHT_NOBITS,
2627                 .sh_flags = SHF_EXECINSTR | SHF_ALLOC,
2628             },
2629             [2] = { /* .debug_info */
2630                 .sh_type = SHT_PROGBITS,
2631                 .sh_offset = offsetof(struct ElfImage, di),
2632                 .sh_size = sizeof(struct DebugInfo),
2633             },
2634             [3] = { /* .debug_abbrev */
2635                 .sh_type = SHT_PROGBITS,
2636                 .sh_offset = offsetof(struct ElfImage, da),
2637                 .sh_size = sizeof(img->da),
2638             },
2639             [4] = { /* .debug_frame */
2640                 .sh_type = SHT_PROGBITS,
2641                 .sh_offset = sizeof(struct ElfImage),
2642             },
2643             [5] = { /* .symtab */
2644                 .sh_type = SHT_SYMTAB,
2645                 .sh_offset = offsetof(struct ElfImage, sym),
2646                 .sh_size = sizeof(img->sym),
2647                 .sh_info = 1,
2648                 .sh_link = ARRAY_SIZE(img->shdr) - 1,
2649                 .sh_entsize = sizeof(ElfW(Sym)),
2650             },
2651             [6] = { /* .strtab */
2652                 .sh_type = SHT_STRTAB,
2653                 .sh_offset = offsetof(struct ElfImage, str),
2654                 .sh_size = sizeof(img->str),
2655             }
2656         },
2657         .sym = {
2658             [1] = { /* code_gen_buffer */
2659                 .st_info = ELF_ST_INFO(STB_GLOBAL, STT_FUNC),
2660                 .st_shndx = 1,
2661             }
2662         },
2663         .di = {
2664             .len = sizeof(struct DebugInfo) - 4,
2665             .version = 2,
2666             .ptr_size = sizeof(void *),
2667             .cu_die = 1,
2668             .cu_lang = 0x8001,  /* DW_LANG_Mips_Assembler */
2669             .fn_die = 2,
2670             .fn_name = "code_gen_buffer"
2671         },
2672         .da = {
2673             1,          /* abbrev number (the cu) */
2674             0x11, 1,    /* DW_TAG_compile_unit, has children */
2675             0x13, 0x5,  /* DW_AT_language, DW_FORM_data2 */
2676             0x11, 0x1,  /* DW_AT_low_pc, DW_FORM_addr */
2677             0x12, 0x1,  /* DW_AT_high_pc, DW_FORM_addr */
2678             0, 0,       /* end of abbrev */
2679             2,          /* abbrev number (the fn) */
2680             0x2e, 0,    /* DW_TAG_subprogram, no children */
2681             0x3, 0x8,   /* DW_AT_name, DW_FORM_string */
2682             0x11, 0x1,  /* DW_AT_low_pc, DW_FORM_addr */
2683             0x12, 0x1,  /* DW_AT_high_pc, DW_FORM_addr */
2684             0, 0,       /* end of abbrev */
2685             0           /* no more abbrev */
2686         },
2687         .str = "\0" ".text\0" ".debug_info\0" ".debug_abbrev\0"
2688                ".debug_frame\0" ".symtab\0" ".strtab\0" "code_gen_buffer",
2689     };
2690
2691     /* We only need a single jit entry; statically allocate it.  */
2692     static struct jit_code_entry one_entry;
2693
2694     uintptr_t buf = (uintptr_t)buf_ptr;
2695     size_t img_size = sizeof(struct ElfImage) + debug_frame_size;
2696     DebugFrameHeader *dfh;
2697
2698     img = g_malloc(img_size);
2699     *img = img_template;
2700
2701     img->phdr.p_vaddr = buf;
2702     img->phdr.p_paddr = buf;
2703     img->phdr.p_memsz = buf_size;
2704
2705     img->shdr[1].sh_name = find_string(img->str, ".text");
2706     img->shdr[1].sh_addr = buf;
2707     img->shdr[1].sh_size = buf_size;
2708
2709     img->shdr[2].sh_name = find_string(img->str, ".debug_info");
2710     img->shdr[3].sh_name = find_string(img->str, ".debug_abbrev");
2711
2712     img->shdr[4].sh_name = find_string(img->str, ".debug_frame");
2713     img->shdr[4].sh_size = debug_frame_size;
2714
2715     img->shdr[5].sh_name = find_string(img->str, ".symtab");
2716     img->shdr[6].sh_name = find_string(img->str, ".strtab");
2717
2718     img->sym[1].st_name = find_string(img->str, "code_gen_buffer");
2719     img->sym[1].st_value = buf;
2720     img->sym[1].st_size = buf_size;
2721
2722     img->di.cu_low_pc = buf;
2723     img->di.cu_high_pc = buf + buf_size;
2724     img->di.fn_low_pc = buf;
2725     img->di.fn_high_pc = buf + buf_size;
2726
2727     dfh = (DebugFrameHeader *)(img + 1);
2728     memcpy(dfh, debug_frame, debug_frame_size);
2729     dfh->fde.func_start = buf;
2730     dfh->fde.func_len = buf_size;
2731
2732 #ifdef DEBUG_JIT
2733     /* Enable this block to be able to debug the ELF image file creation.
2734        One can use readelf, objdump, or other inspection utilities.  */
2735     {
2736         FILE *f = fopen("/tmp/qemu.jit", "w+b");
2737         if (f) {
2738             if (fwrite(img, img_size, 1, f) != img_size) {
2739                 /* Avoid stupid unused return value warning for fwrite.  */
2740             }
2741             fclose(f);
2742         }
2743     }
2744 #endif
2745
2746     one_entry.symfile_addr = img;
2747     one_entry.symfile_size = img_size;
2748
2749     __jit_debug_descriptor.action_flag = JIT_REGISTER_FN;
2750     __jit_debug_descriptor.relevant_entry = &one_entry;
2751     __jit_debug_descriptor.first_entry = &one_entry;
2752     __jit_debug_register_code();
2753 }
2754 #else
2755 /* No support for the feature.  Provide the entry point expected by exec.c,
2756    and implement the internal function we declared earlier.  */
2757
2758 static void tcg_register_jit_int(void *buf, size_t size,
2759                                  const void *debug_frame,
2760                                  size_t debug_frame_size)
2761 {
2762 }
2763
2764 void tcg_register_jit(void *buf, size_t buf_size)
2765 {
2766 }
2767 #endif /* ELF_HOST_MACHINE */
This page took 0.174931 seconds and 4 git commands to generate.