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