1 #include <stdlib.h>
2 #include <stdio.h>
3 #include <string.h>
4 
5 #include "libgccjit.h"
6 
7 #include "harness.h"
8 
9 void
create_code(gcc_jit_context * ctxt,void * user_data)10 create_code (gcc_jit_context *ctxt, void *user_data)
11 {
12   /* Let's try to inject the equivalent of:
13       void *
14       test_memcpy (void *dest, const void *src, size_t n)
15       {
16         return __builtin_memcpy (dest, src, n);
17       }
18    */
19   gcc_jit_type *t_void_ptr
20     = gcc_jit_context_get_type (ctxt, GCC_JIT_TYPE_VOID_PTR);
21   gcc_jit_type *t_const_void_ptr
22     = gcc_jit_type_get_pointer (gcc_jit_type_get_const
23 				(gcc_jit_context_get_type
24 				 (ctxt, GCC_JIT_TYPE_VOID)));
25   gcc_jit_type *t_size_t
26     = gcc_jit_context_get_type (ctxt, GCC_JIT_TYPE_SIZE_T);
27 
28   gcc_jit_param *dest
29     = gcc_jit_context_new_param (ctxt, NULL, t_void_ptr, "dest");
30   gcc_jit_param *src
31     = gcc_jit_context_new_param (ctxt, NULL, t_const_void_ptr, "src");
32   gcc_jit_param *n = gcc_jit_context_new_param (ctxt, NULL, t_size_t, "n");
33   gcc_jit_param *params[3] = {dest, src, n};
34   gcc_jit_function *func =
35     gcc_jit_context_new_function (ctxt, NULL,
36 				  GCC_JIT_FUNCTION_EXPORTED,
37 				  t_void_ptr,
38 				  "test_memcpy",
39 				  3, params, 0);
40 
41   gcc_jit_function *jit_memcpy
42     = gcc_jit_context_get_builtin_function (ctxt, "__builtin_memcpy");
43 
44 
45   gcc_jit_block *b_initial
46     = gcc_jit_function_new_block (func, "initial");
47   gcc_jit_rvalue *args[3] = {gcc_jit_param_as_rvalue (dest),
48 			     gcc_jit_param_as_rvalue (src),
49 			     gcc_jit_param_as_rvalue (n)};
50   gcc_jit_rvalue *call
51     = gcc_jit_context_new_call (ctxt, NULL, jit_memcpy, 3, args);
52   gcc_jit_block_end_with_return (b_initial, NULL, call);
53 }
54 
55 void
verify_code(gcc_jit_context * ctxt,gcc_jit_result * result)56 verify_code (gcc_jit_context *ctxt, gcc_jit_result *result)
57 {
58   typedef void *(*test_memcpy_type) (void *, const void *, size_t);
59   CHECK_NON_NULL (result);
60   test_memcpy_type test_memcpy =
61     (test_memcpy_type)gcc_jit_result_get_code (result, "test_memcpy");
62   CHECK_NON_NULL (test_memcpy);
63 
64   int dst = 13;
65   int src = 42;
66   void *out = test_memcpy (&dst, &src, sizeof(int));
67   CHECK_VALUE(out, &dst);
68   CHECK_VALUE(dst, 42);
69 }
70