1 /* Internals of libgccjit: classes for playing back recorded API calls.
2 Copyright (C) 2013-2017 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"
26 #include "stringpool.h"
32 #include "stor-layout.h"
33 #include "print-tree.h"
35 #include "gcc-driver-name.h"
38 #include "fold-const.h"
40 #include "diagnostic.h"
44 #include "jit-playback.h"
45 #include "jit-result.h"
46 #include "jit-builtins.h"
47 #include "jit-tempdir.h"
50 /* gcc::jit::playback::context::build_cast uses the convert.h API,
51 which in turn requires the frontend to provide a "convert"
52 function, apparently as a fallback.
54 Hence we provide this dummy one, with the requirement that any casts
55 are handled before reaching this. */
56 extern tree
convert (tree type
, tree expr
);
59 convert (tree dst_type
, tree expr
)
61 gcc_assert (gcc::jit::active_playback_ctxt
);
62 gcc::jit::active_playback_ctxt
->add_error (NULL
, "unhandled conversion");
63 fprintf (stderr
, "input expression:\n");
65 fprintf (stderr
, "requested type:\n");
66 debug_tree (dst_type
);
67 return error_mark_node
;
73 /**********************************************************************
75 **********************************************************************/
77 /* The constructor for gcc::jit::playback::context. */
79 playback::context::context (recording::context
*ctxt
)
80 : log_user (ctxt
->get_logger ()),
81 m_recording_ctxt (ctxt
),
83 m_char_array_type_node (NULL
),
84 m_const_char_ptr (NULL
)
86 JIT_LOG_SCOPE (get_logger ());
87 m_functions
.create (0);
89 m_source_files
.create (0);
90 m_cached_locations
.create (0);
93 /* The destructor for gcc::jit::playback::context. */
95 playback::context::~context ()
97 JIT_LOG_SCOPE (get_logger ());
99 /* Normally the playback::context is responsible for cleaning up the
100 tempdir (including "fake.so" within the filesystem).
102 In the normal case, clean it up now.
104 However m_tempdir can be NULL if the context has handed over
105 responsibility for the tempdir cleanup to the jit::result object, so
106 that the cleanup can be delayed (see PR jit/64206). If that's the
107 case this "delete NULL;" is a no-op. */
110 m_functions
.release ();
113 /* A playback::context can reference GC-managed pointers. Mark them
114 ("by hand", rather than by gengtype).
116 This is called on the active playback context (if any) by the
117 my_ggc_walker hook in the jit_root_table in dummy-frontend.c. */
125 FOR_EACH_VEC_ELT (m_functions
, i
, func
)
127 if (ggc_test_and_set_mark (func
))
132 /* Given an enum gcc_jit_types value, get a "tree" type. */
135 get_tree_node_for_type (enum gcc_jit_types type_
)
139 case GCC_JIT_TYPE_VOID
:
140 return void_type_node
;
142 case GCC_JIT_TYPE_VOID_PTR
:
143 return ptr_type_node
;
145 case GCC_JIT_TYPE_BOOL
:
146 return boolean_type_node
;
148 case GCC_JIT_TYPE_CHAR
:
149 return char_type_node
;
150 case GCC_JIT_TYPE_SIGNED_CHAR
:
151 return signed_char_type_node
;
152 case GCC_JIT_TYPE_UNSIGNED_CHAR
:
153 return unsigned_char_type_node
;
155 case GCC_JIT_TYPE_SHORT
:
156 return short_integer_type_node
;
157 case GCC_JIT_TYPE_UNSIGNED_SHORT
:
158 return short_unsigned_type_node
;
160 case GCC_JIT_TYPE_CONST_CHAR_PTR
:
162 tree const_char
= build_qualified_type (char_type_node
,
164 return build_pointer_type (const_char
);
167 case GCC_JIT_TYPE_INT
:
168 return integer_type_node
;
169 case GCC_JIT_TYPE_UNSIGNED_INT
:
170 return unsigned_type_node
;
172 case GCC_JIT_TYPE_LONG
:
173 return long_integer_type_node
;
174 case GCC_JIT_TYPE_UNSIGNED_LONG
:
175 return long_unsigned_type_node
;
177 case GCC_JIT_TYPE_LONG_LONG
:
178 return long_long_integer_type_node
;
179 case GCC_JIT_TYPE_UNSIGNED_LONG_LONG
:
180 return long_long_unsigned_type_node
;
182 case GCC_JIT_TYPE_FLOAT
:
183 return float_type_node
;
184 case GCC_JIT_TYPE_DOUBLE
:
185 return double_type_node
;
186 case GCC_JIT_TYPE_LONG_DOUBLE
:
187 return long_double_type_node
;
189 case GCC_JIT_TYPE_SIZE_T
:
190 return size_type_node
;
192 case GCC_JIT_TYPE_FILE_PTR
:
193 return fileptr_type_node
;
195 case GCC_JIT_TYPE_COMPLEX_FLOAT
:
196 return complex_float_type_node
;
197 case GCC_JIT_TYPE_COMPLEX_DOUBLE
:
198 return complex_double_type_node
;
199 case GCC_JIT_TYPE_COMPLEX_LONG_DOUBLE
:
200 return complex_long_double_type_node
;
206 /* Construct a playback::type instance (wrapping a tree) for the given
211 get_type (enum gcc_jit_types type_
)
213 tree type_node
= get_tree_node_for_type (type_
);
214 if (NULL
== type_node
)
217 "unrecognized (enum gcc_jit_types) value: %i", type_
);
221 return new type (type_node
);
224 /* Construct a playback::type instance (wrapping a tree) for the given
229 new_array_type (playback::location
*loc
,
230 playback::type
*element_type
,
233 gcc_assert (element_type
);
235 tree t
= build_array_type_nelts (element_type
->as_tree (),
240 set_tree_location (t
, loc
);
245 /* Construct a playback::field instance (wrapping a tree). */
249 new_field (location
*loc
,
256 /* compare with c/c-decl.c:grokfield and grokdeclarator. */
257 tree decl
= build_decl (UNKNOWN_LOCATION
, FIELD_DECL
,
258 get_identifier (name
), type
->as_tree ());
261 set_tree_location (decl
, loc
);
263 return new field (decl
);
266 /* Construct a playback::compound_type instance (wrapping a tree). */
268 playback::compound_type
*
270 new_compound_type (location
*loc
,
272 bool is_struct
) /* else is union */
276 /* Compare with c/c-decl.c: start_struct. */
278 tree t
= make_node (is_struct
? RECORD_TYPE
: UNION_TYPE
);
279 TYPE_NAME (t
) = get_identifier (name
);
283 set_tree_location (t
, loc
);
285 return new compound_type (t
);
289 playback::compound_type::set_fields (const auto_vec
<playback::field
*> *fields
)
291 /* Compare with c/c-decl.c: finish_struct. */
294 tree fieldlist
= NULL
;
295 for (unsigned i
= 0; i
< fields
->length (); i
++)
297 field
*f
= (*fields
)[i
];
298 DECL_CONTEXT (f
->as_tree ()) = t
;
299 fieldlist
= chainon (f
->as_tree (), fieldlist
);
301 fieldlist
= nreverse (fieldlist
);
302 TYPE_FIELDS (t
) = fieldlist
;
307 /* Construct a playback::type instance (wrapping a tree) for a function
312 new_function_type (type
*return_type
,
313 const auto_vec
<type
*> *param_types
,
319 tree
*arg_types
= (tree
*)xcalloc(param_types
->length (), sizeof(tree
*));
321 FOR_EACH_VEC_ELT (*param_types
, i
, param_type
)
322 arg_types
[i
] = param_type
->as_tree ();
327 build_varargs_function_type_array (return_type
->as_tree (),
328 param_types
->length (),
331 fn_type
= build_function_type_array (return_type
->as_tree (),
332 param_types
->length (),
336 return new type (fn_type
);
339 /* Construct a playback::param instance (wrapping a tree). */
343 new_param (location
*loc
,
349 tree inner
= build_decl (UNKNOWN_LOCATION
, PARM_DECL
,
350 get_identifier (name
), type
->as_tree ());
352 set_tree_location (inner
, loc
);
354 return new param (this, inner
);
357 /* Construct a playback::function instance. */
361 new_function (location
*loc
,
362 enum gcc_jit_function_kind kind
,
365 const auto_vec
<param
*> *params
,
367 enum built_in_function builtin_id
)
372 //can return_type be NULL?
375 tree
*arg_types
= (tree
*)xcalloc(params
->length (), sizeof(tree
*));
376 FOR_EACH_VEC_ELT (*params
, i
, param
)
377 arg_types
[i
] = TREE_TYPE (param
->as_tree ());
381 fn_type
= build_varargs_function_type_array (return_type
->as_tree (),
382 params
->length (), arg_types
);
384 fn_type
= build_function_type_array (return_type
->as_tree (),
385 params
->length (), arg_types
);
388 /* FIXME: this uses input_location: */
389 tree fndecl
= build_fn_decl (name
, fn_type
);
392 set_tree_location (fndecl
, loc
);
394 tree resdecl
= build_decl (UNKNOWN_LOCATION
, RESULT_DECL
,
395 NULL_TREE
, return_type
->as_tree ());
396 DECL_ARTIFICIAL (resdecl
) = 1;
397 DECL_IGNORED_P (resdecl
) = 1;
398 DECL_RESULT (fndecl
) = resdecl
;
402 DECL_FUNCTION_CODE (fndecl
) = builtin_id
;
403 gcc_assert (loc
== NULL
);
404 DECL_SOURCE_LOCATION (fndecl
) = BUILTINS_LOCATION
;
406 DECL_BUILT_IN_CLASS (fndecl
) =
407 builtins_manager::get_class (builtin_id
);
408 set_builtin_decl (builtin_id
, fndecl
,
409 builtins_manager::implicit_p (builtin_id
));
411 builtins_manager
*bm
= get_builtins_manager ();
412 tree attrs
= bm
->get_attrs_tree (builtin_id
);
414 decl_attributes (&fndecl
, attrs
, ATTR_FLAG_BUILT_IN
);
416 decl_attributes (&fndecl
, NULL_TREE
, 0);
419 if (kind
!= GCC_JIT_FUNCTION_IMPORTED
)
421 tree param_decl_list
= NULL
;
422 FOR_EACH_VEC_ELT (*params
, i
, param
)
424 param_decl_list
= chainon (param
->as_tree (), param_decl_list
);
427 /* The param list was created in reverse order; fix it: */
428 param_decl_list
= nreverse (param_decl_list
);
431 for (t
= param_decl_list
; t
; t
= DECL_CHAIN (t
))
433 DECL_CONTEXT (t
) = fndecl
;
434 DECL_ARG_TYPE (t
) = TREE_TYPE (t
);
437 /* Set it up on DECL_ARGUMENTS */
438 DECL_ARGUMENTS(fndecl
) = param_decl_list
;
441 if (kind
== GCC_JIT_FUNCTION_ALWAYS_INLINE
)
443 DECL_DECLARED_INLINE_P (fndecl
) = 1;
445 /* Add attribute "always_inline": */
446 DECL_ATTRIBUTES (fndecl
) =
447 tree_cons (get_identifier ("always_inline"),
449 DECL_ATTRIBUTES (fndecl
));
452 function
*func
= new function (this, fndecl
, kind
);
453 m_functions
.safe_push (func
);
457 /* Construct a playback::lvalue instance (wrapping a tree). */
461 new_global (location
*loc
,
462 enum gcc_jit_global_kind kind
,
468 tree inner
= build_decl (UNKNOWN_LOCATION
, VAR_DECL
,
469 get_identifier (name
),
471 TREE_PUBLIC (inner
) = (kind
!= GCC_JIT_GLOBAL_INTERNAL
);
472 DECL_COMMON (inner
) = 1;
478 case GCC_JIT_GLOBAL_EXPORTED
:
479 TREE_STATIC (inner
) = 1;
482 case GCC_JIT_GLOBAL_INTERNAL
:
483 TREE_STATIC (inner
) = 1;
486 case GCC_JIT_GLOBAL_IMPORTED
:
487 DECL_EXTERNAL (inner
) = 1;
492 set_tree_location (inner
, loc
);
494 varpool_node::get_create (inner
);
496 varpool_node::finalize_decl (inner
);
498 m_globals
.safe_push (inner
);
500 return new lvalue (this, inner
);
503 /* Implementation of the various
504 gcc::jit::playback::context::new_rvalue_from_const <HOST_TYPE>
506 Each of these constructs a playback::rvalue instance (wrapping a tree).
508 These specializations are required to be in the same namespace
509 as the template, hence we now have to enter the gcc::jit::playback
515 /* Specialization of making an rvalue from a const, for host <int>. */
520 new_rvalue_from_const
<int> (type
*type
,
523 // FIXME: type-checking, or coercion?
524 tree inner_type
= type
->as_tree ();
525 if (INTEGRAL_TYPE_P (inner_type
))
527 tree inner
= build_int_cst (inner_type
, value
);
528 return new rvalue (this, inner
);
532 REAL_VALUE_TYPE real_value
;
533 real_from_integer (&real_value
, VOIDmode
, value
, SIGNED
);
534 tree inner
= build_real (inner_type
, real_value
);
535 return new rvalue (this, inner
);
539 /* Specialization of making an rvalue from a const, for host <long>. */
544 new_rvalue_from_const
<long> (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 <double>. */
568 new_rvalue_from_const
<double> (type
*type
,
571 // FIXME: type-checking, or coercion?
572 tree inner_type
= type
->as_tree ();
574 /* We have a "double", we want a REAL_VALUE_TYPE.
576 real.c:real_from_target appears to require the representation to be
577 split into 32-bit values, and then sent as an pair of host long
579 REAL_VALUE_TYPE real_value
;
583 uint32_t as_uint32s
[2];
586 long int as_long_ints
[2];
587 as_long_ints
[0] = u
.as_uint32s
[0];
588 as_long_ints
[1] = u
.as_uint32s
[1];
589 real_from_target (&real_value
, as_long_ints
, DFmode
);
590 tree inner
= build_real (inner_type
, real_value
);
591 return new rvalue (this, inner
);
594 /* Specialization of making an rvalue from a const, for host <void *>. */
599 new_rvalue_from_const
<void *> (type
*type
,
602 tree inner_type
= type
->as_tree ();
603 /* FIXME: how to ensure we have a wide enough type? */
604 tree inner
= build_int_cstu (inner_type
, (unsigned HOST_WIDE_INT
)value
);
605 return new rvalue (this, inner
);
608 /* We're done implementing the specializations of
609 gcc::jit::playback::context::new_rvalue_from_const <T>
610 so we can exit the gcc::jit::playback namespace. */
612 } // namespace playback
614 /* Construct a playback::rvalue instance (wrapping a tree). */
618 new_string_literal (const char *value
)
620 tree t_str
= build_string (strlen (value
), value
);
621 gcc_assert (m_char_array_type_node
);
622 TREE_TYPE (t_str
) = m_char_array_type_node
;
624 /* Convert to (const char*), loosely based on
625 c/c-typeck.c: array_to_pointer_conversion,
626 by taking address of start of string. */
627 tree t_addr
= build1 (ADDR_EXPR
, m_const_char_ptr
, t_str
);
629 return new rvalue (this, t_addr
);
632 /* Construct a playback::rvalue instance (wrapping a tree) for a
636 playback::context::new_rvalue_from_vector (location
*,
638 const auto_vec
<rvalue
*> &elements
)
640 vec
<constructor_elt
, va_gc
> *v
;
641 vec_alloc (v
, elements
.length ());
642 for (unsigned i
= 0; i
< elements
.length (); ++i
)
643 CONSTRUCTOR_APPEND_ELT (v
, NULL_TREE
, elements
[i
]->as_tree ());
644 tree t_ctor
= build_constructor (type
->as_tree (), v
);
645 return new rvalue (this, t_ctor
);
648 /* Coerce a tree expression into a boolean tree expression. */
652 as_truth_value (tree expr
, location
*loc
)
654 /* Compare to c-typeck.c:c_objc_common_truthvalue_conversion */
655 tree typed_zero
= fold_build1 (CONVERT_EXPR
,
659 set_tree_location (typed_zero
, loc
);
661 expr
= build2 (NE_EXPR
, integer_type_node
, expr
, typed_zero
);
663 set_tree_location (expr
, loc
);
668 /* Construct a playback::rvalue instance (wrapping a tree) for a
673 new_unary_op (location
*loc
,
674 enum gcc_jit_unary_op op
,
678 // FIXME: type-checking, or coercion?
679 enum tree_code inner_op
;
681 gcc_assert (result_type
);
684 tree node
= a
->as_tree ();
685 tree inner_result
= NULL
;
690 add_error (loc
, "unrecognized (enum gcc_jit_unary_op) value: %i", op
);
693 case GCC_JIT_UNARY_OP_MINUS
:
694 inner_op
= NEGATE_EXPR
;
697 case GCC_JIT_UNARY_OP_BITWISE_NEGATE
:
698 inner_op
= BIT_NOT_EXPR
;
701 case GCC_JIT_UNARY_OP_LOGICAL_NEGATE
:
702 node
= as_truth_value (node
, loc
);
703 inner_result
= invert_truthvalue (node
);
705 set_tree_location (inner_result
, loc
);
706 return new rvalue (this, inner_result
);
708 case GCC_JIT_UNARY_OP_ABS
:
713 inner_result
= build1 (inner_op
,
714 result_type
->as_tree (),
717 set_tree_location (inner_result
, loc
);
719 return new rvalue (this, inner_result
);
722 /* Construct a playback::rvalue instance (wrapping a tree) for a
727 new_binary_op (location
*loc
,
728 enum gcc_jit_binary_op op
,
730 rvalue
*a
, rvalue
*b
)
732 // FIXME: type-checking, or coercion?
733 enum tree_code inner_op
;
735 gcc_assert (result_type
);
739 tree node_a
= a
->as_tree ();
740 tree node_b
= b
->as_tree ();
745 add_error (loc
, "unrecognized (enum gcc_jit_binary_op) value: %i", op
);
748 case GCC_JIT_BINARY_OP_PLUS
:
749 inner_op
= PLUS_EXPR
;
752 case GCC_JIT_BINARY_OP_MINUS
:
753 inner_op
= MINUS_EXPR
;
756 case GCC_JIT_BINARY_OP_MULT
:
757 inner_op
= MULT_EXPR
;
760 case GCC_JIT_BINARY_OP_DIVIDE
:
761 if (FLOAT_TYPE_P (result_type
->as_tree ()))
762 /* Floating-point division: */
763 inner_op
= RDIV_EXPR
;
765 /* Truncating to zero: */
766 inner_op
= TRUNC_DIV_EXPR
;
769 case GCC_JIT_BINARY_OP_MODULO
:
770 inner_op
= TRUNC_MOD_EXPR
;
773 case GCC_JIT_BINARY_OP_BITWISE_AND
:
774 inner_op
= BIT_AND_EXPR
;
777 case GCC_JIT_BINARY_OP_BITWISE_XOR
:
778 inner_op
= BIT_XOR_EXPR
;
781 case GCC_JIT_BINARY_OP_BITWISE_OR
:
782 inner_op
= BIT_IOR_EXPR
;
785 case GCC_JIT_BINARY_OP_LOGICAL_AND
:
786 node_a
= as_truth_value (node_a
, loc
);
787 node_b
= as_truth_value (node_b
, loc
);
788 inner_op
= TRUTH_ANDIF_EXPR
;
791 case GCC_JIT_BINARY_OP_LOGICAL_OR
:
792 node_a
= as_truth_value (node_a
, loc
);
793 node_b
= as_truth_value (node_b
, loc
);
794 inner_op
= TRUTH_ORIF_EXPR
;
797 case GCC_JIT_BINARY_OP_LSHIFT
:
798 inner_op
= LSHIFT_EXPR
;
801 case GCC_JIT_BINARY_OP_RSHIFT
:
802 inner_op
= RSHIFT_EXPR
;
806 tree inner_expr
= build2 (inner_op
,
807 result_type
->as_tree (),
811 set_tree_location (inner_expr
, loc
);
813 return new rvalue (this, inner_expr
);
816 /* Construct a playback::rvalue instance (wrapping a tree) for a
821 new_comparison (location
*loc
,
822 enum gcc_jit_comparison op
,
823 rvalue
*a
, rvalue
*b
)
825 // FIXME: type-checking, or coercion?
826 enum tree_code inner_op
;
834 add_error (loc
, "unrecognized (enum gcc_jit_comparison) value: %i", op
);
837 case GCC_JIT_COMPARISON_EQ
:
840 case GCC_JIT_COMPARISON_NE
:
843 case GCC_JIT_COMPARISON_LT
:
846 case GCC_JIT_COMPARISON_LE
:
849 case GCC_JIT_COMPARISON_GT
:
852 case GCC_JIT_COMPARISON_GE
:
857 tree inner_expr
= build2 (inner_op
,
862 set_tree_location (inner_expr
, loc
);
863 return new rvalue (this, inner_expr
);
866 /* Construct a playback::rvalue instance (wrapping a tree) for a
871 build_call (location
*loc
,
873 const auto_vec
<rvalue
*> *args
,
874 bool require_tail_call
)
876 vec
<tree
, va_gc
> *tree_args
;
877 vec_alloc (tree_args
, args
->length ());
878 for (unsigned i
= 0; i
< args
->length (); i
++)
879 tree_args
->quick_push ((*args
)[i
]->as_tree ());
882 set_tree_location (fn_ptr
, loc
);
884 tree fn
= TREE_TYPE (fn_ptr
);
885 tree fn_type
= TREE_TYPE (fn
);
886 tree return_type
= TREE_TYPE (fn_type
);
888 tree call
= build_call_vec (return_type
,
891 if (require_tail_call
)
892 CALL_EXPR_MUST_TAIL_CALL (call
) = 1;
894 return new rvalue (this, call
);
896 /* see c-typeck.c: build_function_call
897 which calls build_function_call_vec
899 which does lots of checking, then:
900 result = build_call_array_loc (loc, TREE_TYPE (fntype),
901 function, nargs, argarray);
903 (see also build_call_vec)
907 /* Construct a playback::rvalue instance (wrapping a tree) for a
908 call to a specific function. */
912 new_call (location
*loc
,
914 const auto_vec
<rvalue
*> *args
,
915 bool require_tail_call
)
921 fndecl
= func
->as_fndecl ();
923 tree fntype
= TREE_TYPE (fndecl
);
925 tree fn
= build1 (ADDR_EXPR
, build_pointer_type (fntype
), fndecl
);
927 return build_call (loc
, fn
, args
, require_tail_call
);
930 /* Construct a playback::rvalue instance (wrapping a tree) for a
931 call through a function pointer. */
935 new_call_through_ptr (location
*loc
,
937 const auto_vec
<rvalue
*> *args
,
938 bool require_tail_call
)
941 tree t_fn_ptr
= fn_ptr
->as_tree ();
943 return build_call (loc
, t_fn_ptr
, args
, require_tail_call
);
946 /* Construct a tree for a cast. */
949 playback::context::build_cast (playback::location
*loc
,
950 playback::rvalue
*expr
,
951 playback::type
*type_
)
953 /* For comparison, see:
954 - c/c-typeck.c:build_c_cast
955 - c/c-convert.c: convert
958 Only some kinds of cast are currently supported here. */
959 tree t_expr
= expr
->as_tree ();
960 tree t_dst_type
= type_
->as_tree ();
962 t_ret
= targetm
.convert_to_type (t_dst_type
, t_expr
);
965 enum tree_code dst_code
= TREE_CODE (t_dst_type
);
970 t_ret
= convert_to_integer (t_dst_type
, t_expr
);
974 /* Compare with c_objc_common_truthvalue_conversion and
975 c_common_truthvalue_conversion. */
976 /* For now, convert to: (t_expr != 0) */
977 t_ret
= build2 (NE_EXPR
, t_dst_type
,
979 build_int_cst (TREE_TYPE (t_expr
), 0));
983 t_ret
= convert_to_real (t_dst_type
, t_expr
);
987 t_ret
= build1 (NOP_EXPR
, t_dst_type
, t_expr
);
991 add_error (loc
, "couldn't handle cast during playback");
992 fprintf (stderr
, "input expression:\n");
994 fprintf (stderr
, "requested type:\n");
995 debug_tree (t_dst_type
);
996 return error_mark_node
;
999 if (TREE_CODE (t_ret
) != C_MAYBE_CONST_EXPR
)
1000 t_ret
= fold (t_ret
);
1005 /* Construct a playback::rvalue instance (wrapping a tree) for a
1010 new_cast (playback::location
*loc
,
1011 playback::rvalue
*expr
,
1012 playback::type
*type_
)
1015 tree t_cast
= build_cast (loc
, expr
, type_
);
1017 set_tree_location (t_cast
, loc
);
1018 return new rvalue (this, t_cast
);
1021 /* Construct a playback::lvalue instance (wrapping a tree) for an
1026 new_array_access (location
*loc
,
1033 /* For comparison, see:
1034 c/c-typeck.c: build_array_ref
1035 c-family/c-common.c: pointer_int_sum
1037 tree t_ptr
= ptr
->as_tree ();
1038 tree t_index
= index
->as_tree ();
1039 tree t_type_ptr
= TREE_TYPE (t_ptr
);
1040 tree t_type_star_ptr
= TREE_TYPE (t_type_ptr
);
1042 if (TREE_CODE (t_type_ptr
) == ARRAY_TYPE
)
1044 tree t_result
= build4 (ARRAY_REF
, t_type_star_ptr
, t_ptr
, t_index
,
1045 NULL_TREE
, NULL_TREE
);
1047 set_tree_location (t_result
, loc
);
1048 return new lvalue (this, t_result
);
1052 /* Convert index to an offset in bytes. */
1053 tree t_sizeof
= size_in_bytes (t_type_star_ptr
);
1054 t_index
= fold_build1 (CONVERT_EXPR
, sizetype
, t_index
);
1055 tree t_offset
= build2 (MULT_EXPR
, sizetype
, t_index
, t_sizeof
);
1057 /* Locate (ptr + offset). */
1058 tree t_address
= build2 (POINTER_PLUS_EXPR
, t_type_ptr
, t_ptr
, t_offset
);
1060 tree t_indirection
= build1 (INDIRECT_REF
, t_type_star_ptr
, t_address
);
1063 set_tree_location (t_sizeof
, loc
);
1064 set_tree_location (t_offset
, loc
);
1065 set_tree_location (t_address
, loc
);
1066 set_tree_location (t_indirection
, loc
);
1069 return new lvalue (this, t_indirection
);
1073 /* Construct a tree for a field access. */
1077 new_field_access (location
*loc
,
1084 /* Compare with c/c-typeck.c:lookup_field, build_indirect_ref, and
1085 build_component_ref. */
1086 tree type
= TREE_TYPE (datum
);
1088 gcc_assert (TREE_CODE (type
) != POINTER_TYPE
);
1090 tree t_field
= field
->as_tree ();
1091 tree ref
= build3 (COMPONENT_REF
, TREE_TYPE (t_field
), datum
,
1092 t_field
, NULL_TREE
);
1094 set_tree_location (ref
, loc
);
1098 /* Construct a tree for a dereference. */
1102 new_dereference (tree ptr
,
1107 tree type
= TREE_TYPE (TREE_TYPE(ptr
));
1108 tree datum
= build1 (INDIRECT_REF
, type
, ptr
);
1110 set_tree_location (datum
, loc
);
1114 /* Construct a playback::type instance (wrapping a tree)
1115 with the given alignment. */
1119 get_aligned (size_t alignment_in_bytes
) const
1121 tree t_new_type
= build_variant_type_copy (m_inner
);
1123 SET_TYPE_ALIGN (t_new_type
, alignment_in_bytes
* BITS_PER_UNIT
);
1124 TYPE_USER_ALIGN (t_new_type
) = 1;
1126 return new type (t_new_type
);
1129 /* Construct a playback::type instance (wrapping a tree)
1130 for the given vector type. */
1134 get_vector (size_t num_units
) const
1136 tree t_new_type
= build_vector_type (m_inner
, num_units
);
1137 return new type (t_new_type
);
1140 /* Construct a playback::lvalue instance (wrapping a tree) for a
1145 access_field (location
*loc
,
1148 tree datum
= as_tree ();
1149 tree ref
= get_context ()->new_field_access (loc
, datum
, field
);
1152 return new lvalue (get_context (), ref
);
1155 /* Construct a playback::rvalue instance (wrapping a tree) for a
1160 access_field (location
*loc
,
1163 tree datum
= as_tree ();
1164 tree ref
= get_context ()->new_field_access (loc
, datum
, field
);
1167 return new rvalue (get_context (), ref
);
1170 /* Construct a playback::lvalue instance (wrapping a tree) for a
1171 dereferenced field access. */
1175 dereference_field (location
*loc
,
1178 tree ptr
= as_tree ();
1179 tree datum
= get_context ()->new_dereference (ptr
, loc
);
1182 tree ref
= get_context ()->new_field_access (loc
, datum
, field
);
1185 return new lvalue (get_context (), ref
);
1188 /* Construct a playback::lvalue instance (wrapping a tree) for a
1193 dereference (location
*loc
)
1195 tree ptr
= as_tree ();
1196 tree datum
= get_context ()->new_dereference (ptr
, loc
);
1197 return new lvalue (get_context (), datum
);
1200 /* Mark EXP saying that we need to be able to take the
1201 address of it; it should not be allocated in a register.
1202 Compare with e.g. c/c-typeck.c: c_mark_addressable. */
1205 jit_mark_addressable (tree exp
)
1210 switch (TREE_CODE (x
))
1213 /* (we don't yet support bitfields) */
1219 x
= TREE_OPERAND (x
, 0);
1222 case COMPOUND_LITERAL_EXPR
:
1224 TREE_ADDRESSABLE (x
) = 1;
1231 /* (we don't have a concept of a "register" declaration) */
1234 TREE_ADDRESSABLE (x
) = 1;
1241 /* Construct a playback::rvalue instance (wrapping a tree) for an
1246 get_address (location
*loc
)
1248 tree t_lvalue
= as_tree ();
1249 tree t_thistype
= TREE_TYPE (t_lvalue
);
1250 tree t_ptrtype
= build_pointer_type (t_thistype
);
1251 tree ptr
= build1 (ADDR_EXPR
, t_ptrtype
, t_lvalue
);
1253 get_context ()->set_tree_location (ptr
, loc
);
1254 jit_mark_addressable (t_lvalue
);
1255 return new rvalue (get_context (), ptr
);
1258 /* The wrapper subclasses are GC-managed, but can own non-GC memory.
1259 Provide this finalization hook for calling then they are collected,
1260 which calls the finalizer vfunc. This allows them to call "release"
1261 on any vec<> within them. */
1264 wrapper_finalizer (void *ptr
)
1266 playback::wrapper
*wrapper
= reinterpret_cast <playback::wrapper
*> (ptr
);
1267 wrapper
->finalizer ();
1270 /* gcc::jit::playback::wrapper subclasses are GC-managed:
1271 allocate them using ggc_internal_cleared_alloc. */
1275 operator new (size_t sz
)
1277 return ggc_internal_cleared_alloc (sz
, wrapper_finalizer
, 0, 1);
1281 /* Constructor for gcc:jit::playback::function. */
1283 playback::function::
1284 function (context
*ctxt
,
1286 enum gcc_jit_function_kind kind
)
1288 m_inner_fndecl (fndecl
),
1289 m_inner_bind_expr (NULL
),
1292 if (m_kind
!= GCC_JIT_FUNCTION_IMPORTED
)
1294 /* Create a BIND_EXPR, and within it, a statement list. */
1295 m_stmt_list
= alloc_stmt_list ();
1296 m_stmt_iter
= tsi_start (m_stmt_list
);
1297 m_inner_block
= make_node (BLOCK
);
1299 build3 (BIND_EXPR
, void_type_node
, NULL
, m_stmt_list
, m_inner_block
);
1303 m_inner_block
= NULL
;
1308 /* Hand-written GC-marking hook for playback functions. */
1311 playback::function::
1314 gt_ggc_m_9tree_node (m_inner_fndecl
);
1315 gt_ggc_m_9tree_node (m_inner_bind_expr
);
1316 gt_ggc_m_9tree_node (m_stmt_list
);
1317 gt_ggc_m_9tree_node (m_inner_block
);
1320 /* Don't leak vec's internal buffer (in non-GC heap) when we are
1324 playback::function::finalizer ()
1326 m_blocks
.release ();
1329 /* Get the return type of a playback function, in tree form. */
1332 playback::function::
1333 get_return_type_as_tree () const
1335 return TREE_TYPE (TREE_TYPE(m_inner_fndecl
));
1338 /* Construct a new local within this playback::function. */
1341 playback::function::
1342 new_local (location
*loc
,
1348 tree inner
= build_decl (UNKNOWN_LOCATION
, VAR_DECL
,
1349 get_identifier (name
),
1351 DECL_CONTEXT (inner
) = this->m_inner_fndecl
;
1353 /* Prepend to BIND_EXPR_VARS: */
1354 DECL_CHAIN (inner
) = BIND_EXPR_VARS (m_inner_bind_expr
);
1355 BIND_EXPR_VARS (m_inner_bind_expr
) = inner
;
1358 set_tree_location (inner
, loc
);
1359 return new lvalue (m_ctxt
, inner
);
1362 /* Construct a new block within this playback::function. */
1365 playback::function::
1366 new_block (const char *name
)
1368 gcc_assert (m_kind
!= GCC_JIT_FUNCTION_IMPORTED
);
1370 block
*result
= new playback::block (this, name
);
1371 m_blocks
.safe_push (result
);
1375 /* Construct a playback::rvalue instance wrapping an ADDR_EXPR for
1376 this playback::function. */
1379 playback::function::get_address (location
*loc
)
1381 tree t_fndecl
= as_fndecl ();
1382 tree t_fntype
= TREE_TYPE (t_fndecl
);
1383 tree t_fnptr
= build1 (ADDR_EXPR
, build_pointer_type (t_fntype
), t_fndecl
);
1385 m_ctxt
->set_tree_location (t_fnptr
, loc
);
1386 return new rvalue (m_ctxt
, t_fnptr
);
1389 /* Build a statement list for the function as a whole out of the
1390 lists of statements for the individual blocks, building labels
1394 playback::function::
1400 JIT_LOG_SCOPE (m_ctxt
->get_logger ());
1402 FOR_EACH_VEC_ELT (m_blocks
, i
, b
)
1407 b
->m_label_expr
= build1 (LABEL_EXPR
,
1409 b
->as_label_decl ());
1410 tsi_link_after (&m_stmt_iter
, b
->m_label_expr
, TSI_CONTINUE_LINKING
);
1412 FOR_EACH_VEC_ELT (b
->m_stmts
, j
, stmt
)
1413 tsi_link_after (&m_stmt_iter
, stmt
, TSI_CONTINUE_LINKING
);
1417 /* Finish compiling the given function, potentially running the
1419 The function will have a statement list by now.
1420 Amongst other things, this gimplifies the statement list,
1421 and calls cgraph_node::finalize_function on the function. */
1424 playback::function::
1427 JIT_LOG_SCOPE (m_ctxt
->get_logger ());
1429 if (m_ctxt
->get_bool_option (GCC_JIT_BOOL_OPTION_DUMP_INITIAL_TREE
))
1430 debug_tree (m_stmt_list
);
1432 /* Do we need this to force cgraphunit.c to output the function? */
1433 if (m_kind
== GCC_JIT_FUNCTION_EXPORTED
)
1435 DECL_EXTERNAL (m_inner_fndecl
) = 0;
1436 DECL_PRESERVE_P (m_inner_fndecl
) = 1;
1439 if (m_kind
== GCC_JIT_FUNCTION_INTERNAL
1440 ||m_kind
== GCC_JIT_FUNCTION_ALWAYS_INLINE
)
1442 DECL_EXTERNAL (m_inner_fndecl
) = 0;
1443 TREE_PUBLIC (m_inner_fndecl
) = 0;
1446 if (m_kind
!= GCC_JIT_FUNCTION_IMPORTED
)
1448 /* Seem to need this in gimple-low.c: */
1449 gcc_assert (m_inner_block
);
1450 DECL_INITIAL (m_inner_fndecl
) = m_inner_block
;
1452 /* how to add to function? the following appears to be how to
1453 set the body of a m_inner_fndecl: */
1454 DECL_SAVED_TREE(m_inner_fndecl
) = m_inner_bind_expr
;
1456 /* Ensure that locals appear in the debuginfo. */
1457 BLOCK_VARS (m_inner_block
) = BIND_EXPR_VARS (m_inner_bind_expr
);
1459 //debug_tree (m_inner_fndecl);
1461 /* Convert to gimple: */
1462 //printf("about to gimplify_function_tree\n");
1463 gimplify_function_tree (m_inner_fndecl
);
1464 //printf("finished gimplify_function_tree\n");
1466 current_function_decl
= m_inner_fndecl
;
1467 if (m_ctxt
->get_bool_option (GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE
))
1468 dump_function_to_file (m_inner_fndecl
, stderr
, TDF_VOPS
|TDF_MEMSYMS
|TDF_LINENO
);
1469 //debug_tree (m_inner_fndecl);
1471 //printf("about to add to cgraph\n");
1472 /* Add to cgraph: */
1473 cgraph_node::finalize_function (m_inner_fndecl
, false);
1474 /* This can trigger a collection, so we need to have all of
1475 the funcs as roots. */
1477 current_function_decl
= NULL
;
1481 /* Don't leak vec's internal buffer (in non-GC heap) when we are
1485 playback::block::finalizer ()
1490 /* Add an eval of the rvalue to the function's statement list. */
1494 add_eval (location
*loc
,
1497 gcc_assert (rvalue
);
1500 set_tree_location (rvalue
->as_tree (), loc
);
1502 add_stmt (rvalue
->as_tree ());
1505 /* Add an assignment to the function's statement list. */
1509 add_assignment (location
*loc
,
1513 gcc_assert (lvalue
);
1514 gcc_assert (rvalue
);
1516 tree t_lvalue
= lvalue
->as_tree ();
1517 tree t_rvalue
= rvalue
->as_tree ();
1518 if (TREE_TYPE (t_rvalue
) != TREE_TYPE (t_lvalue
))
1520 t_rvalue
= build1 (CONVERT_EXPR
,
1521 TREE_TYPE (t_lvalue
),
1524 set_tree_location (t_rvalue
, loc
);
1528 build2 (MODIFY_EXPR
, TREE_TYPE (t_lvalue
),
1529 t_lvalue
, t_rvalue
);
1531 set_tree_location (stmt
, loc
);
1535 /* Add a comment to the function's statement list.
1536 For now this is done by adding a dummy label. */
1540 add_comment (location
*loc
,
1543 /* Wrap the text in C-style comment delimiters. */
1545 (3 /* opening delim */
1547 + 3 /* closing delim */
1548 + 1 /* terminator */);
1549 char *wrapped
= (char *)ggc_internal_alloc (sz
);
1550 snprintf (wrapped
, sz
, "/* %s */", text
);
1552 /* For now we simply implement this by adding a dummy label with a name
1553 containing the given text. */
1554 tree identifier
= get_identifier (wrapped
);
1555 tree label_decl
= build_decl (UNKNOWN_LOCATION
, LABEL_DECL
,
1556 identifier
, void_type_node
);
1557 DECL_CONTEXT (label_decl
) = m_func
->as_fndecl ();
1559 tree label_expr
= build1 (LABEL_EXPR
, void_type_node
, label_decl
);
1561 set_tree_location (label_expr
, loc
);
1562 add_stmt (label_expr
);
1565 /* Add a conditional jump statement to the function's statement list. */
1569 add_conditional (location
*loc
,
1574 gcc_assert (boolval
);
1575 gcc_assert (on_true
);
1576 gcc_assert (on_false
);
1578 /* COND_EXPR wants statement lists for the true/false operands, but we
1580 Shim it by creating jumps to the labels */
1581 tree true_jump
= build1 (GOTO_EXPR
, void_type_node
,
1582 on_true
->as_label_decl ());
1584 set_tree_location (true_jump
, loc
);
1586 tree false_jump
= build1 (GOTO_EXPR
, void_type_node
,
1587 on_false
->as_label_decl ());
1589 set_tree_location (false_jump
, loc
);
1592 build3 (COND_EXPR
, void_type_node
, boolval
->as_tree (),
1593 true_jump
, false_jump
);
1595 set_tree_location (stmt
, loc
);
1599 /* Add an unconditional jump statement to the function's statement list. */
1603 add_jump (location
*loc
,
1606 gcc_assert (target
);
1608 // see c_finish_loop
1609 //tree top = build1 (LABEL_EXPR, void_type_node, NULL_TREE);
1612 //tree stmt = build_and_jump (&LABEL_EXPR_LABEL (target->label_));
1613 TREE_USED (target
->as_label_decl ()) = 1;
1614 tree stmt
= build1 (GOTO_EXPR
, void_type_node
, target
->as_label_decl ());
1616 set_tree_location (stmt
, loc
);
1622 c_finish_goto_label (location_t loc, tree label)
1624 tree decl = lookup_label_for_goto (loc, label);
1627 TREE_USED (decl) = 1;
1629 tree t = build1 (GOTO_EXPR, void_type_node, decl);
1630 SET_EXPR_LOCATION (t, loc);
1631 return add_stmt (t);
1638 /* Add a return statement to the function's statement list. */
1642 add_return (location
*loc
,
1645 tree modify_retval
= NULL
;
1646 tree return_type
= m_func
->get_return_type_as_tree ();
1649 tree t_lvalue
= DECL_RESULT (m_func
->as_fndecl ());
1650 tree t_rvalue
= rvalue
->as_tree ();
1651 if (TREE_TYPE (t_rvalue
) != TREE_TYPE (t_lvalue
))
1652 t_rvalue
= build1 (CONVERT_EXPR
,
1653 TREE_TYPE (t_lvalue
),
1655 modify_retval
= build2 (MODIFY_EXPR
, return_type
,
1656 t_lvalue
, t_rvalue
);
1658 set_tree_location (modify_retval
, loc
);
1660 tree return_stmt
= build1 (RETURN_EXPR
, return_type
,
1663 set_tree_location (return_stmt
, loc
);
1665 add_stmt (return_stmt
);
1668 /* Helper function for playback::block::add_switch.
1669 Construct a case label for the given range, followed by a goto stmt
1670 to the given block, appending them to stmt list *ptr_t_switch_body. */
1673 add_case (tree
*ptr_t_switch_body
,
1676 playback::block
*dest_block
)
1678 tree t_label
= create_artificial_label (UNKNOWN_LOCATION
);
1679 DECL_CONTEXT (t_label
) = dest_block
->get_function ()->as_fndecl ();
1682 build_case_label (t_low_value
, t_high_value
, t_label
);
1683 append_to_statement_list (t_case_label
, ptr_t_switch_body
);
1686 build1 (GOTO_EXPR
, void_type_node
, dest_block
->as_label_decl ());
1687 append_to_statement_list (t_goto_stmt
, ptr_t_switch_body
);
1690 /* Add a switch statement to the function's statement list.
1692 We create a switch body, and populate it with case labels, each
1693 followed by a goto to the desired block. */
1697 add_switch (location
*loc
,
1699 block
*default_block
,
1700 const auto_vec
<case_
> *cases
)
1703 - c/c-typeck.c: c_start_case
1704 - c-family/c-common.c:c_add_case_label
1705 - java/expr.c:expand_java_switch and expand_java_add_case
1706 We've already rejected overlaps and duplicates in
1707 libgccjit.c:case_range_validator::validate. */
1709 tree t_expr
= expr
->as_tree ();
1710 tree t_type
= TREE_TYPE (t_expr
);
1712 tree t_switch_body
= alloc_stmt_list ();
1716 FOR_EACH_VEC_ELT (*cases
, i
, c
)
1718 tree t_low_value
= c
->m_min_value
->as_tree ();
1719 tree t_high_value
= c
->m_max_value
->as_tree ();
1720 add_case (&t_switch_body
, t_low_value
, t_high_value
, c
->m_dest_block
);
1722 /* Default label. */
1723 add_case (&t_switch_body
, NULL_TREE
, NULL_TREE
, default_block
);
1725 tree switch_stmt
= build2 (SWITCH_EXPR
, t_type
, t_expr
, t_switch_body
);
1727 set_tree_location (switch_stmt
, loc
);
1728 add_stmt (switch_stmt
);
1731 /* Constructor for gcc::jit::playback::block. */
1734 block (function
*func
,
1744 identifier
= get_identifier (name
);
1747 m_label_decl
= build_decl (UNKNOWN_LOCATION
, LABEL_DECL
,
1748 identifier
, void_type_node
);
1749 DECL_CONTEXT (m_label_decl
) = func
->as_fndecl ();
1750 m_label_expr
= NULL
;
1753 /* A subclass of auto_vec <char *> that frees all of its elements on
1756 class auto_argvec
: public auto_vec
<char *>
1762 /* auto_argvec's dtor, freeing all contained strings, automatically
1763 chaining up to ~auto_vec <char *>, which frees the internal buffer. */
1765 auto_argvec::~auto_argvec ()
1769 FOR_EACH_VEC_ELT (*this, i
, str
)
1773 /* Compile a playback::context:
1775 - Use the context's options to cconstruct command-line options, and
1776 call into the rest of GCC (toplev::main).
1777 - Assuming it succeeds, we have a .s file.
1778 - We then run the "postprocess" vfunc:
1780 (A) In-memory compile ("gcc_jit_context_compile")
1782 For an in-memory compile we have the playback::compile_to_memory
1783 subclass; "postprocess" will convert the .s file to a .so DSO,
1784 and load it in memory (via dlopen), wrapping the result up as
1785 a jit::result and returning it.
1787 (B) Compile to file ("gcc_jit_context_compile_to_file")
1789 When compiling to a file, we have the playback::compile_to_file
1790 subclass; "postprocess" will either copy the .s file to the
1791 destination (for GCC_JIT_OUTPUT_KIND_ASSEMBLER), or invoke
1792 the driver to convert it as necessary, copying the result. */
1798 JIT_LOG_SCOPE (get_logger ());
1800 const char *ctxt_progname
;
1802 int keep_intermediates
=
1803 get_bool_option (GCC_JIT_BOOL_OPTION_KEEP_INTERMEDIATES
);
1805 m_tempdir
= new tempdir (get_logger (), keep_intermediates
);
1806 if (!m_tempdir
->create ())
1809 /* Call into the rest of gcc.
1810 For now, we have to assemble command-line options to pass into
1811 toplev::main, so that they can be parsed. */
1813 /* Pass in user-provided program name as argv0, if any, so that it
1814 makes it into GCC's "progname" global, used in various diagnostics. */
1815 ctxt_progname
= get_str_option (GCC_JIT_STR_OPTION_PROGNAME
);
1818 ctxt_progname
= "libgccjit.so";
1820 auto_vec
<recording::requested_dump
> requested_dumps
;
1821 m_recording_ctxt
->get_all_requested_dumps (&requested_dumps
);
1823 /* Acquire the JIT mutex and set "this" as the active playback ctxt. */
1826 auto_argvec fake_args
;
1827 make_fake_args (&fake_args
, ctxt_progname
, &requested_dumps
);
1828 if (errors_occurred ())
1834 /* This runs the compiler. */
1835 toplev
toplev (get_timer (), /* external_timer */
1836 false); /* init_signals */
1837 enter_scope ("toplev::main");
1839 for (unsigned i
= 0; i
< fake_args
.length (); i
++)
1840 get_logger ()->log ("argv[%i]: %s", i
, fake_args
[i
]);
1841 toplev
.main (fake_args
.length (),
1842 const_cast <char **> (fake_args
.address ()));
1843 exit_scope ("toplev::main");
1845 /* Extracting dumps makes use of the gcc::dump_manager, hence we
1846 need to do it between toplev::main (which creates the dump manager)
1847 and toplev::finalize (which deletes it). */
1848 extract_any_requested_dumps (&requested_dumps
);
1850 /* Clean up the compiler. */
1851 enter_scope ("toplev::finalize");
1853 exit_scope ("toplev::finalize");
1855 /* Ideally we would release the jit mutex here, but we can't yet since
1856 followup activities use timevars, which are global state. */
1858 if (errors_occurred ())
1864 if (get_bool_option (GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE
))
1865 dump_generated_code ();
1867 /* We now have a .s file.
1869 Run any postprocessing steps. This will either convert the .s file to
1870 a .so DSO, and load it in memory (playback::compile_to_memory), or
1871 convert the .s file to the requested output format, and copy it to a
1872 given file (playback::compile_to_file). */
1873 postprocess (ctxt_progname
);
1878 /* Implementation of class gcc::jit::playback::compile_to_memory,
1879 a subclass of gcc::jit::playback::context. */
1881 /* playback::compile_to_memory's trivial constructor. */
1883 playback::compile_to_memory::compile_to_memory (recording::context
*ctxt
) :
1884 playback::context (ctxt
),
1887 JIT_LOG_SCOPE (get_logger ());
1890 /* Implementation of the playback::context::process vfunc for compiling
1893 Convert the .s file to a .so DSO, and load it in memory (via dlopen),
1894 wrapping the result up as a jit::result and returning it. */
1897 playback::compile_to_memory::postprocess (const char *ctxt_progname
)
1899 JIT_LOG_SCOPE (get_logger ());
1900 convert_to_dso (ctxt_progname
);
1901 if (errors_occurred ())
1903 m_result
= dlopen_built_dso ();
1906 /* Implementation of class gcc::jit::playback::compile_to_file,
1907 a subclass of gcc::jit::playback::context. */
1909 /* playback::compile_to_file's trivial constructor. */
1911 playback::compile_to_file::compile_to_file (recording::context
*ctxt
,
1912 enum gcc_jit_output_kind output_kind
,
1913 const char *output_path
) :
1914 playback::context (ctxt
),
1915 m_output_kind (output_kind
),
1916 m_output_path (output_path
)
1918 JIT_LOG_SCOPE (get_logger ());
1921 /* Implementation of the playback::context::process vfunc for compiling
1924 Either copy the .s file to the given destination (for
1925 GCC_JIT_OUTPUT_KIND_ASSEMBLER), or invoke the driver to convert it
1926 as necessary, copying the result. */
1929 playback::compile_to_file::postprocess (const char *ctxt_progname
)
1931 JIT_LOG_SCOPE (get_logger ());
1933 /* The driver takes different actions based on the filename, so
1934 we provide a filename with an appropriate suffix for the
1935 output kind, and then copy it up to the user-provided path,
1936 rather than directly compiling it to the requested output path. */
1938 switch (m_output_kind
)
1943 case GCC_JIT_OUTPUT_KIND_ASSEMBLER
:
1944 copy_file (get_tempdir ()->get_path_s_file (),
1946 /* The .s file is automatically unlinked by tempdir::~tempdir. */
1949 case GCC_JIT_OUTPUT_KIND_OBJECT_FILE
:
1951 char *tmp_o_path
= ::concat (get_tempdir ()->get_path (),
1954 invoke_driver (ctxt_progname
,
1955 get_tempdir ()->get_path_s_file (),
1958 false, /* bool shared, */
1959 false);/* bool run_linker */
1960 if (!errors_occurred ())
1962 copy_file (tmp_o_path
,
1964 get_tempdir ()->add_temp_file (tmp_o_path
);
1971 case GCC_JIT_OUTPUT_KIND_DYNAMIC_LIBRARY
:
1972 invoke_driver (ctxt_progname
,
1973 get_tempdir ()->get_path_s_file (),
1974 get_tempdir ()->get_path_so_file (),
1976 true, /* bool shared, */
1977 true);/* bool run_linker */
1978 if (!errors_occurred ())
1979 copy_file (get_tempdir ()->get_path_so_file (),
1981 /* The .so file is automatically unlinked by tempdir::~tempdir. */
1984 case GCC_JIT_OUTPUT_KIND_EXECUTABLE
:
1986 char *tmp_exe_path
= ::concat (get_tempdir ()->get_path (),
1989 invoke_driver (ctxt_progname
,
1990 get_tempdir ()->get_path_s_file (),
1993 false, /* bool shared, */
1994 true);/* bool run_linker */
1995 if (!errors_occurred ())
1997 copy_file (tmp_exe_path
,
1999 get_tempdir ()->add_temp_file (tmp_exe_path
);
2002 free (tmp_exe_path
);
2010 /* Copy SRC_PATH to DST_PATH, preserving permission bits (in particular,
2011 the "executable" bits).
2013 Any errors that occur are reported on the context and hence count as
2014 a failure of the compile.
2016 We can't in general hardlink or use "rename" from the tempdir since
2017 it might be on a different filesystem to the destination. For example,
2018 I get EXDEV: "Invalid cross-device link". */
2021 playback::compile_to_file::copy_file (const char *src_path
,
2022 const char *dst_path
)
2024 JIT_LOG_SCOPE (get_logger ());
2027 get_logger ()->log ("src_path: %s", src_path
);
2028 get_logger ()->log ("dst_path: %s", dst_path
);
2033 size_t total_sz_in
= 0;
2034 size_t total_sz_out
= 0;
2037 struct stat stat_buf
;
2039 f_in
= fopen (src_path
, "rb");
2043 "unable to open %s for reading: %s",
2049 /* Use stat on the filedescriptor to get the mode,
2050 so that we can copy it over (in particular, the
2051 "executable" bits). */
2052 if (-1 == fstat (fileno (f_in
), &stat_buf
))
2055 "unable to fstat %s: %s",
2062 f_out
= fopen (dst_path
, "wb");
2066 "unable to open %s for writing: %s",
2073 while ( (sz_in
= fread (buf
, 1, sizeof (buf
), f_in
)) )
2075 total_sz_in
+= sz_in
;
2076 size_t sz_out_remaining
= sz_in
;
2077 size_t sz_out_so_far
= 0;
2078 while (sz_out_remaining
)
2080 size_t sz_out
= fwrite (buf
+ sz_out_so_far
,
2084 gcc_assert (sz_out
<= sz_out_remaining
);
2088 "error writing to %s: %s",
2095 total_sz_out
+= sz_out
;
2096 sz_out_so_far
+= sz_out
;
2097 sz_out_remaining
-= sz_out
;
2099 gcc_assert (sz_out_so_far
== sz_in
);
2104 "error reading from %s: %s",
2110 gcc_assert (total_sz_in
== total_sz_out
);
2112 get_logger ()->log ("total bytes copied: %ld", total_sz_out
);
2114 /* Set the permissions of the copy to those of the original file,
2115 in particular the "executable" bits. */
2116 if (-1 == fchmod (fileno (f_out
), stat_buf
.st_mode
))
2118 "error setting mode of %s: %s",
2125 /* Helper functions for gcc::jit::playback::context::compile. */
2127 /* This mutex guards gcc::jit::recording::context::compile, so that only
2128 one thread can be accessing the bulk of GCC's state at once. */
2130 static pthread_mutex_t jit_mutex
= PTHREAD_MUTEX_INITIALIZER
;
2132 /* Acquire jit_mutex and set "this" as the active playback ctxt. */
2135 playback::context::acquire_mutex ()
2137 auto_timevar
tv (get_timer (), TV_JIT_ACQUIRING_MUTEX
);
2139 /* Acquire the big GCC mutex. */
2140 JIT_LOG_SCOPE (get_logger ());
2141 pthread_mutex_lock (&jit_mutex
);
2142 gcc_assert (NULL
== active_playback_ctxt
);
2143 active_playback_ctxt
= this;
2146 /* Release jit_mutex and clear the active playback ctxt. */
2149 playback::context::release_mutex ()
2151 /* Release the big GCC mutex. */
2152 JIT_LOG_SCOPE (get_logger ());
2153 gcc_assert (active_playback_ctxt
== this);
2154 active_playback_ctxt
= NULL
;
2155 pthread_mutex_unlock (&jit_mutex
);
2158 /* Callback used by gcc::jit::playback::context::make_fake_args when
2159 invoking driver_get_configure_time_options.
2160 Populate a vec <char * > with the configure-time options. */
2163 append_arg_from_driver (const char *option
, void *user_data
)
2165 gcc_assert (option
);
2166 gcc_assert (user_data
);
2167 vec
<char *> *argvec
= static_cast <vec
<char *> *> (user_data
);
2168 argvec
->safe_push (concat ("-", option
, NULL
));
2171 /* Build a fake argv for toplev::main from the options set
2172 by the user on the context . */
2176 make_fake_args (vec
<char *> *argvec
,
2177 const char *ctxt_progname
,
2178 vec
<recording::requested_dump
> *requested_dumps
)
2180 JIT_LOG_SCOPE (get_logger ());
2182 #define ADD_ARG(arg) argvec->safe_push (xstrdup (arg))
2183 #define ADD_ARG_TAKE_OWNERSHIP(arg) argvec->safe_push (arg)
2185 ADD_ARG (ctxt_progname
);
2186 ADD_ARG (get_path_c_file ());
2189 /* Handle int options: */
2190 switch (get_int_option (GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL
))
2194 "unrecognized optimization level: %i",
2195 get_int_option (GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL
));
2214 /* What about -Os? */
2216 /* Handle bool options: */
2217 if (get_bool_option (GCC_JIT_BOOL_OPTION_DEBUGINFO
))
2220 /* Suppress timing (and other) info. */
2221 if (!get_bool_option (GCC_JIT_BOOL_OPTION_DUMP_SUMMARY
))
2227 /* Aggressively garbage-collect, to shake out bugs: */
2228 if (get_bool_option (GCC_JIT_BOOL_OPTION_SELFCHECK_GC
))
2230 ADD_ARG ("--param");
2231 ADD_ARG ("ggc-min-expand=0");
2232 ADD_ARG ("--param");
2233 ADD_ARG ("ggc-min-heapsize=0");
2236 if (get_bool_option (GCC_JIT_BOOL_OPTION_DUMP_EVERYTHING
))
2238 ADD_ARG ("-fdump-tree-all");
2239 ADD_ARG ("-fdump-rtl-all");
2240 ADD_ARG ("-fdump-ipa-all");
2243 /* Add "-fdump-" options for any calls to
2244 gcc_jit_context_enable_dump. */
2247 recording::requested_dump
*d
;
2248 FOR_EACH_VEC_ELT (*requested_dumps
, i
, d
)
2250 char *arg
= concat ("-fdump-", d
->m_dumpname
, NULL
);
2251 ADD_ARG_TAKE_OWNERSHIP (arg
);
2255 /* PR jit/64810: Add any target-specific default options
2256 from OPTION_DEFAULT_SPECS, normally provided by the driver
2257 in the non-jit case.
2259 The target-specific code can define OPTION_DEFAULT_SPECS:
2260 default command options in the form of spec macros for the
2261 driver to expand ().
2263 For cc1 etc, the driver processes OPTION_DEFAULT_SPECS and,
2264 if not overriden, injects the defaults as extra arguments to
2266 For the jit case, we need to add these arguments here. The
2267 input format (using the specs language) means that we have to run
2268 part of the driver code here (driver_get_configure_time_options).
2270 To avoid running the spec-expansion code every time, we just do
2271 it the first time (via a function-static flag), saving the result
2272 into a function-static vec.
2273 This flag and vec are global state (i.e. per-process).
2274 They are guarded by the jit mutex. */
2276 static bool have_configure_time_options
= false;
2277 static vec
<char *> configure_time_options
;
2279 if (have_configure_time_options
)
2280 log ("reusing cached configure-time options");
2283 have_configure_time_options
= true;
2284 log ("getting configure-time options from driver");
2285 driver_get_configure_time_options (append_arg_from_driver
,
2286 &configure_time_options
);
2293 FOR_EACH_VEC_ELT (configure_time_options
, i
, opt
)
2294 log ("configure_time_options[%i]: %s", i
, opt
);
2296 /* configure_time_options should now contain the expanded options
2297 from OPTION_DEFAULT_SPECS (if any). */
2298 FOR_EACH_VEC_ELT (configure_time_options
, i
, opt
)
2301 gcc_assert (opt
[0] == '-');
2307 ADD_ARG ("-ftime-report");
2309 /* Add any user-provided extra options, starting with any from
2311 m_recording_ctxt
->append_command_line_options (argvec
);
2314 #undef ADD_ARG_TAKE_OWNERSHIP
2317 /* The second half of the implementation of gcc_jit_context_enable_dump.
2318 Iterate through the requested dumps, reading the underlying files
2319 into heap-allocated buffers, writing pointers to the buffers into
2320 the char ** pointers provided by client code.
2321 Client code is responsible for calling free on the results. */
2325 extract_any_requested_dumps (vec
<recording::requested_dump
> *requested_dumps
)
2327 JIT_LOG_SCOPE (get_logger ());
2330 recording::requested_dump
*d
;
2331 FOR_EACH_VEC_ELT (*requested_dumps
, i
, d
)
2333 dump_file_info
*dfi
;
2337 dfi
= g
->get_dumps ()->get_dump_file_info_by_switch (d
->m_dumpname
);
2340 add_error (NULL
, "unrecognized dump: %s", d
->m_dumpname
);
2344 filename
= g
->get_dumps ()->get_dump_file_name (dfi
);
2345 content
= read_dump_file (filename
);
2346 *(d
->m_out_ptr
) = content
;
2347 m_tempdir
->add_temp_file (filename
);
2351 /* Helper function for playback::context::extract_any_requested_dumps
2352 (itself for use in implementation of gcc_jit_context_enable_dump).
2354 Attempt to read the complete file at the given path, returning the
2355 bytes found there as a buffer.
2356 The caller is responsible for calling free on the result.
2357 Errors will be reported on the context, and lead to NULL being
2358 returned; an out-of-memory error will terminate the process. */
2361 playback::context::read_dump_file (const char *path
)
2363 char *result
= NULL
;
2364 size_t total_sz
= 0;
2369 f_in
= fopen (path
, "r");
2372 add_error (NULL
, "unable to open %s for reading", path
);
2376 while ( (sz
= fread (buf
, 1, sizeof (buf
), f_in
)) )
2378 size_t old_total_sz
= total_sz
;
2380 result
= reinterpret_cast <char *> (xrealloc (result
, total_sz
+ 1));
2381 memcpy (result
+ old_total_sz
, buf
, sz
);
2386 add_error (NULL
, "error reading from %s", path
);
2396 result
[total_sz
] = '\0';
2400 return xstrdup ("");
2403 /* Part of playback::context::compile ().
2405 We have a .s file; we want a .so file.
2406 We could reuse parts of gcc/gcc.c to do this.
2407 For now, just use the driver binary from the install, as
2408 named in gcc-driver-name.h
2409 e.g. "x86_64-unknown-linux-gnu-gcc-5.0.0". */
2413 convert_to_dso (const char *ctxt_progname
)
2415 JIT_LOG_SCOPE (get_logger ());
2417 invoke_driver (ctxt_progname
,
2418 m_tempdir
->get_path_s_file (),
2419 m_tempdir
->get_path_so_file (),
2421 true, /* bool shared, */
2422 true);/* bool run_linker */
2425 static const char * const gcc_driver_name
= GCC_DRIVER_NAME
;
2429 invoke_driver (const char *ctxt_progname
,
2430 const char *input_file
,
2431 const char *output_file
,
2436 JIT_LOG_SCOPE (get_logger ());
2438 bool embedded_driver
2439 = !get_inner_bool_option (INNER_BOOL_OPTION_USE_EXTERNAL_DRIVER
);
2441 /* Currently this lumps together both assembling and linking into
2443 auto_timevar
assemble_timevar (get_timer (), tv_id
);
2445 #define ADD_ARG(arg) argvec.safe_push (xstrdup (arg))
2447 ADD_ARG (gcc_driver_name
);
2449 add_multilib_driver_arguments (&argvec
);
2452 ADD_ARG ("-shared");
2457 ADD_ARG (input_file
);
2459 ADD_ARG (output_file
);
2461 /* Don't use the linker plugin.
2462 If running with just a "make" and not a "make install", then we'd
2464 "fatal error: -fuse-linker-plugin, but liblto_plugin.so not found"
2465 libto_plugin is a .la at build time, with it becoming installed with
2466 ".so" suffix: i.e. it doesn't exist with a .so suffix until install
2468 ADD_ARG ("-fno-use-linker-plugin");
2470 #if defined (DARWIN_X86) || defined (DARWIN_PPC)
2471 /* OS X's linker defaults to treating undefined symbols as errors.
2472 If the context has any imported functions or globals they will be
2473 undefined until the .so is dynamically-linked into the process.
2474 Ensure that the driver passes in "-undefined dynamic_lookup" to the
2476 ADD_ARG ("-Wl,-undefined,dynamic_lookup");
2484 /* pex_one's error-handling requires pname to be non-NULL. */
2485 gcc_assert (ctxt_progname
);
2488 for (unsigned i
= 0; i
< argvec
.length (); i
++)
2489 get_logger ()->log ("argv[%i]: %s", i
, argvec
[i
]);
2491 if (embedded_driver
)
2492 invoke_embedded_driver (&argvec
);
2494 invoke_external_driver (ctxt_progname
, &argvec
);
2499 invoke_embedded_driver (const vec
<char *> *argvec
)
2501 JIT_LOG_SCOPE (get_logger ());
2502 driver
d (true, /* can_finalize */
2504 int result
= d
.main (argvec
->length (),
2505 const_cast <char **> (argvec
->address ()));
2508 add_error (NULL
, "error invoking gcc driver");
2513 invoke_external_driver (const char *ctxt_progname
,
2514 vec
<char *> *argvec
)
2516 JIT_LOG_SCOPE (get_logger ());
2518 int exit_status
= 0;
2521 /* pex argv arrays are NULL-terminated. */
2522 argvec
->safe_push (NULL
);
2524 errmsg
= pex_one (PEX_SEARCH
, /* int flags, */
2526 const_cast <char *const *> (argvec
->address ()),
2527 ctxt_progname
, /* const char *pname */
2528 NULL
, /* const char *outname */
2529 NULL
, /* const char *errname */
2530 &exit_status
, /* int *status */
2531 &err
); /* int *err*/
2534 add_error (NULL
, "error invoking gcc driver: %s", errmsg
);
2538 /* pex_one can return a NULL errmsg when the executable wasn't
2539 found (or doesn't exist), so trap these cases also. */
2540 if (exit_status
|| err
)
2543 "error invoking gcc driver: exit_status: %i err: %i",
2546 "whilst attempting to run a driver named: %s",
2555 /* Extract the target-specific MULTILIB_DEFAULTS to
2556 multilib_defaults_raw for use by
2557 playback::context::add_multilib_driver_arguments (). */
2559 #ifndef MULTILIB_DEFAULTS
2560 #define MULTILIB_DEFAULTS { "" }
2563 static const char *const multilib_defaults_raw
[] = MULTILIB_DEFAULTS
;
2565 /* Helper function for playback::context::invoke_driver ().
2567 32-bit and 64-bit multilib peer builds of libgccjit.so may share
2568 a driver binary. We need to pass in options to the shared driver
2569 to get the appropriate assembler/linker options for this multilib
2574 add_multilib_driver_arguments (vec
<char *> *argvec
)
2576 JIT_LOG_SCOPE (get_logger ());
2578 /* Add copies of the arguments in multilib_defaults_raw to argvec,
2579 prepending each with a "-". */
2580 for (size_t i
= 0; i
< ARRAY_SIZE (multilib_defaults_raw
); i
++)
2581 if (multilib_defaults_raw
[i
][0])
2582 argvec
->safe_push (concat ("-", multilib_defaults_raw
[i
], NULL
));
2585 /* Dynamically-link the built DSO file into this process, using dlopen.
2586 Wrap it up within a jit::result *, and return that.
2587 Return NULL if any errors occur, reporting them on this context. */
2593 JIT_LOG_SCOPE (get_logger ());
2594 auto_timevar
load_timevar (get_timer (), TV_LOAD
);
2595 void *handle
= NULL
;
2596 const char *error
= NULL
;
2597 result
*result_obj
= NULL
;
2599 /* Clear any existing error. */
2602 handle
= dlopen (m_tempdir
->get_path_so_file (),
2603 RTLD_NOW
| RTLD_LOCAL
);
2604 if ((error
= dlerror()) != NULL
) {
2605 add_error (NULL
, "%s", error
);
2609 /* We've successfully dlopened the result; create a
2610 jit::result object to wrap it.
2612 We're done with the tempdir for now, but if the user
2613 has requested debugging, the user's debugger might not
2614 be capable of dealing with the .so file being unlinked
2615 immediately, so keep it around until after the result
2616 is released. We do this by handing over ownership of
2617 the jit::tempdir to the result. See PR jit/64206. */
2618 tempdir
*handover_tempdir
;
2619 if (get_bool_option (GCC_JIT_BOOL_OPTION_DEBUGINFO
))
2621 handover_tempdir
= m_tempdir
;
2623 /* The tempdir will eventually be cleaned up in the
2624 jit::result's dtor. */
2625 log ("GCC_JIT_BOOL_OPTION_DEBUGINFO was set:"
2626 " handing over tempdir to jit::result");
2630 handover_tempdir
= NULL
;
2631 /* ... and retain ownership of m_tempdir so we clean it
2632 up it the playback::context's dtor. */
2633 log ("GCC_JIT_BOOL_OPTION_DEBUGINFO was not set:"
2634 " retaining ownership of tempdir");
2637 result_obj
= new result (get_logger (), handle
, handover_tempdir
);
2645 /* Top-level hook for playing back a recording context.
2647 This plays back m_recording_ctxt, and, if no errors
2648 occurred builds statement lists for and then postprocesses
2649 every function in the result. */
2655 JIT_LOG_SCOPE (get_logger ());
2656 /* Adapted from c-common.c:c_common_nodes_and_builtins. */
2657 tree array_domain_type
= build_index_type (size_int (200));
2658 m_char_array_type_node
2659 = build_array_type (char_type_node
, array_domain_type
);
2662 = build_pointer_type (build_qualified_type (char_type_node
,
2665 /* Replay the recorded events: */
2666 timevar_push (TV_JIT_REPLAY
);
2668 m_recording_ctxt
->replay_into (this);
2670 /* Clean away the temporary references from recording objects
2671 to playback objects. We have to do this now since the
2672 latter are GC-allocated, but the former don't mark these
2673 refs. Hence we must stop using them before the GC can run. */
2674 m_recording_ctxt
->disassociate_from_playback ();
2676 /* The builtins_manager, if any, is associated with the recording::context
2677 and might be reused for future compiles on other playback::contexts,
2678 but its m_attributes array is not GTY-labeled and hence will become
2679 nonsense if the GC runs. Purge this state. */
2680 builtins_manager
*bm
= get_builtins_manager ();
2682 bm
->finish_playback ();
2684 timevar_pop (TV_JIT_REPLAY
);
2686 if (!errors_occurred ())
2691 /* No GC can happen yet; process the cached source locations. */
2692 handle_locations ();
2694 /* We've now created tree nodes for the stmts in the various blocks
2695 in each function, but we haven't built each function's single stmt
2696 list yet. Do so now. */
2697 FOR_EACH_VEC_ELT (m_functions
, i
, func
)
2698 func
->build_stmt_list ();
2700 /* No GC can have happened yet. */
2702 /* Postprocess the functions. This could trigger GC. */
2703 FOR_EACH_VEC_ELT (m_functions
, i
, func
)
2706 func
->postprocess ();
2711 /* Dump the generated .s file to stderr. */
2715 dump_generated_code ()
2717 JIT_LOG_SCOPE (get_logger ());
2720 FILE *f_in
= fopen (get_path_s_file (), "r");
2724 while ( (sz
= fread (buf
, 1, sizeof (buf
), f_in
)) )
2725 fwrite (buf
, 1, sz
, stderr
);
2730 /* Get the supposed path of the notional "fake.c" file within the
2731 tempdir. This file doesn't exist, but the rest of the compiler
2736 get_path_c_file () const
2738 return m_tempdir
->get_path_c_file ();
2741 /* Get the path of the assembler output file "fake.s" file within the
2746 get_path_s_file () const
2748 return m_tempdir
->get_path_s_file ();
2751 /* Get the path of the DSO object file "fake.so" file within the
2756 get_path_so_file () const
2758 return m_tempdir
->get_path_so_file ();
2761 /* qsort comparator for comparing pairs of playback::source_line *,
2762 ordering them by line number. */
2765 line_comparator (const void *lhs
, const void *rhs
)
2767 const playback::source_line
*line_lhs
= \
2768 *static_cast<const playback::source_line
* const*> (lhs
);
2769 const playback::source_line
*line_rhs
= \
2770 *static_cast<const playback::source_line
* const*> (rhs
);
2771 return line_lhs
->get_line_num () - line_rhs
->get_line_num ();
2774 /* qsort comparator for comparing pairs of playback::location *,
2775 ordering them by column number. */
2778 location_comparator (const void *lhs
, const void *rhs
)
2780 const playback::location
*loc_lhs
= \
2781 *static_cast<const playback::location
* const *> (lhs
);
2782 const playback::location
*loc_rhs
= \
2783 *static_cast<const playback::location
* const *> (rhs
);
2784 return loc_lhs
->get_column_num () - loc_rhs
->get_column_num ();
2787 /* Our API allows locations to be created in arbitrary orders, but the
2788 linemap API requires locations to be created in ascending order
2789 as if we were tokenizing files.
2791 This hook sorts all of the locations that have been created, and
2792 calls into the linemap API, creating linemap entries in sorted order
2793 for our locations. */
2799 /* Create the source code locations, following the ordering rules
2800 imposed by the linemap API.
2802 line_table is a global. */
2803 JIT_LOG_SCOPE (get_logger ());
2807 FOR_EACH_VEC_ELT (m_source_files
, i
, file
)
2809 linemap_add (line_table
, LC_ENTER
, false, file
->get_filename (), 0);
2811 /* Sort lines by ascending line numbers. */
2812 file
->m_source_lines
.qsort (&line_comparator
);
2816 FOR_EACH_VEC_ELT (file
->m_source_lines
, j
, line
)
2821 /* Sort locations in line by ascending column numbers. */
2822 line
->m_locations
.qsort (&location_comparator
);
2824 /* Determine maximum column within this line. */
2825 gcc_assert (line
->m_locations
.length () > 0);
2826 location
*final_column
=
2827 line
->m_locations
[line
->m_locations
.length () - 1];
2828 int max_col
= final_column
->get_column_num ();
2830 linemap_line_start (line_table
, line
->get_line_num (), max_col
);
2831 FOR_EACH_VEC_ELT (line
->m_locations
, k
, loc
)
2834 linemap_position_for_column (line_table
, loc
->get_column_num ());
2838 linemap_add (line_table
, LC_LEAVE
, false, NULL
, 0);
2841 /* line_table should now be populated; every playback::location should
2842 now have an m_srcloc. */
2844 /* Now assign them to tree nodes as appropriate. */
2845 std::pair
<tree
, location
*> *cached_location
;
2847 FOR_EACH_VEC_ELT (m_cached_locations
, i
, cached_location
)
2849 tree t
= cached_location
->first
;
2850 source_location srcloc
= cached_location
->second
->m_srcloc
;
2852 /* This covers expressions: */
2853 if (CAN_HAVE_LOCATION_P (t
))
2854 SET_EXPR_LOCATION (t
, srcloc
);
2855 else if (CODE_CONTAINS_STRUCT(TREE_CODE(t
), TS_DECL_MINIMAL
))
2856 DECL_SOURCE_LOCATION (t
) = srcloc
;
2859 /* Don't know how to set location on this node. */
2864 /* We handle errors on a playback::context by adding them to the
2865 corresponding recording::context. */
2869 add_error (location
*loc
, const char *fmt
, ...)
2873 m_recording_ctxt
->add_error_va (loc
? loc
->get_recording_loc () : NULL
,
2878 /* We handle errors on a playback::context by adding them to the
2879 corresponding recording::context. */
2883 add_error_va (location
*loc
, const char *fmt
, va_list ap
)
2885 m_recording_ctxt
->add_error_va (loc
? loc
->get_recording_loc () : NULL
,
2889 /* Report a diagnostic up to the jit context as an error,
2890 so that the compilation is treated as a failure.
2891 For now, any kind of diagnostic is treated as an error by the jit
2896 add_diagnostic (struct diagnostic_context
*diag_context
,
2897 struct diagnostic_info
*diagnostic
)
2899 /* At this point the text has been formatted into the pretty-printer's
2901 pretty_printer
*pp
= diag_context
->printer
;
2902 const char *text
= pp_formatted_text (pp
);
2904 /* Get location information (if any) from the diagnostic.
2905 The recording::context::add_error[_va] methods require a
2906 recording::location. We can't lookup the playback::location
2907 from the file/line/column since any playback location instances
2908 may have been garbage-collected away by now, so instead we create
2909 another recording::location directly. */
2910 location_t gcc_loc
= diagnostic_location (diagnostic
);
2911 recording::location
*rec_loc
= NULL
;
2914 expanded_location exploc
= expand_location (gcc_loc
);
2916 rec_loc
= m_recording_ctxt
->new_location (exploc
.file
,
2922 m_recording_ctxt
->add_error (rec_loc
, "%s", text
);
2923 pp_clear_output_area (pp
);
2926 /* Dealing with the linemap API. */
2928 /* Construct a playback::location for a recording::location, if it
2929 doesn't exist already. */
2931 playback::location
*
2933 new_location (recording::location
*rloc
,
2934 const char *filename
,
2938 /* Get the source_file for filename, creating if necessary. */
2939 source_file
*src_file
= get_source_file (filename
);
2940 /* Likewise for the line within the file. */
2941 source_line
*src_line
= src_file
->get_source_line (line
);
2942 /* Likewise for the column within the line. */
2943 location
*loc
= src_line
->get_location (rloc
, column
);
2947 /* Deferred setting of the location for a given tree, by adding the
2948 (tree, playback::location) pair to a list of deferred associations.
2949 We will actually set the location on the tree later on once
2950 the source_location for the playback::location exists. */
2954 set_tree_location (tree t
, location
*loc
)
2957 m_cached_locations
.safe_push (std::make_pair (t
, loc
));
2961 /* Construct a playback::source_file for the given source
2962 filename, if it doesn't exist already. */
2964 playback::source_file
*
2966 get_source_file (const char *filename
)
2969 For simplicitly, this is currently a linear search.
2970 Replace with a hash if this shows up in the profile. */
2973 tree ident_filename
= get_identifier (filename
);
2975 FOR_EACH_VEC_ELT (m_source_files
, i
, file
)
2976 if (file
->filename_as_tree () == ident_filename
)
2980 file
= new source_file (ident_filename
);
2981 m_source_files
.safe_push (file
);
2985 /* Constructor for gcc::jit::playback::source_file. */
2987 playback::source_file::source_file (tree filename
) :
2989 m_filename (filename
)
2993 /* Don't leak vec's internal buffer (in non-GC heap) when we are
2997 playback::source_file::finalizer ()
2999 m_source_lines
.release ();
3002 /* Construct a playback::source_line for the given line
3003 within this source file, if one doesn't exist already. */
3005 playback::source_line
*
3006 playback::source_file::
3007 get_source_line (int line_num
)
3010 For simplicitly, this is currently a linear search.
3011 Replace with a hash if this shows up in the profile. */
3015 FOR_EACH_VEC_ELT (m_source_lines
, i
, line
)
3016 if (line
->get_line_num () == line_num
)
3020 line
= new source_line (this, line_num
);
3021 m_source_lines
.safe_push (line
);
3025 /* Constructor for gcc::jit::playback::source_line. */
3027 playback::source_line::source_line (source_file
*file
, int line_num
) :
3029 m_source_file (file
),
3030 m_line_num (line_num
)
3034 /* Don't leak vec's internal buffer (in non-GC heap) when we are
3038 playback::source_line::finalizer ()
3040 m_locations
.release ();
3043 /* Construct a playback::location for the given column
3044 within this line of a specific source file, if one doesn't exist
3047 playback::location
*
3048 playback::source_line::
3049 get_location (recording::location
*rloc
, int column_num
)
3054 /* Another linear search that probably should be a hash table. */
3055 FOR_EACH_VEC_ELT (m_locations
, i
, loc
)
3056 if (loc
->get_column_num () == column_num
)
3060 loc
= new location (rloc
, this, column_num
);
3061 m_locations
.safe_push (loc
);
3065 /* Constructor for gcc::jit::playback::location. */
3067 playback::location::location (recording::location
*loc
,
3070 m_srcloc (UNKNOWN_LOCATION
),
3071 m_recording_loc (loc
),
3073 m_column_num(column_num
)
3077 /* The active gcc::jit::playback::context instance. This is a singleton,
3078 guarded by jit_mutex. */
3080 playback::context
*active_playback_ctxt
;
3082 } // namespace gcc::jit