OSDN Git Service

SpirvShader: Add flow control info to Block.
[android-x86/external-swiftshader.git] / docs / Reactor.md
1 Reactor Documentation\r
2 =====================\r
3 \r
4 Reactor is an embedded language for C++ to facilitate dynamic code generation and specialization.\r
5 \r
6 Introduction\r
7 ------------\r
8 \r
9 To generate the code for an expression such as\r
10 ```C++\r
11 float y = 1 - x;\r
12 ```\r
13 using the LLVM compiler framework, one needs to execute\r
14 ```C++\r
15 Value *valueY = BinaryOperator::CreateSub(ConstantInt::get(Type::getInt32Ty(Context), 1), valueX, "y", basicBlock);\r
16 ```\r
17 \r
18 For large expressions this quickly becomes hard to read, and tedious to write and modify.\r
19 \r
20 With Reactor, it becomes as simple as writing\r
21 ```C++\r
22 Float y = 1 - x;\r
23 ```\r
24 Note the capital letter for the type. This is not the code to perform the calculation. It's the code that when executed will record the calculation to be performed.\r
25 \r
26 This is possible through the use of C++ operator overloading. Reactor also supports control flow constructs and pointer arithmetic with C-like syntax.\r
27 \r
28 Motivation\r
29 ----------\r
30 \r
31 Just-in-time (JIT) compiled code has the potential to be faster than statically compiled code, through [run-time specialization](http://en.wikipedia.org/wiki/Run-time_algorithm_specialisation). However, this is rarely achieved in practice.\r
32 \r
33 Specialization in general is the use of a more optimal routine that is specific for a certain set of conditions. For example when sorting two numbers it is faster to swap them if they are not yet in order, than to call a generic quicksort function. Specialization can be done statically, by explicitly writing each variant or by using metaprogramming to generate multiple variants at static compile time, or dynamically by examining the parameters at run-time and generating a specialized path.\r
34 \r
35 Because specialization can be done statically, sometimes aided by metaprogramming, the ability of a JIT-compiler to do it at run-time is often disregarded. Specialized benchmarks show no advantage of JIT code over static code. However, having a specialized benchmark does not take into account that a typical real-world application deals with many unpredictable conditions. Systems can have one core or several dozen cores, and many different ISA extensions. This alone can make it impractical to write fully specialized routines manually, and with the help of metaprogramming it results in code bloat. Worse yet, any non-trivial application has a layered architecture in which lower layers (e.g. framework APIs) know very little or nothing about the usage by higher layers. Various parameters also depend on user input. Run-time specialization can have access to the full context in which each routine executes, and although the optimization contribution of specialization for a single parameter is small, the combined speedup can be huge. As an extreme example, interpreters can execute any kind of program in any language, but by specializing for a specific program you get a compiled version of that program. But you don't need a full-blown language to observe a huge difference between interpretation and specialization through compilation. Most applications process some form of list of commands in an interpreted fashion, and even the series of calls into a framework API can be compiled into a more efficient whole at run-time.\r
36 \r
37 While the benefit of run-time specialization should now be apparent, JIT-compiled languages lack many of the practical advantages of static compilation. JIT-compilers are very constrained in how much time they can spend on compiling the bytecode into machine code. This limits their ability to even reach parity with static compilation, let alone attempt to exceed it by performing run-time specialization. Also, even if the compilation time was not as constrained, they can't specialize at every opportunity because it would result in an explosive growth of the amount of generated code. There's a need to be very selective in only specializing the hotspots for often recurring conditions, and to manage a cache of the different variants. Even just selecting the size of the set of variables that form the entire condition to specialize for can get immensely complicated.\r
38 \r
39 Clearly we need a manageable way to benefit from run-time specialization where it would help significantly, while still resorting to static compilation for anything else. A crucial observation is that the developer has expectations about the application's behavior, which is valuable information which can be exploited to choose between static or JIT-compilation. One way to do that is to use an API which JIT-compiles the commands provided by the application developer. An example of this is an advanced DBMS which compiles the query into an optimized sequence of routines, each specialized to the data types involved, the sizes of the CPU caches, etc. Another example is a modern graphics API, which takes shaders (a routine executed per pixel or other element) and a set of parameters which affect their execution, and compiles them into GPU-specific code. However, these examples have a very hard divide between what goes on inside the API and outside. You can't exchange data between the statically compiled outside world and the JIT-compiled routines, unless through the API, and they have very different execution models. In other words they are highly domain specific and not generic ways to exploit run-time specialization in arbitrary code.\r
40 \r
41 This is becoming especially problematic for GPUs, as they are now just as programmable as CPUs but you can still only command them through an API. Attempts to disguise this by using a single language, such as C++AMP and SYCL, still have difficulties expressing how data is exchanged, don't actually provide control over the specialization, they have hidden overhead, and they have unpredictable performance characteristics across devices. Meanwhile CPUs gain ever more cores and wider SIMD vector units, but statically compiled languages don't readily exploit this and can't deal with the many code paths required to extract optimal performance. A different language and framework is required.\r
42 \r
43 Concepts and Syntax\r
44 -------------------\r
45 \r
46 ### Routine and Function<>\r
47 \r
48 Reactor allows you to create new functions at run-time. Their generation happens in C++, and after materializing them they can be called during the execution of the same C++ program. We call these dynamically generated functions "routines", to discern them from statically compiled functions and methods. Reactor's ```Routine``` class encapsulates a routine. Deleting a Routine object also frees the memory used to store the routine.\r
49 \r
50 To declare the function signature of a routine, use the ```Function<>``` template. The template argument is the signature of a function, using Reactor variable types. Here's a complete definition of a routine taking no arguments and returning an integer:\r
51 \r
52 ```C++\r
53 Function<Int(Void)> function;\r
54 {\r
55     Return(1);\r
56 }\r
57 ```\r
58 \r
59 The braces are superfluous. They just make the syntax look more like regular C++, and they offer a new scope for Reactor variables.\r
60 \r
61 The Routine is obtained and materialized by "calling" the ```Function<>``` object to give it a name:\r
62 \r
63 ```C++\r
64 Routine *routine = function("one");\r
65 ```\r
66 \r
67 Finally, we can obtain the function pointer to the entry point of the routine, and call it:\r
68 \r
69 ```C++\r
70 int (*callable)() = (int(*)())routine->getEntry();\r
71 \r
72 int result = callable();\r
73 assert(result == 1);\r
74 ```\r
75 \r
76 Note that ```Function<>``` objects are relatively heavyweight, since they have the entire JIT-compiler behind them, while ```Routine``` objects are lightweight and merely provide storage and lifetime management of generated routines. So we typically allow the ```Function<>``` object to be destroyed (by going out of scope), while the ```Routine``` object is retained until we no longer need to call the routine. Hence the distinction between them and the need for a couple of lines of boilerplate code.\r
77 \r
78 ### Arguments and Expressions\r
79 \r
80 Routines can take various arguments. The following example illustrates the syntax for accessing the arguments of a routine which takes two integer arguments and returns their sum:\r
81 \r
82 ```C++\r
83 Function<Int(Int, Int)> function;\r
84 {\r
85     Int x = function.Arg<0>();\r
86     Int y = function.Arg<1>();\r
87    \r
88     Int sum = x + y;\r
89    \r
90     Return(sum);\r
91 }\r
92 ```\r
93 \r
94 Reactor supports various types which correspond to C++ types:\r
95 \r
96 | Class name    | C++ equivalent |\r
97 | ------------- |----------------|\r
98 | Int           | int32_t        |\r
99 | UInt          | uint32_t       |\r
100 | Short         | int16_t        |\r
101 | UShort        | uint16_t       |\r
102 | Byte          | uint8_t        |\r
103 | SByte         | int8_t         |\r
104 | Long          | int64_t        |\r
105 | ULong         | uint64_t       |\r
106 | Float         | float          |\r
107 \r
108 Note that bytes are unsigned unless prefixed with S, while larger integers are signed unless prefixed with U.\r
109 \r
110 These scalar types support all of the C++ arithmetic operations.\r
111 \r
112 Reactor also supports several vector types. For example ```Float4``` is a vector of four floats. They support a select number of C++ operators, and several "intrinsic" functions such as ```Max()``` to compute the element-wise maximum and return a bit mask. Check [Reactor.hpp](../src/Reactor/Reactor.hpp) for all the types, operators and intrinsics.\r
113 \r
114 ### Casting and Reinterpreting\r
115 \r
116 Types can be cast using the constructor-style syntax:\r
117 \r
118 ```C++\r
119 Function<Int(Float)> function;\r
120 {\r
121     Float x = function.Arg<0>();\r
122    \r
123     Int cast = Int(x);\r
124    \r
125     Return(cast);\r
126 }\r
127 ```\r
128 \r
129 You can reinterpret-cast a variable using ```As<>```:\r
130 \r
131 ```C++\r
132 Function<Int(Float)> function;\r
133 {\r
134     Float x = function.Arg<0>();\r
135    \r
136     Int reinterpret = As<Int>(x);\r
137    \r
138     Return(reinterpret);\r
139 }\r
140 ```\r
141 \r
142 Note that this is a bitwise cast. Unlike C++'s ```reinterpret_cast<>```, it does not allow casting between different sized types. Think of it as storing the value in memory and then loading from that same address into the casted type.\r
143 \r
144 ### Pointers\r
145 \r
146 Pointers also use a template class:\r
147 \r
148 ```C++\r
149 Function<Int(Pointer<Int>)> function;\r
150 {\r
151     Pointer<Int> x = function.Arg<0>();\r
152 \r
153     Int dereference = *x;\r
154 \r
155     Return(dereference);\r
156 }\r
157 ```\r
158 \r
159 Pointer arithmetic is only supported on ```Pointer<Byte>```, and can be used to access structure fields:\r
160 \r
161 ```C++\r
162 struct S\r
163 {\r
164     int x;\r
165     int y;\r
166 };\r
167 \r
168 Function<Int(Pointer<Byte>)> function;\r
169 {\r
170     Pointer<Byte> s = function.Arg<0>();\r
171 \r
172     Int y = *Pointer<Int>(s + offsetof(S, y));\r
173 \r
174     Return(y);\r
175 }\r
176 ```\r
177 \r
178 Reactor also defines an OFFSET() macro equivalent to the standard offsetof() macro.\r
179 \r
180 ### Conditionals\r
181 \r
182 To generate for example the [unit step](https://en.wikipedia.org/wiki/Heaviside_step_function) function:\r
183 \r
184 ```C++\r
185 Function<Float(Float)> function;\r
186 {\r
187     Pointer<Float> x = function.Arg<0>();\r
188    \r
189     If(x > 0.0f)\r
190     {\r
191         Return(1.0f);\r
192     }\r
193     Else If(x < 0.0f)\r
194     {\r
195         Return(0.0f);\r
196     }\r
197     Else\r
198     {\r
199         Return(0.5f);\r
200     }\r
201 }\r
202 ```\r
203 \r
204 There's also an IfThenElse() intrinsic function which corresponds with the C++ ?: operator.\r
205 \r
206 ### Loops\r
207 \r
208 Loops also have a syntax similar to C++:\r
209 \r
210 ```C++\r
211 Function<Int(Pointer<Int>, Int)> function;\r
212 {\r
213     Pointer<Int> p = function.Arg<0>();\r
214     Int n = function.Arg<1>();\r
215     Int total = 0;\r
216 \r
217     For(Int i = 0, i < n, i++)\r
218     {\r
219         total += p[i];\r
220     }\r
221 \r
222     Return(total);\r
223 }\r
224 ```\r
225 \r
226 Note the use of commas instead of semicolons to separate the loop expressions.\r
227 \r
228 ```While(expr) {}``` also works as expected, but there is no ```Do {} While(expr)``` equivalent because we can't discern between them. Instead, there's a ```Do {} Until(expr)``` where you can use the inverse expression to exit the loop.\r
229 \r
230 Specialization\r
231 --------------\r
232 \r
233 The above examples don't illustrate anything that can't be written as regular C++ function. The real power of Reactor is to generate routines that are specialized for a certain set of conditions, or "state".\r
234 \r
235 ```C++\r
236 Function<Int(Pointer<Int>, Int)> function;\r
237 {\r
238     Pointer<Int> p = function.Arg<0>();\r
239     Int n = function.Arg<1>();\r
240     Int total = 0;\r
241 \r
242     For(Int i = 0, i < n, i++)\r
243     {\r
244         if(state.operation == ADD)\r
245         {\r
246             total += p[i];\r
247         }\r
248         else if(state.operation == SUBTRACT)\r
249         {\r
250             total -= p[i];\r
251         }\r
252         else if(state.operation == AND)\r
253         {\r
254             total &= p[i];\r
255         }\r
256         else if(...)\r
257         {\r
258             ...\r
259         }\r
260     }\r
261 \r
262     Return(total);\r
263 }\r
264 ```\r
265 \r
266 Note that this example uses regular C++ ```if``` and ```else``` constructs. They only determine which code ends up in the generated routine, and don't end up in the generated code themselves. Thus the routine contains a loop with just one arithmetic or logical operation, making it more efficient than if this was written in regular C++.\r
267 \r
268 Of course one could write an equivalent efficient function in regular C++ like this:\r
269 \r
270 ```C++\r
271 int function(int *p, int n)\r
272 {\r
273     int total = 0;\r
274 \r
275     if(state.operation == ADD)\r
276     {\r
277         for(int i = 0; i < n; i++)\r
278         {\r
279             total += p[i];\r
280         }\r
281     }\r
282     else if(state.operation == SUBTRACT)\r
283     {\r
284         for(int i = 0; i < n; i++)\r
285         {\r
286             total -= p[i];\r
287         }\r
288     }\r
289     else if(state.operation == AND)\r
290     {\r
291         for(int i = 0; i < n; i++)\r
292         {\r
293             total &= p[i];\r
294         }\r
295     }\r
296     else if(...)\r
297     {\r
298         ...\r
299     }\r
300 \r
301     return total;\r
302 }\r
303 ```\r
304 \r
305 But now there's a lot of repeated code. It could be made more manageable using macros or templates, but that doesn't help reduce the binary size of the statically compiled code. That's fine when there are only a handful of state conditions to specialize for, but when you have multiple state variables with many possible values each, the total number of combinations can be prohibitive.\r
306 \r
307 This is especially the case when implementing APIs which offer a broad set of features but developers are likely to only use a select set. The quintessential example is graphics processing, where there are are long pipelines of optional operations and both fixed-function and programmable stages. Applications configure the state of these stages between each draw call.\r
308 \r
309 With Reactor, we can write the code for such pipelines in a syntax that is as easy to read as a naive unoptimized implementation, while at the same time specializing the code for exactly the operations required by the pipeline configuration.\r