Jump to content

  • Log In with Google      Sign In   
  • Create Account

optymizations by self modifying code


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
19 replies to this topic

#1 fir   Members   -  Reputation: -460

Like
0Likes
Like

Posted 08 July 2014 - 03:05 PM

recently i found interesting remark
 
After the continuous headway of GPU rendering, software rasterization was 
increasingly losing ground. Despite this, some great results have been born, such as 
the Pixomatic 1, 2, 3 renderers [15] by Rad Game Tools and the Swiftshader by 
TrasGaming [2]. Both products are highly optimized utilizing the modern threading 
capabilities of today’s Multicore CPUs and have dynamically self-modifying pixel 
pipelines. In addition, Pixomatic 3 and Swiftshader are 100% DirectX 9 
compatible.
 
it seems that in search for top optymizations possible some use old technique of rewriting code at runtime (if i understand it correctly) 
Does maybe someone suspect wkat kind of routines/hotspots can be optymized this way, what kind of benefit it can bring
 
i dont quite get it 


Sponsor:

#2 Samith   Members   -  Reputation: 2256

Like
4Likes
Like

Posted 08 July 2014 - 03:22 PM

Since those software renderers are trying to emulate DX6 or DX7 (or higher?) level capability, they need to have a very flexible pixel shading pipeline. The naive way to implement this would likely be by using a bunch of switch statements or different functions in the pixel shading code that allowed all the features to be enabled/disabled/configured. That's not optimal, so they need to dynamically compile optimal shading functions at runtime, depending on the render state's configuration.

 

The benefit of this is that the pixel drawing code doesn't need to constantly check the render state and decide what to do. It'll just do exactly what it needs to do, because it will have been compiled that way.


Edited by Samith, 08 July 2014 - 03:24 PM.


#3 C0lumbo   Crossbones+   -  Reputation: 2259

Like
0Likes
Like

Posted 08 July 2014 - 03:23 PM

Pretty sure modern Windows doesn't allow self modifying code, so I think that either the article is talking about techniques that can't be used these days, or more likely the compiled shader code is being interpreted instead of executed natively.

 

I would imagine the self-modifying code is more along the lines of branch prediction or patching the shaders to account for values of uniforms, rather than being like the older style code modifications.



#4 Tribad   Members   -  Reputation: 851

Like
0Likes
Like

Posted 08 July 2014 - 03:31 PM

I think this is about GPU code. Write Access to code segments is only allowed by the os

#5 SeanMiddleditch   Members   -  Reputation: 5749

Like
8Likes
Like

Posted 08 July 2014 - 03:48 PM

These kinds of approaches use techniques similar to that found in liboil (Optimize Inner Loops).

Basically, it's a regular ol' Just In Time compiler for shading, color conversions, rasterisation, etc. Modern JavaScript engines can achieve kinda-sorta similar performance in some cases (beating hand-optimized C code in some cases, even!) because the optimizer generates the exact most-efficient assembly not only for the loop in question but for the loop invariants as well.

There's not a lot of direct self-modificatin of code, but new routines can be generated and then function pointers can be changed to jump into the newly-compiled code in place of an old routines. Which is what most JIT compilers do.

Toss in proper threading and use of SIMD and you can generate optimal parallelized code for most math kernels. This is what OpenCL or a shader compiler does, after all, just for the GPU instead of the CPU.
 

Since those software renderers are trying to emulate DX6 or DX7 (or higher?) level capability, they need to have a very flexible pixel shading pipeline.


Higher, definitely. There are complete DX11 and GL4 implementations of these technologies. Windows 8.1 ships with one, many Linux installations have Mesa's LLVMpipe (though it's for GL2/3), and there are other proprietary options that handle modern graphics shading languages.
 

Pretty sure modern Windows doesn't allow self modifying code, so I think that either the article is talking about techniques that can't be used these days, or more likely the compiled shader code is being interpreted instead of executed natively.


Of course it does. You just have to make sure that the pages in question are writable and aren't marked no-execute. Self modification is no different than other other JIT compilation in this respect.

Some console and mobile platforms have restrictions that outright disallow a combination of writeable and executable for either security or DRM purposes, but Windows is fine.
 

I think this is about GPU code. Write Access to code segments is only allowed by the os


Nonsense. This is about emulating GPUs on the CPU (they can't be as efficient, but they can be a lot more efficient than you'd expect). "Code segments" are just memory pages like anything else and nothing implicitly makes them OS-accessible-only, unless the OS decides to enforce those rules in its virtual memory management (which no desktop OS I know of does, due to the prevalence of JIT compilers).

#6 fir   Members   -  Reputation: -460

Like
0Likes
Like

Posted 08 July 2014 - 04:56 PM

 

Pretty sure modern Windows doesn't allow self modifying code, so I think that either the article is talking about techniques that can't be used these days, or more likely the compiled shader code is being interpreted instead of executed natively.


Of course it does. You just have to make sure that the pages in question are writable and aren't marked no-execute. Self modification is no different than other other JIT compilation in this respect.

Some console and mobile platforms have restrictions that outright disallow a combination of writeable and executable for either security or DRM purposes, but Windows is fine.

 

i also think that its possible - probably  such simple thing as

buf = VirtualAlloc(NULL,size,MEM_COMMIT | MEM_RESERVE,PAGE_EXECUTE_READWRITE);

will sufice



#7 fir   Members   -  Reputation: -460

Like
0Likes
Like

Posted 08 July 2014 - 05:06 PM

Since those software renderers are trying to emulate DX6 or DX7 (or higher?) level capability, they need to have a very flexible pixel shading pipeline. The naive way to implement this would likely be by using a bunch of switch statements or different functions in the pixel shading code that allowed all the features to be enabled/disabled/configured. That's not optimal, so they need to dynamically compile optimal shading functions at runtime, depending on the render state's configuration.

 

The benefit of this is that the pixel drawing code doesn't need to constantly check the render state and decide what to do. It'll just do exactly what it needs to do, because it will have been compiled that way.

 

well, thats sad, i thinked if it is maybe some some general way of optymizing (helping get away some ifs or something though i got no idea

how it would look like) - if so this is not general idea on optymizing but more like script compilation  indeed


Edited by fir, 08 July 2014 - 05:06 PM.


#8 jbadams   Senior Staff   -  Reputation: 18546

Like
0Likes
Like

Posted 08 July 2014 - 09:49 PM

Moderation note: a number of off-topic replies have been removed from this discussion, and warnings have been issued to a couple of members.  Please keep all further discussion on topic.



#9 Tribad   Members   -  Reputation: 851

Like
0Likes
Like

Posted 09 July 2014 - 12:21 AM

You can not change the attribute of a a code segment from read only to read-write. You create a new data area that is executable. So the os makes your code segment always read only at load time.

I dont had these self created data areas in mind.

#10 Stainless   Members   -  Reputation: 934

Like
1Likes
Like

Posted 09 July 2014 - 08:19 AM

Executable memory is one of those things that Apple have decided is "far too dangerous for developers to have".

 

So any attempt at self modifying code on IOS is doomed to failure.

 

You can trick windows and get some nice executable memory, I used it for years as a way of injecting my own code into third party games.

 

However in the general case if you think you need self modifying code, you have probably got the algorithm wrong smile.png

 

Even with the best designed bits of self modding, you save nanoseconds (they may be important nanoseconds, if such a beast exists) whereas a change in the algorithm often saves milliseconds.



#11 kalle_h   Members   -  Reputation: 1386

Like
1Likes
Like

Posted 09 July 2014 - 12:08 PM

Executable memory is one of those things that Apple have decided is "far too dangerous for developers to have".

 

So any attempt at self modifying code on IOS is doomed to failure.

 

You can trick windows and get some nice executable memory, I used it for years as a way of injecting my own code into third party games.

 

However in the general case if you think you need self modifying code, you have probably got the algorithm wrong smile.png

 

Even with the best designed bits of self modding, you save nanoseconds (they may be important nanoseconds, if such a beast exists) whereas a change in the algorithm often saves milliseconds.

JIT compilers tend to disagree.



#12 Dave Hunt   Crossbones+   -  Reputation: 2457

Like
1Likes
Like

Posted 09 July 2014 - 12:33 PM

There was a series of articles in Dr. Dobbs Journal detailing the optimization of Pixomatic for x86 processors. The first in the series is here - http://www.drdobbs.com/architecture-and-design/optimizing-pixomatic-for-x86-processors/184405765

 

There's a brief discussion of the self-modifying pipeline in that first article. I didn't spend any time trying to locate the subsequent articles in the series.



#13 fir   Members   -  Reputation: -460

Like
0Likes
Like

Posted 09 July 2014 - 03:27 PM

There was a series of articles in Dr. Dobbs Journal detailing the optimization of Pixomatic for x86 processors. The first in the series is here - http://www.drdobbs.com/architecture-and-design/optimizing-pixomatic-for-x86-processors/184405765

 

There's a brief discussion of the self-modifying pipeline in that first article. I didn't spend any time trying to locate the subsequent articles in the series.

 

Abrash. Kool (at least the one who is not sharing antioptimizatio0n propaganda)) Didnt know he was doing that, Indeed there is detailed interesting description - I readed only half of it by now, but will try to absorb all and can back to comment this a bit



#14 Stainless   Members   -  Reputation: 934

Like
0Likes
Like

Posted 10 July 2014 - 08:39 AM


JIT compilers tend to disagree.

 

The iOS security sandbox will likely kill any app that tries to jump into any dynamically generated data.



#15 Madhed   Crossbones+   -  Reputation: 2897

Like
5Likes
Like

Posted 10 July 2014 - 09:21 AM


Abrash. Kool (at least the one who is not sharing antioptimizatio0n propaganda)) Didnt know he was doing that, Indeed there is detailed interesting description - I readed only half of it by now, but will try to absorb all and can back to comment this a bit

 

And yet in the article he writes about assuming nothing and that his first instinct to optimize the inner loop with assembly didn't improve the performance nearly as much as simply rewriting a function that was implemented naively. Oh the irony...



#16 Krypt0n   Crossbones+   -  Reputation: 2564

Like
2Likes
Like

Posted 11 July 2014 - 03:55 AM

when you write assembly, sooner or later ever programmer gets the idea to modify code on runtime. you can start quite simple by changing some constants, e.g. instead of

mov bx,Variable
.
.
.
add ax,bx
you rather write

lea di, m1 ;load the address of the opcode at marker "m1"
add di, 3 ;this is an offset to the actual constant in the add instruction, skipping the opcode
mov bx, Variable
mov [di], bx
.
.
.
m1:
add ax, 0 ;0 will be replaced by above code
I've used this in dos times for rasterization quite a lot, e.g. if u calculate the borders of a triangle with y=m*x+b, m and b are constants, yet they use otherwise precious register space (and you had just ax,bx,cd,dx,di,si beside stack etc.). and as those don't change, you can rather replace the values in the binary with those kind of constants.

next step that comes into your mind is, if you have some inner loop and you'd need to rewrite it 100 times for various different cases (and some guys do that e.g. http://www.amazon.com/Tricks-Programming-Gurus-Advanced-Graphics-Rasterization/dp/0672318350/ )you could just add some jumps and you modify the destination offset. static jumps are executed in a different part of the cpu than all the math etc. and are essentially free as there is no false prediction. that way you can switch on and off textures, blending etc. of the rasterize with just a few lines of code.
like said above, there are a few guys who write a runtime compiler for that, but that's the crazy banana version if you really really want to get the best performance, but that's rather for complex shader cases where you would otherwise end up with crazy amount of jumps. for simple cases (<=Direct3D 6) modifying some constants was good enough to get the needed performance. it made also no sense to copy around code chunks, as that copy would cost you time and would barely have a different runtime speed than a modified jump (aka jump table) to that code area.

today it's a bit dangerous, caches and pipelines assume that the code is static. even with just data you can run into hazards in multithreaded applications, that's even more dangerous for code segments. tho, it's not impossible, I think pretty much every OS allows you to unlock segments for writing/modifying and if you know the cpu architecture, you can enforce the syncs that are needed.

the craziest think I've done with SMC was for my raytracer, where I've basically 'dumped' the BSP tree as assembly code. Instead of a tiny loop that progresses randomly on either side of the BSP tree, the 'unrolled' code was processed mostly in a very similar way (every ray starts at the same place and most will be split by the same node as the previous ray and most will process the branch of the leaf as the previous node).
sadly it just worked out for a small BSP, before I've even ran out of L1 instruction cache, I've somehow run out of the space that the jump prediction can cover and then the performance dropped dramatically, below the version with the tiny loop. The next more 'crazy' step would be to evaluate every frame the most likely walking path of the BSP and dump a code tree that aligns with what the static code prediction would guess.. but I didn't do that as my way of SMC was to dump a c++ file and invoke the cl.exe of visual studio, which is ok on load time, but not if you have 16ms, to generate a binary-lib that I've parsed and copied into my binary.

#17 fir   Members   -  Reputation: -460

Like
0Likes
Like

Posted 11 July 2014 - 05:29 AM

when you write assembly, sooner or later ever programmer gets the idea to modify code on runtime. you can start quite simple by changing some constants, e.g. instead of


mov bx,Variable
.
.
.
add ax,bx
you rather write

lea di, m1 ;load the address of the opcode at marker "m1"
add di, 3 ;this is an offset to the actual constant in the add instruction, skipping the opcode
mov bx, Variable
mov [di], bx
.
.
.
m1:
add ax, 0 ;0 will be replaced by above code
I've used this in dos times for rasterization quite a lot, e.g. if u calculate the borders of a triangle with y=m*x+b, m and b are constants, yet they use otherwise precious register space (and you had just ax,bx,cd,dx,di,si beside stack etc.). and as those don't change, you can rather replace the values in the binary with those kind of constants.

next step that comes into your mind is, if you have some inner loop and you'd need to rewrite it 100 times for various different cases (and some guys do that e.g. http://www.amazon.com/Tricks-Programming-Gurus-Advanced-Graphics-Rasterization/dp/0672318350/ )you could just add some jumps and you modify the destination offset. static jumps are executed in a different part of the cpu than all the math etc. and are essentially free as there is no false prediction. that way you can switch on and off textures, blending etc. of the rasterize with just a few lines of code.
like said above, there are a few guys who write a runtime compiler for that, but that's the crazy banana version if you really really want to get the best performance, but that's rather for complex shader cases where you would otherwise end up with crazy amount of jumps. for simple cases (<=Direct3D 6) modifying some constants was good enough to get the needed performance. it made also no sense to copy around code chunks, as that copy would cost you time and would barely have a different runtime speed than a modified jump (aka jump table) to that code area.

today it's a bit dangerous, caches and pipelines assume that the code is static. even with just data you can run into hazards in multithreaded applications, that's even more dangerous for code segments. tho, it's not impossible, I think pretty much every OS allows you to unlock segments for writing/modifying and if you know the cpu architecture, you can enforce the syncs that are needed.

the craziest think I've done with SMC was for my raytracer, where I've basically 'dumped' the BSP tree as assembly code. Instead of a tiny loop that progresses randomly on either side of the BSP tree, the 'unrolled' code was processed mostly in a very similar way (every ray starts at the same place and most will be split by the same node as the previous ray and most will process the branch of the leaf as the previous node).
sadly it just worked out for a small BSP, before I've even ran out of L1 instruction cache, I've somehow run out of the space that the jump prediction can cover and then the performance dropped dramatically, below the version with the tiny loop. The next more 'crazy' step would be to evaluate every frame the most likely walking path of the BSP and dump a code tree that aligns with what the static code prediction would guess.. but I didn't do that as my way of SMC was to dump a c++ file and invoke the cl.exe of visual studio, which is ok on load time, but not if you have 16ms, to generate a binary-lib that I've parsed and copied into my binary.

 

those optimizations indeed are a bit crazy (i mean the one you mention is like changing assembly level code interpreter of some data into some compiled version of it (i do not see it 100% clearly)) the other too, idea of saving registers by incompiling constants seem to be be very fine, the problem with this is if such code with more immediates wouldnt be run

slower as the one who holds those constants in registers (as reading immediate involves raeding it form memory maybe not much overhead for processor but it is not 100% clear) - thus compensating the advantage of having some additional registers (but it seem more good than bad for me)

 

anyway those two seem interesting, I dont intend to go such crazy right now (as I have got problems with plain assembly), but ist interesting


Edited by fir, 11 July 2014 - 05:36 AM.


#18 Krypt0n   Crossbones+   -  Reputation: 2564

Like
0Likes
Like

Posted 11 July 2014 - 11:23 AM

those optimizations indeed are a bit crazy (i mean the one you mention is like changing assembly level code interpreter of some data into some compiled version of it (i do not see it 100% clearly)) the other too, idea of saving registers by incompiling constants seem to be be very fine, the problem with this is if such code with more immediates wouldnt be run
slower as the one who holds those constants in registers (as reading immediate involves raeding it form memory maybe not much overhead for processor but it is not 100% clear) - thus compensating the advantage of having some additional registers (but it seem more good than bad for me)

if you don't patch the assembly to embed constants, you have two choices
1. save constants in registers -> if you have enough registers, that's perfectly fine, if you don't have enough, you'll have to push/pop some temporary values out of registers to keep the frequently used constants inside. that push/pop is what costs you more than the constant that is embedded in the opcodes and is loaded implicitly by the instruction decoder
2. you save constants in temporal memory on the stack -> you have to keep a register as stack pointer (so that's one less for you to use for variables) and you have to access the constants using an indirection e.g. mov bx,[sp-4] which won't be faster either, as just the -4 is already a constant, thus on top of decoding the instruction including and immediate, you calculate the address and make a read depending on the address calculation result.

embedding constants and patching jumps was really faster on those old school cpus, I've benchmarked it thousands of times;)



 

anyway those two seem interesting, I dont intend to go such crazy right now (as I have got problems with plain assembly), but ist interesting

I guess it's enough to know how it was done, 99.99% of programmers will probably not need it nowadays, but back then it was tons of fun (I've spent my whole school breaks optimizing rasterizers smile.png )

#19 fir   Members   -  Reputation: -460

Like
-2Likes
Like

Posted 12 July 2014 - 03:53 AM

 

that his first instinct to optimize the inner loop with assembly didn't improve the performance nearly as much as simply rewriting a function that was implemented naively. 

 

 

Those stories about people optymizing wrong places sound a bit strange to me - i naver had such a situation, It was always clear what is a hotspot and indeed every 'optymization session' i was 

working in, always made change in the execution time, often quite big - once (for some mandelbrot set counter on old bcc32, it was weakly generated and i ended with decent sse routine found in the net;/)  it was for example 15X,  recently (for some rastrerizer on mingw) 2.5-3X (without sse yet because I showed a bit to tired)

 

Ofc sometimes optimizations work may involve some work and time and there it is better to maybe go more in creative side, but its good to balance those two wing-sides

 

Imo optimization is important for another reason yet, optimization help you to better know your code, better knowing your code help you to be more focused, and if you are more focused/concentrated you can craft/shape it way more - ofc this is  all not easy work



#20 fastcall22   Crossbones+   -  Reputation: 4330

Like
5Likes
Like

Posted 12 July 2014 - 05:17 PM

Those stories about people optymizing wrong places sound a bit strange to me - i naver had such a situation, It was always clear what is a hotspot and indeed every 'optymization session' i was

Except you have had such a situation.

In your speeding this with sse or sse intrinsics thread, you were looking to optimize an inner loop with SSE. Ohforf showed you could speed up your code by 200% just by using a more efficient algorithm without SSE.
c3RhdGljIGNoYXIgeW91cl9tb21bMVVMTCA8PCA2NF07CnNwcmludGYoeW91cl9tb20sICJpcyBmYXQiKTs=




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS