1 /* Internals of libgccjit: classes for playing back recorded API calls.
2 Copyright (C) 2013-2015 Free Software Foundation, Inc.
3 Contributed by David Malcolm <dmalcolm@redhat.com>.
5 This file is part of GCC.
7 GCC is free software; you can redistribute it and/or modify it
8 under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, or (at your option)
12 GCC is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
23 #include "coretypes.h"
29 #include "statistics.h"
31 #include "double-int.h"
33 #include "fixed-value.h"
37 #include "tree-core.h"
42 #include "plugin-api.h"
47 #include "hard-reg-set.h"
57 #include "stringpool.h"
58 #include "stor-layout.h"
59 #include "print-tree.h"
61 #include "gcc-driver-name.h"
64 #include "fold-const.h"
68 #include "jit-common.h"
69 #include "jit-logging.h"
70 #include "jit-playback.h"
71 #include "jit-result.h"
72 #include "jit-builtins.h"
73 #include "jit-tempdir.h"
76 /* gcc::jit::playback::context::build_cast uses the convert.h API,
77 which in turn requires the frontend to provide a "convert"
78 function, apparently as a fallback.
80 Hence we provide this dummy one, with the requirement that any casts
81 are handled before reaching this. */
82 extern tree
convert (tree type
, tree expr
);
85 convert (tree dst_type
, tree expr
)
87 gcc_assert (gcc::jit::active_playback_ctxt
);
88 gcc::jit::active_playback_ctxt
->add_error (NULL
, "unhandled conversion");
89 fprintf (stderr
, "input expression:\n");
91 fprintf (stderr
, "requested type:\n");
92 debug_tree (dst_type
);
93 return error_mark_node
;
99 /**********************************************************************
101 **********************************************************************/
103 /* The constructor for gcc::jit::playback::context. */
105 playback::context::context (recording::context
*ctxt
)
106 : log_user (ctxt
->get_logger ()),
107 m_recording_ctxt (ctxt
),
109 m_char_array_type_node (NULL
),
110 m_const_char_ptr (NULL
)
112 JIT_LOG_SCOPE (get_logger ());
113 m_functions
.create (0);
114 m_globals
.create (0);
115 m_source_files
.create (0);
116 m_cached_locations
.create (0);
119 /* The destructor for gcc::jit::playback::context. */
121 playback::context::~context ()
123 JIT_LOG_SCOPE (get_logger ());
125 /* Normally the playback::context is responsible for cleaning up the
126 tempdir (including "fake.so" within the filesystem).
128 In the normal case, clean it up now.
130 However m_tempdir can be NULL if the context has handed over
131 responsibility for the tempdir cleanup to the jit::result object, so
132 that the cleanup can be delayed (see PR jit/64206). If that's the
133 case this "delete NULL;" is a no-op. */
136 m_functions
.release ();
139 /* A playback::context can reference GC-managed pointers. Mark them
140 ("by hand", rather than by gengtype).
142 This is called on the active playback context (if any) by the
143 my_ggc_walker hook in the jit_root_table in dummy-frontend.c. */
151 FOR_EACH_VEC_ELT (m_functions
, i
, func
)
153 if (ggc_test_and_set_mark (func
))
158 /* Given an enum gcc_jit_types value, get a "tree" type. */
161 get_tree_node_for_type (enum gcc_jit_types type_
)
165 case GCC_JIT_TYPE_VOID
:
166 return void_type_node
;
168 case GCC_JIT_TYPE_VOID_PTR
:
169 return ptr_type_node
;
171 case GCC_JIT_TYPE_BOOL
:
172 return boolean_type_node
;
174 case GCC_JIT_TYPE_CHAR
:
175 return char_type_node
;
176 case GCC_JIT_TYPE_SIGNED_CHAR
:
177 return signed_char_type_node
;
178 case GCC_JIT_TYPE_UNSIGNED_CHAR
:
179 return unsigned_char_type_node
;
181 case GCC_JIT_TYPE_SHORT
:
182 return short_integer_type_node
;
183 case GCC_JIT_TYPE_UNSIGNED_SHORT
:
184 return short_unsigned_type_node
;
186 case GCC_JIT_TYPE_CONST_CHAR_PTR
:
188 tree const_char
= build_qualified_type (char_type_node
,
190 return build_pointer_type (const_char
);
193 case GCC_JIT_TYPE_INT
:
194 return integer_type_node
;
195 case GCC_JIT_TYPE_UNSIGNED_INT
:
196 return unsigned_type_node
;
198 case GCC_JIT_TYPE_LONG
:
199 return long_integer_type_node
;
200 case GCC_JIT_TYPE_UNSIGNED_LONG
:
201 return long_unsigned_type_node
;
203 case GCC_JIT_TYPE_LONG_LONG
:
204 return long_long_integer_type_node
;
205 case GCC_JIT_TYPE_UNSIGNED_LONG_LONG
:
206 return long_long_unsigned_type_node
;
208 case GCC_JIT_TYPE_FLOAT
:
209 return float_type_node
;
210 case GCC_JIT_TYPE_DOUBLE
:
211 return double_type_node
;
212 case GCC_JIT_TYPE_LONG_DOUBLE
:
213 return long_double_type_node
;
215 case GCC_JIT_TYPE_SIZE_T
:
216 return size_type_node
;
218 case GCC_JIT_TYPE_FILE_PTR
:
219 return fileptr_type_node
;
221 case GCC_JIT_TYPE_COMPLEX_FLOAT
:
222 return complex_float_type_node
;
223 case GCC_JIT_TYPE_COMPLEX_DOUBLE
:
224 return complex_double_type_node
;
225 case GCC_JIT_TYPE_COMPLEX_LONG_DOUBLE
:
226 return complex_long_double_type_node
;
232 /* Construct a playback::type instance (wrapping a tree) for the given
237 get_type (enum gcc_jit_types type_
)
239 tree type_node
= get_tree_node_for_type (type_
);
240 if (NULL
== type_node
)
243 "unrecognized (enum gcc_jit_types) value: %i", type_
);
247 return new type (type_node
);
250 /* Construct a playback::type instance (wrapping a tree) for the given
255 new_array_type (playback::location
*loc
,
256 playback::type
*element_type
,
259 gcc_assert (element_type
);
261 tree t
= build_array_type_nelts (element_type
->as_tree (),
266 set_tree_location (t
, loc
);
271 /* Construct a playback::field instance (wrapping a tree). */
275 new_field (location
*loc
,
282 /* compare with c/c-decl.c:grokfield and grokdeclarator. */
283 tree decl
= build_decl (UNKNOWN_LOCATION
, FIELD_DECL
,
284 get_identifier (name
), type
->as_tree ());
287 set_tree_location (decl
, loc
);
289 return new field (decl
);
292 /* Construct a playback::compound_type instance (wrapping a tree). */
294 playback::compound_type
*
296 new_compound_type (location
*loc
,
298 bool is_struct
) /* else is union */
302 /* Compare with c/c-decl.c: start_struct. */
304 tree t
= make_node (is_struct
? RECORD_TYPE
: UNION_TYPE
);
305 TYPE_NAME (t
) = get_identifier (name
);
309 set_tree_location (t
, loc
);
311 return new compound_type (t
);
315 playback::compound_type::set_fields (const auto_vec
<playback::field
*> *fields
)
317 /* Compare with c/c-decl.c: finish_struct. */
320 tree fieldlist
= NULL
;
321 for (unsigned i
= 0; i
< fields
->length (); i
++)
323 field
*f
= (*fields
)[i
];
324 DECL_CONTEXT (f
->as_tree ()) = t
;
325 fieldlist
= chainon (f
->as_tree (), fieldlist
);
327 fieldlist
= nreverse (fieldlist
);
328 TYPE_FIELDS (t
) = fieldlist
;
333 /* Construct a playback::type instance (wrapping a tree) for a function
338 new_function_type (type
*return_type
,
339 const auto_vec
<type
*> *param_types
,
345 tree
*arg_types
= (tree
*)xcalloc(param_types
->length (), sizeof(tree
*));
347 FOR_EACH_VEC_ELT (*param_types
, i
, param_type
)
348 arg_types
[i
] = param_type
->as_tree ();
353 build_varargs_function_type_array (return_type
->as_tree (),
354 param_types
->length (),
357 fn_type
= build_function_type_array (return_type
->as_tree (),
358 param_types
->length (),
362 return new type (fn_type
);
365 /* Construct a playback::param instance (wrapping a tree). */
369 new_param (location
*loc
,
375 tree inner
= build_decl (UNKNOWN_LOCATION
, PARM_DECL
,
376 get_identifier (name
), type
->as_tree ());
378 set_tree_location (inner
, loc
);
380 return new param (this, inner
);
383 /* Construct a playback::function instance. */
387 new_function (location
*loc
,
388 enum gcc_jit_function_kind kind
,
391 const auto_vec
<param
*> *params
,
393 enum built_in_function builtin_id
)
398 //can return_type be NULL?
401 tree
*arg_types
= (tree
*)xcalloc(params
->length (), sizeof(tree
*));
402 FOR_EACH_VEC_ELT (*params
, i
, param
)
403 arg_types
[i
] = TREE_TYPE (param
->as_tree ());
407 fn_type
= build_varargs_function_type_array (return_type
->as_tree (),
408 params
->length (), arg_types
);
410 fn_type
= build_function_type_array (return_type
->as_tree (),
411 params
->length (), arg_types
);
414 /* FIXME: this uses input_location: */
415 tree fndecl
= build_fn_decl (name
, fn_type
);
418 set_tree_location (fndecl
, loc
);
420 tree resdecl
= build_decl (UNKNOWN_LOCATION
, RESULT_DECL
,
421 NULL_TREE
, return_type
->as_tree ());
422 DECL_ARTIFICIAL (resdecl
) = 1;
423 DECL_IGNORED_P (resdecl
) = 1;
424 DECL_RESULT (fndecl
) = resdecl
;
428 DECL_FUNCTION_CODE (fndecl
) = builtin_id
;
429 gcc_assert (loc
== NULL
);
430 DECL_SOURCE_LOCATION (fndecl
) = BUILTINS_LOCATION
;
432 DECL_BUILT_IN_CLASS (fndecl
) =
433 builtins_manager::get_class (builtin_id
);
434 set_builtin_decl (builtin_id
, fndecl
,
435 builtins_manager::implicit_p (builtin_id
));
437 builtins_manager
*bm
= get_builtins_manager ();
438 tree attrs
= bm
->get_attrs_tree (builtin_id
);
440 decl_attributes (&fndecl
, attrs
, ATTR_FLAG_BUILT_IN
);
442 decl_attributes (&fndecl
, NULL_TREE
, 0);
445 if (kind
!= GCC_JIT_FUNCTION_IMPORTED
)
447 tree param_decl_list
= NULL
;
448 FOR_EACH_VEC_ELT (*params
, i
, param
)
450 param_decl_list
= chainon (param
->as_tree (), param_decl_list
);
453 /* The param list was created in reverse order; fix it: */
454 param_decl_list
= nreverse (param_decl_list
);
457 for (t
= param_decl_list
; t
; t
= DECL_CHAIN (t
))
459 DECL_CONTEXT (t
) = fndecl
;
460 DECL_ARG_TYPE (t
) = TREE_TYPE (t
);
463 /* Set it up on DECL_ARGUMENTS */
464 DECL_ARGUMENTS(fndecl
) = param_decl_list
;
467 if (kind
== GCC_JIT_FUNCTION_ALWAYS_INLINE
)
469 DECL_DECLARED_INLINE_P (fndecl
) = 1;
471 /* Add attribute "always_inline": */
472 DECL_ATTRIBUTES (fndecl
) =
473 tree_cons (get_identifier ("always_inline"),
475 DECL_ATTRIBUTES (fndecl
));
478 function
*func
= new function (this, fndecl
, kind
);
479 m_functions
.safe_push (func
);
483 /* Construct a playback::lvalue instance (wrapping a tree). */
487 new_global (location
*loc
,
488 enum gcc_jit_global_kind kind
,
494 tree inner
= build_decl (UNKNOWN_LOCATION
, VAR_DECL
,
495 get_identifier (name
),
497 TREE_PUBLIC (inner
) = (kind
!= GCC_JIT_GLOBAL_INTERNAL
);
498 DECL_COMMON (inner
) = 1;
504 case GCC_JIT_GLOBAL_EXPORTED
:
505 TREE_STATIC (inner
) = 1;
508 case GCC_JIT_GLOBAL_INTERNAL
:
509 TREE_STATIC (inner
) = 1;
512 case GCC_JIT_GLOBAL_IMPORTED
:
513 DECL_EXTERNAL (inner
) = 1;
518 set_tree_location (inner
, loc
);
520 varpool_node::get_create (inner
);
522 m_globals
.safe_push (inner
);
524 return new lvalue (this, inner
);
527 /* Implementation of the various
528 gcc::jit::playback::context::new_rvalue_from_const <HOST_TYPE>
530 Each of these constructs a playback::rvalue instance (wrapping a tree).
532 These specializations are required to be in the same namespace
533 as the template, hence we now have to enter the gcc::jit::playback
539 /* Specialization of making an rvalue from a const, for host <int>. */
544 new_rvalue_from_const
<int> (type
*type
,
547 // FIXME: type-checking, or coercion?
548 tree inner_type
= type
->as_tree ();
549 if (INTEGRAL_TYPE_P (inner_type
))
551 tree inner
= build_int_cst (inner_type
, value
);
552 return new rvalue (this, inner
);
556 REAL_VALUE_TYPE real_value
;
557 real_from_integer (&real_value
, VOIDmode
, value
, SIGNED
);
558 tree inner
= build_real (inner_type
, real_value
);
559 return new rvalue (this, inner
);
563 /* Specialization of making an rvalue from a const, for host <long>. */
568 new_rvalue_from_const
<long> (type
*type
,
571 // FIXME: type-checking, or coercion?
572 tree inner_type
= type
->as_tree ();
573 if (INTEGRAL_TYPE_P (inner_type
))
575 tree inner
= build_int_cst (inner_type
, value
);
576 return new rvalue (this, inner
);
580 REAL_VALUE_TYPE real_value
;
581 real_from_integer (&real_value
, VOIDmode
, value
, SIGNED
);
582 tree inner
= build_real (inner_type
, real_value
);
583 return new rvalue (this, inner
);
587 /* Specialization of making an rvalue from a const, for host <double>. */
592 new_rvalue_from_const
<double> (type
*type
,
595 // FIXME: type-checking, or coercion?
596 tree inner_type
= type
->as_tree ();
598 /* We have a "double", we want a REAL_VALUE_TYPE.
600 real.c:real_from_target appears to require the representation to be
601 split into 32-bit values, and then sent as an pair of host long
603 REAL_VALUE_TYPE real_value
;
607 uint32_t as_uint32s
[2];
610 long int as_long_ints
[2];
611 as_long_ints
[0] = u
.as_uint32s
[0];
612 as_long_ints
[1] = u
.as_uint32s
[1];
613 real_from_target (&real_value
, as_long_ints
, DFmode
);
614 tree inner
= build_real (inner_type
, real_value
);
615 return new rvalue (this, inner
);
618 /* Specialization of making an rvalue from a const, for host <void *>. */
623 new_rvalue_from_const
<void *> (type
*type
,
626 tree inner_type
= type
->as_tree ();
627 /* FIXME: how to ensure we have a wide enough type? */
628 tree inner
= build_int_cstu (inner_type
, (unsigned HOST_WIDE_INT
)value
);
629 return new rvalue (this, inner
);
632 /* We're done implementing the specializations of
633 gcc::jit::playback::context::new_rvalue_from_const <T>
634 so we can exit the gcc::jit::playback namespace. */
636 } // namespace playback
638 /* Construct a playback::rvalue instance (wrapping a tree). */
642 new_string_literal (const char *value
)
644 tree t_str
= build_string (strlen (value
), value
);
645 gcc_assert (m_char_array_type_node
);
646 TREE_TYPE (t_str
) = m_char_array_type_node
;
648 /* Convert to (const char*), loosely based on
649 c/c-typeck.c: array_to_pointer_conversion,
650 by taking address of start of string. */
651 tree t_addr
= build1 (ADDR_EXPR
, m_const_char_ptr
, t_str
);
653 return new rvalue (this, t_addr
);
656 /* Coerce a tree expression into a boolean tree expression. */
660 as_truth_value (tree expr
, location
*loc
)
662 /* Compare to c-typeck.c:c_objc_common_truthvalue_conversion */
663 tree typed_zero
= fold_build1 (CONVERT_EXPR
,
667 set_tree_location (typed_zero
, loc
);
669 expr
= build2 (NE_EXPR
, integer_type_node
, expr
, typed_zero
);
671 set_tree_location (expr
, loc
);
676 /* For use by jit_langhook_write_globals.
677 Calls varpool_node::finalize_decl on each global. */
681 write_global_decls_1 ()
683 /* Compare with e.g. the C frontend's c_write_global_declarations. */
684 JIT_LOG_SCOPE (get_logger ());
688 FOR_EACH_VEC_ELT (m_globals
, i
, decl
)
690 gcc_assert (TREE_CODE (decl
) == VAR_DECL
);
691 varpool_node::finalize_decl (decl
);
695 /* For use by jit_langhook_write_globals.
696 Calls debug_hooks->global_decl on each global. */
700 write_global_decls_2 ()
702 /* Compare with e.g. the C frontend's c_write_global_declarations_2. */
703 JIT_LOG_SCOPE (get_logger ());
707 FOR_EACH_VEC_ELT (m_globals
, i
, decl
)
709 gcc_assert (TREE_CODE (decl
) == VAR_DECL
);
710 debug_hooks
->global_decl (decl
);
715 /* Construct a playback::rvalue instance (wrapping a tree) for a
720 new_unary_op (location
*loc
,
721 enum gcc_jit_unary_op op
,
725 // FIXME: type-checking, or coercion?
726 enum tree_code inner_op
;
728 gcc_assert (result_type
);
731 tree node
= a
->as_tree ();
732 tree inner_result
= NULL
;
737 add_error (loc
, "unrecognized (enum gcc_jit_unary_op) value: %i", op
);
740 case GCC_JIT_UNARY_OP_MINUS
:
741 inner_op
= NEGATE_EXPR
;
744 case GCC_JIT_UNARY_OP_BITWISE_NEGATE
:
745 inner_op
= BIT_NOT_EXPR
;
748 case GCC_JIT_UNARY_OP_LOGICAL_NEGATE
:
749 node
= as_truth_value (node
, loc
);
750 inner_result
= invert_truthvalue (node
);
752 set_tree_location (inner_result
, loc
);
753 return new rvalue (this, inner_result
);
755 case GCC_JIT_UNARY_OP_ABS
:
760 inner_result
= build1 (inner_op
,
761 result_type
->as_tree (),
764 set_tree_location (inner_result
, loc
);
766 return new rvalue (this, inner_result
);
769 /* Construct a playback::rvalue instance (wrapping a tree) for a
774 new_binary_op (location
*loc
,
775 enum gcc_jit_binary_op op
,
777 rvalue
*a
, rvalue
*b
)
779 // FIXME: type-checking, or coercion?
780 enum tree_code inner_op
;
782 gcc_assert (result_type
);
786 tree node_a
= a
->as_tree ();
787 tree node_b
= b
->as_tree ();
792 add_error (loc
, "unrecognized (enum gcc_jit_binary_op) value: %i", op
);
795 case GCC_JIT_BINARY_OP_PLUS
:
796 inner_op
= PLUS_EXPR
;
799 case GCC_JIT_BINARY_OP_MINUS
:
800 inner_op
= MINUS_EXPR
;
803 case GCC_JIT_BINARY_OP_MULT
:
804 inner_op
= MULT_EXPR
;
807 case GCC_JIT_BINARY_OP_DIVIDE
:
808 if (FLOAT_TYPE_P (result_type
->as_tree ()))
809 /* Floating-point division: */
810 inner_op
= RDIV_EXPR
;
812 /* Truncating to zero: */
813 inner_op
= TRUNC_DIV_EXPR
;
816 case GCC_JIT_BINARY_OP_MODULO
:
817 inner_op
= TRUNC_MOD_EXPR
;
820 case GCC_JIT_BINARY_OP_BITWISE_AND
:
821 inner_op
= BIT_AND_EXPR
;
824 case GCC_JIT_BINARY_OP_BITWISE_XOR
:
825 inner_op
= BIT_XOR_EXPR
;
828 case GCC_JIT_BINARY_OP_BITWISE_OR
:
829 inner_op
= BIT_IOR_EXPR
;
832 case GCC_JIT_BINARY_OP_LOGICAL_AND
:
833 node_a
= as_truth_value (node_a
, loc
);
834 node_b
= as_truth_value (node_b
, loc
);
835 inner_op
= TRUTH_ANDIF_EXPR
;
838 case GCC_JIT_BINARY_OP_LOGICAL_OR
:
839 node_a
= as_truth_value (node_a
, loc
);
840 node_b
= as_truth_value (node_b
, loc
);
841 inner_op
= TRUTH_ORIF_EXPR
;
844 case GCC_JIT_BINARY_OP_LSHIFT
:
845 inner_op
= LSHIFT_EXPR
;
848 case GCC_JIT_BINARY_OP_RSHIFT
:
849 inner_op
= RSHIFT_EXPR
;
853 tree inner_expr
= build2 (inner_op
,
854 result_type
->as_tree (),
858 set_tree_location (inner_expr
, loc
);
860 return new rvalue (this, inner_expr
);
863 /* Construct a playback::rvalue instance (wrapping a tree) for a
868 new_comparison (location
*loc
,
869 enum gcc_jit_comparison op
,
870 rvalue
*a
, rvalue
*b
)
872 // FIXME: type-checking, or coercion?
873 enum tree_code inner_op
;
881 add_error (loc
, "unrecognized (enum gcc_jit_comparison) value: %i", op
);
884 case GCC_JIT_COMPARISON_EQ
:
887 case GCC_JIT_COMPARISON_NE
:
890 case GCC_JIT_COMPARISON_LT
:
893 case GCC_JIT_COMPARISON_LE
:
896 case GCC_JIT_COMPARISON_GT
:
899 case GCC_JIT_COMPARISON_GE
:
904 tree inner_expr
= build2 (inner_op
,
909 set_tree_location (inner_expr
, loc
);
910 return new rvalue (this, inner_expr
);
913 /* Construct a playback::rvalue instance (wrapping a tree) for a
918 build_call (location
*loc
,
920 const auto_vec
<rvalue
*> *args
)
922 vec
<tree
, va_gc
> *tree_args
;
923 vec_alloc (tree_args
, args
->length ());
924 for (unsigned i
= 0; i
< args
->length (); i
++)
925 tree_args
->quick_push ((*args
)[i
]->as_tree ());
928 set_tree_location (fn_ptr
, loc
);
930 tree fn
= TREE_TYPE (fn_ptr
);
931 tree fn_type
= TREE_TYPE (fn
);
932 tree return_type
= TREE_TYPE (fn_type
);
934 return new rvalue (this,
935 build_call_vec (return_type
,
938 /* see c-typeck.c: build_function_call
939 which calls build_function_call_vec
941 which does lots of checking, then:
942 result = build_call_array_loc (loc, TREE_TYPE (fntype),
943 function, nargs, argarray);
945 (see also build_call_vec)
949 /* Construct a playback::rvalue instance (wrapping a tree) for a
950 call to a specific function. */
954 new_call (location
*loc
,
956 const auto_vec
<rvalue
*> *args
)
962 fndecl
= func
->as_fndecl ();
964 tree fntype
= TREE_TYPE (fndecl
);
966 tree fn
= build1 (ADDR_EXPR
, build_pointer_type (fntype
), fndecl
);
968 return build_call (loc
, fn
, args
);
971 /* Construct a playback::rvalue instance (wrapping a tree) for a
972 call through a function pointer. */
976 new_call_through_ptr (location
*loc
,
978 const auto_vec
<rvalue
*> *args
)
981 tree t_fn_ptr
= fn_ptr
->as_tree ();
983 return build_call (loc
, t_fn_ptr
, args
);
986 /* Construct a tree for a cast. */
989 playback::context::build_cast (playback::location
*loc
,
990 playback::rvalue
*expr
,
991 playback::type
*type_
)
993 /* For comparison, see:
994 - c/c-typeck.c:build_c_cast
995 - c/c-convert.c: convert
998 Only some kinds of cast are currently supported here. */
999 tree t_expr
= expr
->as_tree ();
1000 tree t_dst_type
= type_
->as_tree ();
1002 t_ret
= targetm
.convert_to_type (t_dst_type
, t_expr
);
1005 enum tree_code dst_code
= TREE_CODE (t_dst_type
);
1010 t_ret
= convert_to_integer (t_dst_type
, t_expr
);
1014 /* Compare with c_objc_common_truthvalue_conversion and
1015 c_common_truthvalue_conversion. */
1016 /* For now, convert to: (t_expr != 0) */
1017 t_ret
= build2 (NE_EXPR
, t_dst_type
,
1019 build_int_cst (TREE_TYPE (t_expr
), 0));
1023 t_ret
= convert_to_real (t_dst_type
, t_expr
);
1027 t_ret
= build1 (NOP_EXPR
, t_dst_type
, t_expr
);
1031 add_error (loc
, "couldn't handle cast during playback");
1032 fprintf (stderr
, "input expression:\n");
1033 debug_tree (t_expr
);
1034 fprintf (stderr
, "requested type:\n");
1035 debug_tree (t_dst_type
);
1036 return error_mark_node
;
1039 if (TREE_CODE (t_ret
) != C_MAYBE_CONST_EXPR
)
1040 t_ret
= fold (t_ret
);
1045 /* Construct a playback::rvalue instance (wrapping a tree) for a
1050 new_cast (playback::location
*loc
,
1051 playback::rvalue
*expr
,
1052 playback::type
*type_
)
1055 tree t_cast
= build_cast (loc
, expr
, type_
);
1057 set_tree_location (t_cast
, loc
);
1058 return new rvalue (this, t_cast
);
1061 /* Construct a playback::lvalue instance (wrapping a tree) for an
1066 new_array_access (location
*loc
,
1073 /* For comparison, see:
1074 c/c-typeck.c: build_array_ref
1075 c-family/c-common.c: pointer_int_sum
1077 tree t_ptr
= ptr
->as_tree ();
1078 tree t_index
= index
->as_tree ();
1079 tree t_type_ptr
= TREE_TYPE (t_ptr
);
1080 tree t_type_star_ptr
= TREE_TYPE (t_type_ptr
);
1082 if (TREE_CODE (t_type_ptr
) == ARRAY_TYPE
)
1084 tree t_result
= build4 (ARRAY_REF
, t_type_star_ptr
, t_ptr
, t_index
,
1085 NULL_TREE
, NULL_TREE
);
1087 set_tree_location (t_result
, loc
);
1088 return new lvalue (this, t_result
);
1092 /* Convert index to an offset in bytes. */
1093 tree t_sizeof
= size_in_bytes (t_type_star_ptr
);
1094 t_index
= fold_build1 (CONVERT_EXPR
, sizetype
, t_index
);
1095 tree t_offset
= build2 (MULT_EXPR
, sizetype
, t_index
, t_sizeof
);
1097 /* Locate (ptr + offset). */
1098 tree t_address
= build2 (POINTER_PLUS_EXPR
, t_type_ptr
, t_ptr
, t_offset
);
1100 tree t_indirection
= build1 (INDIRECT_REF
, t_type_star_ptr
, t_address
);
1103 set_tree_location (t_sizeof
, loc
);
1104 set_tree_location (t_offset
, loc
);
1105 set_tree_location (t_address
, loc
);
1106 set_tree_location (t_indirection
, loc
);
1109 return new lvalue (this, t_indirection
);
1113 /* Construct a tree for a field access. */
1117 new_field_access (location
*loc
,
1124 /* Compare with c/c-typeck.c:lookup_field, build_indirect_ref, and
1125 build_component_ref. */
1126 tree type
= TREE_TYPE (datum
);
1128 gcc_assert (TREE_CODE (type
) != POINTER_TYPE
);
1130 tree t_field
= field
->as_tree ();
1131 tree ref
= build3 (COMPONENT_REF
, TREE_TYPE (t_field
), datum
,
1132 t_field
, NULL_TREE
);
1134 set_tree_location (ref
, loc
);
1138 /* Construct a tree for a dereference. */
1142 new_dereference (tree ptr
,
1147 tree type
= TREE_TYPE (TREE_TYPE(ptr
));
1148 tree datum
= build1 (INDIRECT_REF
, type
, ptr
);
1150 set_tree_location (datum
, loc
);
1154 /* Construct a playback::lvalue instance (wrapping a tree) for a
1159 access_field (location
*loc
,
1162 tree datum
= as_tree ();
1163 tree ref
= get_context ()->new_field_access (loc
, datum
, field
);
1166 return new lvalue (get_context (), ref
);
1169 /* Construct a playback::rvalue instance (wrapping a tree) for a
1174 access_field (location
*loc
,
1177 tree datum
= as_tree ();
1178 tree ref
= get_context ()->new_field_access (loc
, datum
, field
);
1181 return new rvalue (get_context (), ref
);
1184 /* Construct a playback::lvalue instance (wrapping a tree) for a
1185 dereferenced field access. */
1189 dereference_field (location
*loc
,
1192 tree ptr
= as_tree ();
1193 tree datum
= get_context ()->new_dereference (ptr
, loc
);
1196 tree ref
= get_context ()->new_field_access (loc
, datum
, field
);
1199 return new lvalue (get_context (), ref
);
1202 /* Construct a playback::lvalue instance (wrapping a tree) for a
1207 dereference (location
*loc
)
1209 tree ptr
= as_tree ();
1210 tree datum
= get_context ()->new_dereference (ptr
, loc
);
1211 return new lvalue (get_context (), datum
);
1214 /* Construct a playback::rvalue instance (wrapping a tree) for an
1219 get_address (location
*loc
)
1221 tree t_lvalue
= as_tree ();
1222 tree t_thistype
= TREE_TYPE (t_lvalue
);
1223 tree t_ptrtype
= build_pointer_type (t_thistype
);
1224 tree ptr
= build1 (ADDR_EXPR
, t_ptrtype
, t_lvalue
);
1226 get_context ()->set_tree_location (ptr
, loc
);
1227 return new rvalue (get_context (), ptr
);
1230 /* The wrapper subclasses are GC-managed, but can own non-GC memory.
1231 Provide this finalization hook for calling then they are collected,
1232 which calls the finalizer vfunc. This allows them to call "release"
1233 on any vec<> within them. */
1236 wrapper_finalizer (void *ptr
)
1238 playback::wrapper
*wrapper
= reinterpret_cast <playback::wrapper
*> (ptr
);
1239 wrapper
->finalizer ();
1242 /* gcc::jit::playback::wrapper subclasses are GC-managed:
1243 allocate them using ggc_internal_cleared_alloc. */
1247 operator new (size_t sz
)
1249 return ggc_internal_cleared_alloc (sz
, wrapper_finalizer
, 0, 1);
1253 /* Constructor for gcc:jit::playback::function. */
1255 playback::function::
1256 function (context
*ctxt
,
1258 enum gcc_jit_function_kind kind
)
1260 m_inner_fndecl (fndecl
),
1261 m_inner_bind_expr (NULL
),
1264 if (m_kind
!= GCC_JIT_FUNCTION_IMPORTED
)
1266 /* Create a BIND_EXPR, and within it, a statement list. */
1267 m_stmt_list
= alloc_stmt_list ();
1268 m_stmt_iter
= tsi_start (m_stmt_list
);
1269 m_inner_block
= make_node (BLOCK
);
1271 build3 (BIND_EXPR
, void_type_node
, NULL
, m_stmt_list
, m_inner_block
);
1275 m_inner_block
= NULL
;
1280 /* Hand-written GC-marking hook for playback functions. */
1283 playback::function::
1286 gt_ggc_m_9tree_node (m_inner_fndecl
);
1287 gt_ggc_m_9tree_node (m_inner_bind_expr
);
1288 gt_ggc_m_9tree_node (m_stmt_list
);
1289 gt_ggc_m_9tree_node (m_inner_block
);
1292 /* Don't leak vec's internal buffer (in non-GC heap) when we are
1296 playback::function::finalizer ()
1298 m_blocks
.release ();
1301 /* Get the return type of a playback function, in tree form. */
1304 playback::function::
1305 get_return_type_as_tree () const
1307 return TREE_TYPE (TREE_TYPE(m_inner_fndecl
));
1310 /* Construct a new local within this playback::function. */
1313 playback::function::
1314 new_local (location
*loc
,
1320 tree inner
= build_decl (UNKNOWN_LOCATION
, VAR_DECL
,
1321 get_identifier (name
),
1323 DECL_CONTEXT (inner
) = this->m_inner_fndecl
;
1325 /* Prepend to BIND_EXPR_VARS: */
1326 DECL_CHAIN (inner
) = BIND_EXPR_VARS (m_inner_bind_expr
);
1327 BIND_EXPR_VARS (m_inner_bind_expr
) = inner
;
1330 set_tree_location (inner
, loc
);
1331 return new lvalue (m_ctxt
, inner
);
1334 /* Construct a new block within this playback::function. */
1337 playback::function::
1338 new_block (const char *name
)
1340 gcc_assert (m_kind
!= GCC_JIT_FUNCTION_IMPORTED
);
1342 block
*result
= new playback::block (this, name
);
1343 m_blocks
.safe_push (result
);
1347 /* Build a statement list for the function as a whole out of the
1348 lists of statements for the individual blocks, building labels
1352 playback::function::
1358 JIT_LOG_SCOPE (m_ctxt
->get_logger ());
1360 FOR_EACH_VEC_ELT (m_blocks
, i
, b
)
1365 b
->m_label_expr
= build1 (LABEL_EXPR
,
1367 b
->as_label_decl ());
1368 tsi_link_after (&m_stmt_iter
, b
->m_label_expr
, TSI_CONTINUE_LINKING
);
1370 FOR_EACH_VEC_ELT (b
->m_stmts
, j
, stmt
)
1371 tsi_link_after (&m_stmt_iter
, stmt
, TSI_CONTINUE_LINKING
);
1375 /* Finish compiling the given function, potentially running the
1377 The function will have a statement list by now.
1378 Amongst other things, this gimplifies the statement list,
1379 and calls cgraph_node::finalize_function on the function. */
1382 playback::function::
1385 JIT_LOG_SCOPE (m_ctxt
->get_logger ());
1387 if (m_ctxt
->get_bool_option (GCC_JIT_BOOL_OPTION_DUMP_INITIAL_TREE
))
1388 debug_tree (m_stmt_list
);
1390 /* Do we need this to force cgraphunit.c to output the function? */
1391 if (m_kind
== GCC_JIT_FUNCTION_EXPORTED
)
1393 DECL_EXTERNAL (m_inner_fndecl
) = 0;
1394 DECL_PRESERVE_P (m_inner_fndecl
) = 1;
1397 if (m_kind
== GCC_JIT_FUNCTION_INTERNAL
1398 ||m_kind
== GCC_JIT_FUNCTION_ALWAYS_INLINE
)
1400 DECL_EXTERNAL (m_inner_fndecl
) = 0;
1401 TREE_PUBLIC (m_inner_fndecl
) = 0;
1404 if (m_kind
!= GCC_JIT_FUNCTION_IMPORTED
)
1406 /* Seem to need this in gimple-low.c: */
1407 gcc_assert (m_inner_block
);
1408 DECL_INITIAL (m_inner_fndecl
) = m_inner_block
;
1410 /* how to add to function? the following appears to be how to
1411 set the body of a m_inner_fndecl: */
1412 DECL_SAVED_TREE(m_inner_fndecl
) = m_inner_bind_expr
;
1414 /* Ensure that locals appear in the debuginfo. */
1415 BLOCK_VARS (m_inner_block
) = BIND_EXPR_VARS (m_inner_bind_expr
);
1417 //debug_tree (m_inner_fndecl);
1419 /* Convert to gimple: */
1420 //printf("about to gimplify_function_tree\n");
1421 gimplify_function_tree (m_inner_fndecl
);
1422 //printf("finished gimplify_function_tree\n");
1424 current_function_decl
= m_inner_fndecl
;
1425 if (m_ctxt
->get_bool_option (GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE
))
1426 dump_function_to_file (m_inner_fndecl
, stderr
, TDF_VOPS
|TDF_MEMSYMS
|TDF_LINENO
);
1427 //debug_tree (m_inner_fndecl);
1429 //printf("about to add to cgraph\n");
1430 /* Add to cgraph: */
1431 cgraph_node::finalize_function (m_inner_fndecl
, false);
1432 /* This can trigger a collection, so we need to have all of
1433 the funcs as roots. */
1435 current_function_decl
= NULL
;
1439 /* Don't leak vec's internal buffer (in non-GC heap) when we are
1443 playback::block::finalizer ()
1448 /* Add an eval of the rvalue to the function's statement list. */
1452 add_eval (location
*loc
,
1455 gcc_assert (rvalue
);
1458 set_tree_location (rvalue
->as_tree (), loc
);
1460 add_stmt (rvalue
->as_tree ());
1463 /* Add an assignment to the function's statement list. */
1467 add_assignment (location
*loc
,
1471 gcc_assert (lvalue
);
1472 gcc_assert (rvalue
);
1474 tree t_lvalue
= lvalue
->as_tree ();
1475 tree t_rvalue
= rvalue
->as_tree ();
1476 if (TREE_TYPE (t_rvalue
) != TREE_TYPE (t_lvalue
))
1478 t_rvalue
= build1 (CONVERT_EXPR
,
1479 TREE_TYPE (t_lvalue
),
1482 set_tree_location (t_rvalue
, loc
);
1486 build2 (MODIFY_EXPR
, TREE_TYPE (t_lvalue
),
1487 t_lvalue
, t_rvalue
);
1489 set_tree_location (stmt
, loc
);
1493 /* Add a comment to the function's statement list.
1494 For now this is done by adding a dummy label. */
1498 add_comment (location
*loc
,
1501 /* Wrap the text in C-style comment delimiters. */
1503 (3 /* opening delim */
1505 + 3 /* closing delim */
1506 + 1 /* terminator */);
1507 char *wrapped
= (char *)ggc_internal_alloc (sz
);
1508 snprintf (wrapped
, sz
, "/* %s */", text
);
1510 /* For now we simply implement this by adding a dummy label with a name
1511 containing the given text. */
1512 tree identifier
= get_identifier (wrapped
);
1513 tree label_decl
= build_decl (UNKNOWN_LOCATION
, LABEL_DECL
,
1514 identifier
, void_type_node
);
1515 DECL_CONTEXT (label_decl
) = m_func
->as_fndecl ();
1517 tree label_expr
= build1 (LABEL_EXPR
, void_type_node
, label_decl
);
1519 set_tree_location (label_expr
, loc
);
1520 add_stmt (label_expr
);
1523 /* Add a conditional jump statement to the function's statement list. */
1527 add_conditional (location
*loc
,
1532 gcc_assert (boolval
);
1533 gcc_assert (on_true
);
1534 gcc_assert (on_false
);
1536 /* COND_EXPR wants statement lists for the true/false operands, but we
1538 Shim it by creating jumps to the labels */
1539 tree true_jump
= build1 (GOTO_EXPR
, void_type_node
,
1540 on_true
->as_label_decl ());
1542 set_tree_location (true_jump
, loc
);
1544 tree false_jump
= build1 (GOTO_EXPR
, void_type_node
,
1545 on_false
->as_label_decl ());
1547 set_tree_location (false_jump
, loc
);
1550 build3 (COND_EXPR
, void_type_node
, boolval
->as_tree (),
1551 true_jump
, false_jump
);
1553 set_tree_location (stmt
, loc
);
1557 /* Add an unconditional jump statement to the function's statement list. */
1561 add_jump (location
*loc
,
1564 gcc_assert (target
);
1566 // see c_finish_loop
1567 //tree top = build1 (LABEL_EXPR, void_type_node, NULL_TREE);
1570 //tree stmt = build_and_jump (&LABEL_EXPR_LABEL (target->label_));
1571 TREE_USED (target
->as_label_decl ()) = 1;
1572 tree stmt
= build1 (GOTO_EXPR
, void_type_node
, target
->as_label_decl ());
1574 set_tree_location (stmt
, loc
);
1580 c_finish_goto_label (location_t loc, tree label)
1582 tree decl = lookup_label_for_goto (loc, label);
1585 TREE_USED (decl) = 1;
1587 tree t = build1 (GOTO_EXPR, void_type_node, decl);
1588 SET_EXPR_LOCATION (t, loc);
1589 return add_stmt (t);
1596 /* Add a return statement to the function's statement list. */
1600 add_return (location
*loc
,
1603 tree modify_retval
= NULL
;
1604 tree return_type
= m_func
->get_return_type_as_tree ();
1607 tree t_lvalue
= DECL_RESULT (m_func
->as_fndecl ());
1608 tree t_rvalue
= rvalue
->as_tree ();
1609 if (TREE_TYPE (t_rvalue
) != TREE_TYPE (t_lvalue
))
1610 t_rvalue
= build1 (CONVERT_EXPR
,
1611 TREE_TYPE (t_lvalue
),
1613 modify_retval
= build2 (MODIFY_EXPR
, return_type
,
1614 t_lvalue
, t_rvalue
);
1616 set_tree_location (modify_retval
, loc
);
1618 tree return_stmt
= build1 (RETURN_EXPR
, return_type
,
1621 set_tree_location (return_stmt
, loc
);
1623 add_stmt (return_stmt
);
1626 /* Constructor for gcc::jit::playback::block. */
1629 block (function
*func
,
1639 identifier
= get_identifier (name
);
1642 m_label_decl
= build_decl (UNKNOWN_LOCATION
, LABEL_DECL
,
1643 identifier
, void_type_node
);
1644 DECL_CONTEXT (m_label_decl
) = func
->as_fndecl ();
1645 m_label_expr
= NULL
;
1648 /* A subclass of auto_vec <char *> that frees all of its elements on
1651 class auto_argvec
: public auto_vec
<char *>
1657 /* auto_argvec's dtor, freeing all contained strings, automatically
1658 chaining up to ~auto_vec <char *>, which frees the internal buffer. */
1660 auto_argvec::~auto_argvec ()
1664 FOR_EACH_VEC_ELT (*this, i
, str
)
1668 /* Compile a playback::context:
1670 - Use the context's options to cconstruct command-line options, and
1671 call into the rest of GCC (toplev::main).
1672 - Assuming it succeeds, we have a .s file.
1673 - We then run the "postprocess" vfunc:
1675 (A) In-memory compile ("gcc_jit_context_compile")
1677 For an in-memory compile we have the playback::compile_to_memory
1678 subclass; "postprocess" will convert the .s file to a .so DSO,
1679 and load it in memory (via dlopen), wrapping the result up as
1680 a jit::result and returning it.
1682 (B) Compile to file ("gcc_jit_context_compile_to_file")
1684 When compiling to a file, we have the playback::compile_to_file
1685 subclass; "postprocess" will either copy the .s file to the
1686 destination (for GCC_JIT_OUTPUT_KIND_ASSEMBLER), or invoke
1687 the driver to convert it as necessary, copying the result. */
1693 JIT_LOG_SCOPE (get_logger ());
1695 const char *ctxt_progname
;
1697 int keep_intermediates
=
1698 get_bool_option (GCC_JIT_BOOL_OPTION_KEEP_INTERMEDIATES
);
1700 m_tempdir
= new tempdir (get_logger (), keep_intermediates
);
1701 if (!m_tempdir
->create ())
1704 /* Call into the rest of gcc.
1705 For now, we have to assemble command-line options to pass into
1706 toplev::main, so that they can be parsed. */
1708 /* Pass in user-provided program name as argv0, if any, so that it
1709 makes it into GCC's "progname" global, used in various diagnostics. */
1710 ctxt_progname
= get_str_option (GCC_JIT_STR_OPTION_PROGNAME
);
1713 ctxt_progname
= "libgccjit.so";
1715 auto_vec
<recording::requested_dump
> requested_dumps
;
1716 m_recording_ctxt
->get_all_requested_dumps (&requested_dumps
);
1718 /* Acquire the JIT mutex and set "this" as the active playback ctxt. */
1721 auto_argvec fake_args
;
1722 make_fake_args (&fake_args
, ctxt_progname
, &requested_dumps
);
1723 if (errors_occurred ())
1729 /* This runs the compiler. */
1730 toplev
toplev (false, /* use_TV_TOTAL */
1731 false); /* init_signals */
1732 enter_scope ("toplev::main");
1734 for (unsigned i
= 0; i
< fake_args
.length (); i
++)
1735 get_logger ()->log ("argv[%i]: %s", i
, fake_args
[i
]);
1736 toplev
.main (fake_args
.length (),
1737 const_cast <char **> (fake_args
.address ()));
1738 exit_scope ("toplev::main");
1740 /* Extracting dumps makes use of the gcc::dump_manager, hence we
1741 need to do it between toplev::main (which creates the dump manager)
1742 and toplev::finalize (which deletes it). */
1743 extract_any_requested_dumps (&requested_dumps
);
1745 /* Clean up the compiler. */
1746 enter_scope ("toplev::finalize");
1748 exit_scope ("toplev::finalize");
1750 /* Ideally we would release the jit mutex here, but we can't yet since
1751 followup activities use timevars, which are global state. */
1753 if (errors_occurred ())
1759 if (get_bool_option (GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE
))
1760 dump_generated_code ();
1762 /* We now have a .s file.
1764 Run any postprocessing steps. This will either convert the .s file to
1765 a .so DSO, and load it in memory (playback::compile_to_memory), or
1766 convert the .s file to the requested output format, and copy it to a
1767 given file (playback::compile_to_file). */
1768 postprocess (ctxt_progname
);
1773 /* Implementation of class gcc::jit::playback::compile_to_memory,
1774 a subclass of gcc::jit::playback::context. */
1776 /* playback::compile_to_memory's trivial constructor. */
1778 playback::compile_to_memory::compile_to_memory (recording::context
*ctxt
) :
1779 playback::context (ctxt
),
1782 JIT_LOG_SCOPE (get_logger ());
1785 /* Implementation of the playback::context::process vfunc for compiling
1788 Convert the .s file to a .so DSO, and load it in memory (via dlopen),
1789 wrapping the result up as a jit::result and returning it. */
1792 playback::compile_to_memory::postprocess (const char *ctxt_progname
)
1794 JIT_LOG_SCOPE (get_logger ());
1795 convert_to_dso (ctxt_progname
);
1796 if (errors_occurred ())
1798 m_result
= dlopen_built_dso ();
1801 /* Implementation of class gcc::jit::playback::compile_to_file,
1802 a subclass of gcc::jit::playback::context. */
1804 /* playback::compile_to_file's trivial constructor. */
1806 playback::compile_to_file::compile_to_file (recording::context
*ctxt
,
1807 enum gcc_jit_output_kind output_kind
,
1808 const char *output_path
) :
1809 playback::context (ctxt
),
1810 m_output_kind (output_kind
),
1811 m_output_path (output_path
)
1813 JIT_LOG_SCOPE (get_logger ());
1816 /* Implementation of the playback::context::process vfunc for compiling
1819 Either copy the .s file to the given destination (for
1820 GCC_JIT_OUTPUT_KIND_ASSEMBLER), or invoke the driver to convert it
1821 as necessary, copying the result. */
1824 playback::compile_to_file::postprocess (const char *ctxt_progname
)
1826 JIT_LOG_SCOPE (get_logger ());
1828 /* The driver takes different actions based on the filename, so
1829 we provide a filename with an appropriate suffix for the
1830 output kind, and then copy it up to the user-provided path,
1831 rather than directly compiling it to the requested output path. */
1833 switch (m_output_kind
)
1838 case GCC_JIT_OUTPUT_KIND_ASSEMBLER
:
1839 copy_file (get_tempdir ()->get_path_s_file (),
1843 case GCC_JIT_OUTPUT_KIND_OBJECT_FILE
:
1845 char *tmp_o_path
= ::concat (get_tempdir ()->get_path (),
1848 invoke_driver (ctxt_progname
,
1849 get_tempdir ()->get_path_s_file (),
1852 false, /* bool shared, */
1853 false);/* bool run_linker */
1854 if (!errors_occurred ())
1855 copy_file (tmp_o_path
,
1861 case GCC_JIT_OUTPUT_KIND_DYNAMIC_LIBRARY
:
1862 invoke_driver (ctxt_progname
,
1863 get_tempdir ()->get_path_s_file (),
1864 get_tempdir ()->get_path_so_file (),
1866 true, /* bool shared, */
1867 true);/* bool run_linker */
1868 if (!errors_occurred ())
1869 copy_file (get_tempdir ()->get_path_so_file (),
1873 case GCC_JIT_OUTPUT_KIND_EXECUTABLE
:
1875 char *tmp_exe_path
= ::concat (get_tempdir ()->get_path (),
1878 invoke_driver (ctxt_progname
,
1879 get_tempdir ()->get_path_s_file (),
1882 false, /* bool shared, */
1883 true);/* bool run_linker */
1884 if (!errors_occurred ())
1885 copy_file (tmp_exe_path
,
1887 free (tmp_exe_path
);
1895 /* Copy SRC_PATH to DST_PATH, preserving permission bits (in particular,
1896 the "executable" bits).
1898 Any errors that occur are reported on the context and hence count as
1899 a failure of the compile.
1901 We can't in general hardlink or use "rename" from the tempdir since
1902 it might be on a different filesystem to the destination. For example,
1903 I get EXDEV: "Invalid cross-device link". */
1906 playback::compile_to_file::copy_file (const char *src_path
,
1907 const char *dst_path
)
1909 JIT_LOG_SCOPE (get_logger ());
1912 get_logger ()->log ("src_path: %s", src_path
);
1913 get_logger ()->log ("dst_path: %s", dst_path
);
1918 size_t total_sz_in
= 0;
1919 size_t total_sz_out
= 0;
1922 struct stat stat_buf
;
1924 f_in
= fopen (src_path
, "rb");
1928 "unable to open %s for reading: %s",
1934 /* Use stat on the filedescriptor to get the mode,
1935 so that we can copy it over (in particular, the
1936 "executable" bits). */
1937 if (-1 == fstat (fileno (f_in
), &stat_buf
))
1940 "unable to fstat %s: %s",
1947 f_out
= fopen (dst_path
, "wb");
1951 "unable to open %s for writing: %s",
1958 while ( (sz_in
= fread (buf
, 1, sizeof (buf
), f_in
)) )
1960 total_sz_in
+= sz_in
;
1961 size_t sz_out_remaining
= sz_in
;
1962 size_t sz_out_so_far
= 0;
1963 while (sz_out_remaining
)
1965 size_t sz_out
= fwrite (buf
+ sz_out_so_far
,
1969 gcc_assert (sz_out
<= sz_out_remaining
);
1973 "error writing to %s: %s",
1980 total_sz_out
+= sz_out
;
1981 sz_out_so_far
+= sz_out
;
1982 sz_out_remaining
-= sz_out
;
1984 gcc_assert (sz_out_so_far
== sz_in
);
1989 "error reading from %s: %s",
1995 gcc_assert (total_sz_in
== total_sz_out
);
1997 get_logger ()->log ("total bytes copied: %ld", total_sz_out
);
1999 /* Set the permissions of the copy to those of the original file,
2000 in particular the "executable" bits. */
2001 if (-1 == fchmod (fileno (f_out
), stat_buf
.st_mode
))
2003 "error setting mode of %s: %s",
2010 /* Helper functions for gcc::jit::playback::context::compile. */
2012 /* This mutex guards gcc::jit::recording::context::compile, so that only
2013 one thread can be accessing the bulk of GCC's state at once. */
2015 static pthread_mutex_t jit_mutex
= PTHREAD_MUTEX_INITIALIZER
;
2017 /* Acquire jit_mutex and set "this" as the active playback ctxt. */
2020 playback::context::acquire_mutex ()
2022 /* Acquire the big GCC mutex. */
2023 JIT_LOG_SCOPE (get_logger ());
2024 pthread_mutex_lock (&jit_mutex
);
2025 gcc_assert (NULL
== active_playback_ctxt
);
2026 active_playback_ctxt
= this;
2029 /* Release jit_mutex and clear the active playback ctxt. */
2032 playback::context::release_mutex ()
2034 /* Release the big GCC mutex. */
2035 JIT_LOG_SCOPE (get_logger ());
2036 gcc_assert (active_playback_ctxt
== this);
2037 active_playback_ctxt
= NULL
;
2038 pthread_mutex_unlock (&jit_mutex
);
2041 /* Callback used by gcc::jit::playback::context::make_fake_args when
2042 invoking driver_get_configure_time_options.
2043 Populate a vec <char * > with the configure-time options. */
2046 append_arg_from_driver (const char *option
, void *user_data
)
2048 gcc_assert (option
);
2049 gcc_assert (user_data
);
2050 vec
<char *> *argvec
= static_cast <vec
<char *> *> (user_data
);
2051 argvec
->safe_push (concat ("-", option
, NULL
));
2054 /* Build a fake argv for toplev::main from the options set
2055 by the user on the context . */
2059 make_fake_args (vec
<char *> *argvec
,
2060 const char *ctxt_progname
,
2061 vec
<recording::requested_dump
> *requested_dumps
)
2063 JIT_LOG_SCOPE (get_logger ());
2065 #define ADD_ARG(arg) argvec->safe_push (xstrdup (arg))
2066 #define ADD_ARG_TAKE_OWNERSHIP(arg) argvec->safe_push (arg)
2068 ADD_ARG (ctxt_progname
);
2069 ADD_ARG (get_path_c_file ());
2072 /* Handle int options: */
2073 switch (get_int_option (GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL
))
2077 "unrecognized optimization level: %i",
2078 get_int_option (GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL
));
2097 /* What about -Os? */
2099 /* Handle bool options: */
2100 if (get_bool_option (GCC_JIT_BOOL_OPTION_DEBUGINFO
))
2103 /* Suppress timing (and other) info. */
2104 if (!get_bool_option (GCC_JIT_BOOL_OPTION_DUMP_SUMMARY
))
2110 /* Aggressively garbage-collect, to shake out bugs: */
2111 if (get_bool_option (GCC_JIT_BOOL_OPTION_SELFCHECK_GC
))
2113 ADD_ARG ("--param");
2114 ADD_ARG ("ggc-min-expand=0");
2115 ADD_ARG ("--param");
2116 ADD_ARG ("ggc-min-heapsize=0");
2119 if (get_bool_option (GCC_JIT_BOOL_OPTION_DUMP_EVERYTHING
))
2121 ADD_ARG ("-fdump-tree-all");
2122 ADD_ARG ("-fdump-rtl-all");
2123 ADD_ARG ("-fdump-ipa-all");
2126 /* Add "-fdump-" options for any calls to
2127 gcc_jit_context_enable_dump. */
2130 recording::requested_dump
*d
;
2131 FOR_EACH_VEC_ELT (*requested_dumps
, i
, d
)
2133 char *arg
= concat ("-fdump-", d
->m_dumpname
, NULL
);
2134 ADD_ARG_TAKE_OWNERSHIP (arg
);
2138 /* PR jit/64810: Add any target-specific default options
2139 from OPTION_DEFAULT_SPECS, normally provided by the driver
2140 in the non-jit case.
2142 The target-specific code can define OPTION_DEFAULT_SPECS:
2143 default command options in the form of spec macros for the
2144 driver to expand ().
2146 For cc1 etc, the driver processes OPTION_DEFAULT_SPECS and,
2147 if not overriden, injects the defaults as extra arguments to
2149 For the jit case, we need to add these arguments here. The
2150 input format (using the specs language) means that we have to run
2151 part of the driver code here (driver_get_configure_time_options).
2153 To avoid running the spec-expansion code every time, we just do
2154 it the first time (via a function-static flag), saving the result
2155 into a function-static vec.
2156 This flag and vec are global state (i.e. per-process).
2157 They are guarded by the jit mutex. */
2159 static bool have_configure_time_options
= false;
2160 static vec
<char *> configure_time_options
;
2162 if (have_configure_time_options
)
2163 log ("reusing cached configure-time options");
2166 have_configure_time_options
= true;
2167 log ("getting configure-time options from driver");
2168 driver_get_configure_time_options (append_arg_from_driver
,
2169 &configure_time_options
);
2176 FOR_EACH_VEC_ELT (configure_time_options
, i
, opt
)
2177 log ("configure_time_options[%i]: %s", i
, opt
);
2179 /* configure_time_options should now contain the expanded options
2180 from OPTION_DEFAULT_SPECS (if any). */
2181 FOR_EACH_VEC_ELT (configure_time_options
, i
, opt
)
2184 gcc_assert (opt
[0] == '-');
2190 #undef ADD_ARG_TAKE_OWNERSHIP
2193 /* The second half of the implementation of gcc_jit_context_enable_dump.
2194 Iterate through the requested dumps, reading the underlying files
2195 into heap-allocated buffers, writing pointers to the buffers into
2196 the char ** pointers provided by client code.
2197 Client code is responsible for calling free on the results. */
2201 extract_any_requested_dumps (vec
<recording::requested_dump
> *requested_dumps
)
2203 JIT_LOG_SCOPE (get_logger ());
2206 recording::requested_dump
*d
;
2207 FOR_EACH_VEC_ELT (*requested_dumps
, i
, d
)
2209 dump_file_info
*dfi
;
2213 dfi
= g
->get_dumps ()->get_dump_file_info_by_switch (d
->m_dumpname
);
2216 add_error (NULL
, "unrecognized dump: %s", d
->m_dumpname
);
2220 filename
= g
->get_dumps ()->get_dump_file_name (dfi
);
2221 content
= read_dump_file (filename
);
2222 *(d
->m_out_ptr
) = content
;
2227 /* Helper function for playback::context::extract_any_requested_dumps
2228 (itself for use in implementation of gcc_jit_context_enable_dump).
2230 Attempt to read the complete file at the given path, returning the
2231 bytes found there as a buffer.
2232 The caller is responsible for calling free on the result.
2233 Errors will be reported on the context, and lead to NULL being
2234 returned; an out-of-memory error will terminate the process. */
2237 playback::context::read_dump_file (const char *path
)
2239 char *result
= NULL
;
2240 size_t total_sz
= 0;
2245 f_in
= fopen (path
, "r");
2248 add_error (NULL
, "unable to open %s for reading", path
);
2252 while ( (sz
= fread (buf
, 1, sizeof (buf
), f_in
)) )
2254 size_t old_total_sz
= total_sz
;
2256 result
= reinterpret_cast <char *> (xrealloc (result
, total_sz
+ 1));
2257 memcpy (result
+ old_total_sz
, buf
, sz
);
2262 add_error (NULL
, "error reading from %s", path
);
2272 result
[total_sz
] = '\0';
2276 return xstrdup ("");
2279 /* Part of playback::context::compile ().
2281 We have a .s file; we want a .so file.
2282 We could reuse parts of gcc/gcc.c to do this.
2283 For now, just use the driver binary from the install, as
2284 named in gcc-driver-name.h
2285 e.g. "x86_64-unknown-linux-gnu-gcc-5.0.0". */
2289 convert_to_dso (const char *ctxt_progname
)
2291 JIT_LOG_SCOPE (get_logger ());
2293 invoke_driver (ctxt_progname
,
2294 m_tempdir
->get_path_s_file (),
2295 m_tempdir
->get_path_so_file (),
2297 true, /* bool shared, */
2298 true);/* bool run_linker */
2303 invoke_driver (const char *ctxt_progname
,
2304 const char *input_file
,
2305 const char *output_file
,
2310 JIT_LOG_SCOPE (get_logger ());
2311 /* Currently this lumps together both assembling and linking into
2313 auto_timevar
assemble_timevar (tv_id
);
2315 auto_vec
<const char *> argvec
;
2316 #define ADD_ARG(arg) argvec.safe_push (arg)
2317 int exit_status
= 0;
2319 const char *gcc_driver_name
= GCC_DRIVER_NAME
;
2321 ADD_ARG (gcc_driver_name
);
2324 ADD_ARG ("-shared");
2329 ADD_ARG (input_file
);
2331 ADD_ARG (output_file
);
2333 /* Don't use the linker plugin.
2334 If running with just a "make" and not a "make install", then we'd
2336 "fatal error: -fuse-linker-plugin, but liblto_plugin.so not found"
2337 libto_plugin is a .la at build time, with it becoming installed with
2338 ".so" suffix: i.e. it doesn't exist with a .so suffix until install
2340 ADD_ARG ("-fno-use-linker-plugin");
2342 /* pex argv arrays are NULL-terminated. */
2345 /* pex_one's error-handling requires pname to be non-NULL. */
2346 gcc_assert (ctxt_progname
);
2349 for (unsigned i
= 0; i
< argvec
.length (); i
++)
2350 get_logger ()->log ("argv[%i]: %s", i
, argvec
[i
]);
2352 errmsg
= pex_one (PEX_SEARCH
, /* int flags, */
2354 const_cast <char *const *> (argvec
.address ()),
2355 ctxt_progname
, /* const char *pname */
2356 NULL
, /* const char *outname */
2357 NULL
, /* const char *errname */
2358 &exit_status
, /* int *status */
2359 &err
); /* int *err*/
2362 add_error (NULL
, "error invoking gcc driver: %s", errmsg
);
2366 /* pex_one can return a NULL errmsg when the executable wasn't
2367 found (or doesn't exist), so trap these cases also. */
2368 if (exit_status
|| err
)
2371 "error invoking gcc driver: exit_status: %i err: %i",
2374 "whilst attempting to run a driver named: %s",
2384 /* Dynamically-link the built DSO file into this process, using dlopen.
2385 Wrap it up within a jit::result *, and return that.
2386 Return NULL if any errors occur, reporting them on this context. */
2392 JIT_LOG_SCOPE (get_logger ());
2393 auto_timevar
load_timevar (TV_LOAD
);
2394 void *handle
= NULL
;
2395 const char *error
= NULL
;
2396 result
*result_obj
= NULL
;
2398 /* Clear any existing error. */
2401 handle
= dlopen (m_tempdir
->get_path_so_file (),
2402 RTLD_NOW
| RTLD_LOCAL
);
2403 if ((error
= dlerror()) != NULL
) {
2404 add_error (NULL
, "%s", error
);
2408 /* We've successfully dlopened the result; create a
2409 jit::result object to wrap it.
2411 We're done with the tempdir for now, but if the user
2412 has requested debugging, the user's debugger might not
2413 be capable of dealing with the .so file being unlinked
2414 immediately, so keep it around until after the result
2415 is released. We do this by handing over ownership of
2416 the jit::tempdir to the result. See PR jit/64206. */
2417 tempdir
*handover_tempdir
;
2418 if (get_bool_option (GCC_JIT_BOOL_OPTION_DEBUGINFO
))
2420 handover_tempdir
= m_tempdir
;
2422 /* The tempdir will eventually be cleaned up in the
2423 jit::result's dtor. */
2424 log ("GCC_JIT_BOOL_OPTION_DEBUGINFO was set:"
2425 " handing over tempdir to jit::result");
2429 handover_tempdir
= NULL
;
2430 /* ... and retain ownership of m_tempdir so we clean it
2431 up it the playback::context's dtor. */
2432 log ("GCC_JIT_BOOL_OPTION_DEBUGINFO was not set:"
2433 " retaining ownership of tempdir");
2436 result_obj
= new result (get_logger (), handle
, handover_tempdir
);
2444 /* Top-level hook for playing back a recording context.
2446 This plays back m_recording_ctxt, and, if no errors
2447 occurred builds statement lists for and then postprocesses
2448 every function in the result. */
2454 JIT_LOG_SCOPE (get_logger ());
2455 /* Adapted from c-common.c:c_common_nodes_and_builtins. */
2456 tree array_domain_type
= build_index_type (size_int (200));
2457 m_char_array_type_node
2458 = build_array_type (char_type_node
, array_domain_type
);
2461 = build_pointer_type (build_qualified_type (char_type_node
,
2464 /* Replay the recorded events: */
2465 timevar_push (TV_JIT_REPLAY
);
2467 m_recording_ctxt
->replay_into (this);
2469 /* Clean away the temporary references from recording objects
2470 to playback objects. We have to do this now since the
2471 latter are GC-allocated, but the former don't mark these
2472 refs. Hence we must stop using them before the GC can run. */
2473 m_recording_ctxt
->disassociate_from_playback ();
2475 /* The builtins_manager, if any, is associated with the recording::context
2476 and might be reused for future compiles on other playback::contexts,
2477 but its m_attributes array is not GTY-labeled and hence will become
2478 nonsense if the GC runs. Purge this state. */
2479 builtins_manager
*bm
= get_builtins_manager ();
2481 bm
->finish_playback ();
2483 timevar_pop (TV_JIT_REPLAY
);
2485 if (!errors_occurred ())
2490 /* No GC can happen yet; process the cached source locations. */
2491 handle_locations ();
2493 /* We've now created tree nodes for the stmts in the various blocks
2494 in each function, but we haven't built each function's single stmt
2495 list yet. Do so now. */
2496 FOR_EACH_VEC_ELT (m_functions
, i
, func
)
2497 func
->build_stmt_list ();
2499 /* No GC can have happened yet. */
2501 /* Postprocess the functions. This could trigger GC. */
2502 FOR_EACH_VEC_ELT (m_functions
, i
, func
)
2505 func
->postprocess ();
2510 /* Dump the generated .s file to stderr. */
2514 dump_generated_code ()
2516 JIT_LOG_SCOPE (get_logger ());
2519 FILE *f_in
= fopen (get_path_s_file (), "r");
2523 while ( (sz
= fread (buf
, 1, sizeof (buf
), f_in
)) )
2524 fwrite (buf
, 1, sz
, stderr
);
2529 /* Get the supposed path of the notional "fake.c" file within the
2530 tempdir. This file doesn't exist, but the rest of the compiler
2535 get_path_c_file () const
2537 return m_tempdir
->get_path_c_file ();
2540 /* Get the path of the assembler output file "fake.s" file within the
2545 get_path_s_file () const
2547 return m_tempdir
->get_path_s_file ();
2550 /* Get the path of the DSO object file "fake.so" file within the
2555 get_path_so_file () const
2557 return m_tempdir
->get_path_so_file ();
2560 /* qsort comparator for comparing pairs of playback::source_line *,
2561 ordering them by line number. */
2564 line_comparator (const void *lhs
, const void *rhs
)
2566 const playback::source_line
*line_lhs
= \
2567 *static_cast<const playback::source_line
* const*> (lhs
);
2568 const playback::source_line
*line_rhs
= \
2569 *static_cast<const playback::source_line
* const*> (rhs
);
2570 return line_lhs
->get_line_num () - line_rhs
->get_line_num ();
2573 /* qsort comparator for comparing pairs of playback::location *,
2574 ordering them by column number. */
2577 location_comparator (const void *lhs
, const void *rhs
)
2579 const playback::location
*loc_lhs
= \
2580 *static_cast<const playback::location
* const *> (lhs
);
2581 const playback::location
*loc_rhs
= \
2582 *static_cast<const playback::location
* const *> (rhs
);
2583 return loc_lhs
->get_column_num () - loc_rhs
->get_column_num ();
2586 /* Our API allows locations to be created in arbitrary orders, but the
2587 linemap API requires locations to be created in ascending order
2588 as if we were tokenizing files.
2590 This hook sorts all of the the locations that have been created, and
2591 calls into the linemap API, creating linemap entries in sorted order
2592 for our locations. */
2598 /* Create the source code locations, following the ordering rules
2599 imposed by the linemap API.
2601 line_table is a global. */
2602 JIT_LOG_SCOPE (get_logger ());
2606 FOR_EACH_VEC_ELT (m_source_files
, i
, file
)
2608 linemap_add (line_table
, LC_ENTER
, false, file
->get_filename (), 0);
2610 /* Sort lines by ascending line numbers. */
2611 file
->m_source_lines
.qsort (&line_comparator
);
2615 FOR_EACH_VEC_ELT (file
->m_source_lines
, j
, line
)
2620 /* Sort locations in line by ascending column numbers. */
2621 line
->m_locations
.qsort (&location_comparator
);
2623 /* Determine maximum column within this line. */
2624 gcc_assert (line
->m_locations
.length () > 0);
2625 location
*final_column
=
2626 line
->m_locations
[line
->m_locations
.length () - 1];
2627 int max_col
= final_column
->get_column_num ();
2629 linemap_line_start (line_table
, line
->get_line_num (), max_col
);
2630 FOR_EACH_VEC_ELT (line
->m_locations
, k
, loc
)
2633 linemap_position_for_column (line_table
, loc
->get_column_num ());
2637 linemap_add (line_table
, LC_LEAVE
, false, NULL
, 0);
2640 /* line_table should now be populated; every playback::location should
2641 now have an m_srcloc. */
2643 /* Now assign them to tree nodes as appropriate. */
2644 std::pair
<tree
, location
*> *cached_location
;
2646 FOR_EACH_VEC_ELT (m_cached_locations
, i
, cached_location
)
2648 tree t
= cached_location
->first
;
2649 source_location srcloc
= cached_location
->second
->m_srcloc
;
2651 /* This covers expressions: */
2652 if (CAN_HAVE_LOCATION_P (t
))
2653 SET_EXPR_LOCATION (t
, srcloc
);
2654 else if (CODE_CONTAINS_STRUCT(TREE_CODE(t
), TS_DECL_MINIMAL
))
2655 DECL_SOURCE_LOCATION (t
) = srcloc
;
2658 /* Don't know how to set location on this node. */
2663 /* We handle errors on a playback::context by adding them to the
2664 corresponding recording::context. */
2668 add_error (location
*loc
, const char *fmt
, ...)
2672 m_recording_ctxt
->add_error_va (loc
? loc
->get_recording_loc () : NULL
,
2677 /* We handle errors on a playback::context by adding them to the
2678 corresponding recording::context. */
2682 add_error_va (location
*loc
, const char *fmt
, va_list ap
)
2684 m_recording_ctxt
->add_error_va (loc
? loc
->get_recording_loc () : NULL
,
2688 /* Dealing with the linemap API. */
2690 /* Construct a playback::location for a recording::location, if it
2691 doesn't exist already. */
2693 playback::location
*
2695 new_location (recording::location
*rloc
,
2696 const char *filename
,
2700 /* Get the source_file for filename, creating if necessary. */
2701 source_file
*src_file
= get_source_file (filename
);
2702 /* Likewise for the line within the file. */
2703 source_line
*src_line
= src_file
->get_source_line (line
);
2704 /* Likewise for the column within the line. */
2705 location
*loc
= src_line
->get_location (rloc
, column
);
2709 /* Deferred setting of the location for a given tree, by adding the
2710 (tree, playback::location) pair to a list of deferred associations.
2711 We will actually set the location on the tree later on once
2712 the source_location for the playback::location exists. */
2716 set_tree_location (tree t
, location
*loc
)
2719 m_cached_locations
.safe_push (std::make_pair (t
, loc
));
2723 /* Construct a playback::source_file for the given source
2724 filename, if it doesn't exist already. */
2726 playback::source_file
*
2728 get_source_file (const char *filename
)
2731 For simplicitly, this is currently a linear search.
2732 Replace with a hash if this shows up in the profile. */
2735 tree ident_filename
= get_identifier (filename
);
2737 FOR_EACH_VEC_ELT (m_source_files
, i
, file
)
2738 if (file
->filename_as_tree () == ident_filename
)
2742 file
= new source_file (ident_filename
);
2743 m_source_files
.safe_push (file
);
2747 /* Constructor for gcc::jit::playback::source_file. */
2749 playback::source_file::source_file (tree filename
) :
2751 m_filename (filename
)
2755 /* Don't leak vec's internal buffer (in non-GC heap) when we are
2759 playback::source_file::finalizer ()
2761 m_source_lines
.release ();
2764 /* Construct a playback::source_line for the given line
2765 within this source file, if one doesn't exist already. */
2767 playback::source_line
*
2768 playback::source_file::
2769 get_source_line (int line_num
)
2772 For simplicitly, this is currently a linear search.
2773 Replace with a hash if this shows up in the profile. */
2777 FOR_EACH_VEC_ELT (m_source_lines
, i
, line
)
2778 if (line
->get_line_num () == line_num
)
2782 line
= new source_line (this, line_num
);
2783 m_source_lines
.safe_push (line
);
2787 /* Constructor for gcc::jit::playback::source_line. */
2789 playback::source_line::source_line (source_file
*file
, int line_num
) :
2791 m_source_file (file
),
2792 m_line_num (line_num
)
2796 /* Don't leak vec's internal buffer (in non-GC heap) when we are
2800 playback::source_line::finalizer ()
2802 m_locations
.release ();
2805 /* Construct a playback::location for the given column
2806 within this line of a specific source file, if one doesn't exist
2809 playback::location
*
2810 playback::source_line::
2811 get_location (recording::location
*rloc
, int column_num
)
2816 /* Another linear search that probably should be a hash table. */
2817 FOR_EACH_VEC_ELT (m_locations
, i
, loc
)
2818 if (loc
->get_column_num () == column_num
)
2822 loc
= new location (rloc
, this, column_num
);
2823 m_locations
.safe_push (loc
);
2827 /* Constructor for gcc::jit::playback::location. */
2829 playback::location::location (recording::location
*loc
,
2832 m_srcloc (UNKNOWN_LOCATION
),
2833 m_recording_loc (loc
),
2835 m_column_num(column_num
)
2839 /* The active gcc::jit::playback::context instance. This is a singleton,
2840 guarded by jit_mutex. */
2842 playback::context
*active_playback_ctxt
;
2844 } // namespace gcc::jit