• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
fir

optymizations by self modifying code

19 posts in this topic

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 
0

Share this post


Link to post
Share on other sites

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.

0

Share this post


Link to post
Share on other sites
I think this is about GPU code. Write Access to code segments is only allowed by the os
0

Share this post


Link to post
Share on other sites

 

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

0

Share this post


Link to post
Share on other sites

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
0

Share this post


Link to post
Share on other sites

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.

0

Share this post


Link to post
Share on other sites
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.
0

Share this post


Link to post
Share on other sites

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.

1

Share this post


Link to post
Share on other sites

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.

1

Share this post


Link to post
Share on other sites

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.

1

Share this post


Link to post
Share on other sites

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

0

Share this post


Link to post
Share on other sites


JIT compilers tend to disagree.

 

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

0

Share this post


Link to post
Share on other sites
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.
2

Share this post


Link to post
Share on other sites

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
0

Share this post


Link to post
Share on other sites

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 )
0

Share this post


Link to post
Share on other sites

 

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

-2

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0