HTML and CSS Reference
In-Depth Information
The LLVM IR captures the semantic meaning of the C code, but gives it a consistent structure so that Emscripten
can translate it into JavaScript.
After Clang converts C or C++ source code into LLVM IR, Emscripten takes over (see Figure 18-3 ). Emscripten
translates the LLVM IR into JavaScript operations. It leverages the fact that the JavaScript language has operators and
expressions that match C semantics for signed and unsigned 32-bit integer math.
Figure 18-3. The Emscripten stage
The aforementioned lerp function would get compiled and optimized into the JavaScript shown in Listing 18-3.
Listing 18-3. lerp Translated to JavaScript
function _lerp(a, b, t) {
return(1 - t) * a + t * b
As you can see, for functions that operate only on arguments, the original C and resulting JavaScript often look
similar. However, the vast majority of C and C++ functions involve some kind of memory access. To illustrate how
Emscripten implements pointers and memory access, let's compare C and JavaScript implementations of strlen; .
The standard C strlen function, when translated to JavaScript, dereferences pointers by indexing into the HEAP8 array
(Listings 18-4 and 18-5).
Listing 18-4. strlen in C
size_t strlen(const char *str) {
const char *s = str;
while (*s) ++s;
return s - str;
Listing 18-5. strlen in JavaScript
function _strlen(str) {
for(var s = str;0 != (HEAP8[s] | 0);) {
s = s + 1 | 0
return s - str | 0
Note that these examples are simple C functions to illustrate basic code generation concepts. As C++ can be
considered syntax sugar on top of C semantics, all the same principles apply to compiled C++ code.
Search WWH ::

Custom Search