Document libgccjit++.h
[official-gcc.git] / gcc / jit / docs / _build / texinfo / libgccjit.texi
blob3f13219af7ae36f5208fe3834246d8e2eda7719f
1 \input texinfo   @c -*-texinfo-*-
2 @c %**start of header
3 @setfilename libgccjit.info
4 @documentencoding UTF-8
5 @ifinfo
6 @*Generated by Sphinx 1.1.3.@*
7 @end ifinfo
8 @settitle libgccjit Documentation
9 @defindex ge
10 @paragraphindent 2
11 @exampleindent 4
12 @afourlatex
13 @dircategory Miscellaneous
14 @direntry
15 * libgccjit: (libgccjit.info). One line description of project.
16 @end direntry
18 @c %**end of header
20 @copying
21 @quotation
22 libgccjit 5.0.0 (experimental 20141210), December 10, 2014
24 David Malcolm
26 Copyright @copyright{} 2014, Free Software Foundation
27 @end quotation
29 @end copying
31 @titlepage
32 @title libgccjit Documentation
33 @insertcopying
34 @end titlepage
35 @contents
37 @c %** start of user preamble
39 @c %** end of user preamble
41 @ifnottex
42 @node Top
43 @top libgccjit Documentation
44 @insertcopying
45 @end ifnottex
47 @c %**start of body
48 @anchor{index doc}@anchor{0}
49 @c Copyright (C) 2014 Free Software Foundation, Inc.
50 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
51 @c 
52 @c This is free software: you can redistribute it and/or modify it
53 @c under the terms of the GNU General Public License as published by
54 @c the Free Software Foundation, either version 3 of the License, or
55 @c (at your option) any later version.
56 @c 
57 @c This program is distributed in the hope that it will be useful, but
58 @c WITHOUT ANY WARRANTY; without even the implied warranty of
59 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
60 @c General Public License for more details.
61 @c 
62 @c You should have received a copy of the GNU General Public License
63 @c along with this program.  If not, see
64 @c <http://www.gnu.org/licenses/>.
66 This document describes libgccjit@footnote{http://gcc.gnu.org/wiki/JIT}, an API
67 for embedding GCC inside programs and libraries.
69 Note that libgccjit is currently of "Alpha" quality;
70 the APIs are not yet set in stone, and they shouldn't be used in
71 production yet.
73 There are actually two APIs for the library:
76 @itemize *
78 @item 
79 a pure C API: @code{libgccjit.h}
81 @item 
82 a C++ wrapper API: @code{libgccjit++.h}.  This is a collection of "thin"
83 wrapper classes around the C API, to save typing.
84 @end itemize
86 Contents:
88 @c Copyright (C) 2014 Free Software Foundation, Inc.
89 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
90 @c 
91 @c This is free software: you can redistribute it and/or modify it
92 @c under the terms of the GNU General Public License as published by
93 @c the Free Software Foundation, either version 3 of the License, or
94 @c (at your option) any later version.
95 @c 
96 @c This program is distributed in the hope that it will be useful, but
97 @c WITHOUT ANY WARRANTY; without even the implied warranty of
98 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
99 @c General Public License for more details.
100 @c 
101 @c You should have received a copy of the GNU General Public License
102 @c along with this program.  If not, see
103 @c <http://www.gnu.org/licenses/>.
105 @menu
106 * Tutorial:: 
107 * Topic Reference:: 
108 * C++ bindings for libgccjit:: 
109 * Internals:: 
110 * Indices and tables:: 
111 * Index:: 
113 @detailmenu
114  --- The Detailed Node Listing ---
116 Tutorial
118 * Tutorial part 1; "Hello world": Tutorial part 1 "Hello world". 
119 * Tutorial part 2; Creating a trivial machine code function: Tutorial part 2 Creating a trivial machine code function. 
120 * Tutorial part 3; Loops and variables: Tutorial part 3 Loops and variables. 
121 * Tutorial part 4; Adding JIT-compilation to a toy interpreter: Tutorial part 4 Adding JIT-compilation to a toy interpreter. 
123 Tutorial part 2: Creating a trivial machine code function
125 * Error-handling:: 
126 * Options:: 
127 * Full example:: 
129 Tutorial part 3: Loops and variables
131 * Expressions; lvalues and rvalues: Expressions lvalues and rvalues. 
132 * Control flow:: 
133 * Visualizing the control flow graph:: 
134 * Full example: Full example<2>. 
136 Tutorial part 4: Adding JIT-compilation to a toy interpreter
138 * Our toy interpreter:: 
139 * Compiling to machine code:: 
140 * Setting things up:: 
141 * Populating the function:: 
142 * Verifying the control flow graph:: 
143 * Compiling the context:: 
144 * Single-stepping through the generated code:: 
145 * Examining the generated code:: 
146 * Putting it all together:: 
147 * Behind the curtain; How does our code get optimized?: Behind the curtain How does our code get optimized?. 
149 Behind the curtain: How does our code get optimized?
151 * Optimizing away stack manipulation:: 
152 * Elimination of tail recursion:: 
154 Topic Reference
156 * Compilation contexts:: 
157 * Objects:: 
158 * Types:: 
159 * Expressions:: 
160 * Creating and using functions:: 
161 * Source Locations:: 
162 * Compilation results:: 
164 Compilation contexts
166 * Lifetime-management:: 
167 * Thread-safety:: 
168 * Error-handling: Error-handling<2>. 
169 * Debugging:: 
170 * Options: Options<2>. 
172 Options
174 * String Options:: 
175 * Boolean options:: 
176 * Integer options:: 
178 Types
180 * Standard types:: 
181 * Pointers@comma{} const@comma{} and volatile: Pointers const and volatile. 
182 * Structures and unions:: 
184 Expressions
186 * Rvalues:: 
187 * Lvalues:: 
188 * Working with pointers@comma{} structs and unions: Working with pointers structs and unions. 
190 Rvalues
192 * Simple expressions:: 
193 * Unary Operations:: 
194 * Binary Operations:: 
195 * Comparisons:: 
196 * Function calls:: 
197 * Type-coercion:: 
199 Lvalues
201 * Global variables:: 
203 Creating and using functions
205 * Params:: 
206 * Functions:: 
207 * Blocks:: 
208 * Statements:: 
210 Source Locations
212 * Faking it:: 
214 C++ bindings for libgccjit
216 * Tutorial: Tutorial<2>. 
217 * Topic Reference: Topic Reference<2>. 
219 Tutorial
221 * Tutorial part 1; "Hello world": Tutorial part 1 "Hello world"<2>. 
222 * Tutorial part 2; Creating a trivial machine code function: Tutorial part 2 Creating a trivial machine code function<2>. 
223 * Tutorial part 3; Loops and variables: Tutorial part 3 Loops and variables<2>. 
224 * Tutorial part 4; Adding JIT-compilation to a toy interpreter: Tutorial part 4 Adding JIT-compilation to a toy interpreter<2>. 
226 Tutorial part 2: Creating a trivial machine code function
228 * Options: Options<3>. 
229 * Full example: Full example<3>. 
231 Tutorial part 3: Loops and variables
233 * Expressions; lvalues and rvalues: Expressions lvalues and rvalues<2>. 
234 * Control flow: Control flow<2>. 
235 * Visualizing the control flow graph: Visualizing the control flow graph<2>. 
236 * Full example: Full example<4>. 
238 Tutorial part 4: Adding JIT-compilation to a toy interpreter
240 * Our toy interpreter: Our toy interpreter<2>. 
241 * Compiling to machine code: Compiling to machine code<2>. 
242 * Setting things up: Setting things up<2>. 
243 * Populating the function: Populating the function<2>. 
244 * Verifying the control flow graph: Verifying the control flow graph<2>. 
245 * Compiling the context: Compiling the context<2>. 
246 * Single-stepping through the generated code: Single-stepping through the generated code<2>. 
247 * Examining the generated code: Examining the generated code<2>. 
248 * Putting it all together: Putting it all together<2>. 
249 * Behind the curtain; How does our code get optimized?: Behind the curtain How does our code get optimized?<2>. 
251 Behind the curtain: How does our code get optimized?
253 * Optimizing away stack manipulation: Optimizing away stack manipulation<2>. 
254 * Elimination of tail recursion: Elimination of tail recursion<2>. 
256 Topic Reference
258 * Compilation contexts: Compilation contexts<2>. 
259 * Objects: Objects<2>. 
260 * Types: Types<2>. 
261 * Expressions: Expressions<2>. 
262 * Creating and using functions: Creating and using functions<2>. 
263 * Source Locations: Source Locations<2>. 
264 * Compilation results: Compilation results<2>. 
266 Compilation contexts
268 * Lifetime-management: Lifetime-management<2>. 
269 * Thread-safety: Thread-safety<2>. 
270 * Error-handling: Error-handling<3>. 
271 * Debugging: Debugging<2>. 
272 * Options: Options<4>. 
274 Options
276 * Boolean options: Boolean options<2>. 
277 * Integer options: Integer options<2>. 
279 Types
281 * Standard types: Standard types<2>. 
282 * Pointers@comma{} const@comma{} and volatile: Pointers const and volatile<2>. 
283 * Structures and unions: Structures and unions<2>. 
285 Expressions
287 * Rvalues: Rvalues<2>. 
288 * Lvalues: Lvalues<2>. 
289 * Working with pointers@comma{} structs and unions: Working with pointers structs and unions<2>. 
291 Rvalues
293 * Simple expressions: Simple expressions<2>. 
294 * Unary Operations: Unary Operations<2>. 
295 * Binary Operations: Binary Operations<2>. 
296 * Comparisons: Comparisons<2>. 
297 * Function calls: Function calls<2>. 
298 * Type-coercion: Type-coercion<2>. 
300 Lvalues
302 * Global variables: Global variables<2>. 
304 Creating and using functions
306 * Params: Params<2>. 
307 * Functions: Functions<2>. 
308 * Blocks: Blocks<2>. 
309 * Statements: Statements<2>. 
311 Source Locations
313 * Faking it: Faking it<2>. 
315 Internals
317 * Working on the JIT library:: 
318 * Running the test suite:: 
319 * Environment variables:: 
320 * Overview of code structure:: 
322 Running the test suite
324 * Running under valgrind:: 
326 @end detailmenu
327 @end menu
330 @node Tutorial,Topic Reference,Top,Top
331 @anchor{intro/index libgccjit}@anchor{1}@anchor{intro/index doc}@anchor{2}@anchor{intro/index tutorial}@anchor{3}
332 @chapter Tutorial
335 @c Copyright (C) 2014 Free Software Foundation, Inc.
336 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
337 @c 
338 @c This is free software: you can redistribute it and/or modify it
339 @c under the terms of the GNU General Public License as published by
340 @c the Free Software Foundation, either version 3 of the License, or
341 @c (at your option) any later version.
342 @c 
343 @c This program is distributed in the hope that it will be useful, but
344 @c WITHOUT ANY WARRANTY; without even the implied warranty of
345 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
346 @c General Public License for more details.
347 @c 
348 @c You should have received a copy of the GNU General Public License
349 @c along with this program.  If not, see
350 @c <http://www.gnu.org/licenses/>.
352 @menu
353 * Tutorial part 1; "Hello world": Tutorial part 1 "Hello world". 
354 * Tutorial part 2; Creating a trivial machine code function: Tutorial part 2 Creating a trivial machine code function. 
355 * Tutorial part 3; Loops and variables: Tutorial part 3 Loops and variables. 
356 * Tutorial part 4; Adding JIT-compilation to a toy interpreter: Tutorial part 4 Adding JIT-compilation to a toy interpreter. 
358 @end menu
360 @node Tutorial part 1 "Hello world",Tutorial part 2 Creating a trivial machine code function,,Tutorial
361 @anchor{intro/tutorial01 doc}@anchor{4}@anchor{intro/tutorial01 tutorial-part-1-hello-world}@anchor{5}
362 @section Tutorial part 1: "Hello world"
365 Before we look at the details of the API, let's look at building and
366 running programs that use the library.
368 Here's a toy "hello world" program that uses the library to synthesize
369 a call to @cite{printf} and uses it to write a message to stdout.
371 Don't worry about the content of the program for now; we'll cover
372 the details in later parts of this tutorial.
374 @quotation
376 @example
377 /* Smoketest example for libgccjit.so
378    Copyright (C) 2014 Free Software Foundation, Inc.
380 This file is part of GCC.
382 GCC is free software; you can redistribute it and/or modify it
383 under the terms of the GNU General Public License as published by
384 the Free Software Foundation; either version 3, or (at your option)
385 any later version.
387 GCC is distributed in the hope that it will be useful, but
388 WITHOUT ANY WARRANTY; without even the implied warranty of
389 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
390 General Public License for more details.
392 You should have received a copy of the GNU General Public License
393 along with GCC; see the file COPYING3.  If not see
394 <http://www.gnu.org/licenses/>.  */
396 #include <libgccjit.h>
398 #include <stdlib.h>
399 #include <stdio.h>
401 static void
402 create_code (gcc_jit_context *ctxt)
404   /* Let's try to inject the equivalent of:
405      void
406      greet (const char *name)
407      @{
408         printf ("hello %s\n", name);
409      @}
410   */
411   gcc_jit_type *void_type =
412     gcc_jit_context_get_type (ctxt, GCC_JIT_TYPE_VOID);
413   gcc_jit_type *const_char_ptr_type =
414     gcc_jit_context_get_type (ctxt, GCC_JIT_TYPE_CONST_CHAR_PTR);
415   gcc_jit_param *param_name =
416     gcc_jit_context_new_param (ctxt, NULL, const_char_ptr_type, "name");
417   gcc_jit_function *func =
418     gcc_jit_context_new_function (ctxt, NULL,
419                                   GCC_JIT_FUNCTION_EXPORTED,
420                                   void_type,
421                                   "greet",
422                                   1, &param_name,
423                                   0);
425   gcc_jit_param *param_format =
426     gcc_jit_context_new_param (ctxt, NULL, const_char_ptr_type, "format");
427   gcc_jit_function *printf_func =
428     gcc_jit_context_new_function (ctxt, NULL,
429                                   GCC_JIT_FUNCTION_IMPORTED,
430                                   gcc_jit_context_get_type (
431                                      ctxt, GCC_JIT_TYPE_INT),
432                                   "printf",
433                                   1, &param_format,
434                                   1);
435   gcc_jit_rvalue *args[2];
436   args[0] = gcc_jit_context_new_string_literal (ctxt, "hello %s\n");
437   args[1] = gcc_jit_param_as_rvalue (param_name);
439   gcc_jit_block *block = gcc_jit_function_new_block (func, NULL);
441   gcc_jit_block_add_eval (
442     block, NULL,
443     gcc_jit_context_new_call (ctxt,
444                               NULL,
445                               printf_func,
446                               2, args));
447   gcc_jit_block_end_with_void_return (block, NULL);
451 main (int argc, char **argv)
453   gcc_jit_context *ctxt;
454   gcc_jit_result *result;
456   /* Get a "context" object for working with the library.  */
457   ctxt = gcc_jit_context_acquire ();
458   if (!ctxt)
459     @{
460       fprintf (stderr, "NULL ctxt");
461       exit (1);
462     @}
464   /* Set some options on the context.
465      Let's see the code being generated, in assembler form.  */
466   gcc_jit_context_set_bool_option (
467     ctxt,
468     GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE,
469     0);
471   /* Populate the context.  */
472   create_code (ctxt);
474   /* Compile the code.  */
475   result = gcc_jit_context_compile (ctxt);
476   if (!result)
477     @{
478       fprintf (stderr, "NULL result");
479       exit (1);
480     @}
482   /* Extract the generated code from "result".  */
483   typedef void (*fn_type) (const char *);
484   fn_type greet =
485     (fn_type)gcc_jit_result_get_code (result, "greet");
486   if (!greet)
487     @{
488       fprintf (stderr, "NULL greet");
489       exit (1);
490     @}
492   /* Now call the generated function: */
493   greet ("world");
494   fflush (stdout);
496   gcc_jit_context_release (ctxt);
497   gcc_jit_result_release (result);
498   return 0;
501 @end example
503 @noindent
504 @end quotation
506 Copy the above to @cite{tut01-hello-world.c}.
508 Assuming you have the jit library installed, build the test program
509 using:
511 @example
512 $ gcc \
513     tut01-hello-world.c \
514     -o tut01-hello-world \
515     -lgccjit
516 @end example
518 @noindent
520 You should then be able to run the built program:
522 @example
523 $ ./tut01-hello-world
524 hello world
525 @end example
527 @noindent
529 @c Copyright (C) 2014 Free Software Foundation, Inc.
530 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
531 @c 
532 @c This is free software: you can redistribute it and/or modify it
533 @c under the terms of the GNU General Public License as published by
534 @c the Free Software Foundation, either version 3 of the License, or
535 @c (at your option) any later version.
536 @c 
537 @c This program is distributed in the hope that it will be useful, but
538 @c WITHOUT ANY WARRANTY; without even the implied warranty of
539 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
540 @c General Public License for more details.
541 @c 
542 @c You should have received a copy of the GNU General Public License
543 @c along with this program.  If not, see
544 @c <http://www.gnu.org/licenses/>.
546 @node Tutorial part 2 Creating a trivial machine code function,Tutorial part 3 Loops and variables,Tutorial part 1 "Hello world",Tutorial
547 @anchor{intro/tutorial02 doc}@anchor{6}@anchor{intro/tutorial02 tutorial-part-2-creating-a-trivial-machine-code-function}@anchor{7}
548 @section Tutorial part 2: Creating a trivial machine code function
551 Consider this C function:
553 @example
554 int square (int i)
556   return i * i;
558 @end example
560 @noindent
562 How can we construct this at run-time using libgccjit?
564 First we need to include the relevant header:
566 @example
567 #include <libgccjit.h>
568 @end example
570 @noindent
572 All state associated with compilation is associated with a
573 @pxref{8,,gcc_jit_context *}.
575 Create one using @pxref{9,,gcc_jit_context_acquire()}:
577 @example
578 gcc_jit_context *ctxt;
579 ctxt = gcc_jit_context_acquire ();
580 @end example
582 @noindent
584 The JIT library has a system of types.  It is statically-typed: every
585 expression is of a specific type, fixed at compile-time.  In our example,
586 all of the expressions are of the C @cite{int} type, so let's obtain this from
587 the context, as a @pxref{a,,gcc_jit_type *}, using
588 @pxref{b,,gcc_jit_context_get_type()}:
590 @example
591 gcc_jit_type *int_type =
592   gcc_jit_context_get_type (ctxt, GCC_JIT_TYPE_INT);
593 @end example
595 @noindent
597 @pxref{a,,gcc_jit_type *} is an example of a "contextual" object: every
598 entity in the API is associated with a @pxref{8,,gcc_jit_context *}.
600 Memory management is easy: all such "contextual" objects are automatically
601 cleaned up for you when the context is released, using
602 @pxref{c,,gcc_jit_context_release()}:
604 @example
605 gcc_jit_context_release (ctxt);
606 @end example
608 @noindent
610 so you don't need to manually track and cleanup all objects, just the
611 contexts.
613 Although the API is C-based, there is a form of class hierarchy, which
614 looks like this:
616 @example
617 +- gcc_jit_object
618     +- gcc_jit_location
619     +- gcc_jit_type
620        +- gcc_jit_struct
621     +- gcc_jit_field
622     +- gcc_jit_function
623     +- gcc_jit_block
624     +- gcc_jit_rvalue
625         +- gcc_jit_lvalue
626            +- gcc_jit_param
627 @end example
629 @noindent
631 There are casting methods for upcasting from subclasses to parent classes.
632 For example, @pxref{d,,gcc_jit_type_as_object()}:
634 @example
635 gcc_jit_object *obj = gcc_jit_type_as_object (int_type);
636 @end example
638 @noindent
640 One thing you can do with a @pxref{e,,gcc_jit_object *} is
641 to ask it for a human-readable description, using
642 @pxref{f,,gcc_jit_object_get_debug_string()}:
644 @example
645 printf ("obj: %s\n", gcc_jit_object_get_debug_string (obj));
646 @end example
648 @noindent
650 giving this text on stdout:
652 @example
653 obj: int
654 @end example
656 @noindent
658 This is invaluable when debugging.
660 Let's create the function.  To do so, we first need to construct
661 its single parameter, specifying its type and giving it a name,
662 using @pxref{10,,gcc_jit_context_new_param()}:
664 @example
665 gcc_jit_param *param_i =
666   gcc_jit_context_new_param (ctxt, NULL, int_type, "i");
667 @end example
669 @noindent
671 Now we can create the function, using
672 @pxref{11,,gcc_jit_context_new_function()}:
674 @example
675 gcc_jit_function *func =
676   gcc_jit_context_new_function (ctxt, NULL,
677                                 GCC_JIT_FUNCTION_EXPORTED,
678                                 int_type,
679                                 "square",
680                                 1, &param_i,
681                                 0);
682 @end example
684 @noindent
686 To define the code within the function, we must create basic blocks
687 containing statements.
689 Every basic block contains a list of statements, eventually terminated
690 by a statement that either returns, or jumps to another basic block.
692 Our function has no control-flow, so we just need one basic block:
694 @example
695 gcc_jit_block *block = gcc_jit_function_new_block (func, NULL);
696 @end example
698 @noindent
700 Our basic block is relatively simple: it immediately terminates by
701 returning the value of an expression.
703 We can build the expression using @pxref{12,,gcc_jit_context_new_binary_op()}:
705 @example
706 gcc_jit_rvalue *expr =
707   gcc_jit_context_new_binary_op (
708     ctxt, NULL,
709     GCC_JIT_BINARY_OP_MULT, int_type,
710     gcc_jit_param_as_rvalue (param_i),
711     gcc_jit_param_as_rvalue (param_i));
712 @end example
714 @noindent
716 A @pxref{13,,gcc_jit_rvalue *} is another example of a
717 @pxref{e,,gcc_jit_object *} subclass.  We can upcast it using
718 @pxref{14,,gcc_jit_rvalue_as_object()} and as before print it with
719 @pxref{f,,gcc_jit_object_get_debug_string()}.
721 @example
722 printf ("expr: %s\n",
723         gcc_jit_object_get_debug_string (
724           gcc_jit_rvalue_as_object (expr)));
725 @end example
727 @noindent
729 giving this output:
731 @example
732 expr: i * i
733 @end example
735 @noindent
737 Creating the expression in itself doesn't do anything; we have to add
738 this expression to a statement within the block.  In this case, we use it
739 to build a return statement, which terminates the basic block:
741 @example
742 gcc_jit_block_end_with_return (block, NULL, expr);
743 @end example
745 @noindent
747 OK, we've populated the context.  We can now compile it using
748 @pxref{15,,gcc_jit_context_compile()}:
750 @example
751 gcc_jit_result *result;
752 result = gcc_jit_context_compile (ctxt);
753 @end example
755 @noindent
757 and get a @pxref{16,,gcc_jit_result *}.
759 At this point we're done with the context; we can release it:
761 @example
762 gcc_jit_context_release (ctxt);
763 @end example
765 @noindent
767 We can now use @pxref{17,,gcc_jit_result_get_code()} to look up a specific
768 machine code routine within the result, in this case, the function we
769 created above.
771 @example
772 void *fn_ptr = gcc_jit_result_get_code (result, "square");
773 if (!fn_ptr)
774   @{
775     fprintf (stderr, "NULL fn_ptr");
776     goto error;
777   @}
778 @end example
780 @noindent
782 We can now cast the pointer to an appropriate function pointer type, and
783 then call it:
785 @example
786 typedef int (*fn_type) (int);
787 fn_type square = (fn_type)fn_ptr;
788 printf ("result: %d", square (5));
789 @end example
791 @noindent
793 @example
794 result: 25
795 @end example
797 @noindent
799 Once we're done with the code, we can release the result:
801 @example
802 gcc_jit_result_release (result);
803 @end example
805 @noindent
807 We can't call @code{square} anymore once we've released @code{result}.
809 @menu
810 * Error-handling:: 
811 * Options:: 
812 * Full example:: 
814 @end menu
816 @node Error-handling,Options,,Tutorial part 2 Creating a trivial machine code function
817 @anchor{intro/tutorial02 error-handling}@anchor{18}
818 @subsection Error-handling
821 Various kinds of errors are possible when using the API, such as
822 mismatched types in an assignment.  You can only compile and get code
823 from a context if no errors occur.
825 Errors are printed on stderr; they typically contain the name of the API
826 entrypoint where the error occurred, and pertinent information on the
827 problem:
829 @example
830 ./buggy-program: error: gcc_jit_block_add_assignment: mismatching types: assignment to i (type: int) from "hello world" (type: const char *)
831 @end example
833 @noindent
835 The API is designed to cope with errors without crashing, so you can get
836 away with having a single error-handling check in your code:
838 @example
839 void *fn_ptr = gcc_jit_result_get_code (result, "square");
840 if (!fn_ptr)
841   @{
842     fprintf (stderr, "NULL fn_ptr");
843     goto error;
844   @}
845 @end example
847 @noindent
849 For more information, see the @pxref{19,,error-handling guide}
850 within the Topic eference.
852 @node Options,Full example,Error-handling,Tutorial part 2 Creating a trivial machine code function
853 @anchor{intro/tutorial02 options}@anchor{1a}
854 @subsection Options
857 To get more information on what's going on, you can set debugging flags
858 on the context using @pxref{1b,,gcc_jit_context_set_bool_option()}.
860 @c (I'm deliberately not mentioning
861 @c :c:macro:`GCC_JIT_BOOL_OPTION_DUMP_INITIAL_TREE` here since I think
862 @c it's probably more of use to implementors than to users)
864 Setting @pxref{1c,,GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE} will dump a
865 C-like representation to stderr when you compile (GCC's "GIMPLE"
866 representation):
868 @example
869 gcc_jit_context_set_bool_option (
870   ctxt,
871   GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE,
872   1);
873 result = gcc_jit_context_compile (ctxt);
874 @end example
876 @noindent
878 @example
879 square (signed int i)
881   signed int D.260;
883   entry:
884   D.260 = i * i;
885   return D.260;
887 @end example
889 @noindent
891 We can see the generated machine code in assembler form (on stderr) by
892 setting @pxref{1d,,GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE} on the context
893 before compiling:
895 @example
896 gcc_jit_context_set_bool_option (
897   ctxt,
898   GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE,
899   1);
900 result = gcc_jit_context_compile (ctxt);
901 @end example
903 @noindent
905 @example
906       .file   "fake.c"
907       .text
908       .globl  square
909       .type   square, @@function
910 square:
911 .LFB6:
912       .cfi_startproc
913       pushq   %rbp
914       .cfi_def_cfa_offset 16
915       .cfi_offset 6, -16
916       movq    %rsp, %rbp
917       .cfi_def_cfa_register 6
918       movl    %edi, -4(%rbp)
919 .L14:
920       movl    -4(%rbp), %eax
921       imull   -4(%rbp), %eax
922       popq    %rbp
923       .cfi_def_cfa 7, 8
924       ret
925       .cfi_endproc
926 .LFE6:
927       .size   square, .-square
928       .ident  "GCC: (GNU) 4.9.0 20131023 (Red Hat 0.2-0.5.1920c315ff984892399893b380305ab36e07b455.fc20)"
929       .section       .note.GNU-stack,"",@@progbits
930 @end example
932 @noindent
934 By default, no optimizations are performed, the equivalent of GCC's
935 @cite{-O0} option.  We can turn things up to e.g. @cite{-O3} by calling
936 @pxref{1e,,gcc_jit_context_set_int_option()} with
937 @pxref{1f,,GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL}:
939 @example
940 gcc_jit_context_set_int_option (
941   ctxt,
942   GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL,
943   3);
944 @end example
946 @noindent
948 @example
949       .file   "fake.c"
950       .text
951       .p2align 4,,15
952       .globl  square
953       .type   square, @@function
954 square:
955 .LFB7:
956       .cfi_startproc
957 .L16:
958       movl    %edi, %eax
959       imull   %edi, %eax
960       ret
961       .cfi_endproc
962 .LFE7:
963       .size   square, .-square
964       .ident  "GCC: (GNU) 4.9.0 20131023 (Red Hat 0.2-0.5.1920c315ff984892399893b380305ab36e07b455.fc20)"
965       .section        .note.GNU-stack,"",@@progbits
966 @end example
968 @noindent
970 Naturally this has only a small effect on such a trivial function.
972 @node Full example,,Options,Tutorial part 2 Creating a trivial machine code function
973 @anchor{intro/tutorial02 full-example}@anchor{20}
974 @subsection Full example
977 Here's what the above looks like as a complete program:
979 @quotation
981 @example
982 /* Usage example for libgccjit.so
983    Copyright (C) 2014 Free Software Foundation, Inc.
985 This file is part of GCC.
987 GCC is free software; you can redistribute it and/or modify it
988 under the terms of the GNU General Public License as published by
989 the Free Software Foundation; either version 3, or (at your option)
990 any later version.
992 GCC is distributed in the hope that it will be useful, but
993 WITHOUT ANY WARRANTY; without even the implied warranty of
994 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
995 General Public License for more details.
997 You should have received a copy of the GNU General Public License
998 along with GCC; see the file COPYING3.  If not see
999 <http://www.gnu.org/licenses/>.  */
1001 #include <libgccjit.h>
1003 #include <stdlib.h>
1004 #include <stdio.h>
1006 void
1007 create_code (gcc_jit_context *ctxt)
1009   /* Let's try to inject the equivalent of:
1011       int square (int i)
1012       @{
1013         return i * i;
1014       @}
1015   */
1016   gcc_jit_type *int_type =
1017     gcc_jit_context_get_type (ctxt, GCC_JIT_TYPE_INT);
1018   gcc_jit_param *param_i =
1019     gcc_jit_context_new_param (ctxt, NULL, int_type, "i");
1020   gcc_jit_function *func =
1021     gcc_jit_context_new_function (ctxt, NULL,
1022                                   GCC_JIT_FUNCTION_EXPORTED,
1023                                   int_type,
1024                                   "square",
1025                                   1, &param_i,
1026                                   0);
1028   gcc_jit_block *block = gcc_jit_function_new_block (func, NULL);
1030   gcc_jit_rvalue *expr =
1031     gcc_jit_context_new_binary_op (
1032       ctxt, NULL,
1033       GCC_JIT_BINARY_OP_MULT, int_type,
1034       gcc_jit_param_as_rvalue (param_i),
1035       gcc_jit_param_as_rvalue (param_i));
1037    gcc_jit_block_end_with_return (block, NULL, expr);
1041 main (int argc, char **argv)
1043   gcc_jit_context *ctxt = NULL;
1044   gcc_jit_result *result = NULL;
1046   /* Get a "context" object for working with the library.  */
1047   ctxt = gcc_jit_context_acquire ();
1048   if (!ctxt)
1049     @{
1050       fprintf (stderr, "NULL ctxt");
1051       goto error;
1052     @}
1054   /* Set some options on the context.
1055      Let's see the code being generated, in assembler form.  */
1056   gcc_jit_context_set_bool_option (
1057     ctxt,
1058     GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE,
1059     0);
1061   /* Populate the context.  */
1062   create_code (ctxt);
1064   /* Compile the code.  */
1065   result = gcc_jit_context_compile (ctxt);
1066   if (!result)
1067     @{
1068       fprintf (stderr, "NULL result");
1069       goto error;
1070     @}
1072   /* We're done with the context; we can release it: */
1073   gcc_jit_context_release (ctxt);
1074   ctxt = NULL;
1076   /* Extract the generated code from "result".  */
1077   void *fn_ptr = gcc_jit_result_get_code (result, "square");
1078   if (!fn_ptr)
1079      @{
1080        fprintf (stderr, "NULL fn_ptr");
1081        goto error;
1082      @}
1084   typedef int (*fn_type) (int);
1085   fn_type square = (fn_type)fn_ptr;
1086   printf ("result: %d\n", square (5));
1088  error:
1089   if (ctxt)
1090     gcc_jit_context_release (ctxt);
1091   if (result)
1092     gcc_jit_result_release (result);
1093   return 0;
1096 @end example
1098 @noindent
1099 @end quotation
1101 Building and running it:
1103 @example
1104 $ gcc \
1105     tut02-square.c \
1106     -o tut02-square \
1107     -lgccjit
1109 # Run the built program:
1110 $ ./tut02-square
1111 result: 25
1112 @end example
1114 @noindent
1116 @c Copyright (C) 2014 Free Software Foundation, Inc.
1117 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
1118 @c 
1119 @c This is free software: you can redistribute it and/or modify it
1120 @c under the terms of the GNU General Public License as published by
1121 @c the Free Software Foundation, either version 3 of the License, or
1122 @c (at your option) any later version.
1123 @c 
1124 @c This program is distributed in the hope that it will be useful, but
1125 @c WITHOUT ANY WARRANTY; without even the implied warranty of
1126 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
1127 @c General Public License for more details.
1128 @c 
1129 @c You should have received a copy of the GNU General Public License
1130 @c along with this program.  If not, see
1131 @c <http://www.gnu.org/licenses/>.
1133 @node Tutorial part 3 Loops and variables,Tutorial part 4 Adding JIT-compilation to a toy interpreter,Tutorial part 2 Creating a trivial machine code function,Tutorial
1134 @anchor{intro/tutorial03 tutorial-part-3-loops-and-variables}@anchor{21}@anchor{intro/tutorial03 doc}@anchor{22}
1135 @section Tutorial part 3: Loops and variables
1138 Consider this C function:
1140 @quotation
1142 @example
1143 int loop_test (int n)
1145   int sum = 0;
1146   for (int i = 0; i < n; i++)
1147     sum += i * i;
1148   return sum;
1150 @end example
1152 @noindent
1153 @end quotation
1155 This example demonstrates some more features of libgccjit, with local
1156 variables and a loop.
1158 To break this down into libgccjit terms, it's usually easier to reword
1159 the @cite{for} loop as a @cite{while} loop, giving:
1161 @quotation
1163 @example
1164 int loop_test (int n)
1166   int sum = 0;
1167   int i = 0;
1168   while (i < n)
1169   @{
1170     sum += i * i;
1171     i++;
1172   @}
1173   return sum;
1175 @end example
1177 @noindent
1178 @end quotation
1180 Here's what the final control flow graph will look like:
1182 @quotation
1185 @float Figure
1187 @image{sum-of-squares,,,image of a control flow graph,png}
1189 @end float
1191 @end quotation
1193 As before, we include the libgccjit header and make a
1194 @pxref{8,,gcc_jit_context *}.
1196 @example
1197 #include <libgccjit.h>
1199 void test (void)
1201   gcc_jit_context *ctxt;
1202   ctxt = gcc_jit_context_acquire ();
1203 @end example
1205 @noindent
1207 The function works with the C @cite{int} type:
1209 @example
1210 gcc_jit_type *the_type =
1211   gcc_jit_context_get_type (ctxt, GCC_JIT_TYPE_INT);
1212 gcc_jit_type *return_type = the_type;
1213 @end example
1215 @noindent
1217 though we could equally well make it work on, say, @cite{double}:
1219 @example
1220 gcc_jit_type *the_type =
1221   gcc_jit_context_get_type (ctxt, GCC_JIT_TYPE_DOUBLE);
1222 @end example
1224 @noindent
1226 Let's build the function:
1228 @example
1229 gcc_jit_param *n =
1230   gcc_jit_context_new_param (ctxt, NULL, the_type, "n");
1231 gcc_jit_param *params[1] = @{n@};
1232 gcc_jit_function *func =
1233   gcc_jit_context_new_function (ctxt, NULL,
1234                                 GCC_JIT_FUNCTION_EXPORTED,
1235                                 return_type,
1236                                 "loop_test",
1237                                 1, params, 0);
1238 @end example
1240 @noindent
1242 @menu
1243 * Expressions; lvalues and rvalues: Expressions lvalues and rvalues. 
1244 * Control flow:: 
1245 * Visualizing the control flow graph:: 
1246 * Full example: Full example<2>. 
1248 @end menu
1250 @node Expressions lvalues and rvalues,Control flow,,Tutorial part 3 Loops and variables
1251 @anchor{intro/tutorial03 expressions-lvalues-and-rvalues}@anchor{23}
1252 @subsection Expressions: lvalues and rvalues
1255 The base class of expression is the @pxref{13,,gcc_jit_rvalue *},
1256 representing an expression that can be on the @emph{right}-hand side of
1257 an assignment: a value that can be computed somehow, and assigned
1258 @emph{to} a storage area (such as a variable).  It has a specific
1259 @pxref{a,,gcc_jit_type *}.
1261 Anothe important class is @pxref{24,,gcc_jit_lvalue *}.
1262 A @pxref{24,,gcc_jit_lvalue *}. is something that can of the @emph{left}-hand
1263 side of an assignment: a storage area (such as a variable).
1265 In other words, every assignment can be thought of as:
1267 @example
1268 LVALUE = RVALUE;
1269 @end example
1271 @noindent
1273 Note that @pxref{24,,gcc_jit_lvalue *} is a subclass of
1274 @pxref{13,,gcc_jit_rvalue *}, where in an assignment of the form:
1276 @example
1277 LVALUE_A = LVALUE_B;
1278 @end example
1280 @noindent
1282 the @cite{LVALUE_B} implies reading the current value of that storage
1283 area, assigning it into the @cite{LVALUE_A}.
1285 So far the only expressions we've seen are @cite{i * i}:
1287 @example
1288 gcc_jit_rvalue *expr =
1289   gcc_jit_context_new_binary_op (
1290     ctxt, NULL,
1291     GCC_JIT_BINARY_OP_MULT, int_type,
1292     gcc_jit_param_as_rvalue (param_i),
1293     gcc_jit_param_as_rvalue (param_i));
1294 @end example
1296 @noindent
1298 which is a @pxref{13,,gcc_jit_rvalue *}, and the various function
1299 parameters: @cite{param_i} and @cite{param_n}, instances of
1300 @pxref{25,,gcc_jit_param *}, which is a subclass of
1301 @pxref{24,,gcc_jit_lvalue *} (and, in turn, of @pxref{13,,gcc_jit_rvalue *}):
1302 we can both read from and write to function parameters within the
1303 body of a function.
1305 Our new example has a couple of local variables.  We create them by
1306 calling @pxref{26,,gcc_jit_function_new_local()}, supplying a type and a
1307 name:
1309 @example
1310 /* Build locals:  */
1311 gcc_jit_lvalue *i =
1312   gcc_jit_function_new_local (func, NULL, the_type, "i");
1313 gcc_jit_lvalue *sum =
1314   gcc_jit_function_new_local (func, NULL, the_type, "sum");
1315 @end example
1317 @noindent
1319 These are instances of @pxref{24,,gcc_jit_lvalue *} - they can be read from
1320 and written to.
1322 Note that there is no precanned way to create @emph{and} initialize a variable
1323 like in C:
1325 @example
1326 int i = 0;
1327 @end example
1329 @noindent
1331 Instead, having added the local to the function, we have to separately add
1332 an assignment of @cite{0} to @cite{local_i} at the beginning of the function.
1334 @node Control flow,Visualizing the control flow graph,Expressions lvalues and rvalues,Tutorial part 3 Loops and variables
1335 @anchor{intro/tutorial03 control-flow}@anchor{27}
1336 @subsection Control flow
1339 This function has a loop, so we need to build some basic blocks to
1340 handle the control flow.  In this case, we need 4 blocks:
1343 @enumerate 
1345 @item 
1346 before the loop (initializing the locals)
1348 @item 
1349 the conditional at the top of the loop (comparing @cite{i < n})
1351 @item 
1352 the body of the loop
1354 @item 
1355 after the loop terminates (@cite{return sum})
1356 @end enumerate
1358 so we create these as @pxref{28,,gcc_jit_block *} instances within the
1359 @pxref{29,,gcc_jit_function *}:
1361 @example
1362 gcc_jit_block *b_initial =
1363   gcc_jit_function_new_block (func, "initial");
1364 gcc_jit_block *b_loop_cond =
1365   gcc_jit_function_new_block (func, "loop_cond");
1366 gcc_jit_block *b_loop_body =
1367   gcc_jit_function_new_block (func, "loop_body");
1368 gcc_jit_block *b_after_loop =
1369   gcc_jit_function_new_block (func, "after_loop");
1370 @end example
1372 @noindent
1374 We now populate each block with statements.
1376 The entry block @cite{b_initial} consists of initializations followed by a jump
1377 to the conditional.  We assign @cite{0} to @cite{i} and to @cite{sum}, using
1378 @pxref{2a,,gcc_jit_block_add_assignment()} to add
1379 an assignment statement, and using @pxref{2b,,gcc_jit_context_zero()} to get
1380 the constant value @cite{0} for the relevant type for the right-hand side of
1381 the assignment:
1383 @example
1384 /* sum = 0; */
1385 gcc_jit_block_add_assignment (
1386   b_initial, NULL,
1387   sum,
1388   gcc_jit_context_zero (ctxt, the_type));
1390 /* i = 0; */
1391 gcc_jit_block_add_assignment (
1392   b_initial, NULL,
1393   i,
1394   gcc_jit_context_zero (ctxt, the_type));
1395 @end example
1397 @noindent
1399 We can then terminate the entry block by jumping to the conditional:
1401 @example
1402 gcc_jit_block_end_with_jump (b_initial, NULL, b_loop_cond);
1403 @end example
1405 @noindent
1407 The conditional block is equivalent to the line @cite{while (i < n)} from our
1408 C example. It contains a single statement: a conditional, which jumps to
1409 one of two destination blocks depending on a boolean
1410 @pxref{13,,gcc_jit_rvalue *}, in this case the comparison of @cite{i} and @cite{n}.
1411 We build the comparison using @pxref{2c,,gcc_jit_context_new_comparison()}:
1413 @example
1414 gcc_jit_rvalue *guard =
1415   gcc_jit_context_new_comparison (
1416     ctxt, NULL,
1417     GCC_JIT_COMPARISON_GE,
1418     gcc_jit_lvalue_as_rvalue (i),
1419     gcc_jit_param_as_rvalue (n));
1420 @end example
1422 @noindent
1424 and can then use this to add @cite{b_loop_cond}'s sole statement, via
1425 @pxref{2d,,gcc_jit_block_end_with_conditional()}:
1427 @example
1428 gcc_jit_block_end_with_conditional (b_loop_cond, NULL, guard);
1429 @end example
1431 @noindent
1433 Next, we populate the body of the loop.
1435 The C statement @cite{sum += i * i;} is an assignment operation, where an
1436 lvalue is modified "in-place".  We use
1437 @pxref{2e,,gcc_jit_block_add_assignment_op()} to handle these operations:
1439 @example
1440 /* sum += i * i */
1441 gcc_jit_block_add_assignment_op (
1442   b_loop_body, NULL,
1443   sum,
1444   GCC_JIT_BINARY_OP_PLUS,
1445   gcc_jit_context_new_binary_op (
1446     ctxt, NULL,
1447     GCC_JIT_BINARY_OP_MULT, the_type,
1448     gcc_jit_lvalue_as_rvalue (i),
1449     gcc_jit_lvalue_as_rvalue (i)));
1450 @end example
1452 @noindent
1454 The @cite{i++} can be thought of as @cite{i += 1}, and can thus be handled in
1455 a similar way.  We use @pxref{2f,,gcc_jit_context_one()} to get the constant
1456 value @cite{1} (for the relevant type) for the right-hand side
1457 of the assignment.
1459 @example
1460 /* i++ */
1461 gcc_jit_block_add_assignment_op (
1462   b_loop_body, NULL,
1463   i,
1464   GCC_JIT_BINARY_OP_PLUS,
1465   gcc_jit_context_one (ctxt, the_type));
1466 @end example
1468 @noindent
1470 @cartouche
1471 @quotation Note 
1472 For numeric constants other than 0 or 1, we could use
1473 @pxref{30,,gcc_jit_context_new_rvalue_from_int()} and
1474 @pxref{31,,gcc_jit_context_new_rvalue_from_double()}.
1475 @end quotation
1476 @end cartouche
1478 The loop body completes by jumping back to the conditional:
1480 @example
1481 gcc_jit_block_end_with_jump (b_loop_body, NULL, b_loop_cond);
1482 @end example
1484 @noindent
1486 Finally, we populate the @cite{b_after_loop} block, reached when the loop
1487 conditional is false.  We want to generate the equivalent of:
1489 @example
1490 return sum;
1491 @end example
1493 @noindent
1495 so the block is just one statement:
1497 @example
1498 /* return sum */
1499 gcc_jit_block_end_with_return (
1500   b_after_loop,
1501   NULL,
1502   gcc_jit_lvalue_as_rvalue (sum));
1503 @end example
1505 @noindent
1507 @cartouche
1508 @quotation Note 
1509 You can intermingle block creation with statement creation,
1510 but given that the terminator statements generally include references
1511 to other blocks, I find it's clearer to create all the blocks,
1512 @emph{then} all the statements.
1513 @end quotation
1514 @end cartouche
1516 We've finished populating the function.  As before, we can now compile it
1517 to machine code:
1519 @example
1520 gcc_jit_result *result;
1521 result = gcc_jit_context_compile (ctxt);
1523 typedef int (*loop_test_fn_type) (int);
1524 loop_test_fn_type loop_test =
1525  (loop_test_fn_type)gcc_jit_result_get_code (result, "loop_test");
1526 if (!loop_test)
1527   goto error;
1528 printf ("result: %d", loop_test (10));
1529 @end example
1531 @noindent
1533 @example
1534 result: 285
1535 @end example
1537 @noindent
1539 @node Visualizing the control flow graph,Full example<2>,Control flow,Tutorial part 3 Loops and variables
1540 @anchor{intro/tutorial03 visualizing-the-control-flow-graph}@anchor{32}
1541 @subsection Visualizing the control flow graph
1544 You can see the control flow graph of a function using
1545 @pxref{33,,gcc_jit_function_dump_to_dot()}:
1547 @example
1548 gcc_jit_function_dump_to_dot (func, "/tmp/sum-of-squares.dot");
1549 @end example
1551 @noindent
1553 giving a .dot file in GraphViz format.
1555 You can convert this to an image using @cite{dot}:
1557 @example
1558 $ dot -Tpng /tmp/sum-of-squares.dot -o /tmp/sum-of-squares.png
1559 @end example
1561 @noindent
1563 or use a viewer (my preferred one is xdot.py; see
1564 @indicateurl{https://github.com/jrfonseca/xdot.py}; on Fedora you can
1565 install it with @cite{yum install python-xdot}):
1567 @quotation
1570 @float Figure
1572 @image{sum-of-squares,,,image of a control flow graph,png}
1574 @end float
1576 @end quotation
1578 @node Full example<2>,,Visualizing the control flow graph,Tutorial part 3 Loops and variables
1579 @anchor{intro/tutorial03 full-example}@anchor{34}
1580 @subsection Full example
1583 @quotation
1585 @example
1586 /* Usage example for libgccjit.so
1587    Copyright (C) 2014 Free Software Foundation, Inc.
1589 This file is part of GCC.
1591 GCC is free software; you can redistribute it and/or modify it
1592 under the terms of the GNU General Public License as published by
1593 the Free Software Foundation; either version 3, or (at your option)
1594 any later version.
1596 GCC is distributed in the hope that it will be useful, but
1597 WITHOUT ANY WARRANTY; without even the implied warranty of
1598 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
1599 General Public License for more details.
1601 You should have received a copy of the GNU General Public License
1602 along with GCC; see the file COPYING3.  If not see
1603 <http://www.gnu.org/licenses/>.  */
1605 #include <libgccjit.h>
1607 #include <stdlib.h>
1608 #include <stdio.h>
1610 void
1611 create_code (gcc_jit_context *ctxt)
1613   /*
1614     Simple sum-of-squares, to test conditionals and looping
1616     int loop_test (int n)
1617     @{
1618       int i;
1619       int sum = 0;
1620       for (i = 0; i < n ; i ++)
1621       @{
1622         sum += i * i;
1623       @}
1624       return sum;
1625    */
1626   gcc_jit_type *the_type =
1627     gcc_jit_context_get_type (ctxt, GCC_JIT_TYPE_INT);
1628   gcc_jit_type *return_type = the_type;
1630   gcc_jit_param *n =
1631     gcc_jit_context_new_param (ctxt, NULL, the_type, "n");
1632   gcc_jit_param *params[1] = @{n@};
1633   gcc_jit_function *func =
1634     gcc_jit_context_new_function (ctxt, NULL,
1635                                   GCC_JIT_FUNCTION_EXPORTED,
1636                                   return_type,
1637                                   "loop_test",
1638                                   1, params, 0);
1640   /* Build locals:  */
1641   gcc_jit_lvalue *i =
1642     gcc_jit_function_new_local (func, NULL, the_type, "i");
1643   gcc_jit_lvalue *sum =
1644     gcc_jit_function_new_local (func, NULL, the_type, "sum");
1646   gcc_jit_block *b_initial =
1647     gcc_jit_function_new_block (func, "initial");
1648   gcc_jit_block *b_loop_cond =
1649     gcc_jit_function_new_block (func, "loop_cond");
1650   gcc_jit_block *b_loop_body =
1651     gcc_jit_function_new_block (func, "loop_body");
1652   gcc_jit_block *b_after_loop =
1653     gcc_jit_function_new_block (func, "after_loop");
1655   /* sum = 0; */
1656   gcc_jit_block_add_assignment (
1657     b_initial, NULL,
1658     sum,
1659     gcc_jit_context_zero (ctxt, the_type));
1661   /* i = 0; */
1662   gcc_jit_block_add_assignment (
1663     b_initial, NULL,
1664     i,
1665     gcc_jit_context_zero (ctxt, the_type));
1667   gcc_jit_block_end_with_jump (b_initial, NULL, b_loop_cond);
1669   /* if (i >= n) */
1670   gcc_jit_block_end_with_conditional (
1671     b_loop_cond, NULL,
1672     gcc_jit_context_new_comparison (
1673        ctxt, NULL,
1674        GCC_JIT_COMPARISON_GE,
1675        gcc_jit_lvalue_as_rvalue (i),
1676        gcc_jit_param_as_rvalue (n)),
1677     b_after_loop,
1678     b_loop_body);
1680   /* sum += i * i */
1681   gcc_jit_block_add_assignment_op (
1682     b_loop_body, NULL,
1683     sum,
1684     GCC_JIT_BINARY_OP_PLUS,
1685     gcc_jit_context_new_binary_op (
1686       ctxt, NULL,
1687       GCC_JIT_BINARY_OP_MULT, the_type,
1688       gcc_jit_lvalue_as_rvalue (i),
1689       gcc_jit_lvalue_as_rvalue (i)));
1691   /* i++ */
1692   gcc_jit_block_add_assignment_op (
1693     b_loop_body, NULL,
1694     i,
1695     GCC_JIT_BINARY_OP_PLUS,
1696     gcc_jit_context_one (ctxt, the_type));
1698   gcc_jit_block_end_with_jump (b_loop_body, NULL, b_loop_cond);
1700   /* return sum */
1701   gcc_jit_block_end_with_return (
1702     b_after_loop,
1703     NULL,
1704     gcc_jit_lvalue_as_rvalue (sum));
1708 main (int argc, char **argv)
1710   gcc_jit_context *ctxt = NULL;
1711   gcc_jit_result *result = NULL;
1713   /* Get a "context" object for working with the library.  */
1714   ctxt = gcc_jit_context_acquire ();
1715   if (!ctxt)
1716     @{
1717       fprintf (stderr, "NULL ctxt");
1718       goto error;
1719     @}
1721   /* Set some options on the context.
1722      Let's see the code being generated, in assembler form.  */
1723   gcc_jit_context_set_bool_option (
1724     ctxt,
1725     GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE,
1726     0);
1728   /* Populate the context.  */
1729   create_code (ctxt);
1731   /* Compile the code.  */
1732   result = gcc_jit_context_compile (ctxt);
1733   if (!result)
1734     @{
1735       fprintf (stderr, "NULL result");
1736       goto error;
1737     @}
1739   /* Extract the generated code from "result".  */
1740   typedef int (*loop_test_fn_type) (int);
1741   loop_test_fn_type loop_test =
1742     (loop_test_fn_type)gcc_jit_result_get_code (result, "loop_test");
1743   if (!loop_test)
1744     @{
1745       fprintf (stderr, "NULL loop_test");
1746       goto error;
1747     @}
1749   /* Run the generated code.  */
1750   int val = loop_test (10);
1751   printf("loop_test returned: %d\n", val);
1753  error:
1754   gcc_jit_context_release (ctxt);
1755   gcc_jit_result_release (result);
1756   return 0;
1759 @end example
1761 @noindent
1762 @end quotation
1764 Building and running it:
1766 @example
1767 $ gcc \
1768     tut03-sum-of-squares.c \
1769     -o tut03-sum-of-squares \
1770     -lgccjit
1772 # Run the built program:
1773 $ ./tut03-sum-of-squares
1774 loop_test returned: 285
1775 @end example
1777 @noindent
1779 @c Copyright (C) 2014 Free Software Foundation, Inc.
1780 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
1781 @c 
1782 @c This is free software: you can redistribute it and/or modify it
1783 @c under the terms of the GNU General Public License as published by
1784 @c the Free Software Foundation, either version 3 of the License, or
1785 @c (at your option) any later version.
1786 @c 
1787 @c This program is distributed in the hope that it will be useful, but
1788 @c WITHOUT ANY WARRANTY; without even the implied warranty of
1789 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
1790 @c General Public License for more details.
1791 @c 
1792 @c You should have received a copy of the GNU General Public License
1793 @c along with this program.  If not, see
1794 @c <http://www.gnu.org/licenses/>.
1796 @node Tutorial part 4 Adding JIT-compilation to a toy interpreter,,Tutorial part 3 Loops and variables,Tutorial
1797 @anchor{intro/tutorial04 tutorial-part-4-adding-jit-compilation-to-a-toy-interpreter}@anchor{35}@anchor{intro/tutorial04 doc}@anchor{36}
1798 @section Tutorial part 4: Adding JIT-compilation to a toy interpreter
1801 In this example we construct a "toy" interpreter, and add JIT-compilation
1802 to it.
1804 @menu
1805 * Our toy interpreter:: 
1806 * Compiling to machine code:: 
1807 * Setting things up:: 
1808 * Populating the function:: 
1809 * Verifying the control flow graph:: 
1810 * Compiling the context:: 
1811 * Single-stepping through the generated code:: 
1812 * Examining the generated code:: 
1813 * Putting it all together:: 
1814 * Behind the curtain; How does our code get optimized?: Behind the curtain How does our code get optimized?. 
1816 @end menu
1818 @node Our toy interpreter,Compiling to machine code,,Tutorial part 4 Adding JIT-compilation to a toy interpreter
1819 @anchor{intro/tutorial04 our-toy-interpreter}@anchor{37}
1820 @subsection Our toy interpreter
1823 It's a stack-based interpreter, and is intended as a (very simple) example
1824 of the kind of bytecode interpreter seen in dynamic languages such as
1825 Python, Ruby etc.
1827 For the sake of simplicity, our toy virtual machine is very limited:
1829 @quotation
1832 @itemize *
1834 @item 
1835 The only data type is @cite{int}
1837 @item 
1838 It can only work on one function at a time (so that the only
1839 function call that can be made is to recurse).
1841 @item 
1842 Functions can only take one parameter.
1844 @item 
1845 Functions have a stack of @cite{int} values.
1847 @item 
1848 We'll implement function call within the interpreter by calling a
1849 function in our implementation, rather than implementing our own
1850 frame stack.
1852 @item 
1853 The parser is only good enough to get the examples to work.
1854 @end itemize
1855 @end quotation
1857 Naturally, a real interpreter would be much more complicated that this.
1859 The following operations are supported:
1862 @multitable {xxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxx} 
1863 @headitem
1865 Operation
1867 @tab
1869 Meaning
1871 @tab
1873 Old Stack
1875 @tab
1877 New Stack
1879 @item
1883 @tab
1885 Duplicate top of stack.
1887 @tab
1889 @code{[..., x]}
1891 @tab
1893 @code{[..., x, x]}
1895 @item
1899 @tab
1901 Swap top two elements
1902 of stack.
1904 @tab
1906 @code{[..., x, y]}
1908 @tab
1910 @code{[..., y, x]}
1912 @item
1914 BINARY_ADD
1916 @tab
1918 Add the top two elements
1919 on the stack.
1921 @tab
1923 @code{[..., x, y]}
1925 @tab
1927 @code{[..., (x+y)]}
1929 @item
1931 BINARY_SUBTRACT
1933 @tab
1935 Likewise, but subtract.
1937 @tab
1939 @code{[..., x, y]}
1941 @tab
1943 @code{[..., (x-y)]}
1945 @item
1947 BINARY_MULT
1949 @tab
1951 Likewise, but multiply.
1953 @tab
1955 @code{[..., x, y]}
1957 @tab
1959 @code{[..., (x*y)]}
1961 @item
1963 BINARY_COMPARE_LT
1965 @tab
1967 Compare the top two
1968 elements on the stack
1969 and push a nonzero/zero
1970 if (x<y).
1972 @tab
1974 @code{[..., x, y]}
1976 @tab
1978 @code{[..., (x<y)]}
1980 @item
1982 RECURSE
1984 @tab
1986 Recurse, passing the top
1987 of the stack, and
1988 popping the result.
1990 @tab
1992 @code{[..., x]}
1994 @tab
1996 @code{[..., fn(x)]}
1998 @item
2000 RETURN
2002 @tab
2004 Return the top of the
2005 stack.
2007 @tab
2009 @code{[x]}
2011 @tab
2013 @code{[]}
2015 @item
2017 PUSH_CONST @cite{arg}
2019 @tab
2021 Push an int const.
2023 @tab
2025 @code{[...]}
2027 @tab
2029 @code{[..., arg]}
2031 @item
2033 JUMP_ABS_IF_TRUE @cite{arg}
2035 @tab
2037 Pop; if top of stack was
2038 nonzero, jump to
2039 @code{arg}.
2041 @tab
2043 @code{[..., x]}
2045 @tab
2047 @code{[...]}
2049 @end multitable
2052 Programs can be interpreted, disassembled, and compiled to machine code.
2054 The interpreter reads @code{.toy} scripts.  Here's what a simple recursive
2055 factorial program looks like, the script @code{factorial.toy}.
2056 The parser ignores lines beginning with a @cite{#}.
2058 @quotation
2060 @example
2061 # Simple recursive factorial implementation, roughly equivalent to:
2063 #  int factorial (int arg)
2064 #  @{
2065 #     if (arg < 2)
2066 #       return arg
2067 #     return arg * factorial (arg - 1)
2068 #  @}
2070 # Initial state:
2071 # stack: [arg]
2073 # 0:
2075 # stack: [arg, arg]
2077 # 1:
2078 PUSH_CONST 2
2079 # stack: [arg, arg, 2]
2081 # 2:
2082 BINARY_COMPARE_LT
2083 # stack: [arg, (arg < 2)]
2085 # 3:
2086 JUMP_ABS_IF_TRUE 9
2087 # stack: [arg]
2089 # 4:
2091 # stack: [arg, arg]
2093 # 5:
2094 PUSH_CONST 1
2095 # stack: [arg, arg, 1]
2097 # 6:
2098 BINARY_SUBTRACT
2099 # stack: [arg,  (arg - 1)
2101 # 7:
2102 RECURSE
2103 # stack: [arg, factorial(arg - 1)]
2105 # 8:
2106 BINARY_MULT
2107 # stack: [arg * factorial(arg - 1)]
2109 # 9:
2110 RETURN
2112 @end example
2114 @noindent
2115 @end quotation
2117 The interpreter is a simple infinite loop with a big @code{switch} statement
2118 based on what the next opcode is:
2120 @quotation
2122 @example
2124 static int
2125 toyvm_function_interpret (toyvm_function *fn, int arg, FILE *trace)
2127   toyvm_frame frame;
2128 #define PUSH(ARG) (toyvm_frame_push (&frame, (ARG)))
2129 #define POP(ARG) (toyvm_frame_pop (&frame))
2131   frame.frm_function = fn;
2132   frame.frm_pc = 0;
2133   frame.frm_cur_depth = 0;
2135   PUSH (arg);
2137   while (1)
2138     @{
2139       toyvm_op *op;
2140       int x, y;
2141       assert (frame.frm_pc < fn->fn_num_ops);
2142       op = &fn->fn_ops[frame.frm_pc++];
2144       if (trace)
2145         @{
2146           toyvm_frame_dump_stack (&frame, trace);
2147           toyvm_function_disassemble_op (fn, op, frame.frm_pc, trace);
2148         @}
2150       switch (op->op_opcode)
2151         @{
2152           /* Ops taking no operand.  */
2153         case DUP:
2154           x = POP ();
2155           PUSH (x);
2156           PUSH (x);
2157           break;
2159         case ROT:
2160           y = POP ();
2161           x = POP ();
2162           PUSH (y);
2163           PUSH (x);
2164           break;
2166         case BINARY_ADD:
2167           y = POP ();
2168           x = POP ();
2169           PUSH (x + y);
2170           break;
2172         case BINARY_SUBTRACT:
2173           y = POP ();
2174           x = POP ();
2175           PUSH (x - y);
2176           break;
2178         case BINARY_MULT:
2179           y = POP ();
2180           x = POP ();
2181           PUSH (x * y);
2182           break;
2184         case BINARY_COMPARE_LT:
2185           y = POP ();
2186           x = POP ();
2187           PUSH (x < y);
2188           break;
2190         case RECURSE:
2191           x = POP ();
2192           x = toyvm_function_interpret (fn, x, trace);
2193           PUSH (x);
2194           break;
2196         case RETURN:
2197           return POP ();
2199           /* Ops taking an operand.  */
2200         case PUSH_CONST:
2201           PUSH (op->op_operand);
2202           break;
2204         case JUMP_ABS_IF_TRUE:
2205           x = POP ();
2206           if (x)
2207             frame.frm_pc = op->op_operand;
2208           break;
2210         default:
2211           assert (0); /* unknown opcode */
2213         @} /* end of switch on opcode */
2214     @} /* end of while loop */
2216 #undef PUSH
2217 #undef POP
2221 @end example
2223 @noindent
2224 @end quotation
2226 @node Compiling to machine code,Setting things up,Our toy interpreter,Tutorial part 4 Adding JIT-compilation to a toy interpreter
2227 @anchor{intro/tutorial04 compiling-to-machine-code}@anchor{38}
2228 @subsection Compiling to machine code
2231 We want to generate machine code that can be cast to this type and
2232 then directly executed in-process:
2234 @quotation
2236 @example
2237 typedef int (*toyvm_compiled_code) (int);
2240 @end example
2242 @noindent
2243 @end quotation
2245 The lifetime of the code is tied to that of a @pxref{16,,gcc_jit_result *}.
2246 We'll handle this by bundling them up in a structure, so that we can
2247 clean them up together by calling @pxref{39,,gcc_jit_result_release()}:
2249 @quotation
2251 @example
2253 struct toyvm_compiled_function
2255   gcc_jit_result *cf_jit_result;
2256   toyvm_compiled_code cf_code;
2260 @end example
2262 @noindent
2263 @end quotation
2265 Our compiler isn't very sophisticated; it takes the implementation of
2266 each opcode above, and maps it directly to the operations supported by
2267 the libgccjit API.
2269 How should we handle the stack?  In theory we could calculate what the
2270 stack depth will be at each opcode, and optimize away the stack
2271 manipulation "by hand".  We'll see below that libgccjit is able to do
2272 this for us, so we'll implement stack manipulation
2273 in a direct way, by creating a @code{stack} array and @code{stack_depth}
2274 variables, local within the generated function, equivalent to this C code:
2276 @example
2277 int stack_depth;
2278 int stack[MAX_STACK_DEPTH];
2279 @end example
2281 @noindent
2283 We'll also have local variables @code{x} and @code{y} for use when implementing
2284 the opcodes, equivalent to this:
2286 @example
2287 int x;
2288 int y;
2289 @end example
2291 @noindent
2293 This means our compiler has the following state:
2295 @quotation
2297 @example
2299 struct compilation_state
2301   gcc_jit_context *ctxt;
2303   gcc_jit_type *int_type;
2304   gcc_jit_type *bool_type;
2305   gcc_jit_type *stack_type; /* int[MAX_STACK_DEPTH] */
2307   gcc_jit_rvalue *const_one;
2309   gcc_jit_function *fn;
2310   gcc_jit_param *param_arg;
2311   gcc_jit_lvalue *stack;
2312   gcc_jit_lvalue *stack_depth;
2313   gcc_jit_lvalue *x;
2314   gcc_jit_lvalue *y;
2316   gcc_jit_location *op_locs[MAX_OPS];
2317   gcc_jit_block *initial_block;
2318   gcc_jit_block *op_blocks[MAX_OPS];
2323 @end example
2325 @noindent
2326 @end quotation
2328 @node Setting things up,Populating the function,Compiling to machine code,Tutorial part 4 Adding JIT-compilation to a toy interpreter
2329 @anchor{intro/tutorial04 setting-things-up}@anchor{3a}
2330 @subsection Setting things up
2333 First we create our types:
2335 @quotation
2337 @example
2338   state.int_type =
2339     gcc_jit_context_get_type (state.ctxt, GCC_JIT_TYPE_INT);
2340   state.bool_type =
2341     gcc_jit_context_get_type (state.ctxt, GCC_JIT_TYPE_BOOL);
2342   state.stack_type =
2343     gcc_jit_context_new_array_type (state.ctxt, NULL,
2344                                     state.int_type, MAX_STACK_DEPTH);
2347 @end example
2349 @noindent
2350 @end quotation
2352 along with extracting a useful @cite{int} constant:
2354 @quotation
2356 @example
2357   state.const_one = gcc_jit_context_one (state.ctxt, state.int_type);
2360 @end example
2362 @noindent
2363 @end quotation
2365 We'll implement push and pop in terms of the @code{stack} array and
2366 @code{stack_depth}.  Here are helper functions for adding statements to
2367 a block, implementing pushing and popping values:
2369 @quotation
2371 @example
2373 static void
2374 add_push (compilation_state *state,
2375           gcc_jit_block *block,
2376           gcc_jit_rvalue *rvalue,
2377           gcc_jit_location *loc)
2379   /* stack[stack_depth] = RVALUE */
2380   gcc_jit_block_add_assignment (
2381     block,
2382     loc,
2383     /* stack[stack_depth] */
2384     gcc_jit_context_new_array_access (
2385       state->ctxt,
2386       loc,
2387       gcc_jit_lvalue_as_rvalue (state->stack),
2388       gcc_jit_lvalue_as_rvalue (state->stack_depth)),
2389     rvalue);
2391   /* "stack_depth++;".  */
2392   gcc_jit_block_add_assignment_op (
2393     block,
2394     loc,
2395     state->stack_depth,
2396     GCC_JIT_BINARY_OP_PLUS,
2397     state->const_one);
2400 static void
2401 add_pop (compilation_state *state,
2402          gcc_jit_block *block,
2403          gcc_jit_lvalue *lvalue,
2404          gcc_jit_location *loc)
2406   /* "--stack_depth;".  */
2407   gcc_jit_block_add_assignment_op (
2408     block,
2409     loc,
2410     state->stack_depth,
2411     GCC_JIT_BINARY_OP_MINUS,
2412     state->const_one);
2414   /* "LVALUE = stack[stack_depth];".  */
2415   gcc_jit_block_add_assignment (
2416     block,
2417     loc,
2418     lvalue,
2419     /* stack[stack_depth] */
2420     gcc_jit_lvalue_as_rvalue (
2421       gcc_jit_context_new_array_access (
2422         state->ctxt,
2423         loc,
2424         gcc_jit_lvalue_as_rvalue (state->stack),
2425         gcc_jit_lvalue_as_rvalue (state->stack_depth))));
2429 @end example
2431 @noindent
2432 @end quotation
2434 We will support single-stepping through the generated code in the
2435 debugger, so we need to create @pxref{3b,,gcc_jit_location} instances, one
2436 per operation in the source code.  These will reference the lines of
2437 e.g. @code{factorial.toy}.
2439 @quotation
2441 @example
2442   for (pc = 0; pc < fn->fn_num_ops; pc++)
2443     @{
2444       toyvm_op *op = &fn->fn_ops[pc];
2446       state.op_locs[pc] = gcc_jit_context_new_location (state.ctxt,
2447                                                         fn->fn_filename,
2448                                                         op->op_linenum,
2449                                                         0); /* column */
2450     @}
2453 @end example
2455 @noindent
2456 @end quotation
2458 Let's create the function itself.  As usual, we create its parameter
2459 first, then use the parameter to create the function:
2461 @quotation
2463 @example
2464   state.param_arg =
2465     gcc_jit_context_new_param (state.ctxt, state.op_locs[0],
2466                                state.int_type, "arg");
2467   state.fn =
2468     gcc_jit_context_new_function (state.ctxt,
2469                                   state.op_locs[0],
2470                                   GCC_JIT_FUNCTION_EXPORTED,
2471                                   state.int_type,
2472                                   funcname,
2473                                   1, &state.param_arg, 0);
2476 @end example
2478 @noindent
2479 @end quotation
2481 We create the locals within the function.
2483 @quotation
2485 @example
2486   state.stack =
2487     gcc_jit_function_new_local (state.fn, NULL,
2488                                 state.stack_type, "stack");
2489   state.stack_depth =
2490     gcc_jit_function_new_local (state.fn, NULL,
2491                                 state.int_type, "stack_depth");
2492   state.x =
2493     gcc_jit_function_new_local (state.fn, NULL,
2494                                 state.int_type, "x");
2495   state.y =
2496     gcc_jit_function_new_local (state.fn, NULL,
2497                                 state.int_type, "y");
2500 @end example
2502 @noindent
2503 @end quotation
2505 @node Populating the function,Verifying the control flow graph,Setting things up,Tutorial part 4 Adding JIT-compilation to a toy interpreter
2506 @anchor{intro/tutorial04 populating-the-function}@anchor{3c}
2507 @subsection Populating the function
2510 There's some one-time initialization, and the API treats the first block
2511 you create as the entrypoint of the function, so we need to create that
2512 block first:
2514 @quotation
2516 @example
2517   state.initial_block = gcc_jit_function_new_block (state.fn, "initial");
2520 @end example
2522 @noindent
2523 @end quotation
2525 We can now create blocks for each of the operations.  Most of these will
2526 be consolidated into larger blocks when the optimizer runs.
2528 @quotation
2530 @example
2531   for (pc = 0; pc < fn->fn_num_ops; pc++)
2532     @{
2533       char buf[16];
2534       sprintf (buf, "instr%i", pc);
2535       state.op_blocks[pc] = gcc_jit_function_new_block (state.fn, buf);
2536     @}
2539 @end example
2541 @noindent
2542 @end quotation
2544 Now that we have a block it can jump to when it's done, we can populate
2545 the initial block:
2547 @quotation
2549 @example
2551   /* "stack_depth = 0;".  */
2552   gcc_jit_block_add_assignment (
2553     state.initial_block,
2554     state.op_locs[0],
2555     state.stack_depth,
2556     gcc_jit_context_zero (state.ctxt, state.int_type));
2558   /* "PUSH (arg);".  */
2559   add_push (&state,
2560             state.initial_block,
2561             gcc_jit_param_as_rvalue (state.param_arg),
2562             state.op_locs[0]);
2564   /* ...and jump to insn 0.  */
2565   gcc_jit_block_end_with_jump (state.initial_block,
2566                                state.op_locs[0],
2567                                state.op_blocks[0]);
2570 @end example
2572 @noindent
2573 @end quotation
2575 We can now populate the blocks for the individual operations.  We loop
2576 through them, adding instructions to their blocks:
2578 @quotation
2580 @example
2581   for (pc = 0; pc < fn->fn_num_ops; pc++)
2582     @{
2583       gcc_jit_location *loc = state.op_locs[pc];
2585       gcc_jit_block *block = state.op_blocks[pc];
2586       gcc_jit_block *next_block = (pc < fn->fn_num_ops
2587                                    ? state.op_blocks[pc + 1]
2588                                    : NULL);
2590       toyvm_op *op;
2591       op = &fn->fn_ops[pc];
2594 @end example
2596 @noindent
2597 @end quotation
2599 We're going to have another big @code{switch} statement for implementing
2600 the opcodes, this time for compiling them, rather than interpreting
2601 them.  It's helpful to have macros for implementing push and pop, so that
2602 we can make the @code{switch} statement that's coming up look as much as
2603 possible like the one above within the interpreter:
2605 @example
2607 #define X_EQUALS_POP()\
2608       add_pop (&state, block, state.x, loc)
2609 #define Y_EQUALS_POP()\
2610       add_pop (&state, block, state.y, loc)
2611 #define PUSH_RVALUE(RVALUE)\
2612       add_push (&state, block, (RVALUE), loc)
2613 #define PUSH_X()\
2614       PUSH_RVALUE (gcc_jit_lvalue_as_rvalue (state.x))
2615 #define PUSH_Y() \
2616       PUSH_RVALUE (gcc_jit_lvalue_as_rvalue (state.y))
2619 @end example
2621 @noindent
2623 @cartouche
2624 @quotation Note 
2625 A particularly clever implementation would have an @emph{identical}
2626 @code{switch} statement shared by the interpreter and the compiler, with
2627 some preprocessor "magic".  We're not doing that here, for the sake
2628 of simplicity.
2629 @end quotation
2630 @end cartouche
2632 When I first implemented this compiler, I accidentally missed an edit
2633 when copying and pasting the @code{Y_EQUALS_POP} macro, so that popping the
2634 stack into @code{y} instead erroneously assigned it to @code{x}, leaving @code{y}
2635 uninitialized.
2637 To track this kind of thing down, we can use
2638 @pxref{3d,,gcc_jit_block_add_comment()} to add descriptive comments
2639 to the internal representation.  This is invaluable when looking through
2640 the generated IR for, say @code{factorial}:
2642 @quotation
2644 @example
2646       gcc_jit_block_add_comment (block, loc, opcode_names[op->op_opcode]);
2649 @end example
2651 @noindent
2652 @end quotation
2654 We can now write the big @code{switch} statement that implements the
2655 individual opcodes, populating the relevant block with statements:
2657 @quotation
2659 @example
2661       switch (op->op_opcode)
2662         @{
2663         case DUP:
2664           X_EQUALS_POP ();
2665           PUSH_X ();
2666           PUSH_X ();
2667           break;
2669         case ROT:
2670           Y_EQUALS_POP ();
2671           X_EQUALS_POP ();
2672           PUSH_Y ();
2673           PUSH_X ();
2674           break;
2676         case BINARY_ADD:
2677           Y_EQUALS_POP ();
2678           X_EQUALS_POP ();
2679           PUSH_RVALUE (
2680            gcc_jit_context_new_binary_op (
2681              state.ctxt,
2682              loc,
2683              GCC_JIT_BINARY_OP_PLUS,
2684              state.int_type,
2685              gcc_jit_lvalue_as_rvalue (state.x),
2686              gcc_jit_lvalue_as_rvalue (state.y)));
2687           break;
2689         case BINARY_SUBTRACT:
2690           Y_EQUALS_POP ();
2691           X_EQUALS_POP ();
2692           PUSH_RVALUE (
2693            gcc_jit_context_new_binary_op (
2694              state.ctxt,
2695              loc,
2696              GCC_JIT_BINARY_OP_MINUS,
2697              state.int_type,
2698              gcc_jit_lvalue_as_rvalue (state.x),
2699              gcc_jit_lvalue_as_rvalue (state.y)));
2700           break;
2702         case BINARY_MULT:
2703           Y_EQUALS_POP ();
2704           X_EQUALS_POP ();
2705           PUSH_RVALUE (
2706            gcc_jit_context_new_binary_op (
2707              state.ctxt,
2708              loc,
2709              GCC_JIT_BINARY_OP_MULT,
2710              state.int_type,
2711              gcc_jit_lvalue_as_rvalue (state.x),
2712              gcc_jit_lvalue_as_rvalue (state.y)));
2713           break;
2715         case BINARY_COMPARE_LT:
2716           Y_EQUALS_POP ();
2717           X_EQUALS_POP ();
2718           PUSH_RVALUE (
2719              /* cast of bool to int */
2720              gcc_jit_context_new_cast (
2721                state.ctxt,
2722                loc,
2723                /* (x < y) as a bool */
2724                gcc_jit_context_new_comparison (
2725                  state.ctxt,
2726                  loc,
2727                  GCC_JIT_COMPARISON_LT,
2728                  gcc_jit_lvalue_as_rvalue (state.x),
2729                  gcc_jit_lvalue_as_rvalue (state.y)),
2730                state.int_type));
2731           break;
2733         case RECURSE:
2734           @{
2735             X_EQUALS_POP ();
2736             gcc_jit_rvalue *arg = gcc_jit_lvalue_as_rvalue (state.x);
2737             PUSH_RVALUE (
2738               gcc_jit_context_new_call (
2739                 state.ctxt,
2740                 loc,
2741                 state.fn,
2742                 1, &arg));
2743             break;
2744           @}
2746         case RETURN:
2747           X_EQUALS_POP ();
2748           gcc_jit_block_end_with_return (
2749             block,
2750             loc,
2751             gcc_jit_lvalue_as_rvalue (state.x));
2752           break;
2754           /* Ops taking an operand.  */
2755         case PUSH_CONST:
2756           PUSH_RVALUE (
2757             gcc_jit_context_new_rvalue_from_int (
2758               state.ctxt,
2759               state.int_type,
2760               op->op_operand));
2761           break;
2763         case JUMP_ABS_IF_TRUE:
2764           X_EQUALS_POP ();
2765           gcc_jit_block_end_with_conditional (
2766             block,
2767             loc,
2768             /* "(bool)x".  */
2769             gcc_jit_context_new_cast (
2770               state.ctxt,
2771               loc,
2772               gcc_jit_lvalue_as_rvalue (state.x),
2773               state.bool_type),
2774             state.op_blocks[op->op_operand], /* on_true */
2775             next_block); /* on_false */
2776           break;
2778         default:
2779           assert(0);
2780         @} /* end of switch on opcode */
2783 @end example
2785 @noindent
2786 @end quotation
2788 Every block must be terminated, via a call to one of the
2789 @code{gcc_jit_block_end_with_} entrypoints.  This has been done for two
2790 of the opcodes, but we need to do it for the other ones, by jumping
2791 to the next block.
2793 @quotation
2795 @example
2796       if (op->op_opcode != JUMP_ABS_IF_TRUE
2797           && op->op_opcode != RETURN)
2798         gcc_jit_block_end_with_jump (
2799           block,
2800           loc,
2801           next_block);
2804 @end example
2806 @noindent
2807 @end quotation
2809 This is analogous to simply incrementing the program counter.
2811 @node Verifying the control flow graph,Compiling the context,Populating the function,Tutorial part 4 Adding JIT-compilation to a toy interpreter
2812 @anchor{intro/tutorial04 verifying-the-control-flow-graph}@anchor{3e}
2813 @subsection Verifying the control flow graph
2816 Having finished looping over the blocks, the context is complete.
2818 As before, we can verify that the control flow and statements are sane by
2819 using @pxref{33,,gcc_jit_function_dump_to_dot()}:
2821 @example
2822 gcc_jit_function_dump_to_dot (state.fn, "/tmp/factorial.dot");
2823 @end example
2825 @noindent
2827 and viewing the result.  Note how the label names, comments, and
2828 variable names show up in the dump, to make it easier to spot
2829 errors in our compiler.
2831 @quotation
2834 @float Figure
2836 @image{factorial,,,image of a control flow graph,png}
2838 @end float
2840 @end quotation
2842 @node Compiling the context,Single-stepping through the generated code,Verifying the control flow graph,Tutorial part 4 Adding JIT-compilation to a toy interpreter
2843 @anchor{intro/tutorial04 compiling-the-context}@anchor{3f}
2844 @subsection Compiling the context
2847 Having finished looping over the blocks and populating them with
2848 statements, the context is complete.
2850 We can now compile it, and extract machine code from the result:
2852 @quotation
2854 @example
2855   gcc_jit_result *jit_result = gcc_jit_context_compile (state.ctxt);
2856   gcc_jit_context_release (state.ctxt);
2858   toyvm_compiled_function *toyvm_result =
2859     (toyvm_compiled_function *)calloc (1, sizeof (toyvm_compiled_function));
2860   if (!toyvm_result)
2861     @{
2862       fprintf (stderr, "out of memory allocating toyvm_compiled_function\n");
2863       gcc_jit_result_release (jit_result);
2864       return NULL;
2865     @}
2867   toyvm_result->cf_jit_result = jit_result;
2868   toyvm_result->cf_code =
2869     (toyvm_compiled_code)gcc_jit_result_get_code (jit_result,
2870                                                   funcname);
2872   free (funcname);
2874   return toyvm_result;
2877 char test[1024];
2879 #define CHECK_NON_NULL(PTR) \
2880   do @{                                       \
2881     if ((PTR) != NULL)                       \
2882       @{                                      \
2883         pass ("%s: %s is non-null", test, #PTR); \
2884       @}                                      \
2885     else                                     \
2886       @{                                      \
2887         fail ("%s: %s is NULL", test, #PTR); \
2888         abort ();                            \
2889     @}                                        \
2890   @} while (0)
2892 #define CHECK_VALUE(ACTUAL, EXPECTED) \
2893   do @{                                       \
2894     if ((ACTUAL) == (EXPECTED))              \
2895       @{                                      \
2896         pass ("%s: actual: %s == expected: %s", test, #ACTUAL, #EXPECTED); \
2897       @}                                      \
2898     else                                     \
2899       @{                                        \
2900         fail ("%s: actual: %s != expected: %s", test, #ACTUAL, #EXPECTED); \
2901         fprintf (stderr, "incorrect value\n"); \
2902         abort ();                              \
2903     @}                                        \
2904   @} while (0)
2906 static void
2907 test_script (const char *scripts_dir, const char *script_name, int input,
2908              int expected_result)
2910   char *script_path;
2911   toyvm_function *fn;
2912   int interpreted_result;
2913   toyvm_compiled_function *compiled_fn;
2914   toyvm_compiled_code code;
2915   int compiled_result;
2917   snprintf (test, sizeof (test), "toyvm.c: %s", script_name);
2919   script_path = (char *)malloc (strlen (scripts_dir)
2920                                 + strlen (script_name) + 1);
2921   CHECK_NON_NULL (script_path);
2922   sprintf (script_path, "%s%s", scripts_dir, script_name);
2924   fn = toyvm_function_parse (script_path, script_name);
2925   CHECK_NON_NULL (fn);
2927   interpreted_result = toyvm_function_interpret (fn, input, NULL);
2928   CHECK_VALUE (interpreted_result, expected_result);
2930   compiled_fn = toyvm_function_compile (fn);
2931   CHECK_NON_NULL (compiled_fn);
2933   code = (toyvm_compiled_code)compiled_fn->cf_code;
2934   CHECK_NON_NULL (code);
2936   compiled_result = code (input);
2937   CHECK_VALUE (compiled_result, expected_result);
2939   gcc_jit_result_release (compiled_fn->cf_jit_result);
2940   free (compiled_fn);
2941   free (fn);
2942   free (script_path);
2945 #define PATH_TO_SCRIPTS  ("/jit/docs/examples/tut04-toyvm/")
2947 static void
2948 test_suite (void)
2950   const char *srcdir;
2951   char *scripts_dir;
2953   snprintf (test, sizeof (test), "toyvm.c");
2955   /* We need to locate the test scripts.
2956      Rely on "srcdir" being set in the environment.  */
2958   srcdir = getenv ("srcdir");
2959   CHECK_NON_NULL (srcdir);
2961   scripts_dir = (char *)malloc (strlen (srcdir) + strlen(PATH_TO_SCRIPTS)
2962                                 + 1);
2963   CHECK_NON_NULL (scripts_dir);
2964   sprintf (scripts_dir, "%s%s", srcdir, PATH_TO_SCRIPTS);
2966   test_script (scripts_dir, "factorial.toy", 10, 3628800);
2967   test_script (scripts_dir, "fibonacci.toy", 10, 55);
2969   free (scripts_dir);
2973 main (int argc, char **argv)
2975   const char *filename = NULL;
2976   toyvm_function *fn = NULL;
2978   /* If called with no args, assume we're being run by the test suite.  */
2979   if (argc < 3)
2980     @{
2981       test_suite ();
2982       return 0;
2983     @}
2985   if (argc != 3)
2986     @{
2987       fprintf (stdout,
2988         "%s FILENAME INPUT: Parse and run a .toy file\n",
2989         argv[0]);
2990       exit (1);
2991     @}
2993   filename = argv[1];
2994   fn = toyvm_function_parse (filename, filename);
2995   if (!fn)
2996     exit (1);
2998   if (0)
2999     toyvm_function_disassemble (fn, stdout);
3001   printf ("interpreter result: %d\n",
3002           toyvm_function_interpret (fn, atoi (argv[2]), NULL));
3004   /* JIT-compilation.  */
3005   toyvm_compiled_function *compiled_fn
3006     = toyvm_function_compile (fn);
3008   toyvm_compiled_code code = compiled_fn->cf_code;
3009   printf ("compiler result: %d\n",
3010           code (atoi (argv[2])));
3012   gcc_jit_result_release (compiled_fn->cf_jit_result);
3013   free (compiled_fn);
3015  return 0;
3018 @end example
3020 @noindent
3021 @end quotation
3023 We can now run the result:
3025 @quotation
3027 @example
3028   toyvm_compiled_function *compiled_fn
3029     = toyvm_function_compile (fn);
3031   toyvm_compiled_code code = compiled_fn->cf_code;
3032   printf ("compiler result: %d\n",
3033           code (atoi (argv[2])));
3035   gcc_jit_result_release (compiled_fn->cf_jit_result);
3036   free (compiled_fn);
3039 @end example
3041 @noindent
3042 @end quotation
3044 @node Single-stepping through the generated code,Examining the generated code,Compiling the context,Tutorial part 4 Adding JIT-compilation to a toy interpreter
3045 @anchor{intro/tutorial04 single-stepping-through-the-generated-code}@anchor{40}
3046 @subsection Single-stepping through the generated code
3049 It's possible to debug the generated code.  To do this we need to both:
3051 @quotation
3054 @itemize *
3056 @item 
3057 Set up source code locations for our statements, so that we can
3058 meaningfully step through the code.  We did this above by
3059 calling @pxref{41,,gcc_jit_context_new_location()} and using the
3060 results.
3062 @item 
3063 Enable the generation of debugging information, by setting
3064 @pxref{42,,GCC_JIT_BOOL_OPTION_DEBUGINFO} on the
3065 @pxref{8,,gcc_jit_context} via
3066 @pxref{1b,,gcc_jit_context_set_bool_option()}:
3068 @example
3069 gcc_jit_context_set_bool_option (
3070   ctxt,
3071   GCC_JIT_BOOL_OPTION_DEBUGINFO,
3072   1);
3073 @end example
3075 @noindent
3076 @end itemize
3077 @end quotation
3079 Having done this, we can put a breakpoint on the generated function:
3081 @example
3082 $ gdb --args ./toyvm factorial.toy 10
3083 (gdb) break factorial
3084 Function "factorial" not defined.
3085 Make breakpoint pending on future shared library load? (y or [n]) y
3086 Breakpoint 1 (factorial) pending.
3087 (gdb) run
3088 Breakpoint 1, factorial (arg=10) at factorial.toy:14
3089 14    DUP
3090 @end example
3092 @noindent
3094 We've set up location information, which references @code{factorial.toy}.
3095 This allows us to use e.g. @code{list} to see where we are in the script:
3097 @example
3098 (gdb) list
3100 10    # Initial state:
3101 11    # stack: [arg]
3103 13    # 0:
3104 14    DUP
3105 15    # stack: [arg, arg]
3107 17    # 1:
3108 18    PUSH_CONST 2
3109 @end example
3111 @noindent
3113 and to step through the function, examining the data:
3115 @example
3116 (gdb) n
3117 18    PUSH_CONST 2
3118 (gdb) n
3119 22    BINARY_COMPARE_LT
3120 (gdb) print stack
3121 $5 = @{10, 10, 2, 0, -7152, 32767, 0, 0@}
3122 (gdb) print stack_depth
3123 $6 = 3
3124 @end example
3126 @noindent
3128 You'll see that the parts of the @code{stack} array that haven't been
3129 touched yet are uninitialized.
3131 @cartouche
3132 @quotation Note 
3133 Turning on optimizations may lead to unpredictable results when
3134 stepping through the generated code: the execution may appear to
3135 "jump around" the source code.  This is analogous to turning up the
3136 optimization level in a regular compiler.
3137 @end quotation
3138 @end cartouche
3140 @node Examining the generated code,Putting it all together,Single-stepping through the generated code,Tutorial part 4 Adding JIT-compilation to a toy interpreter
3141 @anchor{intro/tutorial04 examining-the-generated-code}@anchor{43}
3142 @subsection Examining the generated code
3145 How good is the optimized code?
3147 We can turn up optimizations, by calling
3148 @pxref{1e,,gcc_jit_context_set_int_option()} with
3149 @pxref{1f,,GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL}:
3151 @example
3152 gcc_jit_context_set_int_option (
3153   ctxt,
3154   GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL,
3155   3);
3156 @end example
3158 @noindent
3160 One of GCC's internal representations is called "gimple".  A dump of the
3161 initial gimple representation of the code can be seen by setting:
3163 @example
3164 gcc_jit_context_set_bool_option (ctxt,
3165                                  GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE,
3166                                  1);
3167 @end example
3169 @noindent
3171 With optimization on and source locations displayed, this gives:
3173 @c We'll use "c" for gimple dumps
3175 @example
3176 factorial (signed int arg)
3178   <unnamed type> D.80;
3179   signed int D.81;
3180   signed int D.82;
3181   signed int D.83;
3182   signed int D.84;
3183   signed int D.85;
3184   signed int y;
3185   signed int x;
3186   signed int stack_depth;
3187   signed int stack[8];
3189   try
3190     @{
3191       initial:
3192       stack_depth = 0;
3193       stack[stack_depth] = arg;
3194       stack_depth = stack_depth + 1;
3195       goto instr0;
3196       instr0:
3197       /* DUP */:
3198       stack_depth = stack_depth + -1;
3199       x = stack[stack_depth];
3200       stack[stack_depth] = x;
3201       stack_depth = stack_depth + 1;
3202       stack[stack_depth] = x;
3203       stack_depth = stack_depth + 1;
3204       goto instr1;
3205       instr1:
3206       /* PUSH_CONST */:
3207       stack[stack_depth] = 2;
3208       stack_depth = stack_depth + 1;
3209       goto instr2;
3211       /* etc */
3212 @end example
3214 @noindent
3216 You can see the generated machine code in assembly form via:
3218 @example
3219 gcc_jit_context_set_bool_option (
3220   ctxt,
3221   GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE,
3222   1);
3223 result = gcc_jit_context_compile (ctxt);
3224 @end example
3226 @noindent
3228 which shows that (on this x86_64 box) the compiler has unrolled the loop
3229 and is using MMX instructions to perform several multiplications
3230 simultaneously:
3232 @example
3233         .file   "fake.c"
3234         .text
3235 .Ltext0:
3236         .p2align 4,,15
3237         .globl  factorial
3238         .type   factorial, @@function
3239 factorial:
3240 .LFB0:
3241         .file 1 "factorial.toy"
3242         .loc 1 14 0
3243         .cfi_startproc
3244 .LVL0:
3245 .L2:
3246         .loc 1 26 0
3247         cmpl    $1, %edi
3248         jle     .L13
3249         leal    -1(%rdi), %edx
3250         movl    %edx, %ecx
3251         shrl    $2, %ecx
3252         leal    0(,%rcx,4), %esi
3253         testl   %esi, %esi
3254         je      .L14
3255         cmpl    $9, %edx
3256         jbe     .L14
3257         leal    -2(%rdi), %eax
3258         movl    %eax, -16(%rsp)
3259         leal    -3(%rdi), %eax
3260         movd    -16(%rsp), %xmm0
3261         movl    %edi, -16(%rsp)
3262         movl    %eax, -12(%rsp)
3263         movd    -16(%rsp), %xmm1
3264         xorl    %eax, %eax
3265         movl    %edx, -16(%rsp)
3266         movd    -12(%rsp), %xmm4
3267         movd    -16(%rsp), %xmm6
3268         punpckldq       %xmm4, %xmm0
3269         movdqa  .LC1(%rip), %xmm4
3270         punpckldq       %xmm6, %xmm1
3271         punpcklqdq      %xmm0, %xmm1
3272         movdqa  .LC0(%rip), %xmm0
3273         jmp     .L5
3274         # etc - edited for brevity
3275 @end example
3277 @noindent
3279 This is clearly overkill for a function that will likely overflow the
3280 @code{int} type before the vectorization is worthwhile - but then again, this
3281 is a toy example.
3283 Turning down the optimization level to 2:
3285 @example
3286 gcc_jit_context_set_int_option (
3287   ctxt,
3288   GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL,
3289   3);
3290 @end example
3292 @noindent
3294 yields this code, which is simple enough to quote in its entirety:
3296 @example
3297         .file   "fake.c"
3298         .text
3299         .p2align 4,,15
3300         .globl  factorial
3301         .type   factorial, @@function
3302 factorial:
3303 .LFB0:
3304         .cfi_startproc
3305 .L2:
3306         cmpl    $1, %edi
3307         jle     .L8
3308         movl    $1, %edx
3309         jmp     .L4
3310         .p2align 4,,10
3311         .p2align 3
3312 .L6:
3313         movl    %eax, %edi
3314 .L4:
3315 .L5:
3316         leal    -1(%rdi), %eax
3317         imull   %edi, %edx
3318         cmpl    $1, %eax
3319         jne     .L6
3320 .L3:
3321 .L7:
3322         imull   %edx, %eax
3323         ret
3324 .L8:
3325         movl    %edi, %eax
3326         movl    $1, %edx
3327         jmp     .L7
3328         .cfi_endproc
3329 .LFE0:
3330         .size   factorial, .-factorial
3331         .ident  "GCC: (GNU) 4.9.0 20131023 (Red Hat 0.2-%@{gcc_release@})"
3332         .section        .note.GNU-stack,"",@@progbits
3333 @end example
3335 @noindent
3337 Note that the stack pushing and popping have been eliminated, as has the
3338 recursive call (in favor of an iteration).
3340 @node Putting it all together,Behind the curtain How does our code get optimized?,Examining the generated code,Tutorial part 4 Adding JIT-compilation to a toy interpreter
3341 @anchor{intro/tutorial04 putting-it-all-together}@anchor{44}
3342 @subsection Putting it all together
3345 The complete example can be seen in the source tree at
3346 @code{gcc/jit/docs/examples/tut04-toyvm/toyvm.c}
3348 along with a Makefile and a couple of sample .toy scripts:
3350 @example
3351 $ ls -al
3352 drwxrwxr-x. 2 david david   4096 Sep 19 17:46 .
3353 drwxrwxr-x. 3 david david   4096 Sep 19 15:26 ..
3354 -rw-rw-r--. 1 david david    615 Sep 19 12:43 factorial.toy
3355 -rw-rw-r--. 1 david david    834 Sep 19 13:08 fibonacci.toy
3356 -rw-rw-r--. 1 david david    238 Sep 19 14:22 Makefile
3357 -rw-rw-r--. 1 david david  16457 Sep 19 17:07 toyvm.c
3359 $ make toyvm
3360 g++ -Wall -g -o toyvm toyvm.c -lgccjit
3362 $ ./toyvm factorial.toy 10
3363 interpreter result: 3628800
3364 compiler result: 3628800
3366 $ ./toyvm fibonacci.toy 10
3367 interpreter result: 55
3368 compiler result: 55
3369 @end example
3371 @noindent
3373 @node Behind the curtain How does our code get optimized?,,Putting it all together,Tutorial part 4 Adding JIT-compilation to a toy interpreter
3374 @anchor{intro/tutorial04 behind-the-curtain-how-does-our-code-get-optimized}@anchor{45}
3375 @subsection Behind the curtain: How does our code get optimized?
3378 Our example is done, but you may be wondering about exactly how the
3379 compiler turned what we gave it into the machine code seen above.
3381 We can examine what the compiler is doing in detail by setting:
3383 @example
3384 gcc_jit_context_set_bool_option (state.ctxt,
3385                                  GCC_JIT_BOOL_OPTION_DUMP_EVERYTHING,
3386                                  1);
3387 gcc_jit_context_set_bool_option (state.ctxt,
3388                                  GCC_JIT_BOOL_OPTION_KEEP_INTERMEDIATES,
3389                                  1);
3390 @end example
3392 @noindent
3394 This will dump detailed information about the compiler's state to a
3395 directory under @code{/tmp}, and keep it from being cleaned up.
3397 The precise names and their formats of these files is subject to change.
3398 Higher optimization levels lead to more files.
3399 Here's what I saw (edited for brevity; there were almost 200 files):
3401 @example
3402 intermediate files written to /tmp/libgccjit-KPQbGw
3403 $ ls /tmp/libgccjit-KPQbGw/
3404 fake.c.000i.cgraph
3405 fake.c.000i.type-inheritance
3406 fake.c.004t.gimple
3407 fake.c.007t.omplower
3408 fake.c.008t.lower
3409 fake.c.011t.eh
3410 fake.c.012t.cfg
3411 fake.c.014i.visibility
3412 fake.c.015i.early_local_cleanups
3413 fake.c.016t.ssa
3414 # etc
3415 @end example
3417 @noindent
3419 The gimple code is converted into Static Single Assignment form,
3420 with annotations for use when generating the debuginfo:
3422 @example
3423 $ less /tmp/libgccjit-KPQbGw/fake.c.016t.ssa
3424 @end example
3426 @noindent
3428 @example
3429 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
3431 factorial (signed int arg)
3433   signed int stack[8];
3434   signed int stack_depth;
3435   signed int x;
3436   signed int y;
3437   <unnamed type> _20;
3438   signed int _21;
3439   signed int _38;
3440   signed int _44;
3441   signed int _51;
3442   signed int _56;
3444 initial:
3445   stack_depth_3 = 0;
3446   # DEBUG stack_depth => stack_depth_3
3447   stack[stack_depth_3] = arg_5(D);
3448   stack_depth_7 = stack_depth_3 + 1;
3449   # DEBUG stack_depth => stack_depth_7
3450   # DEBUG instr0 => NULL
3451   # DEBUG /* DUP */ => NULL
3452   stack_depth_8 = stack_depth_7 + -1;
3453   # DEBUG stack_depth => stack_depth_8
3454   x_9 = stack[stack_depth_8];
3455   # DEBUG x => x_9
3456   stack[stack_depth_8] = x_9;
3457   stack_depth_11 = stack_depth_8 + 1;
3458   # DEBUG stack_depth => stack_depth_11
3459   stack[stack_depth_11] = x_9;
3460   stack_depth_13 = stack_depth_11 + 1;
3461   # DEBUG stack_depth => stack_depth_13
3462   # DEBUG instr1 => NULL
3463   # DEBUG /* PUSH_CONST */ => NULL
3464   stack[stack_depth_13] = 2;
3466   /* etc; edited for brevity */
3467 @end example
3469 @noindent
3471 We can perhaps better see the code by turning off
3472 @pxref{42,,GCC_JIT_BOOL_OPTION_DEBUGINFO} to suppress all those @code{DEBUG}
3473 statements, giving:
3475 @example
3476 $ less /tmp/libgccjit-1Hywc0/fake.c.016t.ssa
3477 @end example
3479 @noindent
3481 @example
3482 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
3484 factorial (signed int arg)
3486   signed int stack[8];
3487   signed int stack_depth;
3488   signed int x;
3489   signed int y;
3490   <unnamed type> _20;
3491   signed int _21;
3492   signed int _38;
3493   signed int _44;
3494   signed int _51;
3495   signed int _56;
3497 initial:
3498   stack_depth_3 = 0;
3499   stack[stack_depth_3] = arg_5(D);
3500   stack_depth_7 = stack_depth_3 + 1;
3501   stack_depth_8 = stack_depth_7 + -1;
3502   x_9 = stack[stack_depth_8];
3503   stack[stack_depth_8] = x_9;
3504   stack_depth_11 = stack_depth_8 + 1;
3505   stack[stack_depth_11] = x_9;
3506   stack_depth_13 = stack_depth_11 + 1;
3507   stack[stack_depth_13] = 2;
3508   stack_depth_15 = stack_depth_13 + 1;
3509   stack_depth_16 = stack_depth_15 + -1;
3510   y_17 = stack[stack_depth_16];
3511   stack_depth_18 = stack_depth_16 + -1;
3512   x_19 = stack[stack_depth_18];
3513   _20 = x_19 < y_17;
3514   _21 = (signed int) _20;
3515   stack[stack_depth_18] = _21;
3516   stack_depth_23 = stack_depth_18 + 1;
3517   stack_depth_24 = stack_depth_23 + -1;
3518   x_25 = stack[stack_depth_24];
3519   if (x_25 != 0)
3520     goto <bb 4> (instr9);
3521   else
3522     goto <bb 3> (instr4);
3524 instr4:
3525 /* DUP */:
3526   stack_depth_26 = stack_depth_24 + -1;
3527   x_27 = stack[stack_depth_26];
3528   stack[stack_depth_26] = x_27;
3529   stack_depth_29 = stack_depth_26 + 1;
3530   stack[stack_depth_29] = x_27;
3531   stack_depth_31 = stack_depth_29 + 1;
3532   stack[stack_depth_31] = 1;
3533   stack_depth_33 = stack_depth_31 + 1;
3534   stack_depth_34 = stack_depth_33 + -1;
3535   y_35 = stack[stack_depth_34];
3536   stack_depth_36 = stack_depth_34 + -1;
3537   x_37 = stack[stack_depth_36];
3538   _38 = x_37 - y_35;
3539   stack[stack_depth_36] = _38;
3540   stack_depth_40 = stack_depth_36 + 1;
3541   stack_depth_41 = stack_depth_40 + -1;
3542   x_42 = stack[stack_depth_41];
3543   _44 = factorial (x_42);
3544   stack[stack_depth_41] = _44;
3545   stack_depth_46 = stack_depth_41 + 1;
3546   stack_depth_47 = stack_depth_46 + -1;
3547   y_48 = stack[stack_depth_47];
3548   stack_depth_49 = stack_depth_47 + -1;
3549   x_50 = stack[stack_depth_49];
3550   _51 = x_50 * y_48;
3551   stack[stack_depth_49] = _51;
3552   stack_depth_53 = stack_depth_49 + 1;
3554   # stack_depth_1 = PHI <stack_depth_24(2), stack_depth_53(3)>
3555 instr9:
3556 /* RETURN */:
3557   stack_depth_54 = stack_depth_1 + -1;
3558   x_55 = stack[stack_depth_54];
3559   _56 = x_55;
3560   stack =@{v@} @{CLOBBER@};
3561   return _56;
3564 @end example
3566 @noindent
3568 Note in the above how all the @pxref{28,,gcc_jit_block} instances we
3569 created have been consolidated into just 3 blocks in GCC's internal
3570 representation: @code{initial}, @code{instr4} and @code{instr9}.
3572 @menu
3573 * Optimizing away stack manipulation:: 
3574 * Elimination of tail recursion:: 
3576 @end menu
3578 @node Optimizing away stack manipulation,Elimination of tail recursion,,Behind the curtain How does our code get optimized?
3579 @anchor{intro/tutorial04 optimizing-away-stack-manipulation}@anchor{46}
3580 @subsubsection Optimizing away stack manipulation
3583 Recall our simple implementation of stack operations.  Let's examine
3584 how the stack operations are optimized away.
3586 After a pass of constant-propagation, the depth of the stack at each
3587 opcode can be determined at compile-time:
3589 @example
3590 $ less /tmp/libgccjit-1Hywc0/fake.c.021t.ccp1
3591 @end example
3593 @noindent
3595 @example
3596 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
3598 factorial (signed int arg)
3600   signed int stack[8];
3601   signed int stack_depth;
3602   signed int x;
3603   signed int y;
3604   <unnamed type> _20;
3605   signed int _21;
3606   signed int _38;
3607   signed int _44;
3608   signed int _51;
3610 initial:
3611   stack[0] = arg_5(D);
3612   x_9 = stack[0];
3613   stack[0] = x_9;
3614   stack[1] = x_9;
3615   stack[2] = 2;
3616   y_17 = stack[2];
3617   x_19 = stack[1];
3618   _20 = x_19 < y_17;
3619   _21 = (signed int) _20;
3620   stack[1] = _21;
3621   x_25 = stack[1];
3622   if (x_25 != 0)
3623     goto <bb 4> (instr9);
3624   else
3625     goto <bb 3> (instr4);
3627 instr4:
3628 /* DUP */:
3629   x_27 = stack[0];
3630   stack[0] = x_27;
3631   stack[1] = x_27;
3632   stack[2] = 1;
3633   y_35 = stack[2];
3634   x_37 = stack[1];
3635   _38 = x_37 - y_35;
3636   stack[1] = _38;
3637   x_42 = stack[1];
3638   _44 = factorial (x_42);
3639   stack[1] = _44;
3640   y_48 = stack[1];
3641   x_50 = stack[0];
3642   _51 = x_50 * y_48;
3643   stack[0] = _51;
3645 instr9:
3646 /* RETURN */:
3647   x_55 = stack[0];
3648   x_56 = x_55;
3649   stack =@{v@} @{CLOBBER@};
3650   return x_56;
3653 @end example
3655 @noindent
3657 Note how, in the above, all those @code{stack_depth} values are now just
3658 constants: we're accessing specific stack locations at each opcode.
3660 The "esra" pass ("Early Scalar Replacement of Aggregates") breaks
3661 out our "stack" array into individual elements:
3663 @example
3664 $ less /tmp/libgccjit-1Hywc0/fake.c.024t.esra
3665 @end example
3667 @noindent
3669 @example
3670 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
3672 Created a replacement for stack offset: 0, size: 32: stack$0
3673 Created a replacement for stack offset: 32, size: 32: stack$1
3674 Created a replacement for stack offset: 64, size: 32: stack$2
3676 Symbols to be put in SSA form
3677 @{ D.89 D.90 D.91 @}
3678 Incremental SSA update started at block: 0
3679 Number of blocks in CFG: 5
3680 Number of blocks to update: 4 ( 80%)
3683 factorial (signed int arg)
3685   signed int stack$2;
3686   signed int stack$1;
3687   signed int stack$0;
3688   signed int stack[8];
3689   signed int stack_depth;
3690   signed int x;
3691   signed int y;
3692   <unnamed type> _20;
3693   signed int _21;
3694   signed int _38;
3695   signed int _44;
3696   signed int _51;
3698 initial:
3699   stack$0_45 = arg_5(D);
3700   x_9 = stack$0_45;
3701   stack$0_39 = x_9;
3702   stack$1_32 = x_9;
3703   stack$2_30 = 2;
3704   y_17 = stack$2_30;
3705   x_19 = stack$1_32;
3706   _20 = x_19 < y_17;
3707   _21 = (signed int) _20;
3708   stack$1_28 = _21;
3709   x_25 = stack$1_28;
3710   if (x_25 != 0)
3711     goto <bb 4> (instr9);
3712   else
3713     goto <bb 3> (instr4);
3715 instr4:
3716 /* DUP */:
3717   x_27 = stack$0_39;
3718   stack$0_22 = x_27;
3719   stack$1_14 = x_27;
3720   stack$2_12 = 1;
3721   y_35 = stack$2_12;
3722   x_37 = stack$1_14;
3723   _38 = x_37 - y_35;
3724   stack$1_10 = _38;
3725   x_42 = stack$1_10;
3726   _44 = factorial (x_42);
3727   stack$1_6 = _44;
3728   y_48 = stack$1_6;
3729   x_50 = stack$0_22;
3730   _51 = x_50 * y_48;
3731   stack$0_1 = _51;
3733   # stack$0_52 = PHI <stack$0_39(2), stack$0_1(3)>
3734 instr9:
3735 /* RETURN */:
3736   x_55 = stack$0_52;
3737   x_56 = x_55;
3738   stack =@{v@} @{CLOBBER@};
3739   return x_56;
3742 @end example
3744 @noindent
3746 Hence at this point, all those pushes and pops of the stack are now
3747 simply assignments to specific temporary variables.
3749 After some copy propagation, the stack manipulation has been completely
3750 optimized away:
3752 @example
3753 $ less /tmp/libgccjit-1Hywc0/fake.c.026t.copyprop1
3754 @end example
3756 @noindent
3758 @example
3759 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
3761 factorial (signed int arg)
3763   signed int stack$2;
3764   signed int stack$1;
3765   signed int stack$0;
3766   signed int stack[8];
3767   signed int stack_depth;
3768   signed int x;
3769   signed int y;
3770   <unnamed type> _20;
3771   signed int _21;
3772   signed int _38;
3773   signed int _44;
3774   signed int _51;
3776 initial:
3777   stack$0_39 = arg_5(D);
3778   _20 = arg_5(D) <= 1;
3779   _21 = (signed int) _20;
3780   if (_21 != 0)
3781     goto <bb 4> (instr9);
3782   else
3783     goto <bb 3> (instr4);
3785 instr4:
3786 /* DUP */:
3787   _38 = arg_5(D) + -1;
3788   _44 = factorial (_38);
3789   _51 = arg_5(D) * _44;
3790   stack$0_1 = _51;
3792   # stack$0_52 = PHI <arg_5(D)(2), _51(3)>
3793 instr9:
3794 /* RETURN */:
3795   stack =@{v@} @{CLOBBER@};
3796   return stack$0_52;
3799 @end example
3801 @noindent
3803 Later on, another pass finally eliminated @code{stack_depth} local and the
3804 unused parts of the @cite{stack`} array altogether:
3806 @example
3807 $ less /tmp/libgccjit-1Hywc0/fake.c.036t.release_ssa
3808 @end example
3810 @noindent
3812 @example
3813 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
3815 Released 44 names, 314.29%, removed 44 holes
3816 factorial (signed int arg)
3818   signed int stack$0;
3819   signed int mult_acc_1;
3820   <unnamed type> _5;
3821   signed int _6;
3822   signed int _7;
3823   signed int mul_tmp_10;
3824   signed int mult_acc_11;
3825   signed int mult_acc_13;
3827   # arg_9 = PHI <arg_8(D)(0)>
3828   # mult_acc_13 = PHI <1(0)>
3829 initial:
3831   <bb 5>:
3832   # arg_4 = PHI <arg_9(2), _7(3)>
3833   # mult_acc_1 = PHI <mult_acc_13(2), mult_acc_11(3)>
3834   _5 = arg_4 <= 1;
3835   _6 = (signed int) _5;
3836   if (_6 != 0)
3837     goto <bb 4> (instr9);
3838   else
3839     goto <bb 3> (instr4);
3841 instr4:
3842 /* DUP */:
3843   _7 = arg_4 + -1;
3844   mult_acc_11 = mult_acc_1 * arg_4;
3845   goto <bb 5>;
3847   # stack$0_12 = PHI <arg_4(5)>
3848 instr9:
3849 /* RETURN */:
3850   mul_tmp_10 = mult_acc_1 * stack$0_12;
3851   return mul_tmp_10;
3854 @end example
3856 @noindent
3858 @node Elimination of tail recursion,,Optimizing away stack manipulation,Behind the curtain How does our code get optimized?
3859 @anchor{intro/tutorial04 elimination-of-tail-recursion}@anchor{47}
3860 @subsubsection Elimination of tail recursion
3863 Another significant optimization is the detection that the call to
3864 @code{factorial} is tail recursion, which can be eliminated in favor of
3865 an iteration:
3867 @example
3868 $ less /tmp/libgccjit-1Hywc0/fake.c.030t.tailr1
3869 @end example
3871 @noindent
3873 @example
3874 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
3877 Symbols to be put in SSA form
3878 @{ D.88 @}
3879 Incremental SSA update started at block: 0
3880 Number of blocks in CFG: 5
3881 Number of blocks to update: 4 ( 80%)
3884 factorial (signed int arg)
3886   signed int stack$2;
3887   signed int stack$1;
3888   signed int stack$0;
3889   signed int stack[8];
3890   signed int stack_depth;
3891   signed int x;
3892   signed int y;
3893   signed int mult_acc_1;
3894   <unnamed type> _20;
3895   signed int _21;
3896   signed int _38;
3897   signed int mul_tmp_44;
3898   signed int mult_acc_51;
3900   # arg_5 = PHI <arg_39(D)(0), _38(3)>
3901   # mult_acc_1 = PHI <1(0), mult_acc_51(3)>
3902 initial:
3903   _20 = arg_5 <= 1;
3904   _21 = (signed int) _20;
3905   if (_21 != 0)
3906     goto <bb 4> (instr9);
3907   else
3908     goto <bb 3> (instr4);
3910 instr4:
3911 /* DUP */:
3912   _38 = arg_5 + -1;
3913   mult_acc_51 = mult_acc_1 * arg_5;
3914   goto <bb 2> (initial);
3916   # stack$0_52 = PHI <arg_5(2)>
3917 instr9:
3918 /* RETURN */:
3919   stack =@{v@} @{CLOBBER@};
3920   mul_tmp_44 = mult_acc_1 * stack$0_52;
3921   return mul_tmp_44;
3924 @end example
3926 @noindent
3928 @c Copyright (C) 2014 Free Software Foundation, Inc.
3929 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
3930 @c 
3931 @c This is free software: you can redistribute it and/or modify it
3932 @c under the terms of the GNU General Public License as published by
3933 @c the Free Software Foundation, either version 3 of the License, or
3934 @c (at your option) any later version.
3935 @c 
3936 @c This program is distributed in the hope that it will be useful, but
3937 @c WITHOUT ANY WARRANTY; without even the implied warranty of
3938 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
3939 @c General Public License for more details.
3940 @c 
3941 @c You should have received a copy of the GNU General Public License
3942 @c along with this program.  If not, see
3943 @c <http://www.gnu.org/licenses/>.
3945 @node Topic Reference,C++ bindings for libgccjit,Tutorial,Top
3946 @anchor{topics/index doc}@anchor{48}@anchor{topics/index topic-reference}@anchor{49}
3947 @chapter Topic Reference
3950 @c Copyright (C) 2014 Free Software Foundation, Inc.
3951 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
3952 @c 
3953 @c This is free software: you can redistribute it and/or modify it
3954 @c under the terms of the GNU General Public License as published by
3955 @c the Free Software Foundation, either version 3 of the License, or
3956 @c (at your option) any later version.
3957 @c 
3958 @c This program is distributed in the hope that it will be useful, but
3959 @c WITHOUT ANY WARRANTY; without even the implied warranty of
3960 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
3961 @c General Public License for more details.
3962 @c 
3963 @c You should have received a copy of the GNU General Public License
3964 @c along with this program.  If not, see
3965 @c <http://www.gnu.org/licenses/>.
3967 @menu
3968 * Compilation contexts:: 
3969 * Objects:: 
3970 * Types:: 
3971 * Expressions:: 
3972 * Creating and using functions:: 
3973 * Source Locations:: 
3974 * Compilation results:: 
3976 Compilation contexts
3978 * Lifetime-management:: 
3979 * Thread-safety:: 
3980 * Error-handling: Error-handling<2>. 
3981 * Debugging:: 
3982 * Options: Options<2>. 
3984 Options
3986 * String Options:: 
3987 * Boolean options:: 
3988 * Integer options:: 
3990 Types
3992 * Standard types:: 
3993 * Pointers@comma{} const@comma{} and volatile: Pointers const and volatile. 
3994 * Structures and unions:: 
3996 Expressions
3998 * Rvalues:: 
3999 * Lvalues:: 
4000 * Working with pointers@comma{} structs and unions: Working with pointers structs and unions. 
4002 Rvalues
4004 * Simple expressions:: 
4005 * Unary Operations:: 
4006 * Binary Operations:: 
4007 * Comparisons:: 
4008 * Function calls:: 
4009 * Type-coercion:: 
4011 Lvalues
4013 * Global variables:: 
4015 Creating and using functions
4017 * Params:: 
4018 * Functions:: 
4019 * Blocks:: 
4020 * Statements:: 
4022 Source Locations
4024 * Faking it:: 
4026 @end menu
4029 @node Compilation contexts,Objects,,Topic Reference
4030 @anchor{topics/contexts compilation-contexts}@anchor{4a}@anchor{topics/contexts doc}@anchor{4b}
4031 @section Compilation contexts
4034 @geindex gcc_jit_context (C type)
4035 @anchor{topics/contexts gcc_jit_context}@anchor{8}
4036 @deffn {C Type} gcc_jit_context
4037 @end deffn
4039 The top-level of the API is the @pxref{8,,gcc_jit_context} type.
4041 A @pxref{8,,gcc_jit_context} instance encapsulates the state of a
4042 compilation.
4044 You can set up options on it, and add types, functions and code.
4045 Invoking @pxref{15,,gcc_jit_context_compile()} on it gives you a
4046 @pxref{16,,gcc_jit_result}.
4048 @menu
4049 * Lifetime-management:: 
4050 * Thread-safety:: 
4051 * Error-handling: Error-handling<2>. 
4052 * Debugging:: 
4053 * Options: Options<2>. 
4055 @end menu
4057 @node Lifetime-management,Thread-safety,,Compilation contexts
4058 @anchor{topics/contexts lifetime-management}@anchor{4c}
4059 @subsection Lifetime-management
4062 Contexts are the unit of lifetime-management within the API: objects
4063 have their lifetime bounded by the context they are created within, and
4064 cleanup of such objects is done for you when the context is released.
4066 @geindex gcc_jit_context_acquire (C function)
4067 @anchor{topics/contexts gcc_jit_context_acquire}@anchor{9}
4068 @deffn {C Function} gcc_jit_context *gcc_jit_context_acquire (void)
4070 This function acquires a new @pxref{e,,gcc_jit_object *} instance,
4071 which is independent of any others that may be present within this
4072 process.
4073 @end deffn
4075 @geindex gcc_jit_context_release (C function)
4076 @anchor{topics/contexts gcc_jit_context_release}@anchor{c}
4077 @deffn {C Function} void gcc_jit_context_release (gcc_jit_context@w{ }*ctxt)
4079 This function releases all resources associated with the given context.
4080 Both the context itself and all of its @pxref{e,,gcc_jit_object *}
4081 instances are cleaned up.  It should be called exactly once on a given
4082 context.
4084 It is invalid to use the context or any of its "contextual" objects
4085 after calling this.
4087 @example
4088 gcc_jit_context_release (ctxt);
4089 @end example
4091 @noindent
4092 @end deffn
4094 @geindex gcc_jit_context_new_child_context (C function)
4095 @anchor{topics/contexts gcc_jit_context_new_child_context}@anchor{4d}
4096 @deffn {C Function} gcc_jit_context * gcc_jit_context_new_child_context (gcc_jit_context@w{ }*parent_ctxt)
4098 Given an existing JIT context, create a child context.
4100 The child inherits a copy of all option-settings from the parent.
4102 The child can reference objects created within the parent, but not
4103 vice-versa.
4105 The lifetime of the child context must be bounded by that of the
4106 parent: you should release a child context before releasing the parent
4107 context.
4109 If you use a function from a parent context within a child context,
4110 you have to compile the parent context before you can compile the
4111 child context, and the gcc_jit_result of the parent context must
4112 outlive the gcc_jit_result of the child context.
4114 This allows caching of shared initializations.  For example, you could
4115 create types and declarations of global functions in a parent context
4116 once within a process, and then create child contexts whenever a
4117 function or loop becomes hot. Each such child context can be used for
4118 JIT-compiling just one function or loop, but can reference types
4119 and helper functions created within the parent context.
4121 Contexts can be arbitrarily nested, provided the above rules are
4122 followed, but it's probably not worth going above 2 or 3 levels, and
4123 there will likely be a performance hit for such nesting.
4124 @end deffn
4126 @node Thread-safety,Error-handling<2>,Lifetime-management,Compilation contexts
4127 @anchor{topics/contexts thread-safety}@anchor{4e}
4128 @subsection Thread-safety
4131 Instances of @pxref{8,,gcc_jit_context *} created via
4132 @pxref{9,,gcc_jit_context_acquire()} are independent from each other:
4133 only one thread may use a given context at once, but multiple threads
4134 could each have their own contexts without needing locks.
4136 Contexts created via @pxref{4d,,gcc_jit_context_new_child_context()} are
4137 related to their parent context.  They can be partitioned by their
4138 ultimate ancestor into independent "family trees".   Only one thread
4139 within a process may use a given "family tree" of such contexts at once,
4140 and if you're using multiple threads you should provide your own locking
4141 around entire such context partitions.
4143 @node Error-handling<2>,Debugging,Thread-safety,Compilation contexts
4144 @anchor{topics/contexts error-handling}@anchor{19}@anchor{topics/contexts id1}@anchor{4f}
4145 @subsection Error-handling
4148 Various kinds of errors are possible when using the API, such as
4149 mismatched types in an assignment.  You can only compile and get code from
4150 a context if no errors occur.
4152 Errors are printed on stderr and can be queried using
4153 @pxref{50,,gcc_jit_context_get_first_error()}.
4155 They typically contain the name of the API entrypoint where the error
4156 occurred, and pertinent information on the problem:
4158 @example
4159 ./buggy-program: error: gcc_jit_block_add_assignment: mismatching types: assignment to i (type: int) from "hello world" (type: const char *)
4160 @end example
4162 @noindent
4164 In general, if an error occurs when using an API entrypoint, the
4165 entrypoint returns NULL.  You don't have to check everywhere for NULL
4166 results, since the API handles a NULL being passed in for any
4167 argument by issuing another error.  This typically leads to a cascade of
4168 followup error messages, but is safe (albeit verbose).
4170 @geindex gcc_jit_context_get_first_error (C function)
4171 @anchor{topics/contexts gcc_jit_context_get_first_error}@anchor{50}
4172 @deffn {C Function} const char *           gcc_jit_context_get_first_error (gcc_jit_context@w{ }*ctxt)
4174 Returns the first error message that occurred on the context.
4176 The returned string is valid for the rest of the lifetime of the
4177 context.
4179 If no errors occurred, this will be NULL.
4180 @end deffn
4182 @node Debugging,Options<2>,Error-handling<2>,Compilation contexts
4183 @anchor{topics/contexts debugging}@anchor{51}
4184 @subsection Debugging
4187 @geindex gcc_jit_context_dump_to_file (C function)
4188 @anchor{topics/contexts gcc_jit_context_dump_to_file}@anchor{52}
4189 @deffn {C Function} void           gcc_jit_context_dump_to_file (gcc_jit_context@w{ }*ctxt, const char@w{ }*path, int@w{ }update_locations)
4191 To help with debugging: dump a C-like representation to the given path,
4192 describing what's been set up on the context.
4194 If "update_locations" is true, then also set up @pxref{3b,,gcc_jit_location}
4195 information throughout the context, pointing at the dump file as if it
4196 were a source file.  This may be of use in conjunction with
4197 @pxref{42,,GCC_JIT_BOOL_OPTION_DEBUGINFO} to allow stepping through the
4198 code in a debugger.
4199 @end deffn
4201 @geindex gcc_jit_context_enable_dump (C function)
4202 @anchor{topics/contexts gcc_jit_context_enable_dump}@anchor{53}
4203 @deffn {C Function} void           gcc_jit_context_enable_dump (gcc_jit_context@w{ }*ctxt, const char@w{ }*dumpname, char@w{ }**out_ptr)
4205 Enable the dumping of a specific set of internal state from the
4206 compilation, capturing the result in-memory as a buffer.
4208 Parameter "dumpname" corresponds to the equivalent gcc command-line
4209 option, without the "-fdump-" prefix.
4210 For example, to get the equivalent of @code{-fdump-tree-vrp1},
4211 supply @code{"tree-vrp1"}:
4213 @example
4214 static char *dump_vrp1;
4216 void
4217 create_code (gcc_jit_context *ctxt)
4219    gcc_jit_context_enable_dump (ctxt, "tree-vrp1", &dump_vrp1);
4220    /* (other API calls omitted for brevity) */
4222 @end example
4224 @noindent
4226 The context directly stores the dumpname as a @code{(const char *)}, so
4227 the passed string must outlive the context.
4229 @pxref{15,,gcc_jit_context_compile()} will capture the dump as a
4230 dynamically-allocated buffer, writing it to @code{*out_ptr}.
4232 The caller becomes responsible for calling:
4234 @example
4235 free (*out_ptr)
4236 @end example
4238 @noindent
4240 each time that @pxref{15,,gcc_jit_context_compile()} is called.
4241 @code{*out_ptr} will be written to, either with the address of a buffer,
4242 or with @code{NULL} if an error occurred.
4244 @cartouche
4245 @quotation Warning 
4246 This API entrypoint is likely to be less stable than the others.
4247 In particular, both the precise dumpnames, and the format and content
4248 of the dumps are subject to change.
4250 It exists primarily for writing the library's own test suite.
4251 @end quotation
4252 @end cartouche
4253 @end deffn
4255 @node Options<2>,,Debugging,Compilation contexts
4256 @anchor{topics/contexts options}@anchor{54}
4257 @subsection Options
4260 @menu
4261 * String Options:: 
4262 * Boolean options:: 
4263 * Integer options:: 
4265 @end menu
4267 @node String Options,Boolean options,,Options<2>
4268 @anchor{topics/contexts string-options}@anchor{55}
4269 @subsubsection String Options
4272 @geindex gcc_jit_context_set_str_option (C function)
4273 @anchor{topics/contexts gcc_jit_context_set_str_option}@anchor{56}
4274 @deffn {C Function} void gcc_jit_context_set_str_option (gcc_jit_context@w{ }*ctxt, enum gcc_jit_str_option@w{ }opt, const char@w{ }*value)
4276 Set a string option of the context.
4278 @geindex gcc_jit_str_option (C type)
4279 @anchor{topics/contexts gcc_jit_str_option}@anchor{57}
4280 @deffn {C Type} enum gcc_jit_str_option
4281 @end deffn
4283 There is currently just one string option:
4285 @geindex GCC_JIT_STR_OPTION_PROGNAME (C macro)
4286 @anchor{topics/contexts GCC_JIT_STR_OPTION_PROGNAME}@anchor{58}
4287 @deffn {C Macro} GCC_JIT_STR_OPTION_PROGNAME
4289 The name of the program, for use as a prefix when printing error
4290 messages to stderr.  If @cite{NULL}, or default, "libgccjit.so" is used.
4291 @end deffn
4292 @end deffn
4294 @node Boolean options,Integer options,String Options,Options<2>
4295 @anchor{topics/contexts boolean-options}@anchor{59}
4296 @subsubsection Boolean options
4299 @geindex gcc_jit_context_set_bool_option (C function)
4300 @anchor{topics/contexts gcc_jit_context_set_bool_option}@anchor{1b}
4301 @deffn {C Function} void gcc_jit_context_set_bool_option (gcc_jit_context@w{ }*ctxt, enum gcc_jit_bool_option@w{ }opt, int@w{ }value)
4303 Set a boolean option of the context.
4304 Zero is "false" (the default), non-zero is "true".
4306 @geindex gcc_jit_bool_option (C type)
4307 @anchor{topics/contexts gcc_jit_bool_option}@anchor{5a}
4308 @deffn {C Type} enum gcc_jit_bool_option
4309 @end deffn
4311 @geindex GCC_JIT_BOOL_OPTION_DEBUGINFO (C macro)
4312 @anchor{topics/contexts GCC_JIT_BOOL_OPTION_DEBUGINFO}@anchor{42}
4313 @deffn {C Macro} GCC_JIT_BOOL_OPTION_DEBUGINFO
4315 If true, @pxref{15,,gcc_jit_context_compile()} will attempt to do the right
4316 thing so that if you attach a debugger to the process, it will
4317 be able to inspect variables and step through your code.
4319 Note that you can't step through code unless you set up source
4320 location information for the code (by creating and passing in
4321 @pxref{3b,,gcc_jit_location} instances).
4322 @end deffn
4324 @geindex GCC_JIT_BOOL_OPTION_DUMP_INITIAL_TREE (C macro)
4325 @anchor{topics/contexts GCC_JIT_BOOL_OPTION_DUMP_INITIAL_TREE}@anchor{5b}
4326 @deffn {C Macro} GCC_JIT_BOOL_OPTION_DUMP_INITIAL_TREE
4328 If true, @pxref{15,,gcc_jit_context_compile()} will dump its initial
4329 "tree" representation of your code to stderr (before any
4330 optimizations).
4332 Here's some sample output (from the @cite{square} example):
4334 @example
4335 <statement_list 0x7f4875a62cc0
4336    type <void_type 0x7f4875a64bd0 VOID
4337        align 8 symtab 0 alias set -1 canonical type 0x7f4875a64bd0
4338        pointer_to_this <pointer_type 0x7f4875a64c78>>
4339    side-effects head 0x7f4875a761e0 tail 0x7f4875a761f8 stmts 0x7f4875a62d20 0x7f4875a62d00
4341    stmt <label_expr 0x7f4875a62d20 type <void_type 0x7f4875a64bd0>
4342        side-effects
4343        arg 0 <label_decl 0x7f4875a79080 entry type <void_type 0x7f4875a64bd0>
4344            VOID file (null) line 0 col 0
4345            align 1 context <function_decl 0x7f4875a77500 square>>>
4346    stmt <return_expr 0x7f4875a62d00
4347        type <integer_type 0x7f4875a645e8 public SI
4348            size <integer_cst 0x7f4875a623a0 constant 32>
4349            unit size <integer_cst 0x7f4875a623c0 constant 4>
4350            align 32 symtab 0 alias set -1 canonical type 0x7f4875a645e8 precision 32 min <integer_cst 0x7f4875a62340 -2147483648> max <integer_cst 0x7f4875a62360 2147483647>
4351            pointer_to_this <pointer_type 0x7f4875a6b348>>
4352        side-effects
4353        arg 0 <modify_expr 0x7f4875a72a78 type <integer_type 0x7f4875a645e8>
4354            side-effects arg 0 <result_decl 0x7f4875a7a000 D.54>
4355            arg 1 <mult_expr 0x7f4875a72a50 type <integer_type 0x7f4875a645e8>
4356                arg 0 <parm_decl 0x7f4875a79000 i> arg 1 <parm_decl 0x7f4875a79000 i>>>>>
4357 @end example
4359 @noindent
4360 @end deffn
4362 @geindex GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE (C macro)
4363 @anchor{topics/contexts GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE}@anchor{1c}
4364 @deffn {C Macro} GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE
4366 If true, @pxref{15,,gcc_jit_context_compile()} will dump the "gimple"
4367 representation of your code to stderr, before any optimizations
4368 are performed.  The dump resembles C code:
4370 @example
4371 square (signed int i)
4373   signed int D.56;
4375   entry:
4376   D.56 = i * i;
4377   return D.56;
4379 @end example
4381 @noindent
4382 @end deffn
4384 @geindex GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE (C macro)
4385 @anchor{topics/contexts GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE}@anchor{1d}
4386 @deffn {C Macro} GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE
4388 If true, @pxref{15,,gcc_jit_context_compile()} will dump the final
4389 generated code to stderr, in the form of assembly language:
4391 @example
4392     .file    "fake.c"
4393     .text
4394     .globl    square
4395     .type    square, @@function
4396 square:
4397 .LFB0:
4398     .cfi_startproc
4399     pushq    %rbp
4400     .cfi_def_cfa_offset 16
4401     .cfi_offset 6, -16
4402     movq    %rsp, %rbp
4403     .cfi_def_cfa_register 6
4404     movl    %edi, -4(%rbp)
4405 .L2:
4406     movl    -4(%rbp), %eax
4407     imull    -4(%rbp), %eax
4408     popq    %rbp
4409     .cfi_def_cfa 7, 8
4410     ret
4411     .cfi_endproc
4412 .LFE0:
4413     .size    square, .-square
4414     .ident    "GCC: (GNU) 4.9.0 20131023 (Red Hat 0.1-%@{gcc_release@})"
4415     .section    .note.GNU-stack,"",@@progbits
4416 @end example
4418 @noindent
4419 @end deffn
4421 @geindex GCC_JIT_BOOL_OPTION_DUMP_SUMMARY (C macro)
4422 @anchor{topics/contexts GCC_JIT_BOOL_OPTION_DUMP_SUMMARY}@anchor{5c}
4423 @deffn {C Macro} GCC_JIT_BOOL_OPTION_DUMP_SUMMARY
4425 If true, @pxref{15,,gcc_jit_context_compile()} will print information to stderr
4426 on the actions it is performing, followed by a profile showing
4427 the time taken and memory usage of each phase.
4428 @end deffn
4430 @geindex GCC_JIT_BOOL_OPTION_DUMP_EVERYTHING (C macro)
4431 @anchor{topics/contexts GCC_JIT_BOOL_OPTION_DUMP_EVERYTHING}@anchor{5d}
4432 @deffn {C Macro} GCC_JIT_BOOL_OPTION_DUMP_EVERYTHING
4434 If true, @pxref{15,,gcc_jit_context_compile()} will dump copious
4435 amount of information on what it's doing to various
4436 files within a temporary directory.  Use
4437 @pxref{5e,,GCC_JIT_BOOL_OPTION_KEEP_INTERMEDIATES} (see below) to
4438 see the results.  The files are intended to be human-readable,
4439 but the exact files and their formats are subject to change.
4440 @end deffn
4442 @geindex GCC_JIT_BOOL_OPTION_SELFCHECK_GC (C macro)
4443 @anchor{topics/contexts GCC_JIT_BOOL_OPTION_SELFCHECK_GC}@anchor{5f}
4444 @deffn {C Macro} GCC_JIT_BOOL_OPTION_SELFCHECK_GC
4446 If true, libgccjit will aggressively run its garbage collector, to
4447 shake out bugs (greatly slowing down the compile).  This is likely
4448 to only be of interest to developers @emph{of} the library.  It is
4449 used when running the selftest suite.
4450 @end deffn
4452 @geindex GCC_JIT_BOOL_OPTION_KEEP_INTERMEDIATES (C macro)
4453 @anchor{topics/contexts GCC_JIT_BOOL_OPTION_KEEP_INTERMEDIATES}@anchor{5e}
4454 @deffn {C Macro} GCC_JIT_BOOL_OPTION_KEEP_INTERMEDIATES
4456 If true, the @pxref{8,,gcc_jit_context} will not clean up intermediate files
4457 written to the filesystem, and will display their location on stderr.
4458 @end deffn
4459 @end deffn
4461 @node Integer options,,Boolean options,Options<2>
4462 @anchor{topics/contexts integer-options}@anchor{60}
4463 @subsubsection Integer options
4466 @geindex gcc_jit_context_set_int_option (C function)
4467 @anchor{topics/contexts gcc_jit_context_set_int_option}@anchor{1e}
4468 @deffn {C Function} void gcc_jit_context_set_int_option (gcc_jit_context@w{ }*ctxt, enum gcc_jit_int_option@w{ }opt, int@w{ }value)
4470 Set an integer option of the context.
4472 @geindex gcc_jit_int_option (C type)
4473 @anchor{topics/contexts gcc_jit_int_option}@anchor{61}
4474 @deffn {C Type} enum gcc_jit_int_option
4475 @end deffn
4477 There is currently just one integer option:
4479 @geindex GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL (C macro)
4480 @anchor{topics/contexts GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL}@anchor{1f}
4481 @deffn {C Macro} GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL
4483 How much to optimize the code.
4485 Valid values are 0-3, corresponding to GCC's command-line options
4486 -O0 through -O3.
4488 The default value is 0 (unoptimized).
4489 @end deffn
4490 @end deffn
4492 @c Copyright (C) 2014 Free Software Foundation, Inc.
4493 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
4494 @c 
4495 @c This is free software: you can redistribute it and/or modify it
4496 @c under the terms of the GNU General Public License as published by
4497 @c the Free Software Foundation, either version 3 of the License, or
4498 @c (at your option) any later version.
4499 @c 
4500 @c This program is distributed in the hope that it will be useful, but
4501 @c WITHOUT ANY WARRANTY; without even the implied warranty of
4502 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
4503 @c General Public License for more details.
4504 @c 
4505 @c You should have received a copy of the GNU General Public License
4506 @c along with this program.  If not, see
4507 @c <http://www.gnu.org/licenses/>.
4509 @node Objects,Types,Compilation contexts,Topic Reference
4510 @anchor{topics/objects objects}@anchor{62}@anchor{topics/objects doc}@anchor{63}
4511 @section Objects
4514 @geindex gcc_jit_object (C type)
4515 @anchor{topics/objects gcc_jit_object}@anchor{e}
4516 @deffn {C Type} gcc_jit_object
4517 @end deffn
4519 Almost every entity in the API (with the exception of
4520 @pxref{8,,gcc_jit_context *} and @pxref{16,,gcc_jit_result *}) is a
4521 "contextual" object, a @pxref{e,,gcc_jit_object *}
4523 A JIT object:
4525 @quotation
4528 @itemize *
4530 @item 
4531 is associated with a @pxref{8,,gcc_jit_context *}.
4533 @item 
4534 is automatically cleaned up for you when its context is released so
4535 you don't need to manually track and cleanup all objects, just the
4536 contexts.
4537 @end itemize
4538 @end quotation
4540 Although the API is C-based, there is a form of class hierarchy, which
4541 looks like this:
4543 @example
4544 +- gcc_jit_object
4545     +- gcc_jit_location
4546     +- gcc_jit_type
4547        +- gcc_jit_struct
4548     +- gcc_jit_field
4549     +- gcc_jit_function
4550     +- gcc_jit_block
4551     +- gcc_jit_rvalue
4552         +- gcc_jit_lvalue
4553            +- gcc_jit_param
4554 @end example
4556 @noindent
4558 There are casting methods for upcasting from subclasses to parent classes.
4559 For example, @pxref{d,,gcc_jit_type_as_object()}:
4561 @example
4562 gcc_jit_object *obj = gcc_jit_type_as_object (int_type);
4563 @end example
4565 @noindent
4567 The object "base class" has the following operations:
4569 @geindex gcc_jit_object_get_context (C function)
4570 @anchor{topics/objects gcc_jit_object_get_context}@anchor{64}
4571 @deffn {C Function} gcc_jit_context *gcc_jit_object_get_context (gcc_jit_object@w{ }*obj)
4573 Which context is "obj" within?
4574 @end deffn
4576 @geindex gcc_jit_object_get_debug_string (C function)
4577 @anchor{topics/objects gcc_jit_object_get_debug_string}@anchor{f}
4578 @deffn {C Function} const char *gcc_jit_object_get_debug_string (gcc_jit_object@w{ }*obj)
4580 Generate a human-readable description for the given object.
4582 For example,
4584 @example
4585 printf ("obj: %s\n", gcc_jit_object_get_debug_string (obj));
4586 @end example
4588 @noindent
4590 might give this text on stdout:
4592 @example
4593 obj: 4.0 * (float)i
4594 @end example
4596 @noindent
4598 @cartouche
4599 @quotation Note 
4600 If you call this on an object, the @cite{const char *} buffer is allocated
4601 and generated on the first call for that object, and the buffer will
4602 have the same lifetime as the object  i.e. it will exist until the
4603 object's context is released.
4604 @end quotation
4605 @end cartouche
4606 @end deffn
4608 @c Copyright (C) 2014 Free Software Foundation, Inc.
4609 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
4610 @c 
4611 @c This is free software: you can redistribute it and/or modify it
4612 @c under the terms of the GNU General Public License as published by
4613 @c the Free Software Foundation, either version 3 of the License, or
4614 @c (at your option) any later version.
4615 @c 
4616 @c This program is distributed in the hope that it will be useful, but
4617 @c WITHOUT ANY WARRANTY; without even the implied warranty of
4618 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
4619 @c General Public License for more details.
4620 @c 
4621 @c You should have received a copy of the GNU General Public License
4622 @c along with this program.  If not, see
4623 @c <http://www.gnu.org/licenses/>.
4625 @node Types,Expressions,Objects,Topic Reference
4626 @anchor{topics/types doc}@anchor{65}@anchor{topics/types types}@anchor{66}
4627 @section Types
4630 @geindex gcc_jit_type (C type)
4631 @anchor{topics/types gcc_jit_type}@anchor{a}
4632 @deffn {C Type} gcc_jit_type
4634 gcc_jit_type represents a type within the library.
4635 @end deffn
4637 @geindex gcc_jit_type_as_object (C function)
4638 @anchor{topics/types gcc_jit_type_as_object}@anchor{d}
4639 @deffn {C Function} gcc_jit_object *gcc_jit_type_as_object (gcc_jit_type@w{ }*type)
4641 Upcast a type to an object.
4642 @end deffn
4644 Types can be created in several ways:
4647 @itemize *
4649 @item 
4650 fundamental types can be accessed using
4651 @pxref{b,,gcc_jit_context_get_type()}:
4653 @example
4654 gcc_jit_type *int_type = gcc_jit_context_get_type (GCC_JIT_TYPE_INT);
4655 @end example
4657 @noindent
4659 See @pxref{b,,gcc_jit_context_get_type()} for the available types.
4661 @item 
4662 derived types can be accessed by using functions such as
4663 @pxref{67,,gcc_jit_type_get_pointer()} and @pxref{68,,gcc_jit_type_get_const()}:
4665 @example
4666 gcc_jit_type *const_int_star = gcc_jit_type_get_pointer (gcc_jit_type_get_const (int_type));
4667 gcc_jit_type *int_const_star = gcc_jit_type_get_const (gcc_jit_type_get_pointer (int_type));
4668 @end example
4670 @noindent
4672 @item 
4673 by creating structures (see below).
4674 @end itemize
4676 @menu
4677 * Standard types:: 
4678 * Pointers@comma{} const@comma{} and volatile: Pointers const and volatile. 
4679 * Structures and unions:: 
4681 @end menu
4683 @node Standard types,Pointers const and volatile,,Types
4684 @anchor{topics/types standard-types}@anchor{69}
4685 @subsection Standard types
4688 @geindex gcc_jit_context_get_type (C function)
4689 @anchor{topics/types gcc_jit_context_get_type}@anchor{b}
4690 @deffn {C Function} gcc_jit_type *gcc_jit_context_get_type (gcc_jit_context@w{ }*ctxt, enum gcc_jit_types@w{ }type_)
4692 Access a specific type.  The available types are:
4695 @multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
4696 @headitem
4698 @cite{enum gcc_jit_types} value
4700 @tab
4702 Meaning
4704 @item
4706 @code{GCC_JIT_TYPE_VOID}
4708 @tab
4710 C's @code{void} type.
4712 @item
4714 @code{GCC_JIT_TYPE_VOID_PTR}
4716 @tab
4718 C's @code{void *}.
4720 @item
4722 @code{GCC_JIT_TYPE_BOOL}
4724 @tab
4726 C++'s @code{bool} type; also C99's
4727 @code{_Bool} type, aka @code{bool} if
4728 using stdbool.h.
4730 @item
4732 @code{GCC_JIT_TYPE_CHAR}
4734 @tab
4736 C's @code{char} (of some signedness)
4738 @item
4740 @code{GCC_JIT_TYPE_SIGNED_CHAR}
4742 @tab
4744 C's @code{signed char}
4746 @item
4748 @code{GCC_JIT_TYPE_UNSIGNED_CHAR}
4750 @tab
4752 C's @code{unsigned char}
4754 @item
4756 @code{GCC_JIT_TYPE_SHORT}
4758 @tab
4760 C's @code{short} (signed)
4762 @item
4764 @code{GCC_JIT_TYPE_UNSIGNED_SHORT}
4766 @tab
4768 C's @code{unsigned short}
4770 @item
4772 @code{GCC_JIT_TYPE_INT}
4774 @tab
4776 C's @code{int} (signed)
4778 @item
4780 @code{GCC_JIT_TYPE_UNSIGNED_INT}
4782 @tab
4784 C's @code{unsigned int}
4786 @item
4788 @code{GCC_JIT_TYPE_LONG}
4790 @tab
4792 C's @code{long} (signed)
4794 @item
4796 @code{GCC_JIT_TYPE_UNSIGNED_LONG}
4798 @tab
4800 C's @code{unsigned long}
4802 @item
4804 @code{GCC_JIT_TYPE_LONG_LONG}
4806 @tab
4808 C99's @code{long long} (signed)
4810 @item
4812 @code{GCC_JIT_TYPE_UNSIGNED_LONG_LONG}
4814 @tab
4816 C99's @code{unsigned long long}
4818 @item
4820 @code{GCC_JIT_TYPE_FLOAT}
4822 @tab
4824 @item
4826 @code{GCC_JIT_TYPE_DOUBLE}
4828 @tab
4830 @item
4832 @code{GCC_JIT_TYPE_LONG_DOUBLE}
4834 @tab
4836 @item
4838 @code{GCC_JIT_TYPE_CONST_CHAR_PTR}
4840 @tab
4842 C type: @code{(const char *)}
4844 @item
4846 @code{GCC_JIT_TYPE_SIZE_T}
4848 @tab
4850 C's @code{size_t} type
4852 @item
4854 @code{GCC_JIT_TYPE_FILE_PTR}
4856 @tab
4858 C type: @code{(FILE *)}
4860 @item
4862 @code{GCC_JIT_TYPE_COMPLEX_FLOAT}
4864 @tab
4866 C99's @code{_Complex float}
4868 @item
4870 @code{GCC_JIT_TYPE_COMPLEX_DOUBLE}
4872 @tab
4874 C99's @code{_Complex double}
4876 @item
4878 @code{GCC_JIT_TYPE_COMPLEX_LONG_DOUBLE}
4880 @tab
4882 C99's @code{_Complex long double}
4884 @end multitable
4886 @end deffn
4888 @geindex gcc_jit_context_get_int_type (C function)
4889 @anchor{topics/types gcc_jit_context_get_int_type}@anchor{6a}
4890 @deffn {C Function} gcc_jit_type *           gcc_jit_context_get_int_type (gcc_jit_context@w{ }*ctxt, int@w{ }num_bytes, int@w{ }is_signed)
4892 Access the integer type of the given size.
4893 @end deffn
4895 @node Pointers const and volatile,Structures and unions,Standard types,Types
4896 @anchor{topics/types pointers-const-and-volatile}@anchor{6b}
4897 @subsection Pointers, @cite{const}, and @cite{volatile}
4900 @geindex gcc_jit_type_get_pointer (C function)
4901 @anchor{topics/types gcc_jit_type_get_pointer}@anchor{67}
4902 @deffn {C Function} gcc_jit_type *gcc_jit_type_get_pointer (gcc_jit_type@w{ }*type)
4904 Given type "T", get type "T*".
4905 @end deffn
4907 @geindex gcc_jit_type_get_const (C function)
4908 @anchor{topics/types gcc_jit_type_get_const}@anchor{68}
4909 @deffn {C Function} gcc_jit_type *gcc_jit_type_get_const (gcc_jit_type@w{ }*type)
4911 Given type "T", get type "const T".
4912 @end deffn
4914 @geindex gcc_jit_type_get_volatile (C function)
4915 @anchor{topics/types gcc_jit_type_get_volatile}@anchor{6c}
4916 @deffn {C Function} gcc_jit_type *gcc_jit_type_get_volatile (gcc_jit_type@w{ }*type)
4918 Given type "T", get type "volatile T".
4919 @end deffn
4921 @geindex gcc_jit_context_new_array_type (C function)
4922 @anchor{topics/types gcc_jit_context_new_array_type}@anchor{6d}
4923 @deffn {C Function} gcc_jit_type *            gcc_jit_context_new_array_type (gcc_jit_context@w{ }*ctxt, gcc_jit_location@w{ }*loc, gcc_jit_type@w{ }*element_type, int@w{ }num_elements)
4925 Given type "T", get type "T[N]" (for a constant N).
4926 @end deffn
4928 @node Structures and unions,,Pointers const and volatile,Types
4929 @anchor{topics/types structures-and-unions}@anchor{6e}
4930 @subsection Structures and unions
4933 @geindex gcc_jit_struct (C type)
4934 @anchor{topics/types gcc_jit_struct}@anchor{6f}
4935 @deffn {C Type} gcc_jit_struct
4936 @end deffn
4938 A compound type analagous to a C @cite{struct}.
4940 @geindex gcc_jit_field (C type)
4941 @anchor{topics/types gcc_jit_field}@anchor{70}
4942 @deffn {C Type} gcc_jit_field
4943 @end deffn
4945 A field within a @pxref{6f,,gcc_jit_struct}.
4947 You can model C @cite{struct} types by creating @pxref{6f,,gcc_jit_struct *} and
4948 @pxref{70,,gcc_jit_field} instances, in either order:
4951 @itemize *
4953 @item 
4954 by creating the fields, then the structure.  For example, to model:
4956 @example
4957 struct coord @{double x; double y; @};
4958 @end example
4960 @noindent
4962 you could call:
4964 @example
4965 gcc_jit_field *field_x =
4966   gcc_jit_context_new_field (ctxt, NULL, double_type, "x");
4967 gcc_jit_field *field_y =
4968   gcc_jit_context_new_field (ctxt, NULL, double_type, "y");
4969 gcc_jit_field *fields[2] = @{field_x, field_y@};
4970 gcc_jit_struct *coord =
4971   gcc_jit_context_new_struct_type (ctxt, NULL, "coord", 2, fields);
4972 @end example
4974 @noindent
4976 @item 
4977 by creating the structure, then populating it with fields, typically
4978 to allow modelling self-referential structs such as:
4980 @example
4981 struct node @{ int m_hash; struct node *m_next; @};
4982 @end example
4984 @noindent
4986 like this:
4988 @example
4989 gcc_jit_type *node =
4990   gcc_jit_context_new_opaque_struct (ctxt, NULL, "node");
4991 gcc_jit_type *node_ptr =
4992   gcc_jit_type_get_pointer (node);
4993 gcc_jit_field *field_hash =
4994   gcc_jit_context_new_field (ctxt, NULL, int_type, "m_hash");
4995 gcc_jit_field *field_next =
4996   gcc_jit_context_new_field (ctxt, NULL, node_ptr, "m_next");
4997 gcc_jit_field *fields[2] = @{field_hash, field_next@};
4998 gcc_jit_struct_set_fields (node, NULL, 2, fields);
4999 @end example
5001 @noindent
5002 @end itemize
5004 @geindex gcc_jit_context_new_field (C function)
5005 @anchor{topics/types gcc_jit_context_new_field}@anchor{71}
5006 @deffn {C Function} gcc_jit_field *           gcc_jit_context_new_field (gcc_jit_context@w{ }*ctxt, gcc_jit_location@w{ }*loc, gcc_jit_type@w{ }*type, const char@w{ }*name)
5008 Construct a new field, with the given type and name.
5009 @end deffn
5011 @geindex gcc_jit_field_as_object (C function)
5012 @anchor{topics/types gcc_jit_field_as_object}@anchor{72}
5013 @deffn {C Function} gcc_jit_object *           gcc_jit_field_as_object (gcc_jit_field@w{ }*field)
5015 Upcast from field to object.
5016 @end deffn
5018 @geindex gcc_jit_context_new_struct_type (C function)
5019 @anchor{topics/types gcc_jit_context_new_struct_type}@anchor{73}
5020 @deffn {C Function} gcc_jit_struct *gcc_jit_context_new_struct_type (gcc_jit_context@w{ }*ctxt, gcc_jit_location@w{ }*loc, const char@w{ }*name, int@w{ }num_fields, gcc_jit_field@w{ }**fields)
5022 @quotation
5024 Construct a new struct type, with the given name and fields.
5025 @end quotation
5026 @end deffn
5028 @geindex gcc_jit_context_new_opaque_struct (C function)
5029 @anchor{topics/types gcc_jit_context_new_opaque_struct}@anchor{74}
5030 @deffn {C Function} gcc_jit_struct *         gcc_jit_context_new_opaque_struct (gcc_jit_context@w{ }*ctxt, gcc_jit_location@w{ }*loc, const char@w{ }*name)
5032 Construct a new struct type, with the given name, but without
5033 specifying the fields.   The fields can be omitted (in which case the
5034 size of the struct is not known), or later specified using
5035 @pxref{75,,gcc_jit_struct_set_fields()}.
5036 @end deffn
5038 @geindex gcc_jit_struct_as_type (C function)
5039 @anchor{topics/types gcc_jit_struct_as_type}@anchor{76}
5040 @deffn {C Function} gcc_jit_type *           gcc_jit_struct_as_type (gcc_jit_struct@w{ }*struct_type)
5042 Upcast from struct to type.
5043 @end deffn
5045 @geindex gcc_jit_struct_set_fields (C function)
5046 @anchor{topics/types gcc_jit_struct_set_fields}@anchor{75}
5047 @deffn {C Function} void           gcc_jit_struct_set_fields (gcc_jit_struct@w{ }*struct_type, gcc_jit_location@w{ }*loc, int@w{ }num_fields, gcc_jit_field@w{ }**fields)
5049 Populate the fields of a formerly-opaque struct type.
5051 This can only be called once on a given struct type.
5052 @end deffn
5054 @c Copyright (C) 2014 Free Software Foundation, Inc.
5055 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
5056 @c 
5057 @c This is free software: you can redistribute it and/or modify it
5058 @c under the terms of the GNU General Public License as published by
5059 @c the Free Software Foundation, either version 3 of the License, or
5060 @c (at your option) any later version.
5061 @c 
5062 @c This program is distributed in the hope that it will be useful, but
5063 @c WITHOUT ANY WARRANTY; without even the implied warranty of
5064 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
5065 @c General Public License for more details.
5066 @c 
5067 @c You should have received a copy of the GNU General Public License
5068 @c along with this program.  If not, see
5069 @c <http://www.gnu.org/licenses/>.
5071 @node Expressions,Creating and using functions,Types,Topic Reference
5072 @anchor{topics/expressions expressions}@anchor{77}@anchor{topics/expressions doc}@anchor{78}
5073 @section Expressions
5076 @menu
5077 * Rvalues:: 
5078 * Lvalues:: 
5079 * Working with pointers@comma{} structs and unions: Working with pointers structs and unions. 
5081 Rvalues
5083 * Simple expressions:: 
5084 * Unary Operations:: 
5085 * Binary Operations:: 
5086 * Comparisons:: 
5087 * Function calls:: 
5088 * Type-coercion:: 
5090 Lvalues
5092 * Global variables:: 
5094 @end menu
5097 @node Rvalues,Lvalues,,Expressions
5098 @anchor{topics/expressions rvalues}@anchor{79}
5099 @subsection Rvalues
5102 @geindex gcc_jit_rvalue (C type)
5103 @anchor{topics/expressions gcc_jit_rvalue}@anchor{13}
5104 @deffn {C Type} gcc_jit_rvalue
5105 @end deffn
5107 A @pxref{13,,gcc_jit_rvalue *} is an expression that can be computed.
5109 It can be simple, e.g.:
5111 @quotation
5114 @itemize *
5116 @item 
5117 an integer value e.g. @cite{0} or @cite{42}
5119 @item 
5120 a string literal e.g. @cite{"Hello world"}
5122 @item 
5123 a variable e.g. @cite{i}.  These are also lvalues (see below).
5124 @end itemize
5125 @end quotation
5127 or compound e.g.:
5129 @quotation
5132 @itemize *
5134 @item 
5135 a unary expression e.g. @cite{!cond}
5137 @item 
5138 a binary expression e.g. @cite{(a + b)}
5140 @item 
5141 a function call e.g. @cite{get_distance (&player_ship@comma{} &target)}
5143 @item 
5144 etc.
5145 @end itemize
5146 @end quotation
5148 Every rvalue has an associated type, and the API will check to ensure
5149 that types match up correctly (otherwise the context will emit an error).
5151 @geindex gcc_jit_rvalue_get_type (C function)
5152 @anchor{topics/expressions gcc_jit_rvalue_get_type}@anchor{7a}
5153 @deffn {C Function} gcc_jit_type *gcc_jit_rvalue_get_type (gcc_jit_rvalue@w{ }*rvalue)
5155 Get the type of this rvalue.
5156 @end deffn
5158 @geindex gcc_jit_rvalue_as_object (C function)
5159 @anchor{topics/expressions gcc_jit_rvalue_as_object}@anchor{14}
5160 @deffn {C Function} gcc_jit_object *gcc_jit_rvalue_as_object (gcc_jit_rvalue@w{ }*rvalue)
5162 Upcast the given rvalue to be an object.
5163 @end deffn
5165 @menu
5166 * Simple expressions:: 
5167 * Unary Operations:: 
5168 * Binary Operations:: 
5169 * Comparisons:: 
5170 * Function calls:: 
5171 * Type-coercion:: 
5173 @end menu
5175 @node Simple expressions,Unary Operations,,Rvalues
5176 @anchor{topics/expressions simple-expressions}@anchor{7b}
5177 @subsubsection Simple expressions
5180 @geindex gcc_jit_context_new_rvalue_from_int (C function)
5181 @anchor{topics/expressions gcc_jit_context_new_rvalue_from_int}@anchor{30}
5182 @deffn {C Function} gcc_jit_rvalue *           gcc_jit_context_new_rvalue_from_int (gcc_jit_context@w{ }*ctxt, gcc_jit_type@w{ }*numeric_type, int@w{ }value)
5184 Given a numeric type (integer or floating point), build an rvalue for
5185 the given constant value.
5186 @end deffn
5188 @geindex gcc_jit_context_zero (C function)
5189 @anchor{topics/expressions gcc_jit_context_zero}@anchor{2b}
5190 @deffn {C Function} gcc_jit_rvalue *gcc_jit_context_zero (gcc_jit_context@w{ }*ctxt, gcc_jit_type@w{ }*numeric_type)
5192 Given a numeric type (integer or floating point), get the rvalue for
5193 zero.  Essentially this is just a shortcut for:
5195 @example
5196 gcc_jit_context_new_rvalue_from_int (ctxt, numeric_type, 0)
5197 @end example
5199 @noindent
5200 @end deffn
5202 @geindex gcc_jit_context_one (C function)
5203 @anchor{topics/expressions gcc_jit_context_one}@anchor{2f}
5204 @deffn {C Function} gcc_jit_rvalue *gcc_jit_context_one (gcc_jit_context@w{ }*ctxt, gcc_jit_type@w{ }*numeric_type)
5206 Given a numeric type (integer or floating point), get the rvalue for
5207 zero.  Essentially this is just a shortcut for:
5209 @example
5210 gcc_jit_context_new_rvalue_from_int (ctxt, numeric_type, 1)
5211 @end example
5213 @noindent
5214 @end deffn
5216 @geindex gcc_jit_context_new_rvalue_from_double (C function)
5217 @anchor{topics/expressions gcc_jit_context_new_rvalue_from_double}@anchor{31}
5218 @deffn {C Function} gcc_jit_rvalue *            gcc_jit_context_new_rvalue_from_double (gcc_jit_context@w{ }*ctxt, gcc_jit_type@w{ }*numeric_type, double@w{ }value)
5220 Given a numeric type (integer or floating point), build an rvalue for
5221 the given constant value.
5222 @end deffn
5224 @geindex gcc_jit_context_new_rvalue_from_ptr (C function)
5225 @anchor{topics/expressions gcc_jit_context_new_rvalue_from_ptr}@anchor{7c}
5226 @deffn {C Function} gcc_jit_rvalue *           gcc_jit_context_new_rvalue_from_ptr (gcc_jit_context@w{ }*ctxt, gcc_jit_type@w{ }*pointer_type, void@w{ }*value)
5228 Given a pointer type, build an rvalue for the given address.
5229 @end deffn
5231 @geindex gcc_jit_context_null (C function)
5232 @anchor{topics/expressions gcc_jit_context_null}@anchor{7d}
5233 @deffn {C Function} gcc_jit_rvalue *gcc_jit_context_null (gcc_jit_context@w{ }*ctxt, gcc_jit_type@w{ }*pointer_type)
5235 Given a pointer type, build an rvalue for @code{NULL}.  Essentially this
5236 is just a shortcut for:
5238 @example
5239 gcc_jit_context_new_rvalue_from_ptr (ctxt, pointer_type, NULL)
5240 @end example
5242 @noindent
5243 @end deffn
5245 @geindex gcc_jit_context_new_string_literal (C function)
5246 @anchor{topics/expressions gcc_jit_context_new_string_literal}@anchor{7e}
5247 @deffn {C Function} gcc_jit_rvalue *           gcc_jit_context_new_string_literal (gcc_jit_context@w{ }*ctxt, const char@w{ }*value)
5249 Generate an rvalue for the given NIL-terminated string, of type
5250 @code{GCC_JIT_TYPE_CONST_CHAR_PTR}.
5251 @end deffn
5253 @node Unary Operations,Binary Operations,Simple expressions,Rvalues
5254 @anchor{topics/expressions unary-operations}@anchor{7f}
5255 @subsubsection Unary Operations
5258 @geindex gcc_jit_context_new_unary_op (C function)
5259 @anchor{topics/expressions gcc_jit_context_new_unary_op}@anchor{80}
5260 @deffn {C Function} gcc_jit_rvalue *            gcc_jit_context_new_unary_op (gcc_jit_context@w{ }*ctxt, gcc_jit_location@w{ }*loc, enum gcc_jit_unary_op@w{ }op, gcc_jit_type@w{ }*result_type, gcc_jit_rvalue@w{ }*rvalue)
5262 Build a unary operation out of an input rvalue.
5263 @end deffn
5265 @geindex gcc_jit_unary_op (C type)
5266 @anchor{topics/expressions gcc_jit_unary_op}@anchor{81}
5267 @deffn {C Type} enum gcc_jit_unary_op
5268 @end deffn
5270 The available unary operations are:
5273 @multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxx} 
5274 @headitem
5276 Unary Operation
5278 @tab
5280 C equivalent
5282 @item
5284 @pxref{82,,GCC_JIT_UNARY_OP_MINUS}
5286 @tab
5288 @cite{-(EXPR)}
5290 @item
5292 @pxref{83,,GCC_JIT_UNARY_OP_BITWISE_NEGATE}
5294 @tab
5296 @cite{~(EXPR)}
5298 @item
5300 @pxref{84,,GCC_JIT_UNARY_OP_LOGICAL_NEGATE}
5302 @tab
5304 @cite{!(EXPR)}
5306 @end multitable
5309 @geindex GCC_JIT_UNARY_OP_MINUS (C macro)
5310 @anchor{topics/expressions GCC_JIT_UNARY_OP_MINUS}@anchor{82}
5311 @deffn {C Macro} GCC_JIT_UNARY_OP_MINUS
5313 Negate an arithmetic value; analogous to:
5315 @example
5316 -(EXPR)
5317 @end example
5319 @noindent
5321 in C.
5322 @end deffn
5324 @geindex GCC_JIT_UNARY_OP_BITWISE_NEGATE (C macro)
5325 @anchor{topics/expressions GCC_JIT_UNARY_OP_BITWISE_NEGATE}@anchor{83}
5326 @deffn {C Macro} GCC_JIT_UNARY_OP_BITWISE_NEGATE
5328 Bitwise negation of an integer value (one's complement); analogous
5331 @example
5332 ~(EXPR)
5333 @end example
5335 @noindent
5337 in C.
5338 @end deffn
5340 @geindex GCC_JIT_UNARY_OP_LOGICAL_NEGATE (C macro)
5341 @anchor{topics/expressions GCC_JIT_UNARY_OP_LOGICAL_NEGATE}@anchor{84}
5342 @deffn {C Macro} GCC_JIT_UNARY_OP_LOGICAL_NEGATE
5344 Logical negation of an arithmetic or pointer value; analogous to:
5346 @example
5347 !(EXPR)
5348 @end example
5350 @noindent
5352 in C.
5353 @end deffn
5355 @node Binary Operations,Comparisons,Unary Operations,Rvalues
5356 @anchor{topics/expressions binary-operations}@anchor{85}
5357 @subsubsection Binary Operations
5360 @geindex gcc_jit_context_new_binary_op (C function)
5361 @anchor{topics/expressions gcc_jit_context_new_binary_op}@anchor{12}
5362 @deffn {C Function} gcc_jit_rvalue *gcc_jit_context_new_binary_op (gcc_jit_context@w{ }*ctxt, gcc_jit_location@w{ }*loc, enum gcc_jit_binary_op@w{ }op, gcc_jit_type@w{ }*result_type, gcc_jit_rvalue@w{ }*a, gcc_jit_rvalue@w{ }*b)
5364 Build a binary operation out of two constituent rvalues.
5365 @end deffn
5367 @geindex gcc_jit_binary_op (C type)
5368 @anchor{topics/expressions gcc_jit_binary_op}@anchor{86}
5369 @deffn {C Type} enum gcc_jit_binary_op
5370 @end deffn
5372 The available binary operations are:
5375 @multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxx} 
5376 @headitem
5378 Binary Operation
5380 @tab
5382 C equivalent
5384 @item
5386 @pxref{87,,GCC_JIT_BINARY_OP_PLUS}
5388 @tab
5390 @cite{x + y}
5392 @item
5394 @code{GCC_JIT_BINARY_OP_MINUS}
5396 @tab
5398 @cite{x - y}
5400 @item
5402 @pxref{88,,GCC_JIT_BINARY_OP_MULT}
5404 @tab
5406 @cite{x * y}
5408 @item
5410 @pxref{89,,GCC_JIT_BINARY_OP_DIVIDE}
5412 @tab
5414 @cite{x / y}
5416 @item
5418 @pxref{8a,,GCC_JIT_BINARY_OP_MODULO}
5420 @tab
5422 @cite{x % y}
5424 @item
5426 @pxref{8b,,GCC_JIT_BINARY_OP_BITWISE_AND}
5428 @tab
5430 @cite{x & y}
5432 @item
5434 @pxref{8c,,GCC_JIT_BINARY_OP_BITWISE_XOR}
5436 @tab
5438 @cite{x ^ y}
5440 @item
5442 @pxref{8d,,GCC_JIT_BINARY_OP_BITWISE_OR}
5444 @tab
5446 @cite{x | y}
5448 @item
5450 @pxref{8e,,GCC_JIT_BINARY_OP_LOGICAL_AND}
5452 @tab
5454 @cite{x && y}
5456 @item
5458 @pxref{8f,,GCC_JIT_BINARY_OP_LOGICAL_OR}
5460 @tab
5462 @cite{x || y}
5464 @item
5466 @pxref{90,,GCC_JIT_BINARY_OP_LSHIFT}
5468 @tab
5470 @cite{x << y}
5472 @item
5474 @pxref{91,,GCC_JIT_BINARY_OP_RSHIFT}
5476 @tab
5478 @cite{x >> y}
5480 @end multitable
5483 @geindex GCC_JIT_BINARY_OP_PLUS (C macro)
5484 @anchor{topics/expressions GCC_JIT_BINARY_OP_PLUS}@anchor{87}
5485 @deffn {C Macro} GCC_JIT_BINARY_OP_PLUS
5487 Addition of arithmetic values; analogous to:
5489 @example
5490 (EXPR_A) + (EXPR_B)
5491 @end example
5493 @noindent
5495 in C.
5497 For pointer addition, use @pxref{92,,gcc_jit_context_new_array_access()}.
5498 @end deffn
5501 @deffn {C Macro} GCC_JIT_BINARY_OP_MINUS`
5503 Subtraction of arithmetic values; analogous to:
5505 @example
5506 (EXPR_A) - (EXPR_B)
5507 @end example
5509 @noindent
5511 in C.
5512 @end deffn
5514 @geindex GCC_JIT_BINARY_OP_MULT (C macro)
5515 @anchor{topics/expressions GCC_JIT_BINARY_OP_MULT}@anchor{88}
5516 @deffn {C Macro} GCC_JIT_BINARY_OP_MULT
5518 Multiplication of a pair of arithmetic values; analogous to:
5520 @example
5521 (EXPR_A) * (EXPR_B)
5522 @end example
5524 @noindent
5526 in C.
5527 @end deffn
5529 @geindex GCC_JIT_BINARY_OP_DIVIDE (C macro)
5530 @anchor{topics/expressions GCC_JIT_BINARY_OP_DIVIDE}@anchor{89}
5531 @deffn {C Macro} GCC_JIT_BINARY_OP_DIVIDE
5533 Quotient of division of arithmetic values; analogous to:
5535 @example
5536 (EXPR_A) / (EXPR_B)
5537 @end example
5539 @noindent
5541 in C.
5543 The result type affects the kind of division: if the result type is
5544 integer-based, then the result is truncated towards zero, whereas
5545 a floating-point result type indicates floating-point division.
5546 @end deffn
5548 @geindex GCC_JIT_BINARY_OP_MODULO (C macro)
5549 @anchor{topics/expressions GCC_JIT_BINARY_OP_MODULO}@anchor{8a}
5550 @deffn {C Macro} GCC_JIT_BINARY_OP_MODULO
5552 Remainder of division of arithmetic values; analogous to:
5554 @example
5555 (EXPR_A) % (EXPR_B)
5556 @end example
5558 @noindent
5560 in C.
5561 @end deffn
5563 @geindex GCC_JIT_BINARY_OP_BITWISE_AND (C macro)
5564 @anchor{topics/expressions GCC_JIT_BINARY_OP_BITWISE_AND}@anchor{8b}
5565 @deffn {C Macro} GCC_JIT_BINARY_OP_BITWISE_AND
5567 Bitwise AND; analogous to:
5569 @example
5570 (EXPR_A) & (EXPR_B)
5571 @end example
5573 @noindent
5575 in C.
5576 @end deffn
5578 @geindex GCC_JIT_BINARY_OP_BITWISE_XOR (C macro)
5579 @anchor{topics/expressions GCC_JIT_BINARY_OP_BITWISE_XOR}@anchor{8c}
5580 @deffn {C Macro} GCC_JIT_BINARY_OP_BITWISE_XOR
5582 Bitwise exclusive OR; analogous to:
5584 @example
5585 (EXPR_A) ^ (EXPR_B)
5586 @end example
5588 @noindent
5590 in C.
5591 @end deffn
5593 @geindex GCC_JIT_BINARY_OP_BITWISE_OR (C macro)
5594 @anchor{topics/expressions GCC_JIT_BINARY_OP_BITWISE_OR}@anchor{8d}
5595 @deffn {C Macro} GCC_JIT_BINARY_OP_BITWISE_OR
5597 Bitwise inclusive OR; analogous to:
5599 @example
5600 (EXPR_A) | (EXPR_B)
5601 @end example
5603 @noindent
5605 in C.
5606 @end deffn
5608 @geindex GCC_JIT_BINARY_OP_LOGICAL_AND (C macro)
5609 @anchor{topics/expressions GCC_JIT_BINARY_OP_LOGICAL_AND}@anchor{8e}
5610 @deffn {C Macro} GCC_JIT_BINARY_OP_LOGICAL_AND
5612 Logical AND; analogous to:
5614 @example
5615 (EXPR_A) && (EXPR_B)
5616 @end example
5618 @noindent
5620 in C.
5621 @end deffn
5623 @geindex GCC_JIT_BINARY_OP_LOGICAL_OR (C macro)
5624 @anchor{topics/expressions GCC_JIT_BINARY_OP_LOGICAL_OR}@anchor{8f}
5625 @deffn {C Macro} GCC_JIT_BINARY_OP_LOGICAL_OR
5627 Logical OR; analogous to:
5629 @example
5630 (EXPR_A) || (EXPR_B)
5631 @end example
5633 @noindent
5635 in C.
5636 @end deffn
5638 @geindex GCC_JIT_BINARY_OP_LSHIFT (C macro)
5639 @anchor{topics/expressions GCC_JIT_BINARY_OP_LSHIFT}@anchor{90}
5640 @deffn {C Macro} GCC_JIT_BINARY_OP_LSHIFT
5642 Left shift; analogous to:
5644 @example
5645 (EXPR_A) << (EXPR_B)
5646 @end example
5648 @noindent
5650 in C.
5651 @end deffn
5653 @geindex GCC_JIT_BINARY_OP_RSHIFT (C macro)
5654 @anchor{topics/expressions GCC_JIT_BINARY_OP_RSHIFT}@anchor{91}
5655 @deffn {C Macro} GCC_JIT_BINARY_OP_RSHIFT
5657 Right shift; analogous to:
5659 @example
5660 (EXPR_A) >> (EXPR_B)
5661 @end example
5663 @noindent
5665 in C.
5666 @end deffn
5668 @node Comparisons,Function calls,Binary Operations,Rvalues
5669 @anchor{topics/expressions comparisons}@anchor{93}
5670 @subsubsection Comparisons
5673 @geindex gcc_jit_context_new_comparison (C function)
5674 @anchor{topics/expressions gcc_jit_context_new_comparison}@anchor{2c}
5675 @deffn {C Function} gcc_jit_rvalue *           gcc_jit_context_new_comparison (gcc_jit_context@w{ }*ctxt, gcc_jit_location@w{ }*loc, enum gcc_jit_comparison@w{ }op, gcc_jit_rvalue@w{ }*a, gcc_jit_rvalue@w{ }*b)
5677 Build a boolean rvalue out of the comparison of two other rvalues.
5678 @end deffn
5680 @geindex gcc_jit_comparison (C type)
5681 @anchor{topics/expressions gcc_jit_comparison}@anchor{94}
5682 @deffn {C Type} enum gcc_jit_comparison
5683 @end deffn
5686 @multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxx} 
5687 @headitem
5689 Comparison
5691 @tab
5693 C equivalent
5695 @item
5697 @code{GCC_JIT_COMPARISON_EQ}
5699 @tab
5701 @cite{x == y}
5703 @item
5705 @code{GCC_JIT_COMPARISON_NE}
5707 @tab
5709 @cite{x != y}
5711 @item
5713 @code{GCC_JIT_COMPARISON_LT}
5715 @tab
5717 @cite{x < y}
5719 @item
5721 @code{GCC_JIT_COMPARISON_LE}
5723 @tab
5725 @cite{x <= y}
5727 @item
5729 @code{GCC_JIT_COMPARISON_GT}
5731 @tab
5733 @cite{x > y}
5735 @item
5737 @code{GCC_JIT_COMPARISON_GE}
5739 @tab
5741 @cite{x >= y}
5743 @end multitable
5746 @node Function calls,Type-coercion,Comparisons,Rvalues
5747 @anchor{topics/expressions function-calls}@anchor{95}
5748 @subsubsection Function calls
5751 @geindex gcc_jit_context_new_call (C function)
5752 @anchor{topics/expressions gcc_jit_context_new_call}@anchor{96}
5753 @deffn {C Function} gcc_jit_rvalue *           gcc_jit_context_new_call (gcc_jit_context@w{ }*ctxt, gcc_jit_location@w{ }*loc, gcc_jit_function@w{ }*func, int@w{ }numargs, gcc_jit_rvalue@w{ }**args)
5755 Given a function and the given table of argument rvalues, construct a
5756 call to the function, with the result as an rvalue.
5758 @cartouche
5759 @quotation Note 
5760 @pxref{96,,gcc_jit_context_new_call()} merely builds a
5761 @pxref{13,,gcc_jit_rvalue} i.e. an expression that can be evaluated,
5762 perhaps as part of a more complicated expression.
5763 The call @emph{won't} happen unless you add a statement to a function
5764 that evaluates the expression.
5766 For example, if you want to call a function and discard the result
5767 (or to call a function with @code{void} return type), use
5768 @pxref{97,,gcc_jit_block_add_eval()}:
5770 @example
5771 /* Add "(void)printf (arg0, arg1);".  */
5772 gcc_jit_block_add_eval (
5773   block, NULL,
5774   gcc_jit_context_new_call (
5775     ctxt,
5776     NULL,
5777     printf_func,
5778     2, args));
5779 @end example
5781 @noindent
5782 @end quotation
5783 @end cartouche
5784 @end deffn
5786 @node Type-coercion,,Function calls,Rvalues
5787 @anchor{topics/expressions type-coercion}@anchor{98}
5788 @subsubsection Type-coercion
5791 @geindex gcc_jit_context_new_cast (C function)
5792 @anchor{topics/expressions gcc_jit_context_new_cast}@anchor{99}
5793 @deffn {C Function} gcc_jit_rvalue *           gcc_jit_context_new_cast (gcc_jit_context@w{ }*ctxt, gcc_jit_location@w{ }*loc, gcc_jit_rvalue@w{ }*rvalue, gcc_jit_type@w{ }*type)
5795 Given an rvalue of T, construct another rvalue of another type.
5797 Currently only a limited set of conversions are possible:
5799 @quotation
5802 @itemize *
5804 @item 
5805 int <-> float
5807 @item 
5808 int <-> bool
5810 @item 
5811 P*  <-> Q*, for pointer types P and Q
5812 @end itemize
5813 @end quotation
5814 @end deffn
5816 @node Lvalues,Working with pointers structs and unions,Rvalues,Expressions
5817 @anchor{topics/expressions lvalues}@anchor{9a}
5818 @subsection Lvalues
5821 @geindex gcc_jit_lvalue (C type)
5822 @anchor{topics/expressions gcc_jit_lvalue}@anchor{24}
5823 @deffn {C Type} gcc_jit_lvalue
5824 @end deffn
5826 An lvalue is something that can of the @emph{left}-hand side of an assignment:
5827 a storage area (such as a variable).  It is also usable as an rvalue,
5828 where the rvalue is computed by reading from the storage area.
5830 @geindex gcc_jit_lvalue_as_object (C function)
5831 @anchor{topics/expressions gcc_jit_lvalue_as_object}@anchor{9b}
5832 @deffn {C Function} gcc_jit_object *           gcc_jit_lvalue_as_object (gcc_jit_lvalue@w{ }*lvalue)
5834 Upcast an lvalue to be an object.
5835 @end deffn
5837 @geindex gcc_jit_lvalue_as_rvalue (C function)
5838 @anchor{topics/expressions gcc_jit_lvalue_as_rvalue}@anchor{9c}
5839 @deffn {C Function} gcc_jit_rvalue *           gcc_jit_lvalue_as_rvalue (gcc_jit_lvalue@w{ }*lvalue)
5841 Upcast an lvalue to be an rvalue.
5842 @end deffn
5844 @geindex gcc_jit_lvalue_get_address (C function)
5845 @anchor{topics/expressions gcc_jit_lvalue_get_address}@anchor{9d}
5846 @deffn {C Function} gcc_jit_rvalue *           gcc_jit_lvalue_get_address (gcc_jit_lvalue@w{ }*lvalue, gcc_jit_location@w{ }*loc)
5848 Take the address of an lvalue; analogous to:
5850 @example
5851 &(EXPR)
5852 @end example
5854 @noindent
5856 in C.
5857 @end deffn
5859 @menu
5860 * Global variables:: 
5862 @end menu
5864 @node Global variables,,,Lvalues
5865 @anchor{topics/expressions global-variables}@anchor{9e}
5866 @subsubsection Global variables
5869 @geindex gcc_jit_context_new_global (C function)
5870 @anchor{topics/expressions gcc_jit_context_new_global}@anchor{9f}
5871 @deffn {C Function} gcc_jit_lvalue *           gcc_jit_context_new_global (gcc_jit_context@w{ }*ctxt, gcc_jit_location@w{ }*loc, gcc_jit_type@w{ }*type, const char@w{ }*name)
5873 Add a new global variable of the given type and name to the context.
5874 @end deffn
5876 @node Working with pointers structs and unions,,Lvalues,Expressions
5877 @anchor{topics/expressions working-with-pointers-structs-and-unions}@anchor{a0}
5878 @subsection Working with pointers, structs and unions
5881 @geindex gcc_jit_rvalue_dereference (C function)
5882 @anchor{topics/expressions gcc_jit_rvalue_dereference}@anchor{a1}
5883 @deffn {C Function} gcc_jit_lvalue *           gcc_jit_rvalue_dereference (gcc_jit_rvalue@w{ }*rvalue, gcc_jit_location@w{ }*loc)
5885 Given an rvalue of pointer type @code{T *}, dereferencing the pointer,
5886 getting an lvalue of type @code{T}.  Analogous to:
5888 @example
5889 *(EXPR)
5890 @end example
5892 @noindent
5894 in C.
5895 @end deffn
5897 Field access is provided separately for both lvalues and rvalues.
5899 @geindex gcc_jit_lvalue_access_field (C function)
5900 @anchor{topics/expressions gcc_jit_lvalue_access_field}@anchor{a2}
5901 @deffn {C Function} gcc_jit_lvalue *           gcc_jit_lvalue_access_field (gcc_jit_lvalue@w{ }*struct_, gcc_jit_location@w{ }*loc, gcc_jit_field@w{ }*field)
5903 Given an lvalue of struct or union type, access the given field,
5904 getting an lvalue of the field's type.  Analogous to:
5906 @example
5907 (EXPR).field = ...;
5908 @end example
5910 @noindent
5912 in C.
5913 @end deffn
5915 @geindex gcc_jit_rvalue_access_field (C function)
5916 @anchor{topics/expressions gcc_jit_rvalue_access_field}@anchor{a3}
5917 @deffn {C Function} gcc_jit_rvalue *           gcc_jit_rvalue_access_field (gcc_jit_rvalue@w{ }*struct_, gcc_jit_location@w{ }*loc, gcc_jit_field@w{ }*field)
5919 Given an rvalue of struct or union type, access the given field
5920 as an rvalue.  Analogous to:
5922 @example
5923 (EXPR).field
5924 @end example
5926 @noindent
5928 in C.
5929 @end deffn
5931 @geindex gcc_jit_rvalue_dereference_field (C function)
5932 @anchor{topics/expressions gcc_jit_rvalue_dereference_field}@anchor{a4}
5933 @deffn {C Function} gcc_jit_lvalue *           gcc_jit_rvalue_dereference_field (gcc_jit_rvalue@w{ }*ptr, gcc_jit_location@w{ }*loc, gcc_jit_field@w{ }*field)
5935 Given an rvalue of pointer type @code{T *} where T is of struct or union
5936 type, access the given field as an lvalue.  Analogous to:
5938 @example
5939 (EXPR)->field
5940 @end example
5942 @noindent
5944 in C, itself equivalent to @code{(*EXPR).FIELD}.
5945 @end deffn
5947 @geindex gcc_jit_context_new_array_access (C function)
5948 @anchor{topics/expressions gcc_jit_context_new_array_access}@anchor{92}
5949 @deffn {C Function} gcc_jit_lvalue *           gcc_jit_context_new_array_access (gcc_jit_context@w{ }*ctxt, gcc_jit_location@w{ }*loc, gcc_jit_rvalue@w{ }*ptr, gcc_jit_rvalue@w{ }*index)
5951 Given an rvalue of pointer type @code{T *}, get at the element @cite{T} at
5952 the given index, using standard C array indexing rules i.e. each
5953 increment of @code{index} corresponds to @code{sizeof(T)} bytes.
5954 Analogous to:
5956 @example
5957 PTR[INDEX]
5958 @end example
5960 @noindent
5962 in C (or, indeed, to @code{PTR + INDEX}).
5963 @end deffn
5965 @c Copyright (C) 2014 Free Software Foundation, Inc.
5966 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
5967 @c 
5968 @c This is free software: you can redistribute it and/or modify it
5969 @c under the terms of the GNU General Public License as published by
5970 @c the Free Software Foundation, either version 3 of the License, or
5971 @c (at your option) any later version.
5972 @c 
5973 @c This program is distributed in the hope that it will be useful, but
5974 @c WITHOUT ANY WARRANTY; without even the implied warranty of
5975 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
5976 @c General Public License for more details.
5977 @c 
5978 @c You should have received a copy of the GNU General Public License
5979 @c along with this program.  If not, see
5980 @c <http://www.gnu.org/licenses/>.
5982 @node Creating and using functions,Source Locations,Expressions,Topic Reference
5983 @anchor{topics/functions doc}@anchor{a5}@anchor{topics/functions creating-and-using-functions}@anchor{a6}
5984 @section Creating and using functions
5987 @menu
5988 * Params:: 
5989 * Functions:: 
5990 * Blocks:: 
5991 * Statements:: 
5993 @end menu
5995 @node Params,Functions,,Creating and using functions
5996 @anchor{topics/functions params}@anchor{a7}
5997 @subsection Params
6000 @geindex gcc_jit_param (C type)
6001 @anchor{topics/functions gcc_jit_param}@anchor{25}
6002 @deffn {C Type} gcc_jit_param
6004 A @cite{gcc_jit_param} represents a parameter to a function.
6005 @end deffn
6007 @geindex gcc_jit_context_new_param (C function)
6008 @anchor{topics/functions gcc_jit_context_new_param}@anchor{10}
6009 @deffn {C Function} gcc_jit_param *           gcc_jit_context_new_param (gcc_jit_context@w{ }*ctxt, gcc_jit_location@w{ }*loc, gcc_jit_type@w{ }*type, const char@w{ }*name)
6011 In preparation for creating a function, create a new parameter of the
6012 given type and name.
6013 @end deffn
6015 Parameters are lvalues, and thus are also rvalues (and objects), so the
6016 following upcasts are available:
6018 @geindex gcc_jit_param_as_lvalue (C function)
6019 @anchor{topics/functions gcc_jit_param_as_lvalue}@anchor{a8}
6020 @deffn {C Function} gcc_jit_lvalue *            gcc_jit_param_as_lvalue (gcc_jit_param@w{ }*param)
6022 Upcasting from param to lvalue.
6023 @end deffn
6025 @geindex gcc_jit_param_as_rvalue (C function)
6026 @anchor{topics/functions gcc_jit_param_as_rvalue}@anchor{a9}
6027 @deffn {C Function} gcc_jit_rvalue *            gcc_jit_param_as_rvalue (gcc_jit_param@w{ }*param)
6029 Upcasting from param to rvalue.
6030 @end deffn
6032 @geindex gcc_jit_param_as_object (C function)
6033 @anchor{topics/functions gcc_jit_param_as_object}@anchor{aa}
6034 @deffn {C Function} gcc_jit_object *            gcc_jit_param_as_object (gcc_jit_param@w{ }*param)
6036 Upcasting from param to object.
6037 @end deffn
6039 @node Functions,Blocks,Params,Creating and using functions
6040 @anchor{topics/functions functions}@anchor{ab}
6041 @subsection Functions
6044 @geindex gcc_jit_function (C type)
6045 @anchor{topics/functions gcc_jit_function}@anchor{29}
6046 @deffn {C Type} gcc_jit_function
6048 A @cite{gcc_jit_function} represents a function - either one that we're
6049 creating ourselves, or one that we're referencing.
6050 @end deffn
6052 @geindex gcc_jit_context_new_function (C function)
6053 @anchor{topics/functions gcc_jit_context_new_function}@anchor{11}
6054 @deffn {C Function} gcc_jit_function *            gcc_jit_context_new_function (gcc_jit_context@w{ }*ctxt, gcc_jit_location@w{ }*loc, enum gcc_jit_function_kind@w{ }kind, gcc_jit_type@w{ }*return_type, const char@w{ }*name, int@w{ }num_params, gcc_jit_param@w{ }**params, int@w{ }is_variadic)
6056 Create a gcc_jit_function with the given name and parameters.
6058 @geindex gcc_jit_function_kind (C type)
6059 @anchor{topics/functions gcc_jit_function_kind}@anchor{ac}
6060 @deffn {C Type} enum gcc_jit_function_kind
6061 @end deffn
6063 This enum controls the kind of function created, and has the following
6064 values:
6066 @quotation
6068 @geindex GCC_JIT_FUNCTION_EXPORTED (C macro)
6069 @anchor{topics/functions GCC_JIT_FUNCTION_EXPORTED}@anchor{ad}
6070 @deffn {C Macro} GCC_JIT_FUNCTION_EXPORTED
6072 Function is defined by the client code and visible
6073 by name outside of the JIT.
6075 This value is required if you want to extract machine code
6076 for this function from a @pxref{16,,gcc_jit_result} via
6077 @pxref{17,,gcc_jit_result_get_code()}.
6078 @end deffn
6080 @geindex GCC_JIT_FUNCTION_INTERNAL (C macro)
6081 @anchor{topics/functions GCC_JIT_FUNCTION_INTERNAL}@anchor{ae}
6082 @deffn {C Macro} GCC_JIT_FUNCTION_INTERNAL
6084 Function is defined by the client code, but is invisible
6085 outside of the JIT.  Analogous to a "static" function.
6086 @end deffn
6088 @geindex GCC_JIT_FUNCTION_IMPORTED (C macro)
6089 @anchor{topics/functions GCC_JIT_FUNCTION_IMPORTED}@anchor{af}
6090 @deffn {C Macro} GCC_JIT_FUNCTION_IMPORTED
6092 Function is not defined by the client code; we're merely
6093 referring to it.  Analogous to using an "extern" function from a
6094 header file.
6095 @end deffn
6097 @geindex GCC_JIT_FUNCTION_ALWAYS_INLINE (C macro)
6098 @anchor{topics/functions GCC_JIT_FUNCTION_ALWAYS_INLINE}@anchor{b0}
6099 @deffn {C Macro} GCC_JIT_FUNCTION_ALWAYS_INLINE
6101 Function is only ever inlined into other functions, and is
6102 invisible outside of the JIT.
6104 Analogous to prefixing with @code{inline} and adding
6105 @code{__attribute__((always_inline))}
6107 Inlining will only occur when the optimization level is
6108 above 0; when optimization is off, this is essentially the
6109 same as GCC_JIT_FUNCTION_INTERNAL.
6110 @end deffn
6111 @end quotation
6112 @end deffn
6114 @geindex gcc_jit_context_get_builtin_function (C function)
6115 @anchor{topics/functions gcc_jit_context_get_builtin_function}@anchor{b1}
6116 @deffn {C Function} gcc_jit_function *gcc_jit_context_get_builtin_function (gcc_jit_context@w{ }*ctxt, const char@w{ }*name)
6117 @end deffn
6119 @geindex gcc_jit_function_as_object (C function)
6120 @anchor{topics/functions gcc_jit_function_as_object}@anchor{b2}
6121 @deffn {C Function} gcc_jit_object *           gcc_jit_function_as_object (gcc_jit_function@w{ }*func)
6123 Upcasting from function to object.
6124 @end deffn
6126 @geindex gcc_jit_function_get_param (C function)
6127 @anchor{topics/functions gcc_jit_function_get_param}@anchor{b3}
6128 @deffn {C Function} gcc_jit_param *            gcc_jit_function_get_param (gcc_jit_function@w{ }*func, int@w{ }index)
6130 Get the param of the given index (0-based).
6131 @end deffn
6133 @geindex gcc_jit_function_dump_to_dot (C function)
6134 @anchor{topics/functions gcc_jit_function_dump_to_dot}@anchor{33}
6135 @deffn {C Function} void             gcc_jit_function_dump_to_dot (gcc_jit_function@w{ }*func, const char@w{ }*path)
6137 Emit the function in graphviz format to the given path.
6138 @end deffn
6140 @geindex gcc_jit_function_new_local (C function)
6141 @anchor{topics/functions gcc_jit_function_new_local}@anchor{26}
6142 @deffn {C Function} gcc_jit_lvalue *           gcc_jit_function_new_local (gcc_jit_function@w{ }*func, gcc_jit_location@w{ }*loc, gcc_jit_type@w{ }*type, const char@w{ }*name)
6144 Create a new local variable within the function, of the given type and
6145 name.
6146 @end deffn
6148 @node Blocks,Statements,Functions,Creating and using functions
6149 @anchor{topics/functions blocks}@anchor{b4}
6150 @subsection Blocks
6153 @geindex gcc_jit_block (C type)
6154 @anchor{topics/functions gcc_jit_block}@anchor{28}
6155 @deffn {C Type} gcc_jit_block
6157 A @cite{gcc_jit_block} represents a basic block within a function  i.e. a
6158 sequence of statements with a single entry point and a single exit
6159 point.
6161 The first basic block that you create within a function will
6162 be the entrypoint.
6164 Each basic block that you create within a function must be
6165 terminated, either with a conditional, a jump, or a return.
6167 It's legal to have multiple basic blocks that return within
6168 one function.
6169 @end deffn
6171 @geindex gcc_jit_function_new_block (C function)
6172 @anchor{topics/functions gcc_jit_function_new_block}@anchor{b5}
6173 @deffn {C Function} gcc_jit_block *            gcc_jit_function_new_block (gcc_jit_function@w{ }*func, const char@w{ }*name)
6175 Create a basic block of the given name.  The name may be NULL, but
6176 providing meaningful names is often helpful when debugging: it may
6177 show up in dumps of the internal representation, and in error
6178 messages.
6179 @end deffn
6181 @geindex gcc_jit_block_as_object (C function)
6182 @anchor{topics/functions gcc_jit_block_as_object}@anchor{b6}
6183 @deffn {C Function} gcc_jit_object *            gcc_jit_block_as_object (gcc_jit_block@w{ }*block)
6185 Upcast from block to object.
6186 @end deffn
6188 @geindex gcc_jit_block_get_function (C function)
6189 @anchor{topics/functions gcc_jit_block_get_function}@anchor{b7}
6190 @deffn {C Function} gcc_jit_function *            gcc_jit_block_get_function (gcc_jit_block@w{ }*block)
6192 Which function is this block within?
6193 @end deffn
6195 @node Statements,,Blocks,Creating and using functions
6196 @anchor{topics/functions statements}@anchor{b8}
6197 @subsection Statements
6200 @geindex gcc_jit_block_add_eval (C function)
6201 @anchor{topics/functions gcc_jit_block_add_eval}@anchor{97}
6202 @deffn {C Function} void           gcc_jit_block_add_eval (gcc_jit_block@w{ }*block, gcc_jit_location@w{ }*loc, gcc_jit_rvalue@w{ }*rvalue)
6204 Add evaluation of an rvalue, discarding the result
6205 (e.g. a function call that "returns" void).
6207 This is equivalent to this C code:
6209 @example
6210 (void)expression;
6211 @end example
6213 @noindent
6214 @end deffn
6216 @geindex gcc_jit_block_add_assignment (C function)
6217 @anchor{topics/functions gcc_jit_block_add_assignment}@anchor{2a}
6218 @deffn {C Function} void           gcc_jit_block_add_assignment (gcc_jit_block@w{ }*block, gcc_jit_location@w{ }*loc, gcc_jit_lvalue@w{ }*lvalue, gcc_jit_rvalue@w{ }*rvalue)
6220 Add evaluation of an rvalue, assigning the result to the given
6221 lvalue.
6223 This is roughly equivalent to this C code:
6225 @example
6226 lvalue = rvalue;
6227 @end example
6229 @noindent
6230 @end deffn
6232 @geindex gcc_jit_block_add_assignment_op (C function)
6233 @anchor{topics/functions gcc_jit_block_add_assignment_op}@anchor{2e}
6234 @deffn {C Function} void           gcc_jit_block_add_assignment_op (gcc_jit_block@w{ }*block, gcc_jit_location@w{ }*loc, gcc_jit_lvalue@w{ }*lvalue, enum gcc_jit_binary_op@w{ }op, gcc_jit_rvalue@w{ }*rvalue)
6236 Add evaluation of an rvalue, using the result to modify an
6237 lvalue.
6239 This is analogous to "+=" and friends:
6241 @example
6242 lvalue += rvalue;
6243 lvalue *= rvalue;
6244 lvalue /= rvalue;
6245 @end example
6247 @noindent
6249 etc.  For example:
6251 @example
6252 /* "i++" */
6253 gcc_jit_block_add_assignment_op (
6254   loop_body, NULL,
6255   i,
6256   GCC_JIT_BINARY_OP_PLUS,
6257   gcc_jit_context_one (ctxt, int_type));
6258 @end example
6260 @noindent
6261 @end deffn
6263 @geindex gcc_jit_block_add_comment (C function)
6264 @anchor{topics/functions gcc_jit_block_add_comment}@anchor{3d}
6265 @deffn {C Function} void           gcc_jit_block_add_comment (gcc_jit_block@w{ }*block, gcc_jit_location@w{ }*loc, const char@w{ }*text)
6267 Add a no-op textual comment to the internal representation of the
6268 code.  It will be optimized away, but will be visible in the dumps
6269 seen via @pxref{5b,,GCC_JIT_BOOL_OPTION_DUMP_INITIAL_TREE}
6270 and @pxref{1c,,GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE},
6271 and thus may be of use when debugging how your project's internal
6272 representation gets converted to the libgccjit IR.
6273 @end deffn
6275 @geindex gcc_jit_block_end_with_conditional (C function)
6276 @anchor{topics/functions gcc_jit_block_end_with_conditional}@anchor{2d}
6277 @deffn {C Function} void           gcc_jit_block_end_with_conditional (gcc_jit_block@w{ }*block, gcc_jit_location@w{ }*loc, gcc_jit_rvalue@w{ }*boolval, gcc_jit_block@w{ }*on_true, gcc_jit_block@w{ }*on_false)
6279 Terminate a block by adding evaluation of an rvalue, branching on the
6280 result to the appropriate successor block.
6282 This is roughly equivalent to this C code:
6284 @example
6285 if (boolval)
6286   goto on_true;
6287 else
6288   goto on_false;
6289 @end example
6291 @noindent
6293 block, boolval, on_true, and on_false must be non-NULL.
6294 @end deffn
6296 @geindex gcc_jit_block_end_with_jump (C function)
6297 @anchor{topics/functions gcc_jit_block_end_with_jump}@anchor{b9}
6298 @deffn {C Function} void           gcc_jit_block_end_with_jump (gcc_jit_block@w{ }*block, gcc_jit_location@w{ }*loc, gcc_jit_block@w{ }*target)
6300 Terminate a block by adding a jump to the given target block.
6302 This is roughly equivalent to this C code:
6304 @example
6305 goto target;
6306 @end example
6308 @noindent
6309 @end deffn
6311 @geindex gcc_jit_block_end_with_return (C function)
6312 @anchor{topics/functions gcc_jit_block_end_with_return}@anchor{ba}
6313 @deffn {C Function} void           gcc_jit_block_end_with_return (gcc_jit_block@w{ }*block, gcc_jit_location@w{ }*loc, gcc_jit_rvalue@w{ }*rvalue)
6315 Terminate a block by adding evaluation of an rvalue, returning the value.
6317 This is roughly equivalent to this C code:
6319 @example
6320 return expression;
6321 @end example
6323 @noindent
6324 @end deffn
6326 @geindex gcc_jit_block_end_with_void_return (C function)
6327 @anchor{topics/functions gcc_jit_block_end_with_void_return}@anchor{bb}
6328 @deffn {C Function} void           gcc_jit_block_end_with_void_return (gcc_jit_block@w{ }*block, gcc_jit_location@w{ }*loc)
6330 Terminate a block by adding a valueless return, for use within a function
6331 with "void" return type.
6333 This is equivalent to this C code:
6335 @example
6336 return;
6337 @end example
6339 @noindent
6340 @end deffn
6342 @c Copyright (C) 2014 Free Software Foundation, Inc.
6343 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
6344 @c 
6345 @c This is free software: you can redistribute it and/or modify it
6346 @c under the terms of the GNU General Public License as published by
6347 @c the Free Software Foundation, either version 3 of the License, or
6348 @c (at your option) any later version.
6349 @c 
6350 @c This program is distributed in the hope that it will be useful, but
6351 @c WITHOUT ANY WARRANTY; without even the implied warranty of
6352 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
6353 @c General Public License for more details.
6354 @c 
6355 @c You should have received a copy of the GNU General Public License
6356 @c along with this program.  If not, see
6357 @c <http://www.gnu.org/licenses/>.
6359 @node Source Locations,Compilation results,Creating and using functions,Topic Reference
6360 @anchor{topics/locations source-locations}@anchor{bc}@anchor{topics/locations doc}@anchor{bd}
6361 @section Source Locations
6364 @geindex gcc_jit_location (C type)
6365 @anchor{topics/locations gcc_jit_location}@anchor{3b}
6366 @deffn {C Type} gcc_jit_location
6368 A @cite{gcc_jit_location} encapsulates a source code location, so that
6369 you can (optionally) associate locations in your language with
6370 statements in the JIT-compiled code, allowing the debugger to
6371 single-step through your language.
6373 @cite{gcc_jit_location} instances are optional: you can always pass NULL to
6374 any API entrypoint accepting one.
6376 You can construct them using @pxref{41,,gcc_jit_context_new_location()}.
6378 You need to enable @pxref{42,,GCC_JIT_BOOL_OPTION_DEBUGINFO} on the
6379 @pxref{8,,gcc_jit_context} for these locations to actually be usable by
6380 the debugger:
6382 @example
6383 gcc_jit_context_set_bool_option (
6384   ctxt,
6385   GCC_JIT_BOOL_OPTION_DEBUGINFO,
6386   1);
6387 @end example
6389 @noindent
6390 @end deffn
6392 @geindex gcc_jit_context_new_location (C function)
6393 @anchor{topics/locations gcc_jit_context_new_location}@anchor{41}
6394 @deffn {C Function} gcc_jit_location *           gcc_jit_context_new_location (gcc_jit_context@w{ }*ctxt, const char@w{ }*filename, int@w{ }line, int@w{ }column)
6396 Create a @cite{gcc_jit_location} instance representing the given source
6397 location.
6398 @end deffn
6400 @menu
6401 * Faking it:: 
6403 @end menu
6405 @node Faking it,,,Source Locations
6406 @anchor{topics/locations faking-it}@anchor{be}
6407 @subsection Faking it
6410 If you don't have source code for your internal representation, but need
6411 to debug, you can generate a C-like representation of the functions in
6412 your context using @pxref{52,,gcc_jit_context_dump_to_file()}:
6414 @example
6415 gcc_jit_context_dump_to_file (ctxt, "/tmp/something.c",
6416                               1 /* update_locations */);
6417 @end example
6419 @noindent
6421 This will dump C-like code to the given path.  If the @cite{update_locations}
6422 argument is true, this will also set up @cite{gcc_jit_location} information
6423 throughout the context, pointing at the dump file as if it were a source
6424 file, giving you @emph{something} you can step through in the debugger.
6426 @c Copyright (C) 2014 Free Software Foundation, Inc.
6427 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
6428 @c 
6429 @c This is free software: you can redistribute it and/or modify it
6430 @c under the terms of the GNU General Public License as published by
6431 @c the Free Software Foundation, either version 3 of the License, or
6432 @c (at your option) any later version.
6433 @c 
6434 @c This program is distributed in the hope that it will be useful, but
6435 @c WITHOUT ANY WARRANTY; without even the implied warranty of
6436 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
6437 @c General Public License for more details.
6438 @c 
6439 @c You should have received a copy of the GNU General Public License
6440 @c along with this program.  If not, see
6441 @c <http://www.gnu.org/licenses/>.
6443 @node Compilation results,,Source Locations,Topic Reference
6444 @anchor{topics/results compilation-results}@anchor{bf}@anchor{topics/results doc}@anchor{c0}
6445 @section Compilation results
6448 @geindex gcc_jit_result (C type)
6449 @anchor{topics/results gcc_jit_result}@anchor{16}
6450 @deffn {C Type} gcc_jit_result
6452 A @cite{gcc_jit_result} encapsulates the result of compiling a context,
6453 and the lifetimes of any machine code functions that are
6454 returned.
6455 @end deffn
6457 @geindex gcc_jit_context_compile (C function)
6458 @anchor{topics/results gcc_jit_context_compile}@anchor{15}
6459 @deffn {C Function} gcc_jit_result *           gcc_jit_context_compile (gcc_jit_context@w{ }*ctxt)
6461 This calls into GCC and builds the code, returning a
6462 @cite{gcc_jit_result *}.
6463 @end deffn
6465 @geindex gcc_jit_result_get_code (C function)
6466 @anchor{topics/results gcc_jit_result_get_code}@anchor{17}
6467 @deffn {C Function} void *           gcc_jit_result_get_code (gcc_jit_result@w{ }*result, const char@w{ }*funcname)
6469 Locate a given function within the built machine code.
6471 Functions are looked up by name.  For this to succeed, a function
6472 with a name matching @cite{funcname} must have been created on
6473 @cite{result}'s context (or a parent context) via a call to
6474 @pxref{11,,gcc_jit_context_new_function()} with @cite{kind}
6475 @pxref{ad,,GCC_JIT_FUNCTION_EXPORTED}:
6477 @example
6478 gcc_jit_context_new_function (ctxt,
6479                               any_location, /* or NULL */
6480                               /* Required for func to be visible to
6481                                  gcc_jit_result_get_code: */
6482                               GCC_JIT_FUNCTION_EXPORTED,
6483                               any_return_type,
6484                               /* Must string-compare equal: */
6485                               funcname,
6486                               /* etc */);
6487 @end example
6489 @noindent
6491 If such a function is not found (or @cite{result} or @cite{funcname} are
6492 @code{NULL}), an error message will be emitted on stderr and
6493 @code{NULL} will be returned.
6495 If the function is found, the result will need to be cast to a
6496 function pointer of the correct type before it can be called.
6498 Note that the resulting machine code becomes invalid after
6499 @pxref{39,,gcc_jit_result_release()} is called on the
6500 @cite{gcc_jit_result *}; attempting to call it after that may lead
6501 to a segmentation fault.
6502 @end deffn
6504 @geindex gcc_jit_result_release (C function)
6505 @anchor{topics/results gcc_jit_result_release}@anchor{39}
6506 @deffn {C Function} void           gcc_jit_result_release (gcc_jit_result@w{ }*result)
6508 Once we're done with the code, this unloads the built .so file.
6509 This cleans up the result; after calling this, it's no longer
6510 valid to use the result, or any code that was obtained by calling
6511 @pxref{17,,gcc_jit_result_get_code()} on it.
6512 @end deffn
6514 @c Copyright (C) 2014 Free Software Foundation, Inc.
6515 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
6516 @c 
6517 @c This is free software: you can redistribute it and/or modify it
6518 @c under the terms of the GNU General Public License as published by
6519 @c the Free Software Foundation, either version 3 of the License, or
6520 @c (at your option) any later version.
6521 @c 
6522 @c This program is distributed in the hope that it will be useful, but
6523 @c WITHOUT ANY WARRANTY; without even the implied warranty of
6524 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
6525 @c General Public License for more details.
6526 @c 
6527 @c You should have received a copy of the GNU General Public License
6528 @c along with this program.  If not, see
6529 @c <http://www.gnu.org/licenses/>.
6531 @node C++ bindings for libgccjit,Internals,Topic Reference,Top
6532 @anchor{cp/index c-bindings-for-libgccjit}@anchor{c1}@anchor{cp/index doc}@anchor{c2}
6533 @chapter C++ bindings for libgccjit
6536 This document describes the C++ bindings to
6537 libgccjit@footnote{http://gcc.gnu.org/wiki/JIT}, an API for embedding GCC
6538 inside programs and libraries.
6540 The C++ bindings consist of a single header file @code{libgccjit++.h}.
6542 This is a collection of "thin" wrapper classes around the C API.
6543 Everything is an inline function, implemented in terms of the C API,
6544 so there is nothing extra to link against.
6546 Note that libgccjit is currently of "Alpha" quality;
6547 the APIs are not yet set in stone, and they shouldn't be used in
6548 production yet.
6550 Contents:
6552 @c Copyright (C) 2014 Free Software Foundation, Inc.
6553 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
6554 @c 
6555 @c This is free software: you can redistribute it and/or modify it
6556 @c under the terms of the GNU General Public License as published by
6557 @c the Free Software Foundation, either version 3 of the License, or
6558 @c (at your option) any later version.
6559 @c 
6560 @c This program is distributed in the hope that it will be useful, but
6561 @c WITHOUT ANY WARRANTY; without even the implied warranty of
6562 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
6563 @c General Public License for more details.
6564 @c 
6565 @c You should have received a copy of the GNU General Public License
6566 @c along with this program.  If not, see
6567 @c <http://www.gnu.org/licenses/>.
6569 @menu
6570 * Tutorial: Tutorial<2>. 
6571 * Topic Reference: Topic Reference<2>. 
6573 Tutorial
6575 * Tutorial part 1; "Hello world": Tutorial part 1 "Hello world"<2>. 
6576 * Tutorial part 2; Creating a trivial machine code function: Tutorial part 2 Creating a trivial machine code function<2>. 
6577 * Tutorial part 3; Loops and variables: Tutorial part 3 Loops and variables<2>. 
6578 * Tutorial part 4; Adding JIT-compilation to a toy interpreter: Tutorial part 4 Adding JIT-compilation to a toy interpreter<2>. 
6580 Tutorial part 2: Creating a trivial machine code function
6582 * Options: Options<3>. 
6583 * Full example: Full example<3>. 
6585 Tutorial part 3: Loops and variables
6587 * Expressions; lvalues and rvalues: Expressions lvalues and rvalues<2>. 
6588 * Control flow: Control flow<2>. 
6589 * Visualizing the control flow graph: Visualizing the control flow graph<2>. 
6590 * Full example: Full example<4>. 
6592 Tutorial part 4: Adding JIT-compilation to a toy interpreter
6594 * Our toy interpreter: Our toy interpreter<2>. 
6595 * Compiling to machine code: Compiling to machine code<2>. 
6596 * Setting things up: Setting things up<2>. 
6597 * Populating the function: Populating the function<2>. 
6598 * Verifying the control flow graph: Verifying the control flow graph<2>. 
6599 * Compiling the context: Compiling the context<2>. 
6600 * Single-stepping through the generated code: Single-stepping through the generated code<2>. 
6601 * Examining the generated code: Examining the generated code<2>. 
6602 * Putting it all together: Putting it all together<2>. 
6603 * Behind the curtain; How does our code get optimized?: Behind the curtain How does our code get optimized?<2>. 
6605 Behind the curtain: How does our code get optimized?
6607 * Optimizing away stack manipulation: Optimizing away stack manipulation<2>. 
6608 * Elimination of tail recursion: Elimination of tail recursion<2>. 
6610 Topic Reference
6612 * Compilation contexts: Compilation contexts<2>. 
6613 * Objects: Objects<2>. 
6614 * Types: Types<2>. 
6615 * Expressions: Expressions<2>. 
6616 * Creating and using functions: Creating and using functions<2>. 
6617 * Source Locations: Source Locations<2>. 
6618 * Compilation results: Compilation results<2>. 
6620 Compilation contexts
6622 * Lifetime-management: Lifetime-management<2>. 
6623 * Thread-safety: Thread-safety<2>. 
6624 * Error-handling: Error-handling<3>. 
6625 * Debugging: Debugging<2>. 
6626 * Options: Options<4>. 
6628 Options
6630 * Boolean options: Boolean options<2>. 
6631 * Integer options: Integer options<2>. 
6633 Types
6635 * Standard types: Standard types<2>. 
6636 * Pointers@comma{} const@comma{} and volatile: Pointers const and volatile<2>. 
6637 * Structures and unions: Structures and unions<2>. 
6639 Expressions
6641 * Rvalues: Rvalues<2>. 
6642 * Lvalues: Lvalues<2>. 
6643 * Working with pointers@comma{} structs and unions: Working with pointers structs and unions<2>. 
6645 Rvalues
6647 * Simple expressions: Simple expressions<2>. 
6648 * Unary Operations: Unary Operations<2>. 
6649 * Binary Operations: Binary Operations<2>. 
6650 * Comparisons: Comparisons<2>. 
6651 * Function calls: Function calls<2>. 
6652 * Type-coercion: Type-coercion<2>. 
6654 Lvalues
6656 * Global variables: Global variables<2>. 
6658 Creating and using functions
6660 * Params: Params<2>. 
6661 * Functions: Functions<2>. 
6662 * Blocks: Blocks<2>. 
6663 * Statements: Statements<2>. 
6665 Source Locations
6667 * Faking it: Faking it<2>. 
6669 @end menu
6672 @node Tutorial<2>,Topic Reference<2>,,C++ bindings for libgccjit
6673 @anchor{cp/intro/index doc}@anchor{c3}@anchor{cp/intro/index tutorial}@anchor{c4}
6674 @section Tutorial
6677 @c Copyright (C) 2014 Free Software Foundation, Inc.
6678 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
6679 @c 
6680 @c This is free software: you can redistribute it and/or modify it
6681 @c under the terms of the GNU General Public License as published by
6682 @c the Free Software Foundation, either version 3 of the License, or
6683 @c (at your option) any later version.
6684 @c 
6685 @c This program is distributed in the hope that it will be useful, but
6686 @c WITHOUT ANY WARRANTY; without even the implied warranty of
6687 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
6688 @c General Public License for more details.
6689 @c 
6690 @c You should have received a copy of the GNU General Public License
6691 @c along with this program.  If not, see
6692 @c <http://www.gnu.org/licenses/>.
6694 @menu
6695 * Tutorial part 1; "Hello world": Tutorial part 1 "Hello world"<2>. 
6696 * Tutorial part 2; Creating a trivial machine code function: Tutorial part 2 Creating a trivial machine code function<2>. 
6697 * Tutorial part 3; Loops and variables: Tutorial part 3 Loops and variables<2>. 
6698 * Tutorial part 4; Adding JIT-compilation to a toy interpreter: Tutorial part 4 Adding JIT-compilation to a toy interpreter<2>. 
6700 @end menu
6702 @node Tutorial part 1 "Hello world"<2>,Tutorial part 2 Creating a trivial machine code function<2>,,Tutorial<2>
6703 @anchor{cp/intro/tutorial01 doc}@anchor{c5}@anchor{cp/intro/tutorial01 tutorial-part-1-hello-world}@anchor{c6}
6704 @subsection Tutorial part 1: "Hello world"
6707 Before we look at the details of the API, let's look at building and
6708 running programs that use the library.
6710 Here's a toy "hello world" program that uses the library's C++ API to
6711 synthesize a call to @cite{printf} and uses it to write a message to stdout.
6713 Don't worry about the content of the program for now; we'll cover
6714 the details in later parts of this tutorial.
6716 @quotation
6718 @example
6719 /* Smoketest example for libgccjit.so C++ API
6720    Copyright (C) 2014 Free Software Foundation, Inc.
6722 This file is part of GCC.
6724 GCC is free software; you can redistribute it and/or modify it
6725 under the terms of the GNU General Public License as published by
6726 the Free Software Foundation; either version 3, or (at your option)
6727 any later version.
6729 GCC is distributed in the hope that it will be useful, but
6730 WITHOUT ANY WARRANTY; without even the implied warranty of
6731 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
6732 General Public License for more details.
6734 You should have received a copy of the GNU General Public License
6735 along with GCC; see the file COPYING3.  If not see
6736 <http://www.gnu.org/licenses/>.  */
6738 #include <libgccjit++.h>
6740 #include <stdlib.h>
6741 #include <stdio.h>
6743 static void
6744 create_code (gccjit::context ctxt)
6746   /* Let's try to inject the equivalent of this C code:
6747      void
6748      greet (const char *name)
6749      @{
6750         printf ("hello %s\n", name);
6751      @}
6752   */
6753   gccjit::type void_type = ctxt.get_type (GCC_JIT_TYPE_VOID);
6754   gccjit::type const_char_ptr_type =
6755     ctxt.get_type (GCC_JIT_TYPE_CONST_CHAR_PTR);
6756   gccjit::param param_name =
6757     ctxt.new_param (const_char_ptr_type, "name");
6758   std::vector<gccjit::param> func_params;
6759   func_params.push_back (param_name);
6760   gccjit::function func =
6761     ctxt.new_function (GCC_JIT_FUNCTION_EXPORTED,
6762                        void_type,
6763                        "greet",
6764                        func_params, 0);
6766   gccjit::param param_format =
6767     ctxt.new_param (const_char_ptr_type, "format");
6768   std::vector<gccjit::param> printf_params;
6769   printf_params.push_back (param_format);
6770   gccjit::function printf_func =
6771     ctxt.new_function (GCC_JIT_FUNCTION_IMPORTED,
6772                        ctxt.get_type (GCC_JIT_TYPE_INT),
6773                        "printf",
6774                        printf_params, 1);
6776   gccjit::block block = func.new_block ();
6777   block.add_eval (ctxt.new_call (printf_func,
6778                                  ctxt.new_rvalue ("hello %s\n"),
6779                                  param_name));
6780   block.end_with_return ();
6784 main (int argc, char **argv)
6786   gccjit::context ctxt;
6787   gcc_jit_result *result;
6789   /* Get a "context" object for working with the library.  */
6790   ctxt = gccjit::context::acquire ();
6792   /* Set some options on the context.
6793      Turn this on to see the code being generated, in assembler form.  */
6794   ctxt.set_bool_option (GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE, 0);
6796   /* Populate the context.  */
6797   create_code (ctxt);
6799   /* Compile the code.  */
6800   result = ctxt.compile ();
6801   if (!result)
6802     @{
6803       fprintf (stderr, "NULL result");
6804       exit (1);
6805     @}
6807   ctxt.release ();
6809   /* Extract the generated code from "result".  */
6810   typedef void (*fn_type) (const char *);
6811   fn_type greet =
6812     (fn_type)gcc_jit_result_get_code (result, "greet");
6813   if (!greet)
6814     @{
6815       fprintf (stderr, "NULL greet");
6816       exit (1);
6817     @}
6819   /* Now call the generated function: */
6820   greet ("world");
6821   fflush (stdout);
6823   gcc_jit_result_release (result);
6824   return 0;
6827 @end example
6829 @noindent
6830 @end quotation
6832 Copy the above to @cite{tut01-hello-world.cc}.
6834 Assuming you have the jit library installed, build the test program
6835 using:
6837 @example
6838 $ gcc \
6839     tut01-hello-world.cc \
6840     -o tut01-hello-world \
6841     -lgccjit
6842 @end example
6844 @noindent
6846 You should then be able to run the built program:
6848 @example
6849 $ ./tut01-hello-world
6850 hello world
6851 @end example
6853 @noindent
6855 @c Copyright (C) 2014 Free Software Foundation, Inc.
6856 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
6857 @c 
6858 @c This is free software: you can redistribute it and/or modify it
6859 @c under the terms of the GNU General Public License as published by
6860 @c the Free Software Foundation, either version 3 of the License, or
6861 @c (at your option) any later version.
6862 @c 
6863 @c This program is distributed in the hope that it will be useful, but
6864 @c WITHOUT ANY WARRANTY; without even the implied warranty of
6865 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
6866 @c General Public License for more details.
6867 @c 
6868 @c You should have received a copy of the GNU General Public License
6869 @c along with this program.  If not, see
6870 @c <http://www.gnu.org/licenses/>.
6872 @node Tutorial part 2 Creating a trivial machine code function<2>,Tutorial part 3 Loops and variables<2>,Tutorial part 1 "Hello world"<2>,Tutorial<2>
6873 @anchor{cp/intro/tutorial02 doc}@anchor{c7}@anchor{cp/intro/tutorial02 tutorial-part-2-creating-a-trivial-machine-code-function}@anchor{c8}
6874 @subsection Tutorial part 2: Creating a trivial machine code function
6877 Consider this C function:
6879 @example
6880 int square (int i)
6882   return i * i;
6884 @end example
6886 @noindent
6888 How can we construct this at run-time using libgccjit's C++ API?
6890 First we need to include the relevant header:
6892 @example
6893 #include <libgccjit++.h>
6894 @end example
6896 @noindent
6898 All state associated with compilation is associated with a
6899 @code{gccjit::context}, which is a thin C++ wrapper around the C API's
6900 @pxref{8,,gcc_jit_context *}.
6902 Create one using @pxref{c9,,gccjit;;context;;acquire()}:
6904 @example
6905 gccjit::context ctxt;
6906 ctxt = gccjit::context::acquire ();
6907 @end example
6909 @noindent
6911 The JIT library has a system of types.  It is statically-typed: every
6912 expression is of a specific type, fixed at compile-time.  In our example,
6913 all of the expressions are of the C @cite{int} type, so let's obtain this from
6914 the context, as a @code{gccjit::type}, using
6915 @pxref{ca,,gccjit;;context;;get_type()}:
6917 @example
6918 gccjit::type int_type = ctxt.get_type (GCC_JIT_TYPE_INT);
6919 @end example
6921 @noindent
6923 @code{gccjit::type} is an example of a "contextual" object: every
6924 entity in the API is associated with a @code{gccjit::context}.
6926 Memory management is easy: all such "contextual" objects are automatically
6927 cleaned up for you when the context is released, using
6928 @pxref{cb,,gccjit;;context;;release()}:
6930 @example
6931 ctxt.release ();
6932 @end example
6934 @noindent
6936 so you don't need to manually track and cleanup all objects, just the
6937 contexts.
6939 All of the C++ classes in the API are thin wrappers around pointers to
6940 types in the C API.
6942 The C++ class hierarchy within the @code{gccjit} namespace looks like this:
6944 @example
6945 +- object
6946     +- location
6947     +- type
6948        +- struct
6949     +- field
6950     +- function
6951     +- block
6952     +- rvalue
6953         +- lvalue
6954            +- param
6955 @end example
6957 @noindent
6959 One thing you can do with a @code{gccjit::object} is
6960 to ask it for a human-readable description as a @code{std::string}, using
6961 @pxref{cc,,gccjit;;object;;get_debug_string()}:
6963 @example
6964 printf ("obj: %s\n", obj.get_debug_string ().c_str ());
6965 @end example
6967 @noindent
6969 giving this text on stdout:
6971 @example
6972 obj: int
6973 @end example
6975 @noindent
6977 This is invaluable when debugging.
6979 Let's create the function.  To do so, we first need to construct
6980 its single parameter, specifying its type and giving it a name,
6981 using @pxref{cd,,gccjit;;context;;new_param()}:
6983 @example
6984 gccjit::param param_i = ctxt.new_param (int_type, "i");
6985 @end example
6987 @noindent
6989 and we can then make a vector of all of the params of the function,
6990 in this case just one:
6992 @example
6993 std::vector<gccjit::param> params;
6994 params.push_back (param_i);
6995 @end example
6997 @noindent
6999 Now we can create the function, using
7000 @code{gccjit::context::new_function()}:
7002 @example
7003 gccjit::function func =
7004   ctxt.new_function (GCC_JIT_FUNCTION_EXPORTED,
7005                      int_type,
7006                      "square",
7007                      params,
7008                      0);
7009 @end example
7011 @noindent
7013 To define the code within the function, we must create basic blocks
7014 containing statements.
7016 Every basic block contains a list of statements, eventually terminated
7017 by a statement that either returns, or jumps to another basic block.
7019 Our function has no control-flow, so we just need one basic block:
7021 @example
7022 gccjit::block block = func.new_block ();
7023 @end example
7025 @noindent
7027 Our basic block is relatively simple: it immediately terminates by
7028 returning the value of an expression.
7030 We can build the expression using @pxref{ce,,gccjit;;context;;new_binary_op()}:
7032 @example
7033 gccjit::rvalue expr =
7034   ctxt.new_binary_op (
7035     GCC_JIT_BINARY_OP_MULT, int_type,
7036     param_i, param_i);
7037 @end example
7039 @noindent
7041 A @code{gccjit::rvalue} is another example of a
7042 @code{gccjit::object} subclass.  As before, we can print it with
7043 @pxref{cc,,gccjit;;object;;get_debug_string()}.
7045 @example
7046 printf ("expr: %s\n", expr.get_debug_string ().c_str ());
7047 @end example
7049 @noindent
7051 giving this output:
7053 @example
7054 expr: i * i
7055 @end example
7057 @noindent
7059 Note that @code{gccjit::rvalue} provides numerous overloaded operators
7060 which can be used to dramatically reduce the amount of typing needed.
7061 We can build the above binary operation more directly with this one-liner:
7063 @example
7064 gccjit::rvalue expr = param_i * param_i;
7065 @end example
7067 @noindent
7069 Creating the expression in itself doesn't do anything; we have to add
7070 this expression to a statement within the block.  In this case, we use it
7071 to build a return statement, which terminates the basic block:
7073 @example
7074 block.end_with_return (expr);
7075 @end example
7077 @noindent
7079 OK, we've populated the context.  We can now compile it using
7080 @pxref{cf,,gccjit;;context;;compile()}:
7082 @example
7083 gcc_jit_result *result;
7084 result = ctxt.compile ();
7085 @end example
7087 @noindent
7089 and get a @pxref{16,,gcc_jit_result *}.
7091 We can now use @pxref{17,,gcc_jit_result_get_code()} to look up a specific
7092 machine code routine within the result, in this case, the function we
7093 created above.
7095 @example
7096 void *fn_ptr = gcc_jit_result_get_code (result, "square");
7097 if (!fn_ptr)
7098   @{
7099     fprintf (stderr, "NULL fn_ptr");
7100     goto error;
7101   @}
7102 @end example
7104 @noindent
7106 We can now cast the pointer to an appropriate function pointer type, and
7107 then call it:
7109 @example
7110 typedef int (*fn_type) (int);
7111 fn_type square = (fn_type)fn_ptr;
7112 printf ("result: %d", square (5));
7113 @end example
7115 @noindent
7117 @example
7118 result: 25
7119 @end example
7121 @noindent
7123 @menu
7124 * Options: Options<3>. 
7125 * Full example: Full example<3>. 
7127 @end menu
7129 @node Options<3>,Full example<3>,,Tutorial part 2 Creating a trivial machine code function<2>
7130 @anchor{cp/intro/tutorial02 options}@anchor{d0}
7131 @subsubsection Options
7134 To get more information on what's going on, you can set debugging flags
7135 on the context using @pxref{d1,,gccjit;;context;;set_bool_option()}.
7137 @c (I'm deliberately not mentioning
7138 @c :c:macro:`GCC_JIT_BOOL_OPTION_DUMP_INITIAL_TREE` here since I think
7139 @c it's probably more of use to implementors than to users)
7141 Setting @pxref{1c,,GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE} will dump a
7142 C-like representation to stderr when you compile (GCC's "GIMPLE"
7143 representation):
7145 @example
7146 ctxt.set_bool_option (GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE, 1);
7147 result = ctxt.compile ();
7148 @end example
7150 @noindent
7152 @example
7153 square (signed int i)
7155   signed int D.260;
7157   entry:
7158   D.260 = i * i;
7159   return D.260;
7161 @end example
7163 @noindent
7165 We can see the generated machine code in assembler form (on stderr) by
7166 setting @pxref{1d,,GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE} on the context
7167 before compiling:
7169 @example
7170 ctxt.set_bool_option (GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE, 1);
7171 result = ctxt.compile ();
7172 @end example
7174 @noindent
7176 @example
7177       .file   "fake.c"
7178       .text
7179       .globl  square
7180       .type   square, @@function
7181 square:
7182 .LFB6:
7183       .cfi_startproc
7184       pushq   %rbp
7185       .cfi_def_cfa_offset 16
7186       .cfi_offset 6, -16
7187       movq    %rsp, %rbp
7188       .cfi_def_cfa_register 6
7189       movl    %edi, -4(%rbp)
7190 .L14:
7191       movl    -4(%rbp), %eax
7192       imull   -4(%rbp), %eax
7193       popq    %rbp
7194       .cfi_def_cfa 7, 8
7195       ret
7196       .cfi_endproc
7197 .LFE6:
7198       .size   square, .-square
7199       .ident  "GCC: (GNU) 4.9.0 20131023 (Red Hat 0.2-0.5.1920c315ff984892399893b380305ab36e07b455.fc20)"
7200       .section       .note.GNU-stack,"",@@progbits
7201 @end example
7203 @noindent
7205 By default, no optimizations are performed, the equivalent of GCC's
7206 @cite{-O0} option.  We can turn things up to e.g. @cite{-O3} by calling
7207 @pxref{d2,,gccjit;;context;;set_int_option()} with
7208 @pxref{1f,,GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL}:
7210 @example
7211 ctxt.set_int_option (GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL, 3);
7212 @end example
7214 @noindent
7216 @example
7217       .file   "fake.c"
7218       .text
7219       .p2align 4,,15
7220       .globl  square
7221       .type   square, @@function
7222 square:
7223 .LFB7:
7224       .cfi_startproc
7225 .L16:
7226       movl    %edi, %eax
7227       imull   %edi, %eax
7228       ret
7229       .cfi_endproc
7230 .LFE7:
7231       .size   square, .-square
7232       .ident  "GCC: (GNU) 4.9.0 20131023 (Red Hat 0.2-0.5.1920c315ff984892399893b380305ab36e07b455.fc20)"
7233       .section        .note.GNU-stack,"",@@progbits
7234 @end example
7236 @noindent
7238 Naturally this has only a small effect on such a trivial function.
7240 @node Full example<3>,,Options<3>,Tutorial part 2 Creating a trivial machine code function<2>
7241 @anchor{cp/intro/tutorial02 full-example}@anchor{d3}
7242 @subsubsection Full example
7245 Here's what the above looks like as a complete program:
7247 @quotation
7249 @example
7250 /* Usage example for libgccjit.so's C++ API
7251    Copyright (C) 2014 Free Software Foundation, Inc.
7253 This file is part of GCC.
7255 GCC is free software; you can redistribute it and/or modify it
7256 under the terms of the GNU General Public License as published by
7257 the Free Software Foundation; either version 3, or (at your option)
7258 any later version.
7260 GCC is distributed in the hope that it will be useful, but
7261 WITHOUT ANY WARRANTY; without even the implied warranty of
7262 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
7263 General Public License for more details.
7265 You should have received a copy of the GNU General Public License
7266 along with GCC; see the file COPYING3.  If not see
7267 <http://www.gnu.org/licenses/>.  */
7269 #include <libgccjit++.h>
7271 #include <stdlib.h>
7272 #include <stdio.h>
7274 void
7275 create_code (gccjit::context ctxt)
7277   /* Let's try to inject the equivalent of this C code:
7279       int square (int i)
7280       @{
7281         return i * i;
7282       @}
7283   */
7284   gccjit::type int_type = ctxt.get_type (GCC_JIT_TYPE_INT);
7285   gccjit::param param_i = ctxt.new_param (int_type, "i");
7286   std::vector<gccjit::param> params;
7287   params.push_back (param_i);
7288   gccjit::function func = ctxt.new_function (GCC_JIT_FUNCTION_EXPORTED,
7289                                              int_type,
7290                                              "square",
7291                                              params, 0);
7293   gccjit::block block = func.new_block ();
7295   gccjit::rvalue expr =
7296     ctxt.new_binary_op (GCC_JIT_BINARY_OP_MULT, int_type,
7297                         param_i, param_i);
7299   block.end_with_return (expr);
7303 main (int argc, char **argv)
7305   /* Get a "context" object for working with the library.  */
7306   gccjit::context ctxt = gccjit::context::acquire ();
7308   /* Set some options on the context.
7309      Turn this on to see the code being generated, in assembler form.  */
7310   ctxt.set_bool_option (
7311     GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE,
7312     0);
7314   /* Populate the context.  */
7315   create_code (ctxt);
7317   /* Compile the code.  */
7318   gcc_jit_result *result = ctxt.compile ();
7320   /* We're done with the context; we can release it: */
7321   ctxt.release ();
7323   if (!result)
7324     @{
7325       fprintf (stderr, "NULL result");
7326       return 1;
7327     @}
7329   /* Extract the generated code from "result".  */
7330   void *fn_ptr = gcc_jit_result_get_code (result, "square");
7331   if (!fn_ptr)
7332      @{
7333        fprintf (stderr, "NULL fn_ptr");
7334        gcc_jit_result_release (result);
7335        return 1;
7336      @}
7338   typedef int (*fn_type) (int);
7339   fn_type square = (fn_type)fn_ptr;
7340   printf ("result: %d\n", square (5));
7342   gcc_jit_result_release (result);
7343   return 0;
7346 @end example
7348 @noindent
7349 @end quotation
7351 Building and running it:
7353 @example
7354 $ gcc \
7355     tut02-square.cc \
7356     -o tut02-square \
7357     -lgccjit
7359 # Run the built program:
7360 $ ./tut02-square
7361 result: 25
7362 @end example
7364 @noindent
7366 @c Copyright (C) 2014 Free Software Foundation, Inc.
7367 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
7368 @c 
7369 @c This is free software: you can redistribute it and/or modify it
7370 @c under the terms of the GNU General Public License as published by
7371 @c the Free Software Foundation, either version 3 of the License, or
7372 @c (at your option) any later version.
7373 @c 
7374 @c This program is distributed in the hope that it will be useful, but
7375 @c WITHOUT ANY WARRANTY; without even the implied warranty of
7376 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
7377 @c General Public License for more details.
7378 @c 
7379 @c You should have received a copy of the GNU General Public License
7380 @c along with this program.  If not, see
7381 @c <http://www.gnu.org/licenses/>.
7383 @node Tutorial part 3 Loops and variables<2>,Tutorial part 4 Adding JIT-compilation to a toy interpreter<2>,Tutorial part 2 Creating a trivial machine code function<2>,Tutorial<2>
7384 @anchor{cp/intro/tutorial03 tutorial-part-3-loops-and-variables}@anchor{d4}@anchor{cp/intro/tutorial03 doc}@anchor{d5}
7385 @subsection Tutorial part 3: Loops and variables
7388 Consider this C function:
7390 @quotation
7392 @example
7393 int loop_test (int n)
7395   int sum = 0;
7396   for (int i = 0; i < n; i++)
7397     sum += i * i;
7398   return sum;
7400 @end example
7402 @noindent
7403 @end quotation
7405 This example demonstrates some more features of libgccjit, with local
7406 variables and a loop.
7408 To break this down into libgccjit terms, it's usually easier to reword
7409 the @cite{for} loop as a @cite{while} loop, giving:
7411 @quotation
7413 @example
7414 int loop_test (int n)
7416   int sum = 0;
7417   int i = 0;
7418   while (i < n)
7419   @{
7420     sum += i * i;
7421     i++;
7422   @}
7423   return sum;
7425 @end example
7427 @noindent
7428 @end quotation
7430 Here's what the final control flow graph will look like:
7432 @quotation
7435 @float Figure
7437 @image{sum-of-squares1,,,image of a control flow graph,png}
7439 @end float
7441 @end quotation
7443 As before, we include the libgccjit++ header and make a
7444 @code{gccjit::context}.
7446 @example
7447 #include <libgccjit++.h>
7449 void test (void)
7451   gccjit::context ctxt;
7452   ctxt = gccjit::context::acquire ();
7453 @end example
7455 @noindent
7457 The function works with the C @cite{int} type.
7459 In the previous tutorial we acquired this via
7461 @example
7462 gccjit::type the_type = ctxt.get_type (ctxt, GCC_JIT_TYPE_INT);
7463 @end example
7465 @noindent
7467 though we could equally well make it work on, say, @cite{double}:
7469 @example
7470 gccjit::type the_type = ctxt.get_type (ctxt, GCC_JIT_TYPE_DOUBLE);
7471 @end example
7473 @noindent
7475 For integer types we can use @code{gccjit::context::get_int_type}
7476 to directly bind a specific type:
7478 @example
7479 gccjit::type the_type = ctxt.get_int_type <int> ();
7480 @end example
7482 @noindent
7484 Let's build the function:
7486 @example
7487 gcc_jit_param n = ctxt.new_param (the_type, "n");
7488 std::vector<gccjit::param> params;
7489 params.push_back (n);
7490 gccjit::function func =
7491   ctxt.new_function (GCC_JIT_FUNCTION_EXPORTED,
7492                      return_type,
7493                      "loop_test",
7494                      params, 0);
7495 @end example
7497 @noindent
7499 @menu
7500 * Expressions; lvalues and rvalues: Expressions lvalues and rvalues<2>. 
7501 * Control flow: Control flow<2>. 
7502 * Visualizing the control flow graph: Visualizing the control flow graph<2>. 
7503 * Full example: Full example<4>. 
7505 @end menu
7507 @node Expressions lvalues and rvalues<2>,Control flow<2>,,Tutorial part 3 Loops and variables<2>
7508 @anchor{cp/intro/tutorial03 expressions-lvalues-and-rvalues}@anchor{d6}
7509 @subsubsection Expressions: lvalues and rvalues
7512 The base class of expression is the @code{gccjit::rvalue},
7513 representing an expression that can be on the @emph{right}-hand side of
7514 an assignment: a value that can be computed somehow, and assigned
7515 @emph{to} a storage area (such as a variable).  It has a specific
7516 @code{gccjit::type}.
7518 Anothe important class is @code{gccjit::lvalue}.
7519 A @code{gccjit::lvalue}. is something that can of the @emph{left}-hand
7520 side of an assignment: a storage area (such as a variable).
7522 In other words, every assignment can be thought of as:
7524 @example
7525 LVALUE = RVALUE;
7526 @end example
7528 @noindent
7530 Note that @code{gccjit::lvalue} is a subclass of
7531 @code{gccjit::rvalue}, where in an assignment of the form:
7533 @example
7534 LVALUE_A = LVALUE_B;
7535 @end example
7537 @noindent
7539 the @cite{LVALUE_B} implies reading the current value of that storage
7540 area, assigning it into the @cite{LVALUE_A}.
7542 So far the only expressions we've seen are from the previous tutorial:
7545 @enumerate 
7547 @item 
7548 the multiplication @cite{i * i}:
7549 @end enumerate
7551 @quotation
7553 @example
7554 gccjit::rvalue expr =
7555   ctxt.new_binary_op (
7556     GCC_JIT_BINARY_OP_MULT, int_type,
7557     param_i, param_i);
7559 /* Alternatively, using operator-overloading: */
7560 gccjit::rvalue expr = param_i * param_i;
7561 @end example
7563 @noindent
7565 which is a @code{gccjit::rvalue}, and
7566 @end quotation
7569 @enumerate 2
7571 @item 
7572 the various function parameters: @cite{param_i} and @cite{param_n}, instances of
7573 @code{gccjit::param}, which is a subclass of @code{gccjit::lvalue}
7574 (and, in turn, of @code{gccjit::rvalue}):
7575 we can both read from and write to function parameters within the
7576 body of a function.
7577 @end enumerate
7579 Our new example has a new kind of expression: we have two local
7580 variables.  We create them by calling
7581 @pxref{d7,,gccjit;;function;;new_local()}, supplying a type and a name:
7583 @example
7584 /* Build locals:  */
7585 gccjit::lvalue i = func.new_local (the_type, "i");
7586 gccjit::lvalue sum = func.new_local (the_type, "sum");
7587 @end example
7589 @noindent
7591 These are instances of @code{gccjit::lvalue} - they can be read from
7592 and written to.
7594 Note that there is no precanned way to create @emph{and} initialize a variable
7595 like in C:
7597 @example
7598 int i = 0;
7599 @end example
7601 @noindent
7603 Instead, having added the local to the function, we have to separately add
7604 an assignment of @cite{0} to @cite{local_i} at the beginning of the function.
7606 @node Control flow<2>,Visualizing the control flow graph<2>,Expressions lvalues and rvalues<2>,Tutorial part 3 Loops and variables<2>
7607 @anchor{cp/intro/tutorial03 control-flow}@anchor{d8}
7608 @subsubsection Control flow
7611 This function has a loop, so we need to build some basic blocks to
7612 handle the control flow.  In this case, we need 4 blocks:
7615 @enumerate 
7617 @item 
7618 before the loop (initializing the locals)
7620 @item 
7621 the conditional at the top of the loop (comparing @cite{i < n})
7623 @item 
7624 the body of the loop
7626 @item 
7627 after the loop terminates (@cite{return sum})
7628 @end enumerate
7630 so we create these as @code{gccjit::block} instances within the
7631 @code{gccjit::function}:
7633 @example
7634 gccjit::block b_initial = func.new_block ("initial");
7635 gccjit::block b_loop_cond = func.new_block ("loop_cond");
7636 gccjit::block b_loop_body = func.new_block ("loop_body");
7637 gccjit::block b_after_loop = func.new_block ("after_loop");
7638 @end example
7640 @noindent
7642 We now populate each block with statements.
7644 The entry block @cite{b_initial} consists of initializations followed by a jump
7645 to the conditional.  We assign @cite{0} to @cite{i} and to @cite{sum}, using
7646 @pxref{d9,,gccjit;;block;;add_assignment()} to add
7647 an assignment statement, and using @pxref{da,,gccjit;;context;;zero()} to get
7648 the constant value @cite{0} for the relevant type for the right-hand side of
7649 the assignment:
7651 @example
7652 /* sum = 0; */
7653 b_initial.add_assignment (sum, ctxt.zero (the_type));
7655 /* i = 0; */
7656 b_initial.add_assignment (i, ctxt.zero (the_type));
7657 @end example
7659 @noindent
7661 We can then terminate the entry block by jumping to the conditional:
7663 @example
7664 b_initial.end_with_jump (b_loop_cond);
7665 @end example
7667 @noindent
7669 The conditional block is equivalent to the line @cite{while (i < n)} from our
7670 C example. It contains a single statement: a conditional, which jumps to
7671 one of two destination blocks depending on a boolean
7672 @code{gccjit::rvalue}, in this case the comparison of @cite{i} and @cite{n}.
7674 We could build the comparison using @pxref{db,,gccjit;;context;;new_comparison()}:
7676 @example
7677 gccjit::rvalue guard =
7678   ctxt.new_comparison (GCC_JIT_COMPARISON_GE,
7679                        i, n);
7680 @end example
7682 @noindent
7684 and can then use this to add @cite{b_loop_cond}'s sole statement, via
7685 @pxref{dc,,gccjit;;block;;end_with_conditional()}:
7687 @example
7688 b_loop_cond.end_with_conditional (guard);
7689 @end example
7691 @noindent
7693 However @code{gccjit::rvalue} has overloaded operators for this, so we
7694 express the conditional as
7696 @example
7697 gccjit::rvalue guard = (i >= n);
7698 @end example
7700 @noindent
7702 and hence write the block more concisely as:
7704 @example
7705 b_loop_cond.end_with_conditional (
7706   i >= n,
7707   b_after_loop,
7708   b_loop_body);
7709 @end example
7711 @noindent
7713 Next, we populate the body of the loop.
7715 The C statement @cite{sum += i * i;} is an assignment operation, where an
7716 lvalue is modified "in-place".  We use
7717 @pxref{dd,,gccjit;;block;;add_assignment_op()} to handle these operations:
7719 @example
7720 /* sum += i * i */
7721 b_loop_body.add_assignment_op (sum,
7722                                GCC_JIT_BINARY_OP_PLUS,
7723                                i * i);
7724 @end example
7726 @noindent
7728 The @cite{i++} can be thought of as @cite{i += 1}, and can thus be handled in
7729 a similar way.  We use @pxref{2f,,gcc_jit_context_one()} to get the constant
7730 value @cite{1} (for the relevant type) for the right-hand side
7731 of the assignment.
7733 @example
7734 /* i++ */
7735 b_loop_body.add_assignment_op (i,
7736                                GCC_JIT_BINARY_OP_PLUS,
7737                                ctxt.one (the_type));
7738 @end example
7740 @noindent
7742 @cartouche
7743 @quotation Note 
7744 For numeric constants other than 0 or 1, we could use
7745 @pxref{de,,gccjit;;context;;new_rvalue()}, which has overloads
7746 for both @code{int} and @code{double}.
7747 @end quotation
7748 @end cartouche
7750 The loop body completes by jumping back to the conditional:
7752 @example
7753 b_loop_body.end_with_jump (b_loop_cond);
7754 @end example
7756 @noindent
7758 Finally, we populate the @cite{b_after_loop} block, reached when the loop
7759 conditional is false.  We want to generate the equivalent of:
7761 @example
7762 return sum;
7763 @end example
7765 @noindent
7767 so the block is just one statement:
7769 @example
7770 /* return sum */
7771 b_after_loop.end_with_return (sum);
7772 @end example
7774 @noindent
7776 @cartouche
7777 @quotation Note 
7778 You can intermingle block creation with statement creation,
7779 but given that the terminator statements generally include references
7780 to other blocks, I find it's clearer to create all the blocks,
7781 @emph{then} all the statements.
7782 @end quotation
7783 @end cartouche
7785 We've finished populating the function.  As before, we can now compile it
7786 to machine code:
7788 @example
7789 gcc_jit_result *result;
7790 result = ctxt.compile ();
7792 ctxt.release ();
7794 if (!result)
7795   @{
7796     fprintf (stderr, "NULL result");
7797     return 1;
7798   @}
7800 typedef int (*loop_test_fn_type) (int);
7801 loop_test_fn_type loop_test =
7802  (loop_test_fn_type)gcc_jit_result_get_code (result, "loop_test");
7803 if (!loop_test)
7804   @{
7805     fprintf (stderr, "NULL loop_test");
7806     gcc_jit_result_release (result);
7807     return 1;
7808   @}
7809 printf ("result: %d", loop_test (10));
7810 @end example
7812 @noindent
7814 @example
7815 result: 285
7816 @end example
7818 @noindent
7820 @node Visualizing the control flow graph<2>,Full example<4>,Control flow<2>,Tutorial part 3 Loops and variables<2>
7821 @anchor{cp/intro/tutorial03 visualizing-the-control-flow-graph}@anchor{df}
7822 @subsubsection Visualizing the control flow graph
7825 You can see the control flow graph of a function using
7826 @pxref{e0,,gccjit;;function;;dump_to_dot()}:
7828 @example
7829 func.dump_to_dot ("/tmp/sum-of-squares.dot");
7830 @end example
7832 @noindent
7834 giving a .dot file in GraphViz format.
7836 You can convert this to an image using @cite{dot}:
7838 @example
7839 $ dot -Tpng /tmp/sum-of-squares.dot -o /tmp/sum-of-squares.png
7840 @end example
7842 @noindent
7844 or use a viewer (my preferred one is xdot.py; see
7845 @indicateurl{https://github.com/jrfonseca/xdot.py}; on Fedora you can
7846 install it with @cite{yum install python-xdot}):
7848 @quotation
7851 @float Figure
7853 @image{sum-of-squares1,,,image of a control flow graph,png}
7855 @end float
7857 @end quotation
7859 @node Full example<4>,,Visualizing the control flow graph<2>,Tutorial part 3 Loops and variables<2>
7860 @anchor{cp/intro/tutorial03 full-example}@anchor{e1}
7861 @subsubsection Full example
7864 @quotation
7866 @example
7867 /* Usage example for libgccjit.so's C++ API
7868    Copyright (C) 2014 Free Software Foundation, Inc.
7870 This file is part of GCC.
7872 GCC is free software; you can redistribute it and/or modify it
7873 under the terms of the GNU General Public License as published by
7874 the Free Software Foundation; either version 3, or (at your option)
7875 any later version.
7877 GCC is distributed in the hope that it will be useful, but
7878 WITHOUT ANY WARRANTY; without even the implied warranty of
7879 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
7880 General Public License for more details.
7882 You should have received a copy of the GNU General Public License
7883 along with GCC; see the file COPYING3.  If not see
7884 <http://www.gnu.org/licenses/>.  */
7886 #include <libgccjit++.h>
7888 #include <stdlib.h>
7889 #include <stdio.h>
7891 void
7892 create_code (gccjit::context ctxt)
7894   /*
7895     Simple sum-of-squares, to test conditionals and looping
7897     int loop_test (int n)
7898     @{
7899       int i;
7900       int sum = 0;
7901       for (i = 0; i < n ; i ++)
7902       @{
7903         sum += i * i;
7904       @}
7905       return sum;
7906    */
7907   gccjit::type the_type = ctxt.get_int_type <int> ();
7908   gccjit::type return_type = the_type;
7910   gccjit::param n = ctxt.new_param (the_type, "n");
7911   std::vector<gccjit::param> params;
7912   params.push_back (n);
7913   gccjit::function func =
7914     ctxt.new_function (GCC_JIT_FUNCTION_EXPORTED,
7915                        return_type,
7916                        "loop_test",
7917                        params, 0);
7919   /* Build locals:  */
7920   gccjit::lvalue i = func.new_local (the_type, "i");
7921   gccjit::lvalue sum = func.new_local (the_type, "sum");
7923   gccjit::block b_initial = func.new_block ("initial");
7924   gccjit::block b_loop_cond = func.new_block ("loop_cond");
7925   gccjit::block b_loop_body = func.new_block ("loop_body");
7926   gccjit::block b_after_loop = func.new_block ("after_loop");
7928   /* sum = 0; */
7929   b_initial.add_assignment (sum, ctxt.zero (the_type));
7931   /* i = 0; */
7932   b_initial.add_assignment (i, ctxt.zero (the_type));
7934   b_initial.end_with_jump (b_loop_cond);
7936   /* if (i >= n) */
7937   b_loop_cond.end_with_conditional (
7938     i >= n,
7939     b_after_loop,
7940     b_loop_body);
7942   /* sum += i * i */
7943   b_loop_body.add_assignment_op (sum,
7944                                  GCC_JIT_BINARY_OP_PLUS,
7945                                  i * i);
7947   /* i++ */
7948   b_loop_body.add_assignment_op (i,
7949                                 GCC_JIT_BINARY_OP_PLUS,
7950                                 ctxt.one (the_type));
7952   b_loop_body.end_with_jump (b_loop_cond);
7954   /* return sum */
7955   b_after_loop.end_with_return (sum);
7959 main (int argc, char **argv)
7961   gccjit::context ctxt;
7962   gcc_jit_result *result = NULL;
7964   /* Get a "context" object for working with the library.  */
7965   ctxt = gccjit::context::acquire ();
7967   /* Set some options on the context.
7968      Turn this on to see the code being generated, in assembler form.  */
7969   ctxt.set_bool_option (GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE,
7970                         0);
7972   /* Populate the context.  */
7973   create_code (ctxt);
7975   /* Compile the code.  */
7976   result = ctxt.compile ();
7978   ctxt.release ();
7980   if (!result)
7981     @{
7982       fprintf (stderr, "NULL result");
7983       return 1;
7984     @}
7986   /* Extract the generated code from "result".  */
7987   typedef int (*loop_test_fn_type) (int);
7988   loop_test_fn_type loop_test =
7989     (loop_test_fn_type)gcc_jit_result_get_code (result, "loop_test");
7990   if (!loop_test)
7991     @{
7992       fprintf (stderr, "NULL loop_test");
7993       gcc_jit_result_release (result);
7994       return 1;
7995     @}
7997   /* Run the generated code.  */
7998   int val = loop_test (10);
7999   printf("loop_test returned: %d\n", val);
8001   gcc_jit_result_release (result);
8002   return 0;
8005 @end example
8007 @noindent
8008 @end quotation
8010 Building and running it:
8012 @example
8013 $ gcc \
8014     tut03-sum-of-squares.cc \
8015     -o tut03-sum-of-squares \
8016     -lgccjit
8018 # Run the built program:
8019 $ ./tut03-sum-of-squares
8020 loop_test returned: 285
8021 @end example
8023 @noindent
8025 @c Copyright (C) 2014 Free Software Foundation, Inc.
8026 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
8027 @c 
8028 @c This is free software: you can redistribute it and/or modify it
8029 @c under the terms of the GNU General Public License as published by
8030 @c the Free Software Foundation, either version 3 of the License, or
8031 @c (at your option) any later version.
8032 @c 
8033 @c This program is distributed in the hope that it will be useful, but
8034 @c WITHOUT ANY WARRANTY; without even the implied warranty of
8035 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
8036 @c General Public License for more details.
8037 @c 
8038 @c You should have received a copy of the GNU General Public License
8039 @c along with this program.  If not, see
8040 @c <http://www.gnu.org/licenses/>.
8042 @node Tutorial part 4 Adding JIT-compilation to a toy interpreter<2>,,Tutorial part 3 Loops and variables<2>,Tutorial<2>
8043 @anchor{cp/intro/tutorial04 tutorial-part-4-adding-jit-compilation-to-a-toy-interpreter}@anchor{e2}@anchor{cp/intro/tutorial04 doc}@anchor{e3}
8044 @subsection Tutorial part 4: Adding JIT-compilation to a toy interpreter
8047 In this example we construct a "toy" interpreter, and add JIT-compilation
8048 to it.
8050 @menu
8051 * Our toy interpreter: Our toy interpreter<2>. 
8052 * Compiling to machine code: Compiling to machine code<2>. 
8053 * Setting things up: Setting things up<2>. 
8054 * Populating the function: Populating the function<2>. 
8055 * Verifying the control flow graph: Verifying the control flow graph<2>. 
8056 * Compiling the context: Compiling the context<2>. 
8057 * Single-stepping through the generated code: Single-stepping through the generated code<2>. 
8058 * Examining the generated code: Examining the generated code<2>. 
8059 * Putting it all together: Putting it all together<2>. 
8060 * Behind the curtain; How does our code get optimized?: Behind the curtain How does our code get optimized?<2>. 
8062 @end menu
8064 @node Our toy interpreter<2>,Compiling to machine code<2>,,Tutorial part 4 Adding JIT-compilation to a toy interpreter<2>
8065 @anchor{cp/intro/tutorial04 our-toy-interpreter}@anchor{e4}
8066 @subsubsection Our toy interpreter
8069 It's a stack-based interpreter, and is intended as a (very simple) example
8070 of the kind of bytecode interpreter seen in dynamic languages such as
8071 Python, Ruby etc.
8073 For the sake of simplicity, our toy virtual machine is very limited:
8075 @quotation
8078 @itemize *
8080 @item 
8081 The only data type is @cite{int}
8083 @item 
8084 It can only work on one function at a time (so that the only
8085 function call that can be made is to recurse).
8087 @item 
8088 Functions can only take one parameter.
8090 @item 
8091 Functions have a stack of @cite{int} values.
8093 @item 
8094 We'll implement function call within the interpreter by calling a
8095 function in our implementation, rather than implementing our own
8096 frame stack.
8098 @item 
8099 The parser is only good enough to get the examples to work.
8100 @end itemize
8101 @end quotation
8103 Naturally, a real interpreter would be much more complicated that this.
8105 The following operations are supported:
8108 @multitable {xxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxx} 
8109 @headitem
8111 Operation
8113 @tab
8115 Meaning
8117 @tab
8119 Old Stack
8121 @tab
8123 New Stack
8125 @item
8129 @tab
8131 Duplicate top of stack.
8133 @tab
8135 @code{[..., x]}
8137 @tab
8139 @code{[..., x, x]}
8141 @item
8145 @tab
8147 Swap top two elements
8148 of stack.
8150 @tab
8152 @code{[..., x, y]}
8154 @tab
8156 @code{[..., y, x]}
8158 @item
8160 BINARY_ADD
8162 @tab
8164 Add the top two elements
8165 on the stack.
8167 @tab
8169 @code{[..., x, y]}
8171 @tab
8173 @code{[..., (x+y)]}
8175 @item
8177 BINARY_SUBTRACT
8179 @tab
8181 Likewise, but subtract.
8183 @tab
8185 @code{[..., x, y]}
8187 @tab
8189 @code{[..., (x-y)]}
8191 @item
8193 BINARY_MULT
8195 @tab
8197 Likewise, but multiply.
8199 @tab
8201 @code{[..., x, y]}
8203 @tab
8205 @code{[..., (x*y)]}
8207 @item
8209 BINARY_COMPARE_LT
8211 @tab
8213 Compare the top two
8214 elements on the stack
8215 and push a nonzero/zero
8216 if (x<y).
8218 @tab
8220 @code{[..., x, y]}
8222 @tab
8224 @code{[..., (x<y)]}
8226 @item
8228 RECURSE
8230 @tab
8232 Recurse, passing the top
8233 of the stack, and
8234 popping the result.
8236 @tab
8238 @code{[..., x]}
8240 @tab
8242 @code{[..., fn(x)]}
8244 @item
8246 RETURN
8248 @tab
8250 Return the top of the
8251 stack.
8253 @tab
8255 @code{[x]}
8257 @tab
8259 @code{[]}
8261 @item
8263 PUSH_CONST @cite{arg}
8265 @tab
8267 Push an int const.
8269 @tab
8271 @code{[...]}
8273 @tab
8275 @code{[..., arg]}
8277 @item
8279 JUMP_ABS_IF_TRUE @cite{arg}
8281 @tab
8283 Pop; if top of stack was
8284 nonzero, jump to
8285 @code{arg}.
8287 @tab
8289 @code{[..., x]}
8291 @tab
8293 @code{[...]}
8295 @end multitable
8298 Programs can be interpreted, disassembled, and compiled to machine code.
8300 The interpreter reads @code{.toy} scripts.  Here's what a simple recursive
8301 factorial program looks like, the script @code{factorial.toy}.
8302 The parser ignores lines beginning with a @cite{#}.
8304 @quotation
8306 @example
8307 # Simple recursive factorial implementation, roughly equivalent to:
8309 #  int factorial (int arg)
8310 #  @{
8311 #     if (arg < 2)
8312 #       return arg
8313 #     return arg * factorial (arg - 1)
8314 #  @}
8316 # Initial state:
8317 # stack: [arg]
8319 # 0:
8321 # stack: [arg, arg]
8323 # 1:
8324 PUSH_CONST 2
8325 # stack: [arg, arg, 2]
8327 # 2:
8328 BINARY_COMPARE_LT
8329 # stack: [arg, (arg < 2)]
8331 # 3:
8332 JUMP_ABS_IF_TRUE 9
8333 # stack: [arg]
8335 # 4:
8337 # stack: [arg, arg]
8339 # 5:
8340 PUSH_CONST 1
8341 # stack: [arg, arg, 1]
8343 # 6:
8344 BINARY_SUBTRACT
8345 # stack: [arg,  (arg - 1)
8347 # 7:
8348 RECURSE
8349 # stack: [arg, factorial(arg - 1)]
8351 # 8:
8352 BINARY_MULT
8353 # stack: [arg * factorial(arg - 1)]
8355 # 9:
8356 RETURN
8358 @end example
8360 @noindent
8361 @end quotation
8363 The interpreter is a simple infinite loop with a big @code{switch} statement
8364 based on what the next opcode is:
8366 @quotation
8368 @example
8371 toyvm_function::interpret (int arg, FILE *trace)
8373   toyvm_frame frame;
8374 #define PUSH(ARG) (frame.push (ARG))
8375 #define POP(ARG) (frame.pop ())
8377   frame.frm_function = this;
8378   frame.frm_pc = 0;
8379   frame.frm_cur_depth = 0;
8381   PUSH (arg);
8383   while (1)
8384     @{
8385       toyvm_op *op;
8386       int x, y;
8387       assert (frame.frm_pc < fn_num_ops);
8388       op = &fn_ops[frame.frm_pc++];
8390       if (trace)
8391         @{
8392           frame.dump_stack (trace);
8393           disassemble_op (op, frame.frm_pc, trace);
8394         @}
8396       switch (op->op_opcode)
8397         @{
8398           /* Ops taking no operand.  */
8399         case DUP:
8400           x = POP ();
8401           PUSH (x);
8402           PUSH (x);
8403           break;
8405         case ROT:
8406           y = POP ();
8407           x = POP ();
8408           PUSH (y);
8409           PUSH (x);
8410           break;
8412         case BINARY_ADD:
8413           y = POP ();
8414           x = POP ();
8415           PUSH (x + y);
8416           break;
8418         case BINARY_SUBTRACT:
8419           y = POP ();
8420           x = POP ();
8421           PUSH (x - y);
8422           break;
8424         case BINARY_MULT:
8425           y = POP ();
8426           x = POP ();
8427           PUSH (x * y);
8428           break;
8430         case BINARY_COMPARE_LT:
8431           y = POP ();
8432           x = POP ();
8433           PUSH (x < y);
8434           break;
8436         case RECURSE:
8437           x = POP ();
8438           x = interpret (x, trace);
8439           PUSH (x);
8440           break;
8442         case RETURN:
8443           return POP ();
8445           /* Ops taking an operand.  */
8446         case PUSH_CONST:
8447           PUSH (op->op_operand);
8448           break;
8450         case JUMP_ABS_IF_TRUE:
8451           x = POP ();
8452           if (x)
8453             frame.frm_pc = op->op_operand;
8454           break;
8456         default:
8457           assert (0); /* unknown opcode */
8459         @} /* end of switch on opcode */
8460     @} /* end of while loop */
8462 #undef PUSH
8463 #undef POP
8467 @end example
8469 @noindent
8470 @end quotation
8472 @node Compiling to machine code<2>,Setting things up<2>,Our toy interpreter<2>,Tutorial part 4 Adding JIT-compilation to a toy interpreter<2>
8473 @anchor{cp/intro/tutorial04 compiling-to-machine-code}@anchor{e5}
8474 @subsubsection Compiling to machine code
8477 We want to generate machine code that can be cast to this type and
8478 then directly executed in-process:
8480 @quotation
8482 @example
8483 typedef int (*toyvm_compiled_func) (int);
8486 @end example
8488 @noindent
8489 @end quotation
8491 Our compiler isn't very sophisticated; it takes the implementation of
8492 each opcode above, and maps it directly to the operations supported by
8493 the libgccjit API.
8495 How should we handle the stack?  In theory we could calculate what the
8496 stack depth will be at each opcode, and optimize away the stack
8497 manipulation "by hand".  We'll see below that libgccjit is able to do
8498 this for us, so we'll implement stack manipulation
8499 in a direct way, by creating a @code{stack} array and @code{stack_depth}
8500 variables, local within the generated function, equivalent to this C code:
8502 @example
8503 int stack_depth;
8504 int stack[MAX_STACK_DEPTH];
8505 @end example
8507 @noindent
8509 We'll also have local variables @code{x} and @code{y} for use when implementing
8510 the opcodes, equivalent to this:
8512 @example
8513 int x;
8514 int y;
8515 @end example
8517 @noindent
8519 This means our compiler has the following state:
8521 @quotation
8523 @example
8525   toyvm_function &toyvmfn;
8527   gccjit::context ctxt;
8529   gccjit::type int_type;
8530   gccjit::type bool_type;
8531   gccjit::type stack_type; /* int[MAX_STACK_DEPTH] */
8533   gccjit::rvalue const_one;
8535   gccjit::function fn;
8536   gccjit::param param_arg;
8537   gccjit::lvalue stack;
8538   gccjit::lvalue stack_depth;
8539   gccjit::lvalue x;
8540   gccjit::lvalue y;
8542   gccjit::location op_locs[MAX_OPS];
8543   gccjit::block initial_block;
8544   gccjit::block op_blocks[MAX_OPS];
8547 @end example
8549 @noindent
8550 @end quotation
8552 @node Setting things up<2>,Populating the function<2>,Compiling to machine code<2>,Tutorial part 4 Adding JIT-compilation to a toy interpreter<2>
8553 @anchor{cp/intro/tutorial04 setting-things-up}@anchor{e6}
8554 @subsubsection Setting things up
8557 First we create our types:
8559 @quotation
8561 @example
8563 void
8564 compilation_state::create_types ()
8566   /* Create types.  */
8567   int_type = ctxt.get_type (GCC_JIT_TYPE_INT);
8568   bool_type = ctxt.get_type (GCC_JIT_TYPE_BOOL);
8569   stack_type = ctxt.new_array_type (int_type, MAX_STACK_DEPTH);
8572 @end example
8574 @noindent
8575 @end quotation
8577 along with extracting a useful @cite{int} constant:
8579 @quotation
8581 @example
8582   const_one = ctxt.one (int_type);
8587 @end example
8589 @noindent
8590 @end quotation
8592 We'll implement push and pop in terms of the @code{stack} array and
8593 @code{stack_depth}.  Here are helper functions for adding statements to
8594 a block, implementing pushing and popping values:
8596 @quotation
8598 @example
8600 void
8601 compilation_state::add_push (gccjit::block block,
8602                              gccjit::rvalue rvalue,
8603                              gccjit::location loc)
8605   /* stack[stack_depth] = RVALUE */
8606   block.add_assignment (
8607     /* stack[stack_depth] */
8608     ctxt.new_array_access (
8609       stack,
8610       stack_depth,
8611       loc),
8612     rvalue,
8613     loc);
8615   /* "stack_depth++;".  */
8616   block.add_assignment_op (
8617     stack_depth,
8618     GCC_JIT_BINARY_OP_PLUS,
8619     const_one,
8620     loc);
8623 void
8624 compilation_state::add_pop (gccjit::block block,
8625                             gccjit::lvalue lvalue,
8626                             gccjit::location loc)
8628   /* "--stack_depth;".  */
8629   block.add_assignment_op (
8630     stack_depth,
8631     GCC_JIT_BINARY_OP_MINUS,
8632     const_one,
8633     loc);
8635   /* "LVALUE = stack[stack_depth];".  */
8636   block.add_assignment (
8637     lvalue,
8638     /* stack[stack_depth] */
8639     ctxt.new_array_access (stack,
8640                            stack_depth,
8641                            loc),
8642     loc);
8646 @end example
8648 @noindent
8649 @end quotation
8651 We will support single-stepping through the generated code in the
8652 debugger, so we need to create @code{gccjit::location} instances, one
8653 per operation in the source code.  These will reference the lines of
8654 e.g. @code{factorial.toy}.
8656 @quotation
8658 @example
8660 void
8661 compilation_state::create_locations ()
8663   for (int pc = 0; pc < toyvmfn.fn_num_ops; pc++)
8664     @{
8665       toyvm_op *op = &toyvmfn.fn_ops[pc];
8667       op_locs[pc] = ctxt.new_location (toyvmfn.fn_filename,
8668                                        op->op_linenum,
8669                                        0); /* column */
8670     @}
8674 @end example
8676 @noindent
8677 @end quotation
8679 Let's create the function itself.  As usual, we create its parameter
8680 first, then use the parameter to create the function:
8682 @quotation
8684 @example
8686 void
8687 compilation_state::create_function (const char *funcname)
8689   std::vector <gccjit::param> params;
8690   param_arg = ctxt.new_param (int_type, "arg", op_locs[0]);
8691   params.push_back (param_arg);
8692   fn = ctxt.new_function (GCC_JIT_FUNCTION_EXPORTED,
8693                           int_type,
8694                           funcname,
8695                           params, 0,
8696                           op_locs[0]);
8699 @end example
8701 @noindent
8702 @end quotation
8704 We create the locals within the function.
8706 @quotation
8708 @example
8709   stack = fn.new_local (stack_type, "stack");
8710   stack_depth = fn.new_local (int_type, "stack_depth");
8711   x = fn.new_local (int_type, "x");
8712   y = fn.new_local (int_type, "y");
8715 @end example
8717 @noindent
8718 @end quotation
8720 @node Populating the function<2>,Verifying the control flow graph<2>,Setting things up<2>,Tutorial part 4 Adding JIT-compilation to a toy interpreter<2>
8721 @anchor{cp/intro/tutorial04 populating-the-function}@anchor{e7}
8722 @subsubsection Populating the function
8725 There's some one-time initialization, and the API treats the first block
8726 you create as the entrypoint of the function, so we need to create that
8727 block first:
8729 @quotation
8731 @example
8732   initial_block = fn.new_block ("initial");
8735 @end example
8737 @noindent
8738 @end quotation
8740 We can now create blocks for each of the operations.  Most of these will
8741 be consolidated into larger blocks when the optimizer runs.
8743 @quotation
8745 @example
8746   for (int pc = 0; pc < toyvmfn.fn_num_ops; pc++)
8747     @{
8748       char buf[16];
8749       sprintf (buf, "instr%i", pc);
8750       op_blocks[pc] = fn.new_block (buf);
8751     @}
8754 @end example
8756 @noindent
8757 @end quotation
8759 Now that we have a block it can jump to when it's done, we can populate
8760 the initial block:
8762 @quotation
8764 @example
8766   /* "stack_depth = 0;".  */
8767   initial_block.add_assignment (stack_depth,
8768                                 ctxt.zero (int_type),
8769                                 op_locs[0]);
8771   /* "PUSH (arg);".  */
8772   add_push (initial_block,
8773             param_arg,
8774             op_locs[0]);
8776   /* ...and jump to insn 0.  */
8777   initial_block.end_with_jump (op_blocks[0],
8778                                op_locs[0]);
8781 @end example
8783 @noindent
8784 @end quotation
8786 We can now populate the blocks for the individual operations.  We loop
8787 through them, adding instructions to their blocks:
8789 @quotation
8791 @example
8792   for (int pc = 0; pc < toyvmfn.fn_num_ops; pc++)
8793     @{
8794       gccjit::location loc = op_locs[pc];
8796       gccjit::block block = op_blocks[pc];
8797       gccjit::block next_block = (pc < toyvmfn.fn_num_ops
8798                                   ? op_blocks[pc + 1]
8799                                   : NULL);
8801       toyvm_op *op;
8802       op = &toyvmfn.fn_ops[pc];
8805 @end example
8807 @noindent
8808 @end quotation
8810 We're going to have another big @code{switch} statement for implementing
8811 the opcodes, this time for compiling them, rather than interpreting
8812 them.  It's helpful to have macros for implementing push and pop, so that
8813 we can make the @code{switch} statement that's coming up look as much as
8814 possible like the one above within the interpreter:
8816 @example
8818 #define X_EQUALS_POP()\
8819       add_pop (block, x, loc)
8820 #define Y_EQUALS_POP()\
8821       add_pop (block, y, loc)
8822 #define PUSH_RVALUE(RVALUE)\
8823       add_push (block, (RVALUE), loc)
8824 #define PUSH_X()\
8825       PUSH_RVALUE (x)
8826 #define PUSH_Y() \
8827       PUSH_RVALUE (y)
8830 @end example
8832 @noindent
8834 @cartouche
8835 @quotation Note 
8836 A particularly clever implementation would have an @emph{identical}
8837 @code{switch} statement shared by the interpreter and the compiler, with
8838 some preprocessor "magic".  We're not doing that here, for the sake
8839 of simplicity.
8840 @end quotation
8841 @end cartouche
8843 When I first implemented this compiler, I accidentally missed an edit
8844 when copying and pasting the @code{Y_EQUALS_POP} macro, so that popping the
8845 stack into @code{y} instead erroneously assigned it to @code{x}, leaving @code{y}
8846 uninitialized.
8848 To track this kind of thing down, we can use
8849 @pxref{e8,,gccjit;;block;;add_comment()} to add descriptive comments
8850 to the internal representation.  This is invaluable when looking through
8851 the generated IR for, say @code{factorial}:
8853 @quotation
8855 @example
8857       block.add_comment (opcode_names[op->op_opcode], loc);
8860 @end example
8862 @noindent
8863 @end quotation
8865 We can now write the big @code{switch} statement that implements the
8866 individual opcodes, populating the relevant block with statements:
8868 @quotation
8870 @example
8872       switch (op->op_opcode)
8873         @{
8874         case DUP:
8875           X_EQUALS_POP ();
8876           PUSH_X ();
8877           PUSH_X ();
8878           break;
8880         case ROT:
8881           Y_EQUALS_POP ();
8882           X_EQUALS_POP ();
8883           PUSH_Y ();
8884           PUSH_X ();
8885           break;
8887         case BINARY_ADD:
8888           Y_EQUALS_POP ();
8889           X_EQUALS_POP ();
8890           PUSH_RVALUE (
8891            ctxt.new_binary_op (
8892              GCC_JIT_BINARY_OP_PLUS,
8893              int_type,
8894              x, y,
8895              loc));
8896           break;
8898         case BINARY_SUBTRACT:
8899           Y_EQUALS_POP ();
8900           X_EQUALS_POP ();
8901           PUSH_RVALUE (
8902            ctxt.new_binary_op (
8903              GCC_JIT_BINARY_OP_MINUS,
8904              int_type,
8905              x, y,
8906              loc));
8907           break;
8909         case BINARY_MULT:
8910           Y_EQUALS_POP ();
8911           X_EQUALS_POP ();
8912           PUSH_RVALUE (
8913            ctxt.new_binary_op (
8914              GCC_JIT_BINARY_OP_MULT,
8915              int_type,
8916              x, y,
8917              loc));
8918           break;
8920         case BINARY_COMPARE_LT:
8921           Y_EQUALS_POP ();
8922           X_EQUALS_POP ();
8923           PUSH_RVALUE (
8924              /* cast of bool to int */
8925              ctxt.new_cast (
8926                /* (x < y) as a bool */
8927                ctxt.new_comparison (
8928                  GCC_JIT_COMPARISON_LT,
8929                  x, y,
8930                  loc),
8931                int_type,
8932                loc));
8933           break;
8935         case RECURSE:
8936           @{
8937             X_EQUALS_POP ();
8938             PUSH_RVALUE (
8939               ctxt.new_call (
8940                 fn,
8941                 x,
8942                 loc));
8943             break;
8944           @}
8946         case RETURN:
8947           X_EQUALS_POP ();
8948           block.end_with_return (x, loc);
8949           break;
8951           /* Ops taking an operand.  */
8952         case PUSH_CONST:
8953           PUSH_RVALUE (
8954             ctxt.new_rvalue (int_type, op->op_operand));
8955           break;
8957         case JUMP_ABS_IF_TRUE:
8958           X_EQUALS_POP ();
8959           block.end_with_conditional (
8960             /* "(bool)x".  */
8961             ctxt.new_cast (x, bool_type, loc),
8962             op_blocks[op->op_operand], /* on_true */
8963             next_block, /* on_false */
8964             loc); 
8965           break;
8967         default:
8968           assert(0);
8969         @} /* end of switch on opcode */
8972 @end example
8974 @noindent
8975 @end quotation
8977 Every block must be terminated, via a call to one of the
8978 @code{gccjit::block::end_with_} entrypoints.  This has been done for two
8979 of the opcodes, but we need to do it for the other ones, by jumping
8980 to the next block.
8982 @quotation
8984 @example
8985       if (op->op_opcode != JUMP_ABS_IF_TRUE
8986           && op->op_opcode != RETURN)
8987         block.end_with_jump (next_block, loc);
8990 @end example
8992 @noindent
8993 @end quotation
8995 This is analogous to simply incrementing the program counter.
8997 @node Verifying the control flow graph<2>,Compiling the context<2>,Populating the function<2>,Tutorial part 4 Adding JIT-compilation to a toy interpreter<2>
8998 @anchor{cp/intro/tutorial04 verifying-the-control-flow-graph}@anchor{e9}
8999 @subsubsection Verifying the control flow graph
9002 Having finished looping over the blocks, the context is complete.
9004 As before, we can verify that the control flow and statements are sane by
9005 using @pxref{e0,,gccjit;;function;;dump_to_dot()}:
9007 @example
9008 fn.dump_to_dot ("/tmp/factorial.dot");
9009 @end example
9011 @noindent
9013 and viewing the result.  Note how the label names, comments, and
9014 variable names show up in the dump, to make it easier to spot
9015 errors in our compiler.
9017 @quotation
9020 @float Figure
9022 @image{factorial1,,,image of a control flow graph,png}
9024 @end float
9026 @end quotation
9028 @node Compiling the context<2>,Single-stepping through the generated code<2>,Verifying the control flow graph<2>,Tutorial part 4 Adding JIT-compilation to a toy interpreter<2>
9029 @anchor{cp/intro/tutorial04 compiling-the-context}@anchor{ea}
9030 @subsubsection Compiling the context
9033 Having finished looping over the blocks and populating them with
9034 statements, the context is complete.
9036 We can now compile it, and extract machine code from the result:
9038 @quotation
9040 @example
9041   gcc_jit_result *result = state.compile ();
9043   return (toyvm_compiled_func)gcc_jit_result_get_code (result, funcname);
9045 @end example
9047 @noindent
9048 @end quotation
9050 We can now run the result:
9052 @quotation
9054 @example
9055   toyvm_compiled_func code = fn->compile ();
9056   printf ("compiler result: %d\n",
9057           code (atoi (argv[2])));
9060 @end example
9062 @noindent
9063 @end quotation
9065 @node Single-stepping through the generated code<2>,Examining the generated code<2>,Compiling the context<2>,Tutorial part 4 Adding JIT-compilation to a toy interpreter<2>
9066 @anchor{cp/intro/tutorial04 single-stepping-through-the-generated-code}@anchor{eb}
9067 @subsubsection Single-stepping through the generated code
9070 It's possible to debug the generated code.  To do this we need to both:
9072 @quotation
9075 @itemize *
9077 @item 
9078 Set up source code locations for our statements, so that we can
9079 meaningfully step through the code.  We did this above by
9080 calling @pxref{ec,,gccjit;;context;;new_location()} and using the
9081 results.
9083 @item 
9084 Enable the generation of debugging information, by setting
9085 @pxref{42,,GCC_JIT_BOOL_OPTION_DEBUGINFO} on the
9086 @code{gccjit::context} via
9087 @pxref{d1,,gccjit;;context;;set_bool_option()}:
9089 @example
9090 ctxt.set_bool_option (GCC_JIT_BOOL_OPTION_DEBUGINFO, 1);
9091 @end example
9093 @noindent
9094 @end itemize
9095 @end quotation
9097 Having done this, we can put a breakpoint on the generated function:
9099 @example
9100 $ gdb --args ./toyvm factorial.toy 10
9101 (gdb) break factorial
9102 Function "factorial" not defined.
9103 Make breakpoint pending on future shared library load? (y or [n]) y
9104 Breakpoint 1 (factorial) pending.
9105 (gdb) run
9106 Breakpoint 1, factorial (arg=10) at factorial.toy:14
9107 14    DUP
9108 @end example
9110 @noindent
9112 We've set up location information, which references @code{factorial.toy}.
9113 This allows us to use e.g. @code{list} to see where we are in the script:
9115 @example
9116 (gdb) list
9118 10    # Initial state:
9119 11    # stack: [arg]
9121 13    # 0:
9122 14    DUP
9123 15    # stack: [arg, arg]
9125 17    # 1:
9126 18    PUSH_CONST 2
9127 @end example
9129 @noindent
9131 and to step through the function, examining the data:
9133 @example
9134 (gdb) n
9135 18    PUSH_CONST 2
9136 (gdb) n
9137 22    BINARY_COMPARE_LT
9138 (gdb) print stack
9139 $5 = @{10, 10, 2, 0, -7152, 32767, 0, 0@}
9140 (gdb) print stack_depth
9141 $6 = 3
9142 @end example
9144 @noindent
9146 You'll see that the parts of the @code{stack} array that haven't been
9147 touched yet are uninitialized.
9149 @cartouche
9150 @quotation Note 
9151 Turning on optimizations may lead to unpredictable results when
9152 stepping through the generated code: the execution may appear to
9153 "jump around" the source code.  This is analogous to turning up the
9154 optimization level in a regular compiler.
9155 @end quotation
9156 @end cartouche
9158 @node Examining the generated code<2>,Putting it all together<2>,Single-stepping through the generated code<2>,Tutorial part 4 Adding JIT-compilation to a toy interpreter<2>
9159 @anchor{cp/intro/tutorial04 examining-the-generated-code}@anchor{ed}
9160 @subsubsection Examining the generated code
9163 How good is the optimized code?
9165 We can turn up optimizations, by calling
9166 @pxref{d2,,gccjit;;context;;set_int_option()} with
9167 @pxref{1f,,GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL}:
9169 @example
9170 ctxt.set_int_option (GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL, 3);
9171 @end example
9173 @noindent
9175 One of GCC's internal representations is called "gimple".  A dump of the
9176 initial gimple representation of the code can be seen by setting:
9178 @example
9179 ctxt.set_bool_option (GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE, 1);
9180 @end example
9182 @noindent
9184 With optimization on and source locations displayed, this gives:
9186 @c We'll use "c" for gimple dumps
9188 @example
9189 factorial (signed int arg)
9191   <unnamed type> D.80;
9192   signed int D.81;
9193   signed int D.82;
9194   signed int D.83;
9195   signed int D.84;
9196   signed int D.85;
9197   signed int y;
9198   signed int x;
9199   signed int stack_depth;
9200   signed int stack[8];
9202   try
9203     @{
9204       initial:
9205       stack_depth = 0;
9206       stack[stack_depth] = arg;
9207       stack_depth = stack_depth + 1;
9208       goto instr0;
9209       instr0:
9210       /* DUP */:
9211       stack_depth = stack_depth + -1;
9212       x = stack[stack_depth];
9213       stack[stack_depth] = x;
9214       stack_depth = stack_depth + 1;
9215       stack[stack_depth] = x;
9216       stack_depth = stack_depth + 1;
9217       goto instr1;
9218       instr1:
9219       /* PUSH_CONST */:
9220       stack[stack_depth] = 2;
9221       stack_depth = stack_depth + 1;
9222       goto instr2;
9224       /* etc */
9225 @end example
9227 @noindent
9229 You can see the generated machine code in assembly form via:
9231 @example
9232 ctxt.set_bool_option (GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE, 1);
9233 result = ctxt.compile ();
9234 @end example
9236 @noindent
9238 which shows that (on this x86_64 box) the compiler has unrolled the loop
9239 and is using MMX instructions to perform several multiplications
9240 simultaneously:
9242 @example
9243         .file   "fake.c"
9244         .text
9245 .Ltext0:
9246         .p2align 4,,15
9247         .globl  factorial
9248         .type   factorial, @@function
9249 factorial:
9250 .LFB0:
9251         .file 1 "factorial.toy"
9252         .loc 1 14 0
9253         .cfi_startproc
9254 .LVL0:
9255 .L2:
9256         .loc 1 26 0
9257         cmpl    $1, %edi
9258         jle     .L13
9259         leal    -1(%rdi), %edx
9260         movl    %edx, %ecx
9261         shrl    $2, %ecx
9262         leal    0(,%rcx,4), %esi
9263         testl   %esi, %esi
9264         je      .L14
9265         cmpl    $9, %edx
9266         jbe     .L14
9267         leal    -2(%rdi), %eax
9268         movl    %eax, -16(%rsp)
9269         leal    -3(%rdi), %eax
9270         movd    -16(%rsp), %xmm0
9271         movl    %edi, -16(%rsp)
9272         movl    %eax, -12(%rsp)
9273         movd    -16(%rsp), %xmm1
9274         xorl    %eax, %eax
9275         movl    %edx, -16(%rsp)
9276         movd    -12(%rsp), %xmm4
9277         movd    -16(%rsp), %xmm6
9278         punpckldq       %xmm4, %xmm0
9279         movdqa  .LC1(%rip), %xmm4
9280         punpckldq       %xmm6, %xmm1
9281         punpcklqdq      %xmm0, %xmm1
9282         movdqa  .LC0(%rip), %xmm0
9283         jmp     .L5
9284         # etc - edited for brevity
9285 @end example
9287 @noindent
9289 This is clearly overkill for a function that will likely overflow the
9290 @code{int} type before the vectorization is worthwhile - but then again, this
9291 is a toy example.
9293 Turning down the optimization level to 2:
9295 @example
9296 ctxt.set_int_option (GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL, 2);
9297 @end example
9299 @noindent
9301 yields this code, which is simple enough to quote in its entirety:
9303 @example
9304         .file   "fake.c"
9305         .text
9306         .p2align 4,,15
9307         .globl  factorial
9308         .type   factorial, @@function
9309 factorial:
9310 .LFB0:
9311         .cfi_startproc
9312 .L2:
9313         cmpl    $1, %edi
9314         jle     .L8
9315         movl    $1, %edx
9316         jmp     .L4
9317         .p2align 4,,10
9318         .p2align 3
9319 .L6:
9320         movl    %eax, %edi
9321 .L4:
9322 .L5:
9323         leal    -1(%rdi), %eax
9324         imull   %edi, %edx
9325         cmpl    $1, %eax
9326         jne     .L6
9327 .L3:
9328 .L7:
9329         imull   %edx, %eax
9330         ret
9331 .L8:
9332         movl    %edi, %eax
9333         movl    $1, %edx
9334         jmp     .L7
9335         .cfi_endproc
9336 .LFE0:
9337         .size   factorial, .-factorial
9338         .ident  "GCC: (GNU) 4.9.0 20131023 (Red Hat 0.2-%@{gcc_release@})"
9339         .section        .note.GNU-stack,"",@@progbits
9340 @end example
9342 @noindent
9344 Note that the stack pushing and popping have been eliminated, as has the
9345 recursive call (in favor of an iteration).
9347 @node Putting it all together<2>,Behind the curtain How does our code get optimized?<2>,Examining the generated code<2>,Tutorial part 4 Adding JIT-compilation to a toy interpreter<2>
9348 @anchor{cp/intro/tutorial04 putting-it-all-together}@anchor{ee}
9349 @subsubsection Putting it all together
9352 The complete example can be seen in the source tree at
9353 @code{gcc/jit/docs/examples/tut04-toyvm/toyvm.cc}
9355 along with a Makefile and a couple of sample .toy scripts:
9357 @example
9358 $ ls -al
9359 drwxrwxr-x. 2 david david   4096 Sep 19 17:46 .
9360 drwxrwxr-x. 3 david david   4096 Sep 19 15:26 ..
9361 -rw-rw-r--. 1 david david    615 Sep 19 12:43 factorial.toy
9362 -rw-rw-r--. 1 david david    834 Sep 19 13:08 fibonacci.toy
9363 -rw-rw-r--. 1 david david    238 Sep 19 14:22 Makefile
9364 -rw-rw-r--. 1 david david  16457 Sep 19 17:07 toyvm.cc
9366 $ make toyvm
9367 g++ -Wall -g -o toyvm toyvm.cc -lgccjit
9369 $ ./toyvm factorial.toy 10
9370 interpreter result: 3628800
9371 compiler result: 3628800
9373 $ ./toyvm fibonacci.toy 10
9374 interpreter result: 55
9375 compiler result: 55
9376 @end example
9378 @noindent
9380 @node Behind the curtain How does our code get optimized?<2>,,Putting it all together<2>,Tutorial part 4 Adding JIT-compilation to a toy interpreter<2>
9381 @anchor{cp/intro/tutorial04 behind-the-curtain-how-does-our-code-get-optimized}@anchor{ef}
9382 @subsubsection Behind the curtain: How does our code get optimized?
9385 Our example is done, but you may be wondering about exactly how the
9386 compiler turned what we gave it into the machine code seen above.
9388 We can examine what the compiler is doing in detail by setting:
9390 @example
9391 state.ctxt.set_bool_option (GCC_JIT_BOOL_OPTION_DUMP_EVERYTHING, 1);
9392 state.ctxt.set_bool_option (GCC_JIT_BOOL_OPTION_KEEP_INTERMEDIATES, 1);
9393 @end example
9395 @noindent
9397 This will dump detailed information about the compiler's state to a
9398 directory under @code{/tmp}, and keep it from being cleaned up.
9400 The precise names and their formats of these files is subject to change.
9401 Higher optimization levels lead to more files.
9402 Here's what I saw (edited for brevity; there were almost 200 files):
9404 @example
9405 intermediate files written to /tmp/libgccjit-KPQbGw
9406 $ ls /tmp/libgccjit-KPQbGw/
9407 fake.c.000i.cgraph
9408 fake.c.000i.type-inheritance
9409 fake.c.004t.gimple
9410 fake.c.007t.omplower
9411 fake.c.008t.lower
9412 fake.c.011t.eh
9413 fake.c.012t.cfg
9414 fake.c.014i.visibility
9415 fake.c.015i.early_local_cleanups
9416 fake.c.016t.ssa
9417 # etc
9418 @end example
9420 @noindent
9422 The gimple code is converted into Static Single Assignment form,
9423 with annotations for use when generating the debuginfo:
9425 @example
9426 $ less /tmp/libgccjit-KPQbGw/fake.c.016t.ssa
9427 @end example
9429 @noindent
9431 @example
9432 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
9434 factorial (signed int arg)
9436   signed int stack[8];
9437   signed int stack_depth;
9438   signed int x;
9439   signed int y;
9440   <unnamed type> _20;
9441   signed int _21;
9442   signed int _38;
9443   signed int _44;
9444   signed int _51;
9445   signed int _56;
9447 initial:
9448   stack_depth_3 = 0;
9449   # DEBUG stack_depth => stack_depth_3
9450   stack[stack_depth_3] = arg_5(D);
9451   stack_depth_7 = stack_depth_3 + 1;
9452   # DEBUG stack_depth => stack_depth_7
9453   # DEBUG instr0 => NULL
9454   # DEBUG /* DUP */ => NULL
9455   stack_depth_8 = stack_depth_7 + -1;
9456   # DEBUG stack_depth => stack_depth_8
9457   x_9 = stack[stack_depth_8];
9458   # DEBUG x => x_9
9459   stack[stack_depth_8] = x_9;
9460   stack_depth_11 = stack_depth_8 + 1;
9461   # DEBUG stack_depth => stack_depth_11
9462   stack[stack_depth_11] = x_9;
9463   stack_depth_13 = stack_depth_11 + 1;
9464   # DEBUG stack_depth => stack_depth_13
9465   # DEBUG instr1 => NULL
9466   # DEBUG /* PUSH_CONST */ => NULL
9467   stack[stack_depth_13] = 2;
9469   /* etc; edited for brevity */
9470 @end example
9472 @noindent
9474 We can perhaps better see the code by turning off
9475 @pxref{42,,GCC_JIT_BOOL_OPTION_DEBUGINFO} to suppress all those @code{DEBUG}
9476 statements, giving:
9478 @example
9479 $ less /tmp/libgccjit-1Hywc0/fake.c.016t.ssa
9480 @end example
9482 @noindent
9484 @example
9485 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
9487 factorial (signed int arg)
9489   signed int stack[8];
9490   signed int stack_depth;
9491   signed int x;
9492   signed int y;
9493   <unnamed type> _20;
9494   signed int _21;
9495   signed int _38;
9496   signed int _44;
9497   signed int _51;
9498   signed int _56;
9500 initial:
9501   stack_depth_3 = 0;
9502   stack[stack_depth_3] = arg_5(D);
9503   stack_depth_7 = stack_depth_3 + 1;
9504   stack_depth_8 = stack_depth_7 + -1;
9505   x_9 = stack[stack_depth_8];
9506   stack[stack_depth_8] = x_9;
9507   stack_depth_11 = stack_depth_8 + 1;
9508   stack[stack_depth_11] = x_9;
9509   stack_depth_13 = stack_depth_11 + 1;
9510   stack[stack_depth_13] = 2;
9511   stack_depth_15 = stack_depth_13 + 1;
9512   stack_depth_16 = stack_depth_15 + -1;
9513   y_17 = stack[stack_depth_16];
9514   stack_depth_18 = stack_depth_16 + -1;
9515   x_19 = stack[stack_depth_18];
9516   _20 = x_19 < y_17;
9517   _21 = (signed int) _20;
9518   stack[stack_depth_18] = _21;
9519   stack_depth_23 = stack_depth_18 + 1;
9520   stack_depth_24 = stack_depth_23 + -1;
9521   x_25 = stack[stack_depth_24];
9522   if (x_25 != 0)
9523     goto <bb 4> (instr9);
9524   else
9525     goto <bb 3> (instr4);
9527 instr4:
9528 /* DUP */:
9529   stack_depth_26 = stack_depth_24 + -1;
9530   x_27 = stack[stack_depth_26];
9531   stack[stack_depth_26] = x_27;
9532   stack_depth_29 = stack_depth_26 + 1;
9533   stack[stack_depth_29] = x_27;
9534   stack_depth_31 = stack_depth_29 + 1;
9535   stack[stack_depth_31] = 1;
9536   stack_depth_33 = stack_depth_31 + 1;
9537   stack_depth_34 = stack_depth_33 + -1;
9538   y_35 = stack[stack_depth_34];
9539   stack_depth_36 = stack_depth_34 + -1;
9540   x_37 = stack[stack_depth_36];
9541   _38 = x_37 - y_35;
9542   stack[stack_depth_36] = _38;
9543   stack_depth_40 = stack_depth_36 + 1;
9544   stack_depth_41 = stack_depth_40 + -1;
9545   x_42 = stack[stack_depth_41];
9546   _44 = factorial (x_42);
9547   stack[stack_depth_41] = _44;
9548   stack_depth_46 = stack_depth_41 + 1;
9549   stack_depth_47 = stack_depth_46 + -1;
9550   y_48 = stack[stack_depth_47];
9551   stack_depth_49 = stack_depth_47 + -1;
9552   x_50 = stack[stack_depth_49];
9553   _51 = x_50 * y_48;
9554   stack[stack_depth_49] = _51;
9555   stack_depth_53 = stack_depth_49 + 1;
9557   # stack_depth_1 = PHI <stack_depth_24(2), stack_depth_53(3)>
9558 instr9:
9559 /* RETURN */:
9560   stack_depth_54 = stack_depth_1 + -1;
9561   x_55 = stack[stack_depth_54];
9562   _56 = x_55;
9563   stack =@{v@} @{CLOBBER@};
9564   return _56;
9567 @end example
9569 @noindent
9571 Note in the above how all the @code{gccjit::block} instances we
9572 created have been consolidated into just 3 blocks in GCC's internal
9573 representation: @code{initial}, @code{instr4} and @code{instr9}.
9575 @menu
9576 * Optimizing away stack manipulation: Optimizing away stack manipulation<2>. 
9577 * Elimination of tail recursion: Elimination of tail recursion<2>. 
9579 @end menu
9581 @node Optimizing away stack manipulation<2>,Elimination of tail recursion<2>,,Behind the curtain How does our code get optimized?<2>
9582 @anchor{cp/intro/tutorial04 optimizing-away-stack-manipulation}@anchor{f0}
9583 @subsubsection Optimizing away stack manipulation
9586 Recall our simple implementation of stack operations.  Let's examine
9587 how the stack operations are optimized away.
9589 After a pass of constant-propagation, the depth of the stack at each
9590 opcode can be determined at compile-time:
9592 @example
9593 $ less /tmp/libgccjit-1Hywc0/fake.c.021t.ccp1
9594 @end example
9596 @noindent
9598 @example
9599 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
9601 factorial (signed int arg)
9603   signed int stack[8];
9604   signed int stack_depth;
9605   signed int x;
9606   signed int y;
9607   <unnamed type> _20;
9608   signed int _21;
9609   signed int _38;
9610   signed int _44;
9611   signed int _51;
9613 initial:
9614   stack[0] = arg_5(D);
9615   x_9 = stack[0];
9616   stack[0] = x_9;
9617   stack[1] = x_9;
9618   stack[2] = 2;
9619   y_17 = stack[2];
9620   x_19 = stack[1];
9621   _20 = x_19 < y_17;
9622   _21 = (signed int) _20;
9623   stack[1] = _21;
9624   x_25 = stack[1];
9625   if (x_25 != 0)
9626     goto <bb 4> (instr9);
9627   else
9628     goto <bb 3> (instr4);
9630 instr4:
9631 /* DUP */:
9632   x_27 = stack[0];
9633   stack[0] = x_27;
9634   stack[1] = x_27;
9635   stack[2] = 1;
9636   y_35 = stack[2];
9637   x_37 = stack[1];
9638   _38 = x_37 - y_35;
9639   stack[1] = _38;
9640   x_42 = stack[1];
9641   _44 = factorial (x_42);
9642   stack[1] = _44;
9643   y_48 = stack[1];
9644   x_50 = stack[0];
9645   _51 = x_50 * y_48;
9646   stack[0] = _51;
9648 instr9:
9649 /* RETURN */:
9650   x_55 = stack[0];
9651   x_56 = x_55;
9652   stack =@{v@} @{CLOBBER@};
9653   return x_56;
9656 @end example
9658 @noindent
9660 Note how, in the above, all those @code{stack_depth} values are now just
9661 constants: we're accessing specific stack locations at each opcode.
9663 The "esra" pass ("Early Scalar Replacement of Aggregates") breaks
9664 out our "stack" array into individual elements:
9666 @example
9667 $ less /tmp/libgccjit-1Hywc0/fake.c.024t.esra
9668 @end example
9670 @noindent
9672 @example
9673 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
9675 Created a replacement for stack offset: 0, size: 32: stack$0
9676 Created a replacement for stack offset: 32, size: 32: stack$1
9677 Created a replacement for stack offset: 64, size: 32: stack$2
9679 Symbols to be put in SSA form
9680 @{ D.89 D.90 D.91 @}
9681 Incremental SSA update started at block: 0
9682 Number of blocks in CFG: 5
9683 Number of blocks to update: 4 ( 80%)
9686 factorial (signed int arg)
9688   signed int stack$2;
9689   signed int stack$1;
9690   signed int stack$0;
9691   signed int stack[8];
9692   signed int stack_depth;
9693   signed int x;
9694   signed int y;
9695   <unnamed type> _20;
9696   signed int _21;
9697   signed int _38;
9698   signed int _44;
9699   signed int _51;
9701 initial:
9702   stack$0_45 = arg_5(D);
9703   x_9 = stack$0_45;
9704   stack$0_39 = x_9;
9705   stack$1_32 = x_9;
9706   stack$2_30 = 2;
9707   y_17 = stack$2_30;
9708   x_19 = stack$1_32;
9709   _20 = x_19 < y_17;
9710   _21 = (signed int) _20;
9711   stack$1_28 = _21;
9712   x_25 = stack$1_28;
9713   if (x_25 != 0)
9714     goto <bb 4> (instr9);
9715   else
9716     goto <bb 3> (instr4);
9718 instr4:
9719 /* DUP */:
9720   x_27 = stack$0_39;
9721   stack$0_22 = x_27;
9722   stack$1_14 = x_27;
9723   stack$2_12 = 1;
9724   y_35 = stack$2_12;
9725   x_37 = stack$1_14;
9726   _38 = x_37 - y_35;
9727   stack$1_10 = _38;
9728   x_42 = stack$1_10;
9729   _44 = factorial (x_42);
9730   stack$1_6 = _44;
9731   y_48 = stack$1_6;
9732   x_50 = stack$0_22;
9733   _51 = x_50 * y_48;
9734   stack$0_1 = _51;
9736   # stack$0_52 = PHI <stack$0_39(2), stack$0_1(3)>
9737 instr9:
9738 /* RETURN */:
9739   x_55 = stack$0_52;
9740   x_56 = x_55;
9741   stack =@{v@} @{CLOBBER@};
9742   return x_56;
9745 @end example
9747 @noindent
9749 Hence at this point, all those pushes and pops of the stack are now
9750 simply assignments to specific temporary variables.
9752 After some copy propagation, the stack manipulation has been completely
9753 optimized away:
9755 @example
9756 $ less /tmp/libgccjit-1Hywc0/fake.c.026t.copyprop1
9757 @end example
9759 @noindent
9761 @example
9762 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
9764 factorial (signed int arg)
9766   signed int stack$2;
9767   signed int stack$1;
9768   signed int stack$0;
9769   signed int stack[8];
9770   signed int stack_depth;
9771   signed int x;
9772   signed int y;
9773   <unnamed type> _20;
9774   signed int _21;
9775   signed int _38;
9776   signed int _44;
9777   signed int _51;
9779 initial:
9780   stack$0_39 = arg_5(D);
9781   _20 = arg_5(D) <= 1;
9782   _21 = (signed int) _20;
9783   if (_21 != 0)
9784     goto <bb 4> (instr9);
9785   else
9786     goto <bb 3> (instr4);
9788 instr4:
9789 /* DUP */:
9790   _38 = arg_5(D) + -1;
9791   _44 = factorial (_38);
9792   _51 = arg_5(D) * _44;
9793   stack$0_1 = _51;
9795   # stack$0_52 = PHI <arg_5(D)(2), _51(3)>
9796 instr9:
9797 /* RETURN */:
9798   stack =@{v@} @{CLOBBER@};
9799   return stack$0_52;
9802 @end example
9804 @noindent
9806 Later on, another pass finally eliminated @code{stack_depth} local and the
9807 unused parts of the @cite{stack`} array altogether:
9809 @example
9810 $ less /tmp/libgccjit-1Hywc0/fake.c.036t.release_ssa
9811 @end example
9813 @noindent
9815 @example
9816 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
9818 Released 44 names, 314.29%, removed 44 holes
9819 factorial (signed int arg)
9821   signed int stack$0;
9822   signed int mult_acc_1;
9823   <unnamed type> _5;
9824   signed int _6;
9825   signed int _7;
9826   signed int mul_tmp_10;
9827   signed int mult_acc_11;
9828   signed int mult_acc_13;
9830   # arg_9 = PHI <arg_8(D)(0)>
9831   # mult_acc_13 = PHI <1(0)>
9832 initial:
9834   <bb 5>:
9835   # arg_4 = PHI <arg_9(2), _7(3)>
9836   # mult_acc_1 = PHI <mult_acc_13(2), mult_acc_11(3)>
9837   _5 = arg_4 <= 1;
9838   _6 = (signed int) _5;
9839   if (_6 != 0)
9840     goto <bb 4> (instr9);
9841   else
9842     goto <bb 3> (instr4);
9844 instr4:
9845 /* DUP */:
9846   _7 = arg_4 + -1;
9847   mult_acc_11 = mult_acc_1 * arg_4;
9848   goto <bb 5>;
9850   # stack$0_12 = PHI <arg_4(5)>
9851 instr9:
9852 /* RETURN */:
9853   mul_tmp_10 = mult_acc_1 * stack$0_12;
9854   return mul_tmp_10;
9857 @end example
9859 @noindent
9861 @node Elimination of tail recursion<2>,,Optimizing away stack manipulation<2>,Behind the curtain How does our code get optimized?<2>
9862 @anchor{cp/intro/tutorial04 elimination-of-tail-recursion}@anchor{f1}
9863 @subsubsection Elimination of tail recursion
9866 Another significant optimization is the detection that the call to
9867 @code{factorial} is tail recursion, which can be eliminated in favor of
9868 an iteration:
9870 @example
9871 $ less /tmp/libgccjit-1Hywc0/fake.c.030t.tailr1
9872 @end example
9874 @noindent
9876 @example
9877 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
9880 Symbols to be put in SSA form
9881 @{ D.88 @}
9882 Incremental SSA update started at block: 0
9883 Number of blocks in CFG: 5
9884 Number of blocks to update: 4 ( 80%)
9887 factorial (signed int arg)
9889   signed int stack$2;
9890   signed int stack$1;
9891   signed int stack$0;
9892   signed int stack[8];
9893   signed int stack_depth;
9894   signed int x;
9895   signed int y;
9896   signed int mult_acc_1;
9897   <unnamed type> _20;
9898   signed int _21;
9899   signed int _38;
9900   signed int mul_tmp_44;
9901   signed int mult_acc_51;
9903   # arg_5 = PHI <arg_39(D)(0), _38(3)>
9904   # mult_acc_1 = PHI <1(0), mult_acc_51(3)>
9905 initial:
9906   _20 = arg_5 <= 1;
9907   _21 = (signed int) _20;
9908   if (_21 != 0)
9909     goto <bb 4> (instr9);
9910   else
9911     goto <bb 3> (instr4);
9913 instr4:
9914 /* DUP */:
9915   _38 = arg_5 + -1;
9916   mult_acc_51 = mult_acc_1 * arg_5;
9917   goto <bb 2> (initial);
9919   # stack$0_52 = PHI <arg_5(2)>
9920 instr9:
9921 /* RETURN */:
9922   stack =@{v@} @{CLOBBER@};
9923   mul_tmp_44 = mult_acc_1 * stack$0_52;
9924   return mul_tmp_44;
9927 @end example
9929 @noindent
9931 @c Copyright (C) 2014 Free Software Foundation, Inc.
9932 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
9933 @c 
9934 @c This is free software: you can redistribute it and/or modify it
9935 @c under the terms of the GNU General Public License as published by
9936 @c the Free Software Foundation, either version 3 of the License, or
9937 @c (at your option) any later version.
9938 @c 
9939 @c This program is distributed in the hope that it will be useful, but
9940 @c WITHOUT ANY WARRANTY; without even the implied warranty of
9941 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
9942 @c General Public License for more details.
9943 @c 
9944 @c You should have received a copy of the GNU General Public License
9945 @c along with this program.  If not, see
9946 @c <http://www.gnu.org/licenses/>.
9948 @node Topic Reference<2>,,Tutorial<2>,C++ bindings for libgccjit
9949 @anchor{cp/topics/index doc}@anchor{f2}@anchor{cp/topics/index topic-reference}@anchor{f3}
9950 @section Topic Reference
9953 @c Copyright (C) 2014 Free Software Foundation, Inc.
9954 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
9955 @c 
9956 @c This is free software: you can redistribute it and/or modify it
9957 @c under the terms of the GNU General Public License as published by
9958 @c the Free Software Foundation, either version 3 of the License, or
9959 @c (at your option) any later version.
9960 @c 
9961 @c This program is distributed in the hope that it will be useful, but
9962 @c WITHOUT ANY WARRANTY; without even the implied warranty of
9963 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
9964 @c General Public License for more details.
9965 @c 
9966 @c You should have received a copy of the GNU General Public License
9967 @c along with this program.  If not, see
9968 @c <http://www.gnu.org/licenses/>.
9970 @menu
9971 * Compilation contexts: Compilation contexts<2>. 
9972 * Objects: Objects<2>. 
9973 * Types: Types<2>. 
9974 * Expressions: Expressions<2>. 
9975 * Creating and using functions: Creating and using functions<2>. 
9976 * Source Locations: Source Locations<2>. 
9977 * Compilation results: Compilation results<2>. 
9979 Compilation contexts
9981 * Lifetime-management: Lifetime-management<2>. 
9982 * Thread-safety: Thread-safety<2>. 
9983 * Error-handling: Error-handling<3>. 
9984 * Debugging: Debugging<2>. 
9985 * Options: Options<4>. 
9987 Options
9989 * Boolean options: Boolean options<2>. 
9990 * Integer options: Integer options<2>. 
9992 Types
9994 * Standard types: Standard types<2>. 
9995 * Pointers@comma{} const@comma{} and volatile: Pointers const and volatile<2>. 
9996 * Structures and unions: Structures and unions<2>. 
9998 Expressions
10000 * Rvalues: Rvalues<2>. 
10001 * Lvalues: Lvalues<2>. 
10002 * Working with pointers@comma{} structs and unions: Working with pointers structs and unions<2>. 
10004 Rvalues
10006 * Simple expressions: Simple expressions<2>. 
10007 * Unary Operations: Unary Operations<2>. 
10008 * Binary Operations: Binary Operations<2>. 
10009 * Comparisons: Comparisons<2>. 
10010 * Function calls: Function calls<2>. 
10011 * Type-coercion: Type-coercion<2>. 
10013 Lvalues
10015 * Global variables: Global variables<2>. 
10017 Creating and using functions
10019 * Params: Params<2>. 
10020 * Functions: Functions<2>. 
10021 * Blocks: Blocks<2>. 
10022 * Statements: Statements<2>. 
10024 Source Locations
10026 * Faking it: Faking it<2>. 
10028 @end menu
10031 @node Compilation contexts<2>,Objects<2>,,Topic Reference<2>
10032 @anchor{cp/topics/contexts compilation-contexts}@anchor{f4}@anchor{cp/topics/contexts doc}@anchor{f5}
10033 @subsection Compilation contexts
10036 @geindex gccjit;;context (C++ class)
10037 @anchor{cp/topics/contexts gccjit context}@anchor{f6}
10038 @deffn {C++ Class} gccjit::context
10039 @end deffn
10041 The top-level of the C++ API is the @pxref{f6,,gccjit;;context} type.
10043 A @pxref{f6,,gccjit;;context} instance encapsulates the state of a
10044 compilation.
10046 You can set up options on it, and add types, functions and code.
10047 Invoking @pxref{cf,,gccjit;;context;;compile()} on it gives you a
10048 @pxref{16,,gcc_jit_result *}.
10050 It is a thin wrapper around the C API's @pxref{8,,gcc_jit_context *}.
10052 @menu
10053 * Lifetime-management: Lifetime-management<2>. 
10054 * Thread-safety: Thread-safety<2>. 
10055 * Error-handling: Error-handling<3>. 
10056 * Debugging: Debugging<2>. 
10057 * Options: Options<4>. 
10059 @end menu
10061 @node Lifetime-management<2>,Thread-safety<2>,,Compilation contexts<2>
10062 @anchor{cp/topics/contexts lifetime-management}@anchor{f7}
10063 @subsubsection Lifetime-management
10066 Contexts are the unit of lifetime-management within the API: objects
10067 have their lifetime bounded by the context they are created within, and
10068 cleanup of such objects is done for you when the context is released.
10070 @geindex gccjit;;context;;acquire (C++ function)
10071 @anchor{cp/topics/contexts gccjit context acquire}@anchor{c9}
10072 @deffn {C++ Function} gccjit::context gccjit::context::acquire ()
10074 This function acquires a new @pxref{f6,,gccjit;;context} instance,
10075 which is independent of any others that may be present within this
10076 process.
10077 @end deffn
10079 @geindex gccjit;;context;;release (C++ function)
10080 @anchor{cp/topics/contexts gccjit context release}@anchor{cb}
10081 @deffn {C++ Function} void gccjit::context::release ()
10083 This function releases all resources associated with the given context.
10084 Both the context itself and all of its @code{gccjit::object *}
10085 instances are cleaned up.  It should be called exactly once on a given
10086 context.
10088 It is invalid to use the context or any of its "contextual" objects
10089 after calling this.
10091 @example
10092 ctxt.release ();
10093 @end example
10095 @noindent
10096 @end deffn
10098 @geindex gccjit;;context;;new_child_context (C++ function)
10099 @anchor{cp/topics/contexts gccjit context new_child_context}@anchor{f8}
10100 @deffn {C++ Function} gccjit::context gccjit::context::new_child_context ()
10102 Given an existing JIT context, create a child context.
10104 The child inherits a copy of all option-settings from the parent.
10106 The child can reference objects created within the parent, but not
10107 vice-versa.
10109 The lifetime of the child context must be bounded by that of the
10110 parent: you should release a child context before releasing the parent
10111 context.
10113 If you use a function from a parent context within a child context,
10114 you have to compile the parent context before you can compile the
10115 child context, and the gccjit::result of the parent context must
10116 outlive the gccjit::result of the child context.
10118 This allows caching of shared initializations.  For example, you could
10119 create types and declarations of global functions in a parent context
10120 once within a process, and then create child contexts whenever a
10121 function or loop becomes hot. Each such child context can be used for
10122 JIT-compiling just one function or loop, but can reference types
10123 and helper functions created within the parent context.
10125 Contexts can be arbitrarily nested, provided the above rules are
10126 followed, but it's probably not worth going above 2 or 3 levels, and
10127 there will likely be a performance hit for such nesting.
10128 @end deffn
10130 @node Thread-safety<2>,Error-handling<3>,Lifetime-management<2>,Compilation contexts<2>
10131 @anchor{cp/topics/contexts thread-safety}@anchor{f9}
10132 @subsubsection Thread-safety
10135 Instances of @pxref{f6,,gccjit;;context} created via
10136 @pxref{c9,,gccjit;;context;;acquire()} are independent from each other:
10137 only one thread may use a given context at once, but multiple threads
10138 could each have their own contexts without needing locks.
10140 Contexts created via @pxref{f8,,gccjit;;context;;new_child_context()} are
10141 related to their parent context.  They can be partitioned by their
10142 ultimate ancestor into independent "family trees".   Only one thread
10143 within a process may use a given "family tree" of such contexts at once,
10144 and if you're using multiple threads you should provide your own locking
10145 around entire such context partitions.
10147 @node Error-handling<3>,Debugging<2>,Thread-safety<2>,Compilation contexts<2>
10148 @anchor{cp/topics/contexts error-handling}@anchor{fa}
10149 @subsubsection Error-handling
10152 @c FIXME: How does error-handling work for C++ API?
10154 You can only compile and get code from a context if no errors occur.
10156 In general, if an error occurs when using an API entrypoint, it returns
10157 NULL.  You don't have to check everywhere for NULL results, since the
10158 API gracefully handles a NULL being passed in for any argument.
10160 Errors are printed on stderr and can be queried using
10161 @pxref{fb,,gccjit;;context;;get_first_error()}.
10163 @geindex gccjit;;context;;get_first_error (C++ function)
10164 @anchor{cp/topics/contexts gccjit context get_first_error__gccjit contextP}@anchor{fb}
10165 @deffn {C++ Function} const char* gccjit::context::get_first_error (gccjit::context* ctxt)
10167 Returns the first error message that occurred on the context.
10169 The returned string is valid for the rest of the lifetime of the
10170 context.
10172 If no errors occurred, this will be NULL.
10173 @end deffn
10175 @node Debugging<2>,Options<4>,Error-handling<3>,Compilation contexts<2>
10176 @anchor{cp/topics/contexts debugging}@anchor{fc}
10177 @subsubsection Debugging
10180 @geindex gccjit;;context;;dump_to_file (C++ function)
10181 @anchor{cp/topics/contexts gccjit context dump_to_file__ssCR i}@anchor{fd}
10182 @deffn {C++ Function} void gccjit::context::dump_to_file (const std::string& path, int update_locations)
10184 To help with debugging: dump a C-like representation to the given path,
10185 describing what's been set up on the context.
10187 If "update_locations" is true, then also set up @pxref{fe,,gccjit;;location}
10188 information throughout the context, pointing at the dump file as if it
10189 were a source file.  This may be of use in conjunction with
10190 @code{GCCJIT::BOOL_OPTION_DEBUGINFO} to allow stepping through the
10191 code in a debugger.
10192 @end deffn
10194 @node Options<4>,,Debugging<2>,Compilation contexts<2>
10195 @anchor{cp/topics/contexts options}@anchor{ff}
10196 @subsubsection Options
10199 @c FIXME: gccjit::context::set_str_option doesn't seem to exist yet in the
10200 @c C++ API
10202 @menu
10203 * Boolean options: Boolean options<2>. 
10204 * Integer options: Integer options<2>. 
10206 @end menu
10208 @node Boolean options<2>,Integer options<2>,,Options<4>
10209 @anchor{cp/topics/contexts boolean-options}@anchor{100}
10210 @subsubsection Boolean options
10213 @geindex gccjit;;context;;set_bool_option (C++ function)
10214 @anchor{cp/topics/contexts gccjit context set_bool_option__enum i}@anchor{d1}
10215 @deffn {C++ Function} void gccjit::context::set_bool_option (enum gcc_jit_bool_option, int value)
10217 Set a boolean option of the context.
10219 This is a thin wrapper around the C API
10220 @pxref{1b,,gcc_jit_context_set_bool_option()}; the options have the same
10221 meaning.
10222 @end deffn
10224 @node Integer options<2>,,Boolean options<2>,Options<4>
10225 @anchor{cp/topics/contexts integer-options}@anchor{101}
10226 @subsubsection Integer options
10229 @geindex gccjit;;context;;set_int_option (C++ function)
10230 @anchor{cp/topics/contexts gccjit context set_int_option__enum i}@anchor{d2}
10231 @deffn {C++ Function} void gccjit::context::set_int_option (enum gcc_jit_int_option, int value)
10233 Set an integer option of the context.
10235 This is a thin wrapper around the C API
10236 @pxref{1e,,gcc_jit_context_set_int_option()}; the options have the same
10237 meaning.
10238 @end deffn
10240 @c Copyright (C) 2014 Free Software Foundation, Inc.
10241 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
10242 @c 
10243 @c This is free software: you can redistribute it and/or modify it
10244 @c under the terms of the GNU General Public License as published by
10245 @c the Free Software Foundation, either version 3 of the License, or
10246 @c (at your option) any later version.
10247 @c 
10248 @c This program is distributed in the hope that it will be useful, but
10249 @c WITHOUT ANY WARRANTY; without even the implied warranty of
10250 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
10251 @c General Public License for more details.
10252 @c 
10253 @c You should have received a copy of the GNU General Public License
10254 @c along with this program.  If not, see
10255 @c <http://www.gnu.org/licenses/>.
10257 @node Objects<2>,Types<2>,Compilation contexts<2>,Topic Reference<2>
10258 @anchor{cp/topics/objects objects}@anchor{102}@anchor{cp/topics/objects doc}@anchor{103}
10259 @subsection Objects
10262 @geindex gccjit;;object (C++ class)
10263 @anchor{cp/topics/objects gccjit object}@anchor{104}
10264 @deffn {C++ Class} gccjit::object
10265 @end deffn
10267 Almost every entity in the API (with the exception of
10268 @pxref{f6,,gccjit;;context} and @pxref{16,,gcc_jit_result *}) is a
10269 "contextual" object, a @pxref{104,,gccjit;;object}.
10271 A JIT object:
10273 @quotation
10276 @itemize *
10278 @item 
10279 is associated with a @pxref{f6,,gccjit;;context}.
10281 @item 
10282 is automatically cleaned up for you when its context is released so
10283 you don't need to manually track and cleanup all objects, just the
10284 contexts.
10285 @end itemize
10286 @end quotation
10288 The C++ class hierarchy within the @code{gccjit} namespace looks like this:
10290 @example
10291 +- object
10292     +- location
10293     +- type
10294        +- struct
10295     +- field
10296     +- function
10297     +- block
10298     +- rvalue
10299         +- lvalue
10300            +- param
10301 @end example
10303 @noindent
10305 The @pxref{104,,gccjit;;object} base class has the following operations:
10307 @geindex gccjit;;object;;get_context (C++ function)
10308 @anchor{cp/topics/objects gccjit object get_contextC}@anchor{105}
10309 @deffn {C++ Function} gccjit::context gccjit::object::get_context () const
10311 Which context is the obj within?
10312 @end deffn
10314 @geindex gccjit;;object;;get_debug_string (C++ function)
10315 @anchor{cp/topics/objects gccjit object get_debug_stringC}@anchor{cc}
10316 @deffn {C++ Function} std::string gccjit::object::get_debug_string () const
10318 Generate a human-readable description for the given object.
10320 For example,
10322 @example
10323 printf ("obj: %s\n", obj.get_debug_string ().c_str ());
10324 @end example
10326 @noindent
10328 might give this text on stdout:
10330 @example
10331 obj: 4.0 * (float)i
10332 @end example
10334 @noindent
10335 @end deffn
10337 @c Copyright (C) 2014 Free Software Foundation, Inc.
10338 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
10339 @c 
10340 @c This is free software: you can redistribute it and/or modify it
10341 @c under the terms of the GNU General Public License as published by
10342 @c the Free Software Foundation, either version 3 of the License, or
10343 @c (at your option) any later version.
10344 @c 
10345 @c This program is distributed in the hope that it will be useful, but
10346 @c WITHOUT ANY WARRANTY; without even the implied warranty of
10347 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
10348 @c General Public License for more details.
10349 @c 
10350 @c You should have received a copy of the GNU General Public License
10351 @c along with this program.  If not, see
10352 @c <http://www.gnu.org/licenses/>.
10354 @node Types<2>,Expressions<2>,Objects<2>,Topic Reference<2>
10355 @anchor{cp/topics/types doc}@anchor{106}@anchor{cp/topics/types types}@anchor{107}
10356 @subsection Types
10359 @geindex gccjit;;type (C++ class)
10360 @anchor{cp/topics/types gccjit type}@anchor{108}
10361 @deffn {C++ Class} gccjit::type
10363 gccjit::type represents a type within the library.  It is a subclass
10364 of @pxref{104,,gccjit;;object}.
10365 @end deffn
10367 Types can be created in several ways:
10370 @itemize *
10372 @item 
10373 fundamental types can be accessed using
10374 @pxref{ca,,gccjit;;context;;get_type()}:
10376 @example
10377 gccjit::type int_type = ctxt.get_type (GCC_JIT_TYPE_INT);
10378 @end example
10380 @noindent
10382 or using the @code{gccjit::context::get_int_type} template:
10384 @example
10385 gccjit::type t = ctxt.get_int_type <unsigned short> ();
10386 @end example
10388 @noindent
10390 See @pxref{b,,gcc_jit_context_get_type()} for the available types.
10392 @item 
10393 derived types can be accessed by using functions such as
10394 @pxref{109,,gccjit;;type;;get_pointer()} and @pxref{10a,,gccjit;;type;;get_const()}:
10396 @example
10397 gccjit::type const_int_star = int_type.get_const ().get_pointer ();
10398 gccjit::type int_const_star = int_type.get_pointer ().get_const ();
10399 @end example
10401 @noindent
10403 @item 
10404 by creating structures (see below).
10405 @end itemize
10407 @menu
10408 * Standard types: Standard types<2>. 
10409 * Pointers@comma{} const@comma{} and volatile: Pointers const and volatile<2>. 
10410 * Structures and unions: Structures and unions<2>. 
10412 @end menu
10414 @node Standard types<2>,Pointers const and volatile<2>,,Types<2>
10415 @anchor{cp/topics/types standard-types}@anchor{10b}
10416 @subsubsection Standard types
10419 @geindex gccjit;;context;;get_type (C++ function)
10420 @anchor{cp/topics/types gccjit context get_type__enum}@anchor{ca}
10421 @deffn {C++ Function} gccjit::type gccjit::context::get_type (enum gcc_jit_types)
10423 Access a specific type.  This is a thin wrapper around
10424 @pxref{b,,gcc_jit_context_get_type()}; the parameter has the same meaning.
10425 @end deffn
10427 @geindex gccjit;;context;;get_int_type (C++ function)
10428 @anchor{cp/topics/types gccjit context get_int_type__s i}@anchor{10c}
10429 @deffn {C++ Function} gccjit::type gccjit::context::get_int_type (size_t num_bytes, int is_signed)
10431 Access the integer type of the given size.
10432 @end deffn
10434 @geindex gccjit;;context;;get_int_type<T> (C++ function)
10435 @anchor{cp/topics/types gccjit context get_int_type T}@anchor{10d}
10436 @deffn {C++ Function} gccjit::type gccjit::context::get_int_type<T> ()
10438 Access the given integer type.  For example, you could map the
10439 @code{unsigned short} type into a gccjit::type via:
10441 @example
10442 gccjit::type t = ctxt.get_int_type <unsigned short> ();
10443 @end example
10445 @noindent
10446 @end deffn
10448 @node Pointers const and volatile<2>,Structures and unions<2>,Standard types<2>,Types<2>
10449 @anchor{cp/topics/types pointers-const-and-volatile}@anchor{10e}
10450 @subsubsection Pointers, @cite{const}, and @cite{volatile}
10453 @geindex gccjit;;type;;get_pointer (C++ function)
10454 @anchor{cp/topics/types gccjit type get_pointer}@anchor{109}
10455 @deffn {C++ Function} gccjit::type gccjit::type::get_pointer ()
10457 Given type "T", get type "T*".
10458 @end deffn
10460 @c FIXME: get_const doesn't seem to exist
10462 @geindex gccjit;;type;;get_const (C++ function)
10463 @anchor{cp/topics/types gccjit type get_const}@anchor{10a}
10464 @deffn {C++ Function} gccjit::type gccjit::type::get_const ()
10466 Given type "T", get type "const T".
10467 @end deffn
10469 @geindex gccjit;;type;;get_volatile (C++ function)
10470 @anchor{cp/topics/types gccjit type get_volatile}@anchor{10f}
10471 @deffn {C++ Function} gccjit::type gccjit::type::get_volatile ()
10473 Given type "T", get type "volatile T".
10474 @end deffn
10476 @geindex gccjit;;context;;new_array_type (C++ function)
10477 @anchor{cp/topics/types gccjit context new_array_type__gccjit type i gccjit location}@anchor{110}
10478 @deffn {C++ Function} gccjit::type gccjit::context::new_array_type (gccjit::type element_type, int num_elements, gccjit::location loc)
10480 Given type "T", get type "T[N]" (for a constant N).
10481 Param "loc" is optional.
10482 @end deffn
10484 @node Structures and unions<2>,,Pointers const and volatile<2>,Types<2>
10485 @anchor{cp/topics/types structures-and-unions}@anchor{111}
10486 @subsubsection Structures and unions
10489 @geindex gccjit;;struct_ (C++ class)
10490 @anchor{cp/topics/types gccjit struct_}@anchor{112}
10491 @deffn {C++ Class} gccjit::struct_
10492 @end deffn
10494 A compound type analagous to a C @cite{struct}.
10496 @pxref{112,,gccjit;;struct_} is a subclass of @pxref{108,,gccjit;;type} (and thus
10497 of @pxref{104,,gccjit;;object} in turn).
10499 @geindex gccjit;;field (C++ class)
10500 @anchor{cp/topics/types gccjit field}@anchor{113}
10501 @deffn {C++ Class} gccjit::field
10502 @end deffn
10504 A field within a @pxref{112,,gccjit;;struct_}.
10506 @pxref{113,,gccjit;;field} is a subclass of @pxref{104,,gccjit;;object}.
10508 You can model C @cite{struct} types by creating @pxref{112,,gccjit;;struct_} and
10509 @pxref{113,,gccjit;;field} instances, in either order:
10512 @itemize *
10514 @item 
10515 by creating the fields, then the structure.  For example, to model:
10517 @example
10518 struct coord @{double x; double y; @};
10519 @end example
10521 @noindent
10523 you could call:
10525 @example
10526 gccjit::field field_x = ctxt.new_field (double_type, "x");
10527 gccjit::field field_y = ctxt.new_field (double_type, "y");
10528 std::vector fields;
10529 fields.push_back (field_x);
10530 fields.push_back (field_y);
10531 gccjit::struct_ coord = ctxt.new_struct_type ("coord", fields);
10532 @end example
10534 @noindent
10536 @item 
10537 by creating the structure, then populating it with fields, typically
10538 to allow modelling self-referential structs such as:
10540 @example
10541 struct node @{ int m_hash; struct node *m_next; @};
10542 @end example
10544 @noindent
10546 like this:
10548 @example
10549 gccjit::struct_ node = ctxt.new_opaque_struct_type ("node");
10550 gccjit::type node_ptr = node.get_pointer ();
10551 gccjit::field field_hash = ctxt.new_field (int_type, "m_hash");
10552 gccjit::field field_next = ctxt.new_field (node_ptr, "m_next");
10553 std::vector fields;
10554 fields.push_back (field_hash);
10555 fields.push_back (field_next);
10556 node.set_fields (fields);
10557 @end example
10559 @noindent
10560 @end itemize
10562 @c FIXME: the above API doesn't seem to exist yet
10564 @geindex gccjit;;context;;new_field (C++ function)
10565 @anchor{cp/topics/types gccjit context new_field__gccjit type cCP gccjit location}@anchor{114}
10566 @deffn {C++ Function} gccjit::field gccjit::context::new_field (gccjit::type type, const char* name, gccjit::location loc)
10568 Construct a new field, with the given type and name.
10569 @end deffn
10571 @geindex gccjit;;context;;new_struct_type (C++ function)
10572 @anchor{cp/topics/types gccjit context new_struct_type__ssCR std vector field R gccjit location}@anchor{115}
10573 @deffn {C++ Function} gccjit::struct_ gccjit::context::new_struct_type (const std::string& name, std::vector<field>& fields, gccjit::location loc)
10575 @quotation
10577 Construct a new struct type, with the given name and fields.
10578 @end quotation
10579 @end deffn
10581 @geindex gccjit;;context;;new_opaque_struct (C++ function)
10582 @anchor{cp/topics/types gccjit context new_opaque_struct__ssCR gccjit location}@anchor{116}
10583 @deffn {C++ Function} gccjit::struct_ gccjit::context::new_opaque_struct (const std::string& name, gccjit::location loc)
10585 Construct a new struct type, with the given name, but without
10586 specifying the fields.   The fields can be omitted (in which case the
10587 size of the struct is not known), or later specified using
10588 @pxref{75,,gcc_jit_struct_set_fields()}.
10589 @end deffn
10591 @c Copyright (C) 2014 Free Software Foundation, Inc.
10592 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
10593 @c 
10594 @c This is free software: you can redistribute it and/or modify it
10595 @c under the terms of the GNU General Public License as published by
10596 @c the Free Software Foundation, either version 3 of the License, or
10597 @c (at your option) any later version.
10598 @c 
10599 @c This program is distributed in the hope that it will be useful, but
10600 @c WITHOUT ANY WARRANTY; without even the implied warranty of
10601 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
10602 @c General Public License for more details.
10603 @c 
10604 @c You should have received a copy of the GNU General Public License
10605 @c along with this program.  If not, see
10606 @c <http://www.gnu.org/licenses/>.
10608 @node Expressions<2>,Creating and using functions<2>,Types<2>,Topic Reference<2>
10609 @anchor{cp/topics/expressions expressions}@anchor{117}@anchor{cp/topics/expressions doc}@anchor{118}
10610 @subsection Expressions
10613 @menu
10614 * Rvalues: Rvalues<2>. 
10615 * Lvalues: Lvalues<2>. 
10616 * Working with pointers@comma{} structs and unions: Working with pointers structs and unions<2>. 
10618 Rvalues
10620 * Simple expressions: Simple expressions<2>. 
10621 * Unary Operations: Unary Operations<2>. 
10622 * Binary Operations: Binary Operations<2>. 
10623 * Comparisons: Comparisons<2>. 
10624 * Function calls: Function calls<2>. 
10625 * Type-coercion: Type-coercion<2>. 
10627 Lvalues
10629 * Global variables: Global variables<2>. 
10631 @end menu
10634 @node Rvalues<2>,Lvalues<2>,,Expressions<2>
10635 @anchor{cp/topics/expressions rvalues}@anchor{119}
10636 @subsubsection Rvalues
10639 @geindex gccjit;;rvalue (C++ class)
10640 @anchor{cp/topics/expressions gccjit rvalue}@anchor{11a}
10641 @deffn {C++ Class} gccjit::rvalue
10642 @end deffn
10644 A @pxref{11a,,gccjit;;rvalue} is an expression that can be computed.  It is a
10645 subclass of @pxref{104,,gccjit;;object}, and is a thin wrapper around
10646 @pxref{13,,gcc_jit_rvalue *} from the C API.
10648 It can be simple, e.g.:
10650 @quotation
10653 @itemize *
10655 @item 
10656 an integer value e.g. @cite{0} or @cite{42}
10658 @item 
10659 a string literal e.g. @cite{"Hello world"}
10661 @item 
10662 a variable e.g. @cite{i}.  These are also lvalues (see below).
10663 @end itemize
10664 @end quotation
10666 or compound e.g.:
10668 @quotation
10671 @itemize *
10673 @item 
10674 a unary expression e.g. @cite{!cond}
10676 @item 
10677 a binary expression e.g. @cite{(a + b)}
10679 @item 
10680 a function call e.g. @cite{get_distance (&player_ship@comma{} &target)}
10682 @item 
10683 etc.
10684 @end itemize
10685 @end quotation
10687 Every rvalue has an associated type, and the API will check to ensure
10688 that types match up correctly (otherwise the context will emit an error).
10690 @geindex gccjit;;rvalue;;get_type (C++ function)
10691 @anchor{cp/topics/expressions gccjit rvalue get_type}@anchor{11b}
10692 @deffn {C++ Function} gccjit::type gccjit::rvalue::get_type ()
10694 Get the type of this rvalue.
10695 @end deffn
10697 @menu
10698 * Simple expressions: Simple expressions<2>. 
10699 * Unary Operations: Unary Operations<2>. 
10700 * Binary Operations: Binary Operations<2>. 
10701 * Comparisons: Comparisons<2>. 
10702 * Function calls: Function calls<2>. 
10703 * Type-coercion: Type-coercion<2>. 
10705 @end menu
10707 @node Simple expressions<2>,Unary Operations<2>,,Rvalues<2>
10708 @anchor{cp/topics/expressions simple-expressions}@anchor{11c}
10709 @subsubsection Simple expressions
10712 @geindex gccjit;;context;;new_rvalue (C++ function)
10713 @anchor{cp/topics/expressions gccjit context new_rvalue__gccjit type iC}@anchor{de}
10714 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_rvalue (gccjit::type numeric_type, int value) const
10716 Given a numeric type (integer or floating point), build an rvalue for
10717 the given constant @code{int} value.
10718 @end deffn
10720 @geindex gccjit;;context;;zero (C++ function)
10721 @anchor{cp/topics/expressions gccjit context zero__gccjit typeC}@anchor{da}
10722 @deffn {C++ Function} gccjit::rvalue gccjit::context::zero (gccjit::type numeric_type) const
10724 Given a numeric type (integer or floating point), get the rvalue for
10725 zero.  Essentially this is just a shortcut for:
10727 @example
10728 ctxt.new_rvalue (numeric_type, 0)
10729 @end example
10731 @noindent
10732 @end deffn
10734 @geindex gccjit;;context;;one (C++ function)
10735 @anchor{cp/topics/expressions gccjit context one__gccjit typeC}@anchor{11d}
10736 @deffn {C++ Function} gccjit::rvalue gccjit::context::one (gccjit::type numeric_type) const
10738 Given a numeric type (integer or floating point), get the rvalue for
10739 zero.  Essentially this is just a shortcut for:
10741 @example
10742 ctxt.new_rvalue (numeric_type, 1)
10743 @end example
10745 @noindent
10746 @end deffn
10748 @geindex gccjit;;context;;new_rvalue (C++ function)
10749 @anchor{cp/topics/expressions gccjit context new_rvalue__gccjit type doubleC}@anchor{11e}
10750 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_rvalue (gccjit::type numeric_type, double value) const
10752 Given a numeric type (integer or floating point), build an rvalue for
10753 the given constant value.
10754 @end deffn
10756 @geindex gccjit;;context;;new_rvalue (C++ function)
10757 @anchor{cp/topics/expressions gccjit context new_rvalue__gccjit type voidPC}@anchor{11f}
10758 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_rvalue (gccjit::type pointer_type, void* value) const
10760 Given a pointer type, build an rvalue for the given address.
10761 @end deffn
10763 @geindex gccjit;;context;;new_rvalue (C++ function)
10764 @anchor{cp/topics/expressions gccjit context new_rvalue__ssCRC}@anchor{120}
10765 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_rvalue (const std::string& value) const
10767 Generate an rvalue of type @code{GCC_JIT_TYPE_CONST_CHAR_PTR} for
10768 the given string.  This is akin to a string literal.
10769 @end deffn
10771 @node Unary Operations<2>,Binary Operations<2>,Simple expressions<2>,Rvalues<2>
10772 @anchor{cp/topics/expressions unary-operations}@anchor{121}
10773 @subsubsection Unary Operations
10776 @geindex gccjit;;context;;new_unary_op (C++ function)
10777 @anchor{cp/topics/expressions gccjit context new_unary_op__enum gccjit type gccjit rvalue gccjit location}@anchor{122}
10778 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_unary_op (enum gcc_jit_unary_op, gccjit::type result_type, gccjit::rvalue rvalue, gccjit::location loc)
10780 Build a unary operation out of an input rvalue.
10782 Parameter @code{loc} is optional.
10784 This is a thin wrapper around the C API's
10785 @pxref{80,,gcc_jit_context_new_unary_op()} and the available unary
10786 operations are documented there.
10787 @end deffn
10789 There are shorter ways to spell the various specific kinds of unary
10790 operation:
10792 @geindex gccjit;;context;;new_minus (C++ function)
10793 @anchor{cp/topics/expressions gccjit context new_minus__gccjit type gccjit rvalue gccjit location}@anchor{123}
10794 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_minus (gccjit::type result_type, gccjit::rvalue a, gccjit::location loc)
10796 Negate an arithmetic value; for example:
10798 @example
10799 gccjit::rvalue negpi = ctxt.new_minus (t_double, pi);
10800 @end example
10802 @noindent
10804 builds the equivalent of this C expression:
10806 @example
10808 @end example
10810 @noindent
10811 @end deffn
10813 @geindex new_bitwise_negate (C++ function)
10814 @anchor{cp/topics/expressions new_bitwise_negate__gccjit type gccjit rvalue gccjit location}@anchor{124}
10815 @deffn {C++ Function} gccjit::rvalue new_bitwise_negate (gccjit::type result_type, gccjit::rvalue a, gccjit::location loc)
10817 Bitwise negation of an integer value (one's complement); for example:
10819 @example
10820 gccjit::rvalue mask = ctxt.new_bitwise_negate (t_int, a);
10821 @end example
10823 @noindent
10825 builds the equivalent of this C expression:
10827 @example
10829 @end example
10831 @noindent
10832 @end deffn
10834 @geindex new_logical_negate (C++ function)
10835 @anchor{cp/topics/expressions new_logical_negate__gccjit type gccjit rvalue gccjit location}@anchor{125}
10836 @deffn {C++ Function} gccjit::rvalue new_logical_negate (gccjit::type result_type, gccjit::rvalue a, gccjit::location loc)
10838 Logical negation of an arithmetic or pointer value; for example:
10840 @example
10841 gccjit::rvalue guard = ctxt.new_logical_negate (t_bool, cond);
10842 @end example
10844 @noindent
10846 builds the equivalent of this C expression:
10848 @example
10849 !cond
10850 @end example
10852 @noindent
10853 @end deffn
10855 The most concise way to spell them is with overloaded operators:
10857 @geindex operator- (C++ function)
10858 @anchor{cp/topics/expressions sub-operator__gccjit rvalue}@anchor{126}
10859 @deffn {C++ Function} gccjit::rvalue operator- (gccjit::rvalue a)
10861 @example
10862 gccjit::rvalue negpi = -pi;
10863 @end example
10865 @noindent
10866 @end deffn
10868 @geindex operator~ (C++ function)
10869 @anchor{cp/topics/expressions inv-operator__gccjit rvalue}@anchor{127}
10870 @deffn {C++ Function} gccjit::rvalue operator~ (gccjit::rvalue a)
10872 @example
10873 gccjit::rvalue mask = ~a;
10874 @end example
10876 @noindent
10877 @end deffn
10879 @geindex operator! (C++ function)
10880 @anchor{cp/topics/expressions not-operator__gccjit rvalue}@anchor{128}
10881 @deffn {C++ Function} gccjit::rvalue operator! (gccjit::rvalue a)
10883 @example
10884 gccjit::rvalue guard = !cond;
10885 @end example
10887 @noindent
10888 @end deffn
10890 @node Binary Operations<2>,Comparisons<2>,Unary Operations<2>,Rvalues<2>
10891 @anchor{cp/topics/expressions binary-operations}@anchor{129}
10892 @subsubsection Binary Operations
10895 @geindex gccjit;;context;;new_binary_op (C++ function)
10896 @anchor{cp/topics/expressions gccjit context new_binary_op__enum gccjit type gccjit rvalue gccjit rvalue gccjit location}@anchor{ce}
10897 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_binary_op (enum gcc_jit_binary_op, gccjit::type result_type, gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
10899 Build a binary operation out of two constituent rvalues.
10901 Parameter @code{loc} is optional.
10903 This is a thin wrapper around the C API's
10904 @pxref{12,,gcc_jit_context_new_binary_op()} and the available binary
10905 operations are documented there.
10906 @end deffn
10908 There are shorter ways to spell the various specific kinds of binary
10909 operation:
10911 @geindex gccjit;;context;;new_plus (C++ function)
10912 @anchor{cp/topics/expressions gccjit context new_plus__gccjit type gccjit rvalue gccjit rvalue gccjit location}@anchor{12a}
10913 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_plus (gccjit::type result_type, gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
10914 @end deffn
10916 @geindex gccjit;;context;;new_minus (C++ function)
10917 @anchor{cp/topics/expressions gccjit context new_minus__gccjit type gccjit rvalue gccjit rvalue gccjit location}@anchor{12b}
10918 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_minus (gccjit::type result_type, gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
10919 @end deffn
10921 @geindex gccjit;;context;;new_mult (C++ function)
10922 @anchor{cp/topics/expressions gccjit context new_mult__gccjit type gccjit rvalue gccjit rvalue gccjit location}@anchor{12c}
10923 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_mult (gccjit::type result_type, gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
10924 @end deffn
10926 @geindex gccjit;;context;;new_divide (C++ function)
10927 @anchor{cp/topics/expressions gccjit context new_divide__gccjit type gccjit rvalue gccjit rvalue gccjit location}@anchor{12d}
10928 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_divide (gccjit::type result_type, gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
10929 @end deffn
10931 @geindex gccjit;;context;;new_modulo (C++ function)
10932 @anchor{cp/topics/expressions gccjit context new_modulo__gccjit type gccjit rvalue gccjit rvalue gccjit location}@anchor{12e}
10933 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_modulo (gccjit::type result_type, gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
10934 @end deffn
10936 @geindex gccjit;;context;;new_bitwise_and (C++ function)
10937 @anchor{cp/topics/expressions gccjit context new_bitwise_and__gccjit type gccjit rvalue gccjit rvalue gccjit location}@anchor{12f}
10938 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_bitwise_and (gccjit::type result_type, gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
10939 @end deffn
10941 @geindex gccjit;;context;;new_bitwise_xor (C++ function)
10942 @anchor{cp/topics/expressions gccjit context new_bitwise_xor__gccjit type gccjit rvalue gccjit rvalue gccjit location}@anchor{130}
10943 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_bitwise_xor (gccjit::type result_type, gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
10944 @end deffn
10946 @geindex gccjit;;context;;new_bitwise_or (C++ function)
10947 @anchor{cp/topics/expressions gccjit context new_bitwise_or__gccjit type gccjit rvalue gccjit rvalue gccjit location}@anchor{131}
10948 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_bitwise_or (gccjit::type result_type, gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
10949 @end deffn
10951 @geindex gccjit;;context;;new_logical_and (C++ function)
10952 @anchor{cp/topics/expressions gccjit context new_logical_and__gccjit type gccjit rvalue gccjit rvalue gccjit location}@anchor{132}
10953 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_logical_and (gccjit::type result_type, gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
10954 @end deffn
10956 @geindex gccjit;;context;;new_logical_or (C++ function)
10957 @anchor{cp/topics/expressions gccjit context new_logical_or__gccjit type gccjit rvalue gccjit rvalue gccjit location}@anchor{133}
10958 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_logical_or (gccjit::type result_type, gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
10959 @end deffn
10961 The most concise way to spell them is with overloaded operators:
10963 @geindex operator+ (C++ function)
10964 @anchor{cp/topics/expressions add-operator__gccjit rvalue gccjit rvalue}@anchor{134}
10965 @deffn {C++ Function} gccjit::rvalue operator+ (gccjit::rvalue a, gccjit::rvalue b)
10967 @example
10968 gccjit::rvalue sum = a + b;
10969 @end example
10971 @noindent
10972 @end deffn
10974 @geindex operator- (C++ function)
10975 @anchor{cp/topics/expressions sub-operator__gccjit rvalue gccjit rvalue}@anchor{135}
10976 @deffn {C++ Function} gccjit::rvalue operator- (gccjit::rvalue a, gccjit::rvalue b)
10978 @example
10979 gccjit::rvalue diff = a - b;
10980 @end example
10982 @noindent
10983 @end deffn
10985 @geindex operator* (C++ function)
10986 @anchor{cp/topics/expressions mul-operator__gccjit rvalue gccjit rvalue}@anchor{136}
10987 @deffn {C++ Function} gccjit::rvalue operator* (gccjit::rvalue a, gccjit::rvalue b)
10989 @example
10990 gccjit::rvalue prod = a * b;
10991 @end example
10993 @noindent
10994 @end deffn
10996 @geindex operator/ (C++ function)
10997 @anchor{cp/topics/expressions div-operator__gccjit rvalue gccjit rvalue}@anchor{137}
10998 @deffn {C++ Function} gccjit::rvalue operator/ (gccjit::rvalue a, gccjit::rvalue b)
11000 @example
11001 gccjit::rvalue result = a / b;
11002 @end example
11004 @noindent
11005 @end deffn
11007 @geindex operator% (C++ function)
11008 @anchor{cp/topics/expressions mod-operator__gccjit rvalue gccjit rvalue}@anchor{138}
11009 @deffn {C++ Function} gccjit::rvalue operator% (gccjit::rvalue a, gccjit::rvalue b)
11011 @example
11012 gccjit::rvalue mod = a % b;
11013 @end example
11015 @noindent
11016 @end deffn
11018 @geindex operator& (C++ function)
11019 @anchor{cp/topics/expressions and-operator__gccjit rvalue gccjit rvalue}@anchor{139}
11020 @deffn {C++ Function} gccjit::rvalue operator& (gccjit::rvalue a, gccjit::rvalue b)
11022 @example
11023 gccjit::rvalue x = a & b;
11024 @end example
11026 @noindent
11027 @end deffn
11029 @geindex operator^ (C++ function)
11030 @anchor{cp/topics/expressions xor-operator__gccjit rvalue gccjit rvalue}@anchor{13a}
11031 @deffn {C++ Function} gccjit::rvalue operator^ (gccjit::rvalue a, gccjit::rvalue b)
11033 @example
11034 gccjit::rvalue x = a ^ b;
11035 @end example
11037 @noindent
11038 @end deffn
11040 @geindex operator| (C++ function)
11041 @anchor{cp/topics/expressions or-operator__gccjit rvalue gccjit rvalue}@anchor{13b}
11042 @deffn {C++ Function} gccjit::rvalue operator| (gccjit::rvalue a, gccjit::rvalue b)
11044 @example
11045 gccjit::rvalue x = a | b;
11046 @end example
11048 @noindent
11049 @end deffn
11051 @geindex operator&& (C++ function)
11052 @anchor{cp/topics/expressions sand-operator__gccjit rvalue gccjit rvalue}@anchor{13c}
11053 @deffn {C++ Function} gccjit::rvalue operator&& (gccjit::rvalue a, gccjit::rvalue b)
11055 @example
11056 gccjit::rvalue cond = a && b;
11057 @end example
11059 @noindent
11060 @end deffn
11062 @geindex operator|| (C++ function)
11063 @anchor{cp/topics/expressions sor-operator__gccjit rvalue gccjit rvalue}@anchor{13d}
11064 @deffn {C++ Function} gccjit::rvalue operator|| (gccjit::rvalue a, gccjit::rvalue b)
11066 @example
11067 gccjit::rvalue cond = a || b;
11068 @end example
11070 @noindent
11071 @end deffn
11073 These can of course be combined, giving a terse way to build compound
11074 expressions:
11076 @quotation
11078 @example
11079 gccjit::rvalue discriminant = (b * b) - (four * a * c);
11080 @end example
11082 @noindent
11083 @end quotation
11085 @node Comparisons<2>,Function calls<2>,Binary Operations<2>,Rvalues<2>
11086 @anchor{cp/topics/expressions comparisons}@anchor{13e}
11087 @subsubsection Comparisons
11090 @geindex gccjit;;context;;new_comparison (C++ function)
11091 @anchor{cp/topics/expressions gccjit context new_comparison__enum gccjit rvalue gccjit rvalue gccjit location}@anchor{db}
11092 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_comparison (enum gcc_jit_comparison, gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
11094 Build a boolean rvalue out of the comparison of two other rvalues.
11096 Parameter @code{loc} is optional.
11098 This is a thin wrapper around the C API's
11099 @pxref{2c,,gcc_jit_context_new_comparison()} and the available kinds
11100 of comparison are documented there.
11101 @end deffn
11103 There are shorter ways to spell the various specific kinds of binary
11104 operation:
11106 @geindex gccjit;;context;;new_eq (C++ function)
11107 @anchor{cp/topics/expressions gccjit context new_eq__gccjit rvalue gccjit rvalue gccjit location}@anchor{13f}
11108 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_eq (gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
11109 @end deffn
11111 @geindex gccjit;;context;;new_ne (C++ function)
11112 @anchor{cp/topics/expressions gccjit context new_ne__gccjit rvalue gccjit rvalue gccjit location}@anchor{140}
11113 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_ne (gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
11114 @end deffn
11116 @geindex gccjit;;context;;new_lt (C++ function)
11117 @anchor{cp/topics/expressions gccjit context new_lt__gccjit rvalue gccjit rvalue gccjit location}@anchor{141}
11118 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_lt (gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
11119 @end deffn
11121 @geindex gccjit;;context;;new_le (C++ function)
11122 @anchor{cp/topics/expressions gccjit context new_le__gccjit rvalue gccjit rvalue gccjit location}@anchor{142}
11123 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_le (gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
11124 @end deffn
11126 @geindex gccjit;;context;;new_gt (C++ function)
11127 @anchor{cp/topics/expressions gccjit context new_gt__gccjit rvalue gccjit rvalue gccjit location}@anchor{143}
11128 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_gt (gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
11129 @end deffn
11131 @geindex gccjit;;context;;new_ge (C++ function)
11132 @anchor{cp/topics/expressions gccjit context new_ge__gccjit rvalue gccjit rvalue gccjit location}@anchor{144}
11133 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_ge (gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
11134 @end deffn
11136 The most concise way to spell them is with overloaded operators:
11138 @geindex operator== (C++ function)
11139 @anchor{cp/topics/expressions eq-operator__gccjit rvalue gccjit rvalue}@anchor{145}
11140 @deffn {C++ Function} gccjit::rvalue operator== (gccjit::rvalue a, gccjit::rvalue b)
11142 @example
11143 gccjit::rvalue cond = (a == ctxt.zero (t_int));
11144 @end example
11146 @noindent
11147 @end deffn
11149 @geindex operator!= (C++ function)
11150 @anchor{cp/topics/expressions neq-operator__gccjit rvalue gccjit rvalue}@anchor{146}
11151 @deffn {C++ Function} gccjit::rvalue operator!= (gccjit::rvalue a, gccjit::rvalue b)
11153 @example
11154 gccjit::rvalue cond = (i != j);
11155 @end example
11157 @noindent
11158 @end deffn
11160 @geindex operator< (C++ function)
11161 @anchor{cp/topics/expressions lt-operator__gccjit rvalue gccjit rvalue}@anchor{147}
11162 @deffn {C++ Function} gccjit::rvalue operator< (gccjit::rvalue a, gccjit::rvalue b)
11164 @example
11165 gccjit::rvalue cond = i < n;
11166 @end example
11168 @noindent
11169 @end deffn
11171 @geindex operator<= (C++ function)
11172 @anchor{cp/topics/expressions lte-operator__gccjit rvalue gccjit rvalue}@anchor{148}
11173 @deffn {C++ Function} gccjit::rvalue operator<= (gccjit::rvalue a, gccjit::rvalue b)
11175 @example
11176 gccjit::rvalue cond = i <= n;
11177 @end example
11179 @noindent
11180 @end deffn
11182 @geindex operator> (C++ function)
11183 @anchor{cp/topics/expressions gt-operator__gccjit rvalue gccjit rvalue}@anchor{149}
11184 @deffn {C++ Function} gccjit::rvalue operator> (gccjit::rvalue a, gccjit::rvalue b)
11186 @example
11187 gccjit::rvalue cond = (ch > limit);
11188 @end example
11190 @noindent
11191 @end deffn
11193 @geindex operator>= (C++ function)
11194 @anchor{cp/topics/expressions gte-operator__gccjit rvalue gccjit rvalue}@anchor{14a}
11195 @deffn {C++ Function} gccjit::rvalue operator>= (gccjit::rvalue a, gccjit::rvalue b)
11197 @example
11198 gccjit::rvalue cond = (score >= ctxt.new_rvalue (t_int, 100));
11199 @end example
11201 @noindent
11202 @end deffn
11204 @c TODO: beyond this point
11206 @node Function calls<2>,Type-coercion<2>,Comparisons<2>,Rvalues<2>
11207 @anchor{cp/topics/expressions function-calls}@anchor{14b}
11208 @subsubsection Function calls
11211 @geindex gcc_jit_context_new_call (C++ function)
11212 @anchor{cp/topics/expressions gcc_jit_context_new_call__gcc_jit_contextP gcc_jit_locationP gcc_jit_functionP i gcc_jit_rvaluePP}@anchor{14c}
11213 @deffn {C++ Function} gcc_jit_rvalue* gcc_jit_context_new_call (gcc_jit_context* ctxt, gcc_jit_location* loc, gcc_jit_function* func, int numargs, gcc_jit_rvalue** args)
11215 Given a function and the given table of argument rvalues, construct a
11216 call to the function, with the result as an rvalue.
11218 @cartouche
11219 @quotation Note 
11220 @code{gccjit::context::new_call()} merely builds a
11221 @pxref{11a,,gccjit;;rvalue} i.e. an expression that can be evaluated,
11222 perhaps as part of a more complicated expression.
11223 The call @emph{won't} happen unless you add a statement to a function
11224 that evaluates the expression.
11226 For example, if you want to call a function and discard the result
11227 (or to call a function with @code{void} return type), use
11228 @pxref{14d,,gccjit;;block;;add_eval()}:
11230 @example
11231 /* Add "(void)printf (arg0, arg1);".  */
11232 block.add_eval (ctxt.new_call (printf_func, arg0, arg1));
11233 @end example
11235 @noindent
11236 @end quotation
11237 @end cartouche
11238 @end deffn
11240 @node Type-coercion<2>,,Function calls<2>,Rvalues<2>
11241 @anchor{cp/topics/expressions type-coercion}@anchor{14e}
11242 @subsubsection Type-coercion
11245 @geindex gccjit;;context;;new_cast (C++ function)
11246 @anchor{cp/topics/expressions gccjit context new_cast__gccjit rvalue gccjit type gccjit location}@anchor{14f}
11247 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_cast (gccjit::rvalue rvalue, gccjit::type type, gccjit::location loc)
11249 Given an rvalue of T, construct another rvalue of another type.
11251 Currently only a limited set of conversions are possible:
11253 @quotation
11256 @itemize *
11258 @item 
11259 int <-> float
11261 @item 
11262 int <-> bool
11264 @item 
11265 P*  <-> Q*, for pointer types P and Q
11266 @end itemize
11267 @end quotation
11268 @end deffn
11270 @node Lvalues<2>,Working with pointers structs and unions<2>,Rvalues<2>,Expressions<2>
11271 @anchor{cp/topics/expressions lvalues}@anchor{150}
11272 @subsubsection Lvalues
11275 @geindex gccjit;;lvalue (C++ class)
11276 @anchor{cp/topics/expressions gccjit lvalue}@anchor{151}
11277 @deffn {C++ Class} gccjit::lvalue
11278 @end deffn
11280 An lvalue is something that can of the @emph{left}-hand side of an assignment:
11281 a storage area (such as a variable).  It is a subclass of
11282 @pxref{11a,,gccjit;;rvalue}, where the rvalue is computed by reading from the
11283 storage area.
11285 It iss a thin wrapper around @pxref{24,,gcc_jit_lvalue *} from the C API.
11287 @geindex gccjit;;lvalue;;get_address (C++ function)
11288 @anchor{cp/topics/expressions gccjit lvalue get_address__gccjit location}@anchor{152}
11289 @deffn {C++ Function} gccjit::rvalue gccjit::lvalue::get_address (gccjit::location loc)
11291 Take the address of an lvalue; analogous to:
11293 @example
11294 &(EXPR)
11295 @end example
11297 @noindent
11299 in C.
11301 Parameter "loc" is optional.
11302 @end deffn
11304 @menu
11305 * Global variables: Global variables<2>. 
11307 @end menu
11309 @node Global variables<2>,,,Lvalues<2>
11310 @anchor{cp/topics/expressions global-variables}@anchor{153}
11311 @subsubsection Global variables
11314 @geindex gccjit;;context;;new_global (C++ function)
11315 @anchor{cp/topics/expressions gccjit context new_global__gccjit type cCP gccjit location}@anchor{154}
11316 @deffn {C++ Function} gccjit::lvalue gccjit::context::new_global (gccjit::type type, const char* name, gccjit::location loc)
11318 Add a new global variable of the given type and name to the context.
11319 @end deffn
11321 @node Working with pointers structs and unions<2>,,Lvalues<2>,Expressions<2>
11322 @anchor{cp/topics/expressions working-with-pointers-structs-and-unions}@anchor{155}
11323 @subsubsection Working with pointers, structs and unions
11326 @geindex gccjit;;rvalue;;dereference (C++ function)
11327 @anchor{cp/topics/expressions gccjit rvalue dereference__gccjit location}@anchor{156}
11328 @deffn {C++ Function} gccjit::lvalue gccjit::rvalue::dereference (gccjit::location loc)
11330 Given an rvalue of pointer type @code{T *}, dereferencing the pointer,
11331 getting an lvalue of type @code{T}.  Analogous to:
11333 @example
11334 *(EXPR)
11335 @end example
11337 @noindent
11339 in C.
11341 Parameter "loc" is optional.
11342 @end deffn
11344 If you don't need to specify the location, this can also be expressed using
11345 an overloaded operator:
11348 @deffn {C++ Function} gccjit::lvalue            gccjit::rvalue::operator* ();
11350 @example
11351 gccjit::lvalue content = *ptr;
11352 @end example
11354 @noindent
11355 @end deffn
11357 Field access is provided separately for both lvalues and rvalues:
11359 @geindex gccjit;;lvalue;;access_field (C++ function)
11360 @anchor{cp/topics/expressions gccjit lvalue access_field__gccjit field gccjit location}@anchor{157}
11361 @deffn {C++ Function} gccjit::lvalue gccjit::lvalue::access_field (gccjit::field field, gccjit::location loc)
11363 Given an lvalue of struct or union type, access the given field,
11364 getting an lvalue of the field's type.  Analogous to:
11366 @example
11367 (EXPR).field = ...;
11368 @end example
11370 @noindent
11372 in C.
11373 @end deffn
11375 @geindex gccjit;;rvalue;;access_field (C++ function)
11376 @anchor{cp/topics/expressions gccjit rvalue access_field__gccjit field gccjit location}@anchor{158}
11377 @deffn {C++ Function} gccjit::rvalue gccjit::rvalue::access_field (gccjit::field field, gccjit::location loc)
11379 Given an rvalue of struct or union type, access the given field
11380 as an rvalue.  Analogous to:
11382 @example
11383 (EXPR).field
11384 @end example
11386 @noindent
11388 in C.
11389 @end deffn
11391 @geindex gccjit;;rvalue;;dereference_field (C++ function)
11392 @anchor{cp/topics/expressions gccjit rvalue dereference_field__gccjit field gccjit location}@anchor{159}
11393 @deffn {C++ Function} gccjit::lvalue gccjit::rvalue::dereference_field (gccjit::field field, gccjit::location loc)
11395 Given an rvalue of pointer type @code{T *} where T is of struct or union
11396 type, access the given field as an lvalue.  Analogous to:
11398 @example
11399 (EXPR)->field
11400 @end example
11402 @noindent
11404 in C, itself equivalent to @code{(*EXPR).FIELD}.
11405 @end deffn
11407 @geindex gccjit;;context;;new_array_access (C++ function)
11408 @anchor{cp/topics/expressions gccjit context new_array_access__gccjit rvalue gccjit rvalue gccjit location}@anchor{15a}
11409 @deffn {C++ Function} gccjit::lvalue gccjit::context::new_array_access (gccjit::rvalue ptr, gccjit::rvalue index, gccjit::location loc)
11411 Given an rvalue of pointer type @code{T *}, get at the element @cite{T} at
11412 the given index, using standard C array indexing rules i.e. each
11413 increment of @code{index} corresponds to @code{sizeof(T)} bytes.
11414 Analogous to:
11416 @example
11417 PTR[INDEX]
11418 @end example
11420 @noindent
11422 in C (or, indeed, to @code{PTR + INDEX}).
11424 Parameter "loc" is optional.
11425 @end deffn
11427 For array accesses where you don't need to specify a @pxref{fe,,gccjit;;location},
11428 two overloaded operators are available:
11430 @quotation
11432 gccjit::lvalue gccjit::rvalue::operator[] (gccjit::rvalue index)
11434 @example
11435 gccjit::lvalue element = array[idx];
11436 @end example
11438 @noindent
11440 gccjit::lvalue gccjit::rvalue::operator[] (int index)
11442 @example
11443 gccjit::lvalue element = array[0];
11444 @end example
11446 @noindent
11447 @end quotation
11449 @c Copyright (C) 2014 Free Software Foundation, Inc.
11450 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
11451 @c 
11452 @c This is free software: you can redistribute it and/or modify it
11453 @c under the terms of the GNU General Public License as published by
11454 @c the Free Software Foundation, either version 3 of the License, or
11455 @c (at your option) any later version.
11456 @c 
11457 @c This program is distributed in the hope that it will be useful, but
11458 @c WITHOUT ANY WARRANTY; without even the implied warranty of
11459 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11460 @c General Public License for more details.
11461 @c 
11462 @c You should have received a copy of the GNU General Public License
11463 @c along with this program.  If not, see
11464 @c <http://www.gnu.org/licenses/>.
11466 @node Creating and using functions<2>,Source Locations<2>,Expressions<2>,Topic Reference<2>
11467 @anchor{cp/topics/functions doc}@anchor{15b}@anchor{cp/topics/functions creating-and-using-functions}@anchor{15c}
11468 @subsection Creating and using functions
11471 @menu
11472 * Params: Params<2>. 
11473 * Functions: Functions<2>. 
11474 * Blocks: Blocks<2>. 
11475 * Statements: Statements<2>. 
11477 @end menu
11479 @node Params<2>,Functions<2>,,Creating and using functions<2>
11480 @anchor{cp/topics/functions params}@anchor{15d}
11481 @subsubsection Params
11484 @geindex gccjit;;param (C++ class)
11485 @anchor{cp/topics/functions gccjit param}@anchor{15e}
11486 @deffn {C++ Class} gccjit::param
11488 A @cite{gccjit::param} represents a parameter to a function.
11489 @end deffn
11491 @geindex gccjit;;context;;new_param (C++ function)
11492 @anchor{cp/topics/functions gccjit context new_param__gccjit type cCP gccjit location}@anchor{cd}
11493 @deffn {C++ Function} gccjit::param gccjit::context::new_param (gccjit::type type, const char* name, gccjit::location loc)
11495 In preparation for creating a function, create a new parameter of the
11496 given type and name.
11497 @end deffn
11499 @pxref{15e,,gccjit;;param} is a subclass of @pxref{151,,gccjit;;lvalue} (and thus
11500 of @pxref{11a,,gccjit;;rvalue} and @pxref{104,,gccjit;;object}).  It is a thin
11501 wrapper around the C API's @pxref{25,,gcc_jit_param *}.
11503 @node Functions<2>,Blocks<2>,Params<2>,Creating and using functions<2>
11504 @anchor{cp/topics/functions functions}@anchor{15f}
11505 @subsubsection Functions
11508 @geindex gccjit;;function (C++ class)
11509 @anchor{cp/topics/functions gccjit function}@anchor{160}
11510 @deffn {C++ Class} gccjit::function
11512 A @cite{gccjit::function} represents a function - either one that we're
11513 creating ourselves, or one that we're referencing.
11514 @end deffn
11517 @deffn {C++ Function} gccjit::function             gccjit::context::new_function (enum gcc_jit_function_kind,                                           gccjit::type return_type,                                            const char *name,                                            std::vector<param> &params,                                            int is_variadic,                                            gccjit::location loc) \
11519 Create a gcc_jit_function with the given name and parameters.
11521 Parameters "is_variadic" and "loc" are optional.
11523 This is a wrapper around the C API's @pxref{11,,gcc_jit_context_new_function()}.
11524 @end deffn
11526 @geindex gccjit;;context;;get_builtin_function (C++ function)
11527 @anchor{cp/topics/functions gccjit context get_builtin_function__cCP}@anchor{161}
11528 @deffn {C++ Function} gccjit::function gccjit::context::get_builtin_function (const char* name)
11530 This is a wrapper around the C API's
11531 @pxref{b1,,gcc_jit_context_get_builtin_function()}.
11532 @end deffn
11534 @geindex gccjit;;function;;get_param (C++ function)
11535 @anchor{cp/topics/functions gccjit function get_param__iC}@anchor{162}
11536 @deffn {C++ Function} gccjit::param gccjit::function::get_param (int index) const
11538 Get the param of the given index (0-based).
11539 @end deffn
11541 @geindex gccjit;;function;;dump_to_dot (C++ function)
11542 @anchor{cp/topics/functions gccjit function dump_to_dot__cCP}@anchor{e0}
11543 @deffn {C++ Function} void gccjit::function::dump_to_dot (const char* path)
11545 Emit the function in graphviz format to the given path.
11546 @end deffn
11548 @geindex gccjit;;function;;new_local (C++ function)
11549 @anchor{cp/topics/functions gccjit function new_local__gccjit type cCP gccjit location}@anchor{d7}
11550 @deffn {C++ Function} gccjit::lvalue gccjit::function::new_local (gccjit::type type, const char* name, gccjit::location loc)
11552 Create a new local variable within the function, of the given type and
11553 name.
11554 @end deffn
11556 @node Blocks<2>,Statements<2>,Functions<2>,Creating and using functions<2>
11557 @anchor{cp/topics/functions blocks}@anchor{163}
11558 @subsubsection Blocks
11561 @geindex gccjit;;block (C++ class)
11562 @anchor{cp/topics/functions gccjit block}@anchor{164}
11563 @deffn {C++ Class} gccjit::block
11565 A @cite{gccjit::block} represents a basic block within a function  i.e. a
11566 sequence of statements with a single entry point and a single exit
11567 point.
11569 @pxref{164,,gccjit;;block} is a subclass of @pxref{104,,gccjit;;object}.
11571 The first basic block that you create within a function will
11572 be the entrypoint.
11574 Each basic block that you create within a function must be
11575 terminated, either with a conditional, a jump, or a return.
11577 It's legal to have multiple basic blocks that return within
11578 one function.
11579 @end deffn
11581 @geindex gccjit;;function;;new_block (C++ function)
11582 @anchor{cp/topics/functions gccjit function new_block__cCP}@anchor{165}
11583 @deffn {C++ Function} gccjit::block gccjit::function::new_block (const char* name)
11585 Create a basic block of the given name.  The name may be NULL, but
11586 providing meaningful names is often helpful when debugging: it may
11587 show up in dumps of the internal representation, and in error
11588 messages.
11589 @end deffn
11591 @node Statements<2>,,Blocks<2>,Creating and using functions<2>
11592 @anchor{cp/topics/functions statements}@anchor{166}
11593 @subsubsection Statements
11596 @geindex gccjit;;block;;add_eval (C++ function)
11597 @anchor{cp/topics/functions gccjit block add_eval__gccjit rvalue gccjit location}@anchor{14d}
11598 @deffn {C++ Function} void gccjit::block::add_eval (gccjit::rvalue rvalue, gccjit::location loc)
11600 Add evaluation of an rvalue, discarding the result
11601 (e.g. a function call that "returns" void).
11603 This is equivalent to this C code:
11605 @example
11606 (void)expression;
11607 @end example
11609 @noindent
11610 @end deffn
11612 @geindex gccjit;;block;;add_assignment (C++ function)
11613 @anchor{cp/topics/functions gccjit block add_assignment__gccjit lvalue gccjit rvalue gccjit location}@anchor{d9}
11614 @deffn {C++ Function} void gccjit::block::add_assignment (gccjit::lvalue lvalue, gccjit::rvalue rvalue, gccjit::location loc)
11616 Add evaluation of an rvalue, assigning the result to the given
11617 lvalue.
11619 This is roughly equivalent to this C code:
11621 @example
11622 lvalue = rvalue;
11623 @end example
11625 @noindent
11626 @end deffn
11628 @geindex gccjit;;block;;add_assignment_op (C++ function)
11629 @anchor{cp/topics/functions gccjit block add_assignment_op__gccjit lvalue enum gccjit rvalue gccjit location}@anchor{dd}
11630 @deffn {C++ Function} void gccjit::block::add_assignment_op (gccjit::lvalue lvalue, enum gcc_jit_binary_op, gccjit::rvalue rvalue, gccjit::location loc)
11632 Add evaluation of an rvalue, using the result to modify an
11633 lvalue.
11635 This is analogous to "+=" and friends:
11637 @example
11638 lvalue += rvalue;
11639 lvalue *= rvalue;
11640 lvalue /= rvalue;
11641 @end example
11643 @noindent
11645 etc.  For example:
11647 @example
11648 /* "i++" */
11649 loop_body.add_assignment_op (
11650   i,
11651   GCC_JIT_BINARY_OP_PLUS,
11652   ctxt.one (int_type));
11653 @end example
11655 @noindent
11656 @end deffn
11658 @geindex gccjit;;block;;add_comment (C++ function)
11659 @anchor{cp/topics/functions gccjit block add_comment__cCP gccjit location}@anchor{e8}
11660 @deffn {C++ Function} void gccjit::block::add_comment (const char* text, gccjit::location loc)
11662 Add a no-op textual comment to the internal representation of the
11663 code.  It will be optimized away, but will be visible in the dumps
11664 seen via @pxref{5b,,GCC_JIT_BOOL_OPTION_DUMP_INITIAL_TREE}
11665 and @pxref{1c,,GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE},
11666 and thus may be of use when debugging how your project's internal
11667 representation gets converted to the libgccjit IR.
11669 Parameter "loc" is optional.
11670 @end deffn
11672 @geindex gccjit;;block;;end_with_conditional (C++ function)
11673 @anchor{cp/topics/functions gccjit block end_with_conditional__gccjit rvalue gccjit block gccjit block gccjit location}@anchor{dc}
11674 @deffn {C++ Function} void gccjit::block::end_with_conditional (gccjit::rvalue boolval, gccjit::block on_true, gccjit::block on_false, gccjit::location loc)
11676 Terminate a block by adding evaluation of an rvalue, branching on the
11677 result to the appropriate successor block.
11679 This is roughly equivalent to this C code:
11681 @example
11682 if (boolval)
11683   goto on_true;
11684 else
11685   goto on_false;
11686 @end example
11688 @noindent
11690 block, boolval, on_true, and on_false must be non-NULL.
11691 @end deffn
11693 @geindex gccjit;;block;;end_with_jump (C++ function)
11694 @anchor{cp/topics/functions gccjit block end_with_jump__gccjit block gccjit location}@anchor{167}
11695 @deffn {C++ Function} void gccjit::block::end_with_jump (gccjit::block target, gccjit::location loc)
11697 Terminate a block by adding a jump to the given target block.
11699 This is roughly equivalent to this C code:
11701 @example
11702 goto target;
11703 @end example
11705 @noindent
11706 @end deffn
11708 @geindex gccjit;;block;;end_with_return (C++ function)
11709 @anchor{cp/topics/functions gccjit block end_with_return__gccjit rvalue gccjit location}@anchor{168}
11710 @deffn {C++ Function} void gccjit::block::end_with_return (gccjit::rvalue rvalue, gccjit::location loc)
11712 Terminate a block.
11714 Both params are optional.
11716 An rvalue must be provided for a function returning non-void, and
11717 must not be provided by a function "returning" @cite{void}.
11719 If an rvalue is provided, the block is terminated by evaluating the
11720 rvalue and returning the value.
11722 This is roughly equivalent to this C code:
11724 @example
11725 return expression;
11726 @end example
11728 @noindent
11730 If an rvalue is not provided, the block is terminated by adding a
11731 valueless return, for use within a function with "void" return type.
11733 This is equivalent to this C code:
11735 @example
11736 return;
11737 @end example
11739 @noindent
11740 @end deffn
11742 @c Copyright (C) 2014 Free Software Foundation, Inc.
11743 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
11744 @c 
11745 @c This is free software: you can redistribute it and/or modify it
11746 @c under the terms of the GNU General Public License as published by
11747 @c the Free Software Foundation, either version 3 of the License, or
11748 @c (at your option) any later version.
11749 @c 
11750 @c This program is distributed in the hope that it will be useful, but
11751 @c WITHOUT ANY WARRANTY; without even the implied warranty of
11752 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11753 @c General Public License for more details.
11754 @c 
11755 @c You should have received a copy of the GNU General Public License
11756 @c along with this program.  If not, see
11757 @c <http://www.gnu.org/licenses/>.
11759 @node Source Locations<2>,Compilation results<2>,Creating and using functions<2>,Topic Reference<2>
11760 @anchor{cp/topics/locations source-locations}@anchor{169}@anchor{cp/topics/locations doc}@anchor{16a}
11761 @subsection Source Locations
11764 @geindex gccjit;;location (C++ class)
11765 @anchor{cp/topics/locations gccjit location}@anchor{fe}
11766 @deffn {C++ Class} gccjit::location
11768 A @cite{gccjit::location} encapsulates a source code location, so that
11769 you can (optionally) associate locations in your language with
11770 statements in the JIT-compiled code, allowing the debugger to
11771 single-step through your language.
11773 @cite{gccjit::location} instances are optional: you can always omit them
11774 from any C++ API entrypoint accepting one.
11776 You can construct them using @pxref{ec,,gccjit;;context;;new_location()}.
11778 You need to enable @pxref{42,,GCC_JIT_BOOL_OPTION_DEBUGINFO} on the
11779 @pxref{f6,,gccjit;;context} for these locations to actually be usable by
11780 the debugger:
11782 @example
11783 ctxt.set_bool_option (GCC_JIT_BOOL_OPTION_DEBUGINFO, 1);
11784 @end example
11786 @noindent
11787 @end deffn
11789 @geindex gccjit;;context;;new_location (C++ function)
11790 @anchor{cp/topics/locations gccjit context new_location__cCP i i}@anchor{ec}
11791 @deffn {C++ Function} gccjit::location gccjit::context::new_location (const char* filename, int line, int column)
11793 Create a @cite{gccjit::location} instance representing the given source
11794 location.
11795 @end deffn
11797 @menu
11798 * Faking it: Faking it<2>. 
11800 @end menu
11802 @node Faking it<2>,,,Source Locations<2>
11803 @anchor{cp/topics/locations faking-it}@anchor{16b}
11804 @subsubsection Faking it
11807 If you don't have source code for your internal representation, but need
11808 to debug, you can generate a C-like representation of the functions in
11809 your context using @pxref{fd,,gccjit;;context;;dump_to_file()}:
11811 @example
11812 ctxt.dump_to_file ("/tmp/something.c",
11813                    1 /* update_locations */);
11814 @end example
11816 @noindent
11818 This will dump C-like code to the given path.  If the @cite{update_locations}
11819 argument is true, this will also set up @cite{gccjit::location} information
11820 throughout the context, pointing at the dump file as if it were a source
11821 file, giving you @emph{something} you can step through in the debugger.
11823 @c Copyright (C) 2014 Free Software Foundation, Inc.
11824 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
11825 @c 
11826 @c This is free software: you can redistribute it and/or modify it
11827 @c under the terms of the GNU General Public License as published by
11828 @c the Free Software Foundation, either version 3 of the License, or
11829 @c (at your option) any later version.
11830 @c 
11831 @c This program is distributed in the hope that it will be useful, but
11832 @c WITHOUT ANY WARRANTY; without even the implied warranty of
11833 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11834 @c General Public License for more details.
11835 @c 
11836 @c You should have received a copy of the GNU General Public License
11837 @c along with this program.  If not, see
11838 @c <http://www.gnu.org/licenses/>.
11840 @node Compilation results<2>,,Source Locations<2>,Topic Reference<2>
11841 @anchor{cp/topics/results compilation-results}@anchor{16c}@anchor{cp/topics/results doc}@anchor{16d}
11842 @subsection Compilation results
11845 @geindex gcc_jit_result (C++ type)
11846 @anchor{cp/topics/results gcc_jit_result}@anchor{16e}
11847 @deffn {C++ Type} gcc_jit_result
11849 A @cite{gcc_jit_result} encapsulates the result of compiling a context.
11850 @end deffn
11852 @geindex gccjit;;context;;compile (C++ function)
11853 @anchor{cp/topics/results gccjit context compile}@anchor{cf}
11854 @deffn {C++ Function} @pxref{16e,,gcc_jit_result*} gccjit::context::compile ()
11856 This calls into GCC and builds the code, returning a
11857 @cite{gcc_jit_result *}.
11858 @end deffn
11860 @geindex gcc_jit_result_get_code (C++ function)
11861 @anchor{cp/topics/results gcc_jit_result_get_code__gcc_jit_resultP cCP}@anchor{16f}
11862 @deffn {C++ Function} void* gcc_jit_result_get_code (gcc_jit_result* result, const char* funcname)
11864 Locate a given function within the built machine code.
11865 This will need to be cast to a function pointer of the
11866 correct type before it can be called.
11867 @end deffn
11869 @geindex gcc_jit_result_release (C++ function)
11870 @anchor{cp/topics/results gcc_jit_result_release__gcc_jit_resultP}@anchor{170}
11871 @deffn {C++ Function} void gcc_jit_result_release (gcc_jit_result* result)
11873 Once we're done with the code, this unloads the built .so file.
11874 This cleans up the result; after calling this, it's no longer
11875 valid to use the result.
11876 @end deffn
11878 @c Copyright (C) 2014 Free Software Foundation, Inc.
11879 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
11880 @c 
11881 @c This is free software: you can redistribute it and/or modify it
11882 @c under the terms of the GNU General Public License as published by
11883 @c the Free Software Foundation, either version 3 of the License, or
11884 @c (at your option) any later version.
11885 @c 
11886 @c This program is distributed in the hope that it will be useful, but
11887 @c WITHOUT ANY WARRANTY; without even the implied warranty of
11888 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11889 @c General Public License for more details.
11890 @c 
11891 @c You should have received a copy of the GNU General Public License
11892 @c along with this program.  If not, see
11893 @c <http://www.gnu.org/licenses/>.
11895 @node Internals,Indices and tables,C++ bindings for libgccjit,Top
11896 @anchor{internals/index internals}@anchor{171}@anchor{internals/index doc}@anchor{172}
11897 @chapter Internals
11900 @menu
11901 * Working on the JIT library:: 
11902 * Running the test suite:: 
11903 * Environment variables:: 
11904 * Overview of code structure:: 
11906 @end menu
11908 @node Working on the JIT library,Running the test suite,,Internals
11909 @anchor{internals/index working-on-the-jit-library}@anchor{173}
11910 @section Working on the JIT library
11913 Having checked out the source code (to "src"), you can configure and build
11914 the JIT library like this:
11916 @example
11917 mkdir build
11918 mkdir install
11919 PREFIX=$(pwd)/install
11920 cd build
11921 ../src/configure \
11922    --enable-host-shared \
11923    --enable-languages=jit \
11924    --disable-bootstrap \
11925    --enable-checking=release \
11926    --prefix=$PREFIX
11927 nice make -j4 # altering the "4" to however many cores you have
11928 @end example
11930 @noindent
11932 This should build a libgccjit.so within jit/build/gcc:
11934 @example
11935 [build] $ file gcc/libgccjit.so*
11936 gcc/libgccjit.so:       symbolic link to `libgccjit.so.0'
11937 gcc/libgccjit.so.0:     symbolic link to `libgccjit.so.0.0.1'
11938 gcc/libgccjit.so.0.0.1: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, not stripped
11939 @end example
11941 @noindent
11943 Here's what those configuration options mean:
11945 @geindex command line option; --enable-host-shared
11946 @anchor{internals/index cmdoption--enable-host-shared}@anchor{174}
11947 @deffn {Option} --enable-host-shared
11949 Configuring with this option means that the compiler is built as
11950 position-independent code, which incurs a slight performance hit,
11951 but it necessary for a shared library.
11952 @end deffn
11954 @geindex command line option; --enable-languages=jit
11955 @anchor{internals/index cmdoption--enable-languages}@anchor{175}
11956 @deffn {Option} --enable-languages=jit
11958 This specifies which frontends to build.  The JIT library looks like
11959 a frontend to the rest of the code.
11960 @end deffn
11962 @geindex command line option; --disable-bootstrap
11963 @anchor{internals/index cmdoption--disable-bootstrap}@anchor{176}
11964 @deffn {Option} --disable-bootstrap
11966 For hacking on the "jit" subdirectory, performing a full
11967 bootstrap can be overkill, since it's unused by a bootstrap.  However,
11968 when submitting patches, you should remove this option, to ensure that
11969 the compiler can still bootstrap itself.
11970 @end deffn
11972 @geindex command line option; --enable-checking=release
11973 @anchor{internals/index cmdoption--enable-checking}@anchor{177}
11974 @deffn {Option} --enable-checking=release
11976 The compile can perform extensive self-checking as it runs, useful when
11977 debugging, but slowing things down.
11979 For maximum speed, configure with @code{--enable-checking=release} to
11980 disable this self-checking.
11981 @end deffn
11983 @node Running the test suite,Environment variables,Working on the JIT library,Internals
11984 @anchor{internals/index running-the-test-suite}@anchor{178}
11985 @section Running the test suite
11988 @example
11989 [build] $ cd gcc
11990 [gcc] $ make check-jit RUNTESTFLAGS="-v -v -v"
11991 @end example
11993 @noindent
11995 A summary of the tests can then be seen in:
11997 @example
11998 jit/build/gcc/testsuite/jit/jit.sum
11999 @end example
12001 @noindent
12003 and detailed logs in:
12005 @example
12006 jit/build/gcc/testsuite/jit/jit.log
12007 @end example
12009 @noindent
12011 The test executables can be seen as:
12013 @example
12014 jit/build/gcc/testsuite/jit/*.exe
12015 @end example
12017 @noindent
12019 which can be run independently.
12021 You can compile and run individual tests by passing "jit.exp=TESTNAME" to RUNTESTFLAGS e.g.:
12023 @example
12024 [gcc] $ make check-jit RUNTESTFLAGS="-v -v -v jit.exp=test-factorial.c"
12025 @end example
12027 @noindent
12029 and once a test has been compiled, you can debug it directly:
12031 @example
12032 [gcc] $ PATH=.:$PATH \
12033         LD_LIBRARY_PATH=. \
12034         LIBRARY_PATH=. \
12035           gdb --args \
12036             testsuite/jit/test-factorial.exe
12037 @end example
12039 @noindent
12041 @menu
12042 * Running under valgrind:: 
12044 @end menu
12046 @node Running under valgrind,,,Running the test suite
12047 @anchor{internals/index running-under-valgrind}@anchor{179}
12048 @subsection Running under valgrind
12051 The jit testsuite detects if RUN_UNDER_VALGRIND is present in the
12052 environment (with any value).  If it is present, it runs the test client
12053 code under valgrind@footnote{http://valgrind.org},
12054 specifcally, the default
12055 memcheck@footnote{http://valgrind.org/docs/manual/mc-manual.html}
12056 tool with
12057 --leak-check=full@footnote{http://valgrind.org/docs/manual/mc-manual.html#opt.leak-check}.
12059 It automatically parses the output from valgrind, injecting XFAIL results if
12060 any issues are found, or PASS results if the output is clean.  The output
12061 is saved to @code{TESTNAME.exe.valgrind.txt}.
12063 For example, the following invocation verbosely runs the testcase
12064 @code{test-sum-of-squares.c} under valgrind, showing an issue:
12066 @example
12067 $ RUN_UNDER_VALGRIND= \
12068     make check-jit \
12069       RUNTESTFLAGS="-v -v -v jit.exp=test-sum-of-squares.c"
12071 (...verbose log contains detailed valgrind errors, if any...)
12073                 === jit Summary ===
12075 # of expected passes            28
12076 # of expected failures          2
12078 $ less testsuite/jit/jit.sum
12079 (...other results...)
12080 XFAIL: jit.dg/test-sum-of-squares.c: test-sum-of-squares.exe.valgrind.txt: definitely lost: 8 bytes in 1 blocks
12081 XFAIL: jit.dg/test-sum-of-squares.c: test-sum-of-squares.exe.valgrind.txt: unsuppressed errors: 1
12082 (...other results...)
12084 $ less testsuite/jit/test-sum-of-squares.exe.valgrind.txt
12085 (...shows full valgrind report for this test case...)
12086 @end example
12088 @noindent
12090 When running under valgrind, it's best to have configured gcc with
12091 @code{--enable-valgrind-annotations}, which automatically suppresses
12092 various known false positives.
12094 @node Environment variables,Overview of code structure,Running the test suite,Internals
12095 @anchor{internals/index environment-variables}@anchor{17a}
12096 @section Environment variables
12099 When running client code against a locally-built libgccjit, three
12100 environment variables need to be set up:
12102 @geindex environment variable; LD_LIBRARY_PATH
12103 @anchor{internals/index envvar-LD_LIBRARY_PATH}@anchor{17b}
12104 @deffn {Environment Variable} LD_LIBRARY_PATH
12106 @quotation
12108 @cite{libgccjit.so} is dynamically linked into client code, so if running
12109 against a locally-built library, @code{LD_LIBRARY_PATH} needs to be set
12110 up appropriately.  The library can be found within the "gcc"
12111 subdirectory of the build tree:
12112 @end quotation
12114 @example
12115 $ file libgccjit.so*
12116 libgccjit.so:       symbolic link to `libgccjit.so.0'
12117 libgccjit.so.0:     symbolic link to `libgccjit.so.0.0.1'
12118 libgccjit.so.0.0.1: ELF 64-bit LSB shared object, x86-64, version 1 (GNU/Linux), dynamically linked, not stripped
12119 @end example
12121 @noindent
12122 @end deffn
12124 @geindex environment variable; PATH
12125 @anchor{internals/index envvar-PATH}@anchor{17c}
12126 @deffn {Environment Variable} PATH
12128 The library uses a driver executable for converting from .s assembler
12129 files to .so shared libraries.  Specifically, it looks for a name
12130 expanded from
12131 @code{$@{target_noncanonical@}-gcc-$@{gcc_BASEVER@}$@{exeext@}}
12132 such as @code{x86_64-unknown-linux-gnu-gcc-5.0.0}.
12134 Hence @code{PATH} needs to include a directory where the library can
12135 locate this executable.
12137 The executable is normally installed to the installation bindir
12138 (e.g. /usr/bin), but a copy is also created within the "gcc"
12139 subdirectory of the build tree for running the testsuite, and for ease
12140 of development.
12141 @end deffn
12143 @geindex environment variable; LIBRARY_PATH
12144 @anchor{internals/index envvar-LIBRARY_PATH}@anchor{17d}
12145 @deffn {Environment Variable} LIBRARY_PATH
12147 The driver executable invokes the linker, and the latter needs to locate
12148 support libraries needed by the generated code, or you will see errors
12149 like:
12151 @example
12152 ld: cannot find crtbeginS.o: No such file or directory
12153 ld: cannot find -lgcc
12154 ld: cannot find -lgcc_s
12155 @end example
12157 @noindent
12159 Hence if running directly from a locally-built copy (without installing),
12160 @code{LIBRARY_PATH} needs to contain the "gcc" subdirectory of the build
12161 tree.
12162 @end deffn
12164 For example, to run a binary that uses the library against a non-installed
12165 build of the library in LIBGCCJIT_BUILD_DIR you need an invocation of the
12166 client code like this, to preprend the dir to each of the environment
12167 variables:
12169 @example
12170 $ LD_LIBRARY_PATH=$(LIBGCCJIT_BUILD_DIR):$(LD_LIBRARY_PATH) \
12171   PATH=$(LIBGCCJIT_BUILD_DIR):$(PATH) \
12172   LIBRARY_PATH=$(LIBGCCJIT_BUILD_DIR):$(LIBRARY_PATH) \
12173     ./jit-hello-world
12174 hello world
12175 @end example
12177 @noindent
12179 @node Overview of code structure,,Environment variables,Internals
12180 @anchor{internals/index overview-of-code-structure}@anchor{17e}
12181 @section Overview of code structure
12185 @itemize *
12187 @item 
12188 @code{libgccjit.c} implements the API entrypoints.  It performs error
12189 checking, then calls into classes of the gcc::jit::recording namespace
12190 within @code{jit-recording.c} and @code{jit-recording.h}.
12192 @item 
12193 The gcc::jit::recording classes (within @code{jit-recording.c} and
12194 @code{jit-recording.h}) record the API calls that are made:
12196 @quotation
12198 @example
12200   /* Indentation indicates inheritance: */
12201   class context;
12202   class memento;
12203     class string;
12204     class location;
12205     class type;
12206       class function_type;
12207       class compound_type;
12208         class struct_;
12209         class union_;
12210     class field;
12211     class fields;
12212     class function;
12213     class block;
12214     class rvalue;
12215       class lvalue;
12216         class local;
12217         class global;
12218         class param;
12219     class statement;
12222 @end example
12224 @noindent
12225 @end quotation
12227 @item 
12228 When the context is compiled, the gcc::jit::playback classes (within
12229 @code{jit-playback.c} and @code{jit-playback.h}) replay the API calls
12230 within langhook:parse_file:
12232 @quotation
12234 @example
12236   /* Indentation indicates inheritance: */
12237   class context;
12238   class wrapper;
12239     class type;
12240       class compound_type;
12241     class field;
12242     class function;
12243     class block;
12244     class rvalue;
12245       class lvalue;
12246         class param;
12247     class source_file;
12248     class source_line;
12249     class location;
12252 @end example
12254 @noindent
12256 @example
12257 Client Code   . Generated .            libgccjit.so
12258               . code      .
12259               .           . JIT API  . JIT "Frontend". (libbackend.a)
12260 ....................................................................................
12261    │          .           .          .               .
12262     ──────────────────────────>      .               .
12263               .           .    │     .               .
12264               .           .    V     .               .
12265               .           .    ──> libgccjit.c       .
12266               .           .        │ (error-checking).
12267               .           .        │                 .
12268               .           .        ──> jit-recording.c
12269               .           .              (record API calls)
12270               .           .    <───────              .
12271               .           .    │     .               .
12272    <───────────────────────────      .               .
12273    │          .           .          .               .
12274    │          .           .          .               .
12275    V          .           .  gcc_jit_context_compile .
12276     ──────────────────────────>      .               .
12277               .           .    │ start of recording::context::compile ()
12278               .           .    │     .               .
12279               .           .    │ start of playback::context::compile ()
12280               .           .    │   (create tempdir)  .
12281               .           .    │     .               .
12282               .           .    │ ACQUIRE MUTEX       .
12283               .           .    │     .               .
12284               .           .    V───────────────────────> toplev::main (for now)
12285               .           .          .               .       │
12286               .           .          .               .   (various code)
12287               .           .          .               .       │
12288               .           .          .               .       V
12289               .           .          .    <───────────────── langhook:parse_file
12290               .           .          .    │          .
12291               .           .          .    │ (jit_langhook_parse_file)
12292               .           .          .    │          .
12293 ..........................................│..................VVVVVVVVVVVVV...
12294               .           .          .    │          .       No GC in here
12295               .           .          .    │ jit-playback.c
12296               .           .          .    │   (playback of API calls)
12297               .           .          .    ───────────────> creation of functions,
12298               .           .          .               .     types, expression trees
12299               .           .          .    <──────────────── etc
12300               .           .          .    │(handle_locations: add locations to
12301               .           .          .    │ linemap and associate them with trees)
12302               .           .          .    │          .
12303               .           .          .    │          .       No GC in here
12304 ..........................................│..................AAAAAAAAAAAAA...
12305               .           .          .    │ for each function
12306               .           .          .    ──> postprocess
12307               .           .          .        │      .
12308               .           .          .        ────────────> cgraph_finalize_function
12309               .           .          .        <────────────
12310               .           .          .     <──       .
12311               .           .          .    │          .
12312               .           .          .    ──────────────────> (end of
12313               .           .          .               .       │ langhook_parse_file)
12314               .           .          .               .       │
12315               .           .          .               .   (various code)
12316               .           .          .               .       │
12317               .           .          .               .       ↓
12318               .           .          .    <───────────────── langhook:write_globals
12319               .           .          .    │          .
12320               .           .          .    │ (jit_langhook_write_globals)
12321               .           .          .    │          .
12322               .           .          .    │          .
12323               .           .          .    ──────────────────> finalize_compilation_unit
12324               .           .          .               .       │
12325               .           .          .               .   (the middle─end and backend)
12326               .           .          .               .       ↓
12327               .           .    <───────────────────────────── end of toplev::main
12328               .           .    │     .               .
12329               .           .    V───────────────────────> toplev::finalize
12330               .           .          .               . │   (purge internal state)
12331               .           .    <──────────────────────── end of toplev::finalize
12332               .           .    │     .               .
12333               .           .    │ Convert assembler to DSO ("fake.so")
12334               .           .    │     .               .
12335               .           .    │ Load DSO (dlopen "fake.so")
12336               .           .    │     .               .
12337               .           .    │ RELEASE MUTEX       .
12338               .           .    │     .               .
12339               .           .    │ end of playback::context::compile ()
12340               .           .    │     .               .
12341               .           .    │ playback::context dtor
12342               .           .     ──>  .               .
12343               .           .       │ Cleanup tempdir  .
12344               .           .       │   ("fake.so" is unlinked from the
12345               .           .       │    filesystem at this point)
12346               .           .    <──   .               .
12347               .           .    │     .               .
12348               .           .    │ end of recording::context::compile ()
12349    <───────────────────────────      .               .
12350    │          .           .          .               .
12351    V          .           .  gcc_jit_result_get_code .
12352     ──────────────────────────>      .               .
12353               .           .    │ dlsym () within loaded DSO
12354    <───────────────────────────      .               .
12355    Get (void*).           .          .               .
12356    │          .           .          .               .
12357    │ Call it  .           .          .               .
12358    ───────────────>       .          .               .
12359               .    │      .          .               .
12360               .    │      .          .               .
12361    <───────────────       .          .               .
12362    │          .           .          .               .
12363 etc│          .           .          .               .
12364    │          .           .          .               .
12365    V          .           .  gcc_jit_result_release  .
12366     ──────────────────────────>      .               .
12367               .           .    │ dlclose () the loaded DSO
12368               .           .    │    (code becomes uncallable)
12369    <───────────────────────────      .               .
12370    │          .           .          .               .
12372 @end example
12374 @noindent
12375 @end quotation
12376 @end itemize
12378 Here is a high-level summary from @code{jit-common.h}:
12380 @quotation
12382 In order to allow jit objects to be usable outside of a compile
12383 whilst working with the existing structure of GCC's code the
12384 C API is implemented in terms of a gcc::jit::recording::context,
12385 which records the calls made to it.
12387 When a gcc_jit_context is compiled, the recording context creates a
12388 playback context.  The playback context invokes the bulk of the GCC
12389 code, and within the "frontend" parsing hook, plays back the recorded
12390 API calls, creating GCC tree objects.
12392 So there are two parallel families of classes: those relating to
12393 recording, and those relating to playback:
12396 @itemize *
12398 @item 
12399 Visibility: recording objects are exposed back to client code,
12400 whereas playback objects are internal to the library.
12402 @item 
12403 Lifetime: recording objects have a lifetime equal to that of the
12404 recording context that created them, whereas playback objects only
12405 exist within the frontend hook.
12407 @item 
12408 Memory allocation: recording objects are allocated by the recording
12409 context, and automatically freed by it when the context is released,
12410 whereas playback objects are allocated within the GC heap, and
12411 garbage-collected; they can own GC-references.
12413 @item 
12414 Integration with rest of GCC: recording objects are unrelated to the
12415 rest of GCC, whereas playback objects are wrappers around "tree"
12416 instances.  Hence you can't ask a recording rvalue or lvalue what its
12417 type is, whereas you can for a playback rvalue of lvalue (since it
12418 can work with the underlying GCC tree nodes).
12420 @item 
12421 Instancing: There can be multiple recording contexts "alive" at once
12422 (albeit it only one compiling at once), whereas there can only be one
12423 playback context alive at one time (since it interacts with the GC).
12424 @end itemize
12426 Ultimately if GCC could support multiple GC heaps and contexts, and
12427 finer-grained initialization, then this recording vs playback
12428 distinction could be eliminated.
12430 During a playback, we associate objects from the recording with
12431 their counterparts during this playback.  For simplicity, we store this
12432 within the recording objects, as @code{void *m_playback_obj}, casting it to
12433 the appropriate playback object subclass.  For these casts to make
12434 sense, the two class hierarchies need to have the same structure.
12436 Note that the playback objects that @code{m_playback_obj} points to are
12437 GC-allocated, but the recording objects don't own references:
12438 these associations only exist within a part of the code where
12439 the GC doesn't collect, and are set back to NULL before the GC can
12440 run.
12441 @end quotation
12443 @node Indices and tables,Index,Internals,Top
12444 @anchor{index indices-and-tables}@anchor{17f}
12445 @unnumbered Indices and tables
12449 @itemize *
12451 @item 
12452 @emph{genindex}
12454 @item 
12455 @emph{modindex}
12457 @item 
12458 @emph{search}
12459 @end itemize
12461 @c Some notes:
12462 @c 
12463 @c The Sphinx C domain appears to lack explicit support for enum values,
12464 @c so I've been using :c:macro: for them.
12465 @c 
12466 @c See http://sphinx-doc.org/domains.html#the-c-domain
12468 @node Index,,Indices and tables,Top
12469 @unnumbered Index
12472 @printindex ge
12474 @c %**end of body
12475 @bye