instruction optimization thoughts
Hi all,
Today I've been playing around with qemu trying to understand how the emulation works. I've tried some debug flags and looked at log files.
This is how I believe the translation between x86 opcodes and micro operations is performed today, please correct me if I am wrong:
gen_intermediate_code_internal() in target-i386/translate.c is used to build intermediate code. The function disas_insn() is used to convert each opcode into several micro operations. When the block is finished, the function optimize_flags() is used to optimize away some flag related micro operations.
After looking at some log files I wonder if it would be possible to reduce the number of micro operations (especially the ones involved in flag handling) by analyzing resources used and set by each x86 instruction and then feed that information into the code that converts x86 opcodes into micro operations.
Have a look at the following example:
----------------
IN:
0x300a8b99: pop ebx 0x300a8b9a: add ebx 0x300a8ba0: mov DWORD PTR [ebp-684],eax 0x300a8ba6: xor edx,edx 0x300a8ba8: lea eax,[ebp-528] 0x300a8bae: mov esi,esi 0x300a8bb0: inc edx 0x300a8bb1: mov DWORD PTR [eax] 0x300a8bb7: add eax 0x300a8bba: cmp edx 0x300a8bbd: jbe 0x300a8bb0
If we analyze the x86 instructions and keep track of resources first, instead of generating the micro operations directly, we would come up with a table containing resource information related to each x86 instruction. This table contains data about required resources and resources that will be set by each instruction.
The table could also quite easily be extended to contain flags that mark if resources are constant or not which leads to further optimization possibilities later.
instruction | resources required | resources set
pop ebx | ESP | EBX add ebx,0x11927 | EBX | EBX OF SF ZF AF PF CF mov ..ebp-684],eax | EBP EAX | IO xor edx,edx | EDX | EDX OF SF ZF AF PF CF lea eax,[ebp-528] | EBP | EAX mov esi,esi | ESI | ESI
inc edx | EDX | EDX OF SF ZF AF PF mov ..[eax], 0 | EAX | IO add eax, 4 | EAX | EAX OF SF ZF AF PF CF cmp edx, 0x4a | EDX | OF SF ZF AF PF CF jbe .. | EIP CF ZF | EIP
Then we perform a optimization step. This step removes resources marked as set that are redundant. Maybe the code for this step could be shared by many target processors, think of it as some kind of generic resource optimizer.
After optimization:
instruction | resources required | resources set
pop ebx | ESP | EBX add ebx,0x11927 | EBX | EBX mov ..ebp-684],eax | EBP EAX | IO xor edx,edx | EDX | EDX lea eax,[ebp-528] | EBP | EAX mov esi,esi | ESI | ESI
inc edx | EDX | EDX mov ..[eax], 0 | EAX | IO add eax, 4 | EAX | EAX cmp edx, 0x4a | EDX | OF SF ZF AF PF CF jbe .. | EIP CF ZF | EIP
Several flag-related resources have been removed above. No other registers have been removed, but that would also be possible. The information left in the table is fed into the code that translates the x86 opcodes into micro operations and it is up to that code to generate as few micro operations as possible.
I guess what I am trying to say is that it would be cool to add a generic optimization step before the opcode to micro operations translation. But would it be useful? Or just slow?
Any thoughts? Maybe the flag handling code is fast enough today?
/ magnus
I have been thinking along these lines and believe that it could be taken even further. Let's assume that your pre-translation table optimizer could be made to work. As a second step after eliminating redundancy and removing effective NOPs, entries in the intermediate instruction stream could be considered keys into a database of translations. Depending on the amount of memory we want to spend, these keys could be small or even quite large - I imagine that we could go through a process of using something along the lines of a genetic algorithm to build highly optimized translation blocks for the most commonly occurring streams of instructions. The rudimentary building blocks that the genetic algorithm would work with would be all the various translations that a particular instruction stream could result in (e.g. different ordering of order independent instructions, etc..). The tables would, of course, be built off-line (a datafile could be placed in CVS, allowing us to contribute a large amount of upfront compute time to build highly optimized tables for a variety of different platforms).
Thinking along these lines is important. This project not only presents a fantastic emulator, but the "possibility" of eventually reaching par or better performance (if we are smart about it).
-Daniel
Quoted 105 lines · Magnus Damm
Hi all,
Today I've been playing around with qemu trying to understand how the emulation works. I've tried some debug flags and looked at log files.
This is how I believe the translation between x86 opcodes and micro operations is performed today, please correct me if I am wrong:
gen_intermediate_code_internal()intarget-i386/translate.cis used to build intermediate code. The functiondisas_insn()is used to convert each opcode into several micro operations. When the block is finished, the functionoptimize_flags()is used to optimize away some flag related micro operations.After looking at some log files I wonder if it would be possible to reduce the number of micro operations (especially the ones involved in flag handling) by analyzing resources used and set by each x86 instruction and then feed that information into the code that converts x86 opcodes into micro operations.
Have a look at the following example:
----------------
IN:0x300a8b99: pop ebx 0x300a8b9a: add ebx 0x300a8ba0: mov DWORD PTR [ebp-684],eax 0x300a8ba6: xor edx,edx 0x300a8ba8: lea eax,[ebp-528] 0x300a8bae: mov esi,esi 0x300a8bb0: inc edx 0x300a8bb1: mov DWORD PTR [eax] 0x300a8bb7: add eax 0x300a8bba: cmp edx 0x300a8bbd: jbe 0x300a8bb0If we analyze the x86 instructions and keep track of resources first, instead of generating the micro operations directly, we would come up with a table containing resource information related to each x86 instruction. This table contains data about required resources and resources that will be set by each instruction.
The table could also quite easily be extended to contain flags that mark if resources are constant or not which leads to further optimization possibilities later.
instruction | resources required | resources set
pop ebx | ESP | EBX add ebx,0x11927 | EBX | EBX OF SF ZF AF PF CF mov ..ebp-684],eax | EBP EAX | IO xor edx,edx | EDX | EDX OF SF ZF AF PF CF lea eax,[ebp-528] | EBP | EAX mov esi,esi | ESI | ESIinc edx | EDX | EDX OF SF ZF AF PF mov ..[eax], 0 | EAX | IO add eax, 4 | EAX | EAX OF SF ZF AF PF CF cmp edx, 0x4a | EDX | OF SF ZF AF PF CF jbe .. | EIP CF ZF | EIPThen we perform a optimization step. This step removes resources marked as set that are redundant. Maybe the code for this step could be shared by many target processors, think of it as some kind of generic resource optimizer.
After optimization:
instruction | resources required | resources set
pop ebx | ESP | EBX add ebx,0x11927 | EBX | EBX mov ..ebp-684],eax | EBP EAX | IO xor edx,edx | EDX | EDX lea eax,[ebp-528] | EBP | EAX mov esi,esi | ESI | ESIinc edx | EDX | EDX mov ..[eax], 0 | EAX | IO add eax, 4 | EAX | EAX cmp edx, 0x4a | EDX | OF SF ZF AF PF CF jbe .. | EIP CF ZF | EIPSeveral flag-related resources have been removed above. No other registers have been removed, but that would also be possible. The information left in the table is fed into the code that translates the x86 opcodes into micro operations and it is up to that code to generate as few micro operations as possible.
I guess what I am trying to say is that it would be cool to add a generic optimization step before the opcode to micro operations translation. But would it be useful? Or just slow?
Any thoughts? Maybe the flag handling code is fast enough today?
/ magnus
_______________________________________________
Qemu-devel mailing list
[email protected]
http://lists.nongnu.org/mailman/listinfo/qemu-devel
I don't think the database solution would work. First of all the
database would have to be very big in order to be effective. That means that in order to lookup the streams of instructions in the database you would thrash the cache (lots and lots of memory reads to various places).
The Magnus's idea is very interesting because it looks like a very
simple peephole optimizer. That is why it would be effective for blocks that get executed more than once. For a little more work qemu would have more efficient code to execute.
Nevertheless i don't now how much of Magnus idea qemu implements right
now. Maybe "Condition code optimisations" + "CPU state optimisations" from ' http://fabrice.bellard.free.fr/qemu/qemu-tech.html ' come very close to what Magnus suggests.
Fabrice or anyone else with qemu internals knowledge would be more
qualified to answer.
teris.
ps All these code optimizing ideas pale in effectiveness with what a mmu optimization work would produce. There is a reason why there is a qemu-fast and a qemu-soft. If somehow these too could be consolidated then the performance gain would be considerable.... I think.
Quoted 120 lines · [email protected] wrote:
I have been thinking along these lines and believe that it could be taken even further. Let's assume that your pre-translation table optimizer could be made to work. As a second step after eliminating redundancy and removing effective NOPs, entries in the intermediate instruction stream could be considered keys into a database of translations. Depending on the amount of memory we want to spend, these keys could be small or even quite large - I imagine that we could go through a process of using something along the lines of a genetic algorithm to build highly optimized translation blocks for the most commonly occurring streams of instructions. The rudimentary building blocks that the genetic algorithm would work with would be all the various translations that a particular instruction stream could result in (e.g. different ordering of order independent instructions, etc..). The tables would, of course, be built off-line (a datafile could be placed in CVS, allowing us to contribute a large amount of upfront compute time to build highly optimized tables for a variety of different platforms).
Thinking along these lines is important. This project not only presents a fantastic emulator, but the "possibility" of eventually reaching par or better performance (if we are smart about it).
-Daniel
Quoted 100 lines · Magnus Damm
Hi all,
Today I've been playing around with qemu trying to understand how the emulation works. I've tried some debug flags and looked at log files.
This is how I believe the translation between x86 opcodes and micro operations is performed today, please correct me if I am wrong:
gen_intermediate_code_internal()intarget-i386/translate.cis used to build intermediate code. The functiondisas_insn()is used to convert each opcode into several micro operations. When the block is finished, the functionoptimize_flags()is used to optimize away some flag related micro operations.After looking at some log files I wonder if it would be possible to reduce the number of micro operations (especially the ones involved in flag handling) by analyzing resources used and set by each x86 instruction and then feed that information into the code that converts x86 opcodes into micro operations.
Have a look at the following example:
----------------
IN:0x300a8b99: pop ebx 0x300a8b9a: add ebx 0x300a8ba0: mov DWORD PTR [ebp-684],eax 0x300a8ba6: xor edx,edx 0x300a8ba8: lea eax,[ebp-528] 0x300a8bae: mov esi,esi 0x300a8bb0: inc edx 0x300a8bb1: mov DWORD PTR [eax] 0x300a8bb7: add eax 0x300a8bba: cmp edx 0x300a8bbd: jbe 0x300a8bb0If we analyze the x86 instructions and keep track of resources first, instead of generating the micro operations directly, we would come up with a table containing resource information related to each x86 instruction. This table contains data about required resources and resources that will be set by each instruction.
The table could also quite easily be extended to contain flags that mark if resources are constant or not which leads to further optimization possibilities later.
instruction | resources required | resources set
pop ebx | ESP | EBX add ebx,0x11927 | EBX | EBX OF SF ZF AF PF CF mov ..ebp-684],eax | EBP EAX | IO xor edx,edx | EDX | EDX OF SF ZF AF PF CF lea eax,[ebp-528] | EBP | EAX mov esi,esi | ESI | ESIinc edx | EDX | EDX OF SF ZF AF PF mov ..[eax], 0 | EAX | IO add eax, 4 | EAX | EAX OF SF ZF AF PF CF cmp edx, 0x4a | EDX | OF SF ZF AF PF CF jbe .. | EIP CF ZF | EIPThen we perform a optimization step. This step removes resources marked as set that are redundant. Maybe the code for this step could be shared by many target processors, think of it as some kind of generic resource optimizer.
After optimization:
instruction | resources required | resources set
pop ebx | ESP | EBX add ebx,0x11927 | EBX | EBX mov ..ebp-684],eax | EBP EAX | IO xor edx,edx | EDX | EDX lea eax,[ebp-528] | EBP | EAX mov esi,esi | ESI | ESIinc edx | EDX | EDX mov ..[eax], 0 | EAX | IO add eax, 4 | EAX | EAX cmp edx, 0x4a | EDX | OF SF ZF AF PF CF jbe .. | EIP CF ZF | EIPSeveral flag-related resources have been removed above. No other registers have been removed, but that would also be possible. The information left in the table is fed into the code that translates the x86 opcodes into micro operations and it is up to that code to generate as few micro operations as possible.
I guess what I am trying to say is that it would be cool to add a generic optimization step before the opcode to micro operations translation. But would it be useful? Or just slow?
Any thoughts? Maybe the flag handling code is fast enough today?
/ magnus
Quoted 5 lines
_______________________________________________
Qemu-devel mailing list
[email protected]
http://lists.nongnu.org/mailman/listinfo/qemu-devel_______________________________________________
Qemu-devel mailing list
[email protected]
http://lists.nongnu.org/mailman/listinfo/qemu-devel
--- Elefterios Stamatogiannakis
Quoted 6 lines · <[email protected]> wrote:
I don't think the database solution would work.
First of all the database would have to be very big in order to be effective. That means that in order to lookup the streams of instructions in the database you would thrash the cache (lots and lots of memory reads to various places).
Hi!
The database lookup can be very fast -- use good hash function and memory mapped file. For best performance used code fragments should be located in sequence (single page fault and disk read would bring a few useful code fragments to RAM). For this reason the database should be optimized for specific programs executed by particular user.
But once you have a nice optimizer for building the database why not integrate it in Qemu to optimize most frequently executed blocks (HotSpot)? Once we find the optimization to be CPU-expensive, we could add small persistent database.
[...]
Quoted 9 lines
teris.
ps All these code optimizing ideas pale in effectiveness with what a mmu optimization work would produce. There is a reason why there is a qemu-fast and a qemu-soft. If somehow these too could be consolidated then the performance gain would be considerable....
I think.
The MMU optimization improves performance a lot, but most of qemu-fast speed comes from code-copy optimization (to compare, run benchmarks with qemu-fast -no-code-copy). The MMU optimization is important for code-copy as it allows running blocks that read/write memory.
For MMU optimization to work it is necessary to have as big as possible continuous region of virtual address space that is dedicated to the guest. For this reason qemu-fast uses special memory layout and it causes some problems (it requires static compilation, hacking of libc). Qemu-fast will never be as portable as softmmu is. Except, maybe, when running 32-bit guest on 64-bit host.
I did some experiments to check if optimization of softmmu, by using techniques of MMU optimization is feasible. For this I tried to remove memory layout constraint of qemu-fast by using a memory "mapping table".
In this experiments I redirect memory access of guest code via a mapping table to an area of virtual address space, where guest pages are mapped (using mmap). This area can be much smaller than guest address space, so I minimize problems of qemu-fast and improve its portability. In future this approach could help MMU optimization to enter qemu-softmmu.
As memory access is much simpler that softmmu, the benchmarks give better results (but still it's 20% slower than qemu-fast with -no-code-copy). When running real OS, Linux seems faster then under softmmu but Windows 98 -- much slower. The problem with Windows is that it "likes" to modify pages where code is executing, and this causes lots of page faults.
I'm attaching a patch, so other developers can see what I'm doing. Before using the patch, please make sure you can build working qemu-fast with your setup. To see it working run qemu-fast with -no-code-copy option.
Fabrice, does it make sense to modify code-copy to be compatible with this patch (I know it's a lot of work)?
Regards,
Piotrek
__________________________________
Do you Yahoo!?
New and Improved Yahoo! Mail - 100MB free storage!
http://promotions.yahoo.com/new_mail
cpu-all.h +171 -0
@@ -24,6 +24,17 @@#define WORDS_ALIGNED #endif +/* keep in sync with exec-all.h +*/ +#ifndef offsetof +#define offsetof (type, field) ((size_t) &((type *)0)->field) +#endif + +/* XXX: assume sizeof(long) >= sizeof(void*) +*/ +#define map_target2host (env, ptr) \ + (env->map[((unsigned long) (ptr)) >> MAP_BLOCK_BITS] + ((unsigned long) (ptr))) +/* some important defines: * * WORDS_ALIGNED : if defined, the host cpu can only make word aligned
@@ -181,6 +192,67 @@ *(uint8_t *)ptr = v; } +static inline int ldub_map (void *ptr) +{ +#if defined(__i386__) +int val; + asmvolatile ( +"mov %3, %%eax\n" +"shr %2, %%eax\n" +"mov %1(%%ebp,%%eax,4), %%eax\n" +"movzbl (%3,%%eax,1), %0\n" + :"=r" (val) + : "m" (*(uint8_t *)offsetof(CPUX86State, map[0])), +"I" (MAP_BLOCK_BITS ), +"r" (ptr) + : "%eax"); +return (val); +#else +#error unsupported target CPU +#endif +} + +static inline int ldsb_map (void *ptr) +{ +#if defined(__i386__) +int val; + asmvolatile ( +"mov %3, %%eax\n" +"shr %2, %%eax\n" +"mov %1(%%ebp,%%eax,4), %%eax\n" +"movsbl (%3,%%eax,1), %0\n" + :"=r" (val) + : "m" (*(uint8_t *)offsetof(CPUX86State, map[0])), +"I" (MAP_BLOCK_BITS ), +"r" (ptr) + : "%eax"); +return (val); +#else +#error unsupported target CPU +#endif +} + +static inline void stb_map (void *ptr,int v) +{ +#if defined(__i386__) + asmvolatile ( +"mov %2, %%eax\n" +"shr %1, %%eax\n" +"mov %0(%%ebp,%%eax,4), %%eax\n" +"movb %b3, (%2,%%eax)\n" + : + : "m" (*(uint8_t *)offsetof(CPUX86State, map[0])), +"I" (MAP_BLOCK_BITS ), +"r" (ptr), +"r" (v) + : "%eax"); +#else +#error unsupported target CPU +#endif +} + + +/* NOTE: on arm, putting 2 in /proc/sys/debug/alignment so that the kernel handles unaligned load/stores may give better results, but it is a system wide setting : bad */
@@ -467,6 +539,105 @@ *(uint64_t *)ptr = v; } +static inline int lduw_map (void *ptr) +{ +#if defined(__i386__) +int val; + asmvolatile ( +"mov %3, %%eax\n" +"shr %2, %%eax\n" +"mov %1(%%ebp,%%eax,4), %%eax\n" +"movzwl (%3,%%eax,1), %0\n" + :"=r" (val) + : "m" (*(uint8_t *)offsetof(CPUX86State, map[0])), +"I" (MAP_BLOCK_BITS ), +"r" (ptr) + : "%eax"); +return (val); +#else +#error unsupported target CPU +#endif +} + +static inline int ldsw_map (void *ptr) +{ +#if defined(__i386__) +int val; + asmvolatile ( +"mov %3, %%eax\n" +"shr %2, %%eax\n" +"mov %1(%%ebp,%%eax,4), %%eax\n" +"movswl (%3,%%eax,1), %0\n" + :"=r" (val) + : "m" (*(uint8_t *)offsetof(CPUX86State, map[0])), +"I" (MAP_BLOCK_BITS ), +"r" (ptr) + : "%eax"); +return (val); +#else +#error unsupported target CPU +#endif +} + +static inline int ldl_map (void *ptr) +{ +#if defined(__i386__) +int val; + asmvolatile ( +"mov %3, %%eax\n" +"shr %2, %%eax\n" +"mov %1(%%ebp,%%eax,4), %%eax\n" +"movl (%3,%%eax,1), %0\n" + :"=r" (val) + : "m" (*(uint8_t *)offsetof(CPUX86State, map[0])), +"I" (MAP_BLOCK_BITS ), +"r" (ptr) + : "%eax"); +return (val); +#else +#error unsupported target CPU +#endif +} + +static inline void stw_map (void *ptr,int v) +{ +#if defined(__i386__) + asmvolatile ( +"mov %2, %%eax\n" +"shr %1, %%eax\n" +"mov %0(%%ebp,%%eax,4), %%eax\n" +"movw %w3, (%2,%%eax)\n" + : + : "m" (*(uint8_t *)offsetof(CPUX86State, map[0])), +"I" (MAP_BLOCK_BITS ), +"r" (ptr), +"r" (v) + : "%eax"); +/* XXX PK: clobber memory? */ +#else +#error unsupported target CPU +#endif +} + +static inline void stl_map (void *ptr,int v) +{ +#if defined(__i386__) + asmvolatile ( +"mov %2, %%eax\n" +"shr %1, %%eax\n" +"mov %0(%%ebp,%%eax,4), %%eax\n" +"movl %3, (%2,%%eax)\n" + : + : "m" (*(uint8_t *)offsetof(CPUX86State, map[0])), +"I" (MAP_BLOCK_BITS ), +"r" (ptr), +"r" (v) + : "%eax"); +#else +#error unsupported target CPU +#endif +} +/* float access */ static inline float ldfl_raw (void *ptr)
cpu-exec.c +17 -4
@@ -814,10 +814,13 @@ {struct ucontext *uc = puc;unsigned long pc; +unsigned long addr;int trapno; +int res;#ifndef REG_EIP /* for glibc 2.1 */ +#define REG_EAX EAX#define REG_EIP EIP#define REG_ERR ERR#define REG_TRAPNO TRAPNO
@@ -831,10 +834,20 @@ return 1; } else#endif -return handle_cpu_signal (pc, (unsigned long )info->si_addr, - trapno ==0xe ? - (uc->uc_mcontext.gregs[REG_ERR ] >>1 ) &1 :0 , - &uc->uc_sigmask, puc); + { +/* EAX == env->map[addr >> MAP_BLOCK_BITS] +* see *_map functions in cpu-all.h +*/ +/* XXX: check opcode at pc to detect possible inconsistency? +*/ + addr = (unsigned long )info->si_addr - uc->uc_mcontext.gregs[REG_EAX ]; + res =handle_cpu_signal (pc, addr, + trapno ==0xe ? + (uc->uc_mcontext.gregs[REG_ERR ] >>1 ) &1 :0 , + &uc->uc_sigmask, puc); + uc->uc_mcontext.gregs[REG_EAX ] = (uint32_t )cpu_single_env->map[addr >>MAP_BLOCK_BITS ]; +return (res); + } }#elif defined(__x86_64__)
exec.c +133 -38
235 lines not on this page · raw message
target-i386/cpu.h +9 -0
@@ -20,6 +20,12 @@#ifndef CPU_I386_H #define CPU_I386_H +#define MAP_PAGE_BITS 12 +#define MAP_BLOCK_BITS 24 +#define MAP_ADDR_BITS 32 +#define MAP_PAGE_SIZE (1L << MAP_PAGE_BITS) +#define MAP_BLOCK_SIZE (1L << MAP_BLOCK_BITS) +#define TARGET_LONG_BITS 32/* target supports implicit self modifying code */
@@ -291,6 +297,9 @@int32_t df;/* D flag : 1 if D = 0, -1 if D = 1 */ uint32_t hflags;/* hidden flags, see HF_xxx constants */ +/* offset <= 127 to enable assembly optimization */ +void *map[1L << (MAP_ADDR_BITS -MAP_BLOCK_BITS )]; +/* FPU state */ unsigned int fpstt;/* top of stack index */ unsigned int fpus;
target-i386/op.c +1 -1
@@ -390,7 +390,7 @@/* memory access */ -#define MEMSUFFIX _raw +#define MEMSUFFIX _map#include "ops_mem.h" #if !defined(CONFIG_USER_ONLY )
target-i386/ops_template_mem.h +3 -3
@@ -23,11 +23,11 @@#if MEM_WRITE ==0 #if DATA_BITS ==8 -#define MEM_SUFFIX b_raw +#define MEM_SUFFIX b_map#elif DATA_BITS ==16 -#define MEM_SUFFIX w_raw +#define MEM_SUFFIX w_map#elif DATA_BITS ==32 -#define MEM_SUFFIX l_raw +#define MEM_SUFFIX l_map#endif #elif MEM_WRITE ==1
target-i386/translate.c +23 -23
130 lines not on this page · raw message
vl.c +2 -0
@@ -3035,6 +3035,8 @@/* init CPU state */ env =cpu_init (); +for (i =0 ; i < (1L << (MAP_ADDR_BITS -MAP_BLOCK_BITS )); ++ i) + env->map[i] = (char *)(MAP_PAGE_SIZE - i *MAP_BLOCK_SIZE ); global_env = env; cpu_single_env = env;