Debian Codegraph @

gcc/jit/jit-playback.cc

raw
1 /* Internals of libgccjit: classes for playing back recorded API calls.
2 Copyright (C) 2013-2025 Free Software Foundation, Inc.
3 Contributed by David Malcolm <[email protected]>.
4
5 This file is part of GCC.
6
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)
10 any later version.
11
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.
16
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/>. */
20
21 #include "config.h"
22 #define INCLUDE_MUTEX
23 #define INCLUDE_DLFCN_H
24 #include "libgccjit.h"
25 #include "system.h"
26 #include "coretypes.h"
27 #include "target.h"
28 #include "tree.h"
29 #include "stringpool.h"
30 #include "cgraph.h"
31 #include "dumpfile.h"
32 #include "toplev.h"
33 #include "tree-cfg.h"
34 #include "convert.h"
35 #include "gimple-expr.h"
36 #include "stor-layout.h"
37 #include "print-tree.h"
38 #include "gimplify.h"
39 #include "gcc-driver-name.h"
40 #include "attribs.h"
41 #include "context.h"
42 #include "fold-const.h"
43 #include "opt-suggestions.h"
44 #include "gcc.h"
45 #include "diagnostic.h"
46 #include "stmt.h"
47 #include "realmpfr.h"
48
49 #include "jit-playback.h"
50 #include "jit-result.h"
51 #include "jit-builtins.h"
52 #include "jit-tempdir.h"
53
54 #ifdef _WIN32
55 #include "jit-w32.h"
56 #endif
57
58 /* Compare with gcc/c-family/c-common.h: DECL_C_BIT_FIELD,
59 SET_DECL_C_BIT_FIELD.
60 These are redefined here to avoid depending from the C frontend. */
61 #define DECL_JIT_BIT_FIELD(NODE) \
62 (DECL_LANG_FLAG_4 (FIELD_DECL_CHECK (NODE)) == 1)
63 #define SET_DECL_JIT_BIT_FIELD(NODE) \
64 (DECL_LANG_FLAG_4 (FIELD_DECL_CHECK (NODE)) = 1)
65
66 /* gcc::jit::playback::context::build_cast uses the convert.h API,
67 which in turn requires the frontend to provide a "convert"
68 function, apparently as a fallback for casts that can be simplified
69 (truncation, extension). */
70 extern tree convert (tree type, tree expr);
71
72 tree
73 convert (tree dst_type, tree expr)
74 {
75 tree t_ret = NULL;
76 t_ret = targetm.convert_to_type (dst_type, expr);
77 if (t_ret)
78 return t_ret;
79 switch (TREE_CODE (dst_type))
80 {
81 case INTEGER_TYPE:
82 case ENUMERAL_TYPE:
83 return fold (convert_to_integer (dst_type, expr));
84
85 default:
86 gcc_assert (gcc::jit::active_playback_ctxt);
87 gcc::jit::active_playback_ctxt->add_error (NULL, "unhandled conversion");
88 fprintf (stderr, "input expression:\n");
89 debug_tree (expr);
90 fprintf (stderr, "requested type:\n");
91 debug_tree (dst_type);
92 return error_mark_node;
93 }
94 }
95
96 namespace gcc {
97 namespace jit {
98
99 /**********************************************************************
100 Playback.
101 **********************************************************************/
102
103 /* Fold a readonly non-volatile variable with an initial constant value,
104 to that value.
105
106 Otherwise return the argument unchanged.
107
108 This fold is needed for setting a variable's DECL_INITIAL to the value
109 of a const variable. The c-frontend does this in its own special
110 fold (), so we lift this part out and do it explicitly where there is a
111 potential for variables to be used as rvalues. */
112 static tree
113 fold_const_var (tree node)
114 {
115 /* See c_fully_fold_internal in c-fold.cc and decl_constant_value_1
116 in c-typeck.cc. */
117 if (VAR_P (node)
118 && TREE_READONLY (node)
119 && !TREE_THIS_VOLATILE (node)
120 && DECL_INITIAL (node) != NULL_TREE
121 /* "This is invalid if initial value is not constant.
122 If it has either a function call, a memory reference,
123 or a variable, then re-evaluating it could give different
124 results." */
125 && TREE_CONSTANT (DECL_INITIAL (node)))
126 {
127 tree ret = DECL_INITIAL (node);
128 /* "Avoid unwanted tree sharing between the initializer and current
129 function's body where the tree can be modified e.g. by the
130 gimplifier." */
131 if (TREE_STATIC (node))
132 ret = unshare_expr (ret);
133
134 return ret;
135 }
136
137 return node;
138 }
139
140 /* Build a STRING_CST tree for STR, or return NULL if it is NULL.
141 The TREE_TYPE is not initialized. */
142
143 static tree
144 build_string (const char *str)
145 {
146 if (str)
147 return ::build_string (strlen (str), str);
148 else
149 return NULL_TREE;
150 }
151
152 /* The constructor for gcc::jit::playback::context. */
153
154 playback::context::context (recording::context *ctxt)
155 : log_user (ctxt->get_logger ()),
156 m_recording_ctxt (ctxt),
157 m_tempdir (NULL),
158 m_const_char_ptr (NULL)
159 {
160 JIT_LOG_SCOPE (get_logger ());
161 m_functions.create (0);
162 m_globals.create (0);
163 m_source_files.create (0);
164 m_cached_locations.create (0);
165 }
166
167 /* The destructor for gcc::jit::playback::context. */
168
169 playback::context::~context ()
170 {
171 JIT_LOG_SCOPE (get_logger ());
172
173 /* Normally the playback::context is responsible for cleaning up the
174 tempdir (including "fake.so" within the filesystem).
175
176 In the normal case, clean it up now.
177
178 However m_tempdir can be NULL if the context has handed over
179 responsibility for the tempdir cleanup to the jit::result object, so
180 that the cleanup can be delayed (see PR jit/64206). If that's the
181 case this "delete NULL;" is a no-op. */
182 delete m_tempdir;
183
184 m_functions.release ();
185 }
186
187 /* A playback::context can reference GC-managed pointers. Mark them
188 ("by hand", rather than by gengtype).
189
190 This is called on the active playback context (if any) by the
191 my_ggc_walker hook in the jit_root_table in dummy-frontend.cc. */
192
193 void
194 playback::context::
195 gt_ggc_mx ()
196 {
197 int i;
198 function *func;
199 FOR_EACH_VEC_ELT (m_functions, i, func)
200 {
201 if (ggc_test_and_set_mark (func))
202 func->gt_ggc_mx ();
203 }
204 }
205
206 /* Given an enum gcc_jit_types value, get a "tree" type. */
207
208 tree
209 playback::context::
210 get_tree_node_for_type (enum gcc_jit_types type_)
211 {
212 switch (type_)
213 {
214 case GCC_JIT_TYPE_VOID:
215 return void_type_node;
216
217 case GCC_JIT_TYPE_VOID_PTR:
218 return ptr_type_node;
219
220 case GCC_JIT_TYPE_BOOL:
221 return boolean_type_node;
222
223 case GCC_JIT_TYPE_CHAR:
224 return char_type_node;
225 case GCC_JIT_TYPE_SIGNED_CHAR:
226 return signed_char_type_node;
227 case GCC_JIT_TYPE_UNSIGNED_CHAR:
228 return unsigned_char_type_node;
229
230 case GCC_JIT_TYPE_SHORT:
231 return short_integer_type_node;
232 case GCC_JIT_TYPE_UNSIGNED_SHORT:
233 return short_unsigned_type_node;
234
235 case GCC_JIT_TYPE_CONST_CHAR_PTR:
236 return m_const_char_ptr;
237
238 case GCC_JIT_TYPE_INT:
239 return integer_type_node;
240 case GCC_JIT_TYPE_UNSIGNED_INT:
241 return unsigned_type_node;
242
243 case GCC_JIT_TYPE_UINT8_T:
244 return unsigned_intQI_type_node;
245 case GCC_JIT_TYPE_UINT16_T:
246 return uint16_type_node;
247 case GCC_JIT_TYPE_UINT32_T:
248 return uint32_type_node;
249 case GCC_JIT_TYPE_UINT64_T:
250 return uint64_type_node;
251 case GCC_JIT_TYPE_UINT128_T:
252 if (targetm.scalar_mode_supported_p (TImode))
253 return uint128_type_node;
254
255 add_error (NULL, "gcc_jit_types value unsupported on this target: %i",
256 type_);
257 return NULL;
258
259 case GCC_JIT_TYPE_INT8_T:
260 return intQI_type_node;
261 case GCC_JIT_TYPE_INT16_T:
262 return intHI_type_node;
263 case GCC_JIT_TYPE_INT32_T:
264 return intSI_type_node;
265 case GCC_JIT_TYPE_INT64_T:
266 return intDI_type_node;
267 case GCC_JIT_TYPE_INT128_T:
268 if (targetm.scalar_mode_supported_p (TImode))
269 return intTI_type_node;
270
271 add_error (NULL, "gcc_jit_types value unsupported on this target: %i",
272 type_);
273 return NULL;
274
275 case GCC_JIT_TYPE_LONG:
276 return long_integer_type_node;
277 case GCC_JIT_TYPE_UNSIGNED_LONG:
278 return long_unsigned_type_node;
279
280 case GCC_JIT_TYPE_LONG_LONG:
281 return long_long_integer_type_node;
282 case GCC_JIT_TYPE_UNSIGNED_LONG_LONG:
283 return long_long_unsigned_type_node;
284
285 case GCC_JIT_TYPE_FLOAT:
286 return float_type_node;
287 case GCC_JIT_TYPE_BFLOAT16:
288 #ifndef HAVE_BFmode
289 add_error (NULL, "gcc_jit_types value unsupported on this target: %i",
290 type_);
291 #endif
292 return bfloat16_type_node;
293 case GCC_JIT_TYPE_DOUBLE:
294 return double_type_node;
295 case GCC_JIT_TYPE_LONG_DOUBLE:
296 return long_double_type_node;
297
298 case GCC_JIT_TYPE_SIZE_T:
299 return size_type_node;
300
301 case GCC_JIT_TYPE_FILE_PTR:
302 return fileptr_type_node;
303
304 case GCC_JIT_TYPE_COMPLEX_FLOAT:
305 return complex_float_type_node;
306 case GCC_JIT_TYPE_COMPLEX_DOUBLE:
307 return complex_double_type_node;
308 case GCC_JIT_TYPE_COMPLEX_LONG_DOUBLE:
309 return complex_long_double_type_node;
310 }
311
312 add_error (NULL, "unrecognized (enum gcc_jit_types) value: %i",
313 type_);
314
315 return NULL;
316 }
317
318 /* Construct a playback::type instance (wrapping a tree) for the given
319 enum value. */
320
321 playback::type *
322 playback::context::
323 get_type (enum gcc_jit_types type_)
324 {
325 tree type_node = get_tree_node_for_type (type_);
326 if (type_node == NULL)
327 return NULL;
328
329 return new type (type_node);
330 }
331
332 void
333 playback::context::
334 set_output_ident (const char* ident)
335 {
336 targetm.asm_out.output_ident (ident);
337 }
338
339 /* Construct a playback::type instance (wrapping a tree) for the given
340 array type. */
341
342 playback::type *
343 playback::context::
344 new_array_type (playback::location *loc,
345 playback::type *element_type,
346 int num_elements)
347 {
348 gcc_assert (element_type);
349
350 tree t = build_array_type_nelts (element_type->as_tree (),
351 num_elements);
352 layout_type (t);
353
354 if (loc)
355 set_tree_location (t, loc);
356
357 return new type (t);
358 }
359
360 /* Construct a playback::field instance (wrapping a tree). */
361
362 playback::field *
363 playback::context::
364 new_field (location *loc,
365 type *type,
366 const char *name)
367 {
368 gcc_assert (type);
369 gcc_assert (name);
370
371 /* compare with c/c-decl.cc:grokfield and grokdeclarator. */
372 tree decl = build_decl (UNKNOWN_LOCATION, FIELD_DECL,
373 get_identifier (name), type->as_tree ());
374
375 if (loc)
376 set_tree_location (decl, loc);
377
378 return new field (decl);
379 }
380
381 /* Construct a playback::bitfield instance (wrapping a tree). */
382
383 playback::field *
384 playback::context::
385 new_bitfield (location *loc,
386 type *type,
387 int width,
388 const char *name)
389 {
390 gcc_assert (type);
391 gcc_assert (name);
392 gcc_assert (width);
393
394 /* compare with c/c-decl.cc:grokfield, grokdeclarator and
395 check_bitfield_type_and_width. */
396
397 tree tree_type = type->as_tree ();
398 gcc_assert (INTEGRAL_TYPE_P (tree_type));
399 tree tree_width = build_int_cst (integer_type_node, width);
400 if (compare_tree_int (tree_width, TYPE_PRECISION (tree_type)) > 0)
401 {
402 add_error (
403 loc,
404 "width of bit-field %s (width: %i) is wider than its type (width: %i)",
405 name, width, TYPE_PRECISION (tree_type));
406 return NULL;
407 }
408
409 tree decl = build_decl (UNKNOWN_LOCATION, FIELD_DECL,
410 get_identifier (name), type->as_tree ());
411 DECL_NONADDRESSABLE_P (decl) = true;
412 DECL_INITIAL (decl) = tree_width;
413 SET_DECL_JIT_BIT_FIELD (decl);
414
415 if (loc)
416 set_tree_location (decl, loc);
417
418 return new field (decl);
419 }
420
421 /* Construct a playback::compound_type instance (wrapping a tree). */
422
423 playback::compound_type *
424 playback::context::
425 new_compound_type (location *loc,
426 const char *name,
427 bool is_struct) /* else is union */
428 {
429 gcc_assert (name);
430
431 /* Compare with c/c-decl.cc: start_struct. */
432
433 tree t = make_node (is_struct ? RECORD_TYPE : UNION_TYPE);
434 TYPE_NAME (t) = get_identifier (name);
435 TYPE_SIZE (t) = 0;
436
437 if (loc)
438 set_tree_location (t, loc);
439
440 return new compound_type (t);
441 }
442
443 void
444 playback::compound_type::set_fields (const auto_vec<playback::field *> *fields)
445 {
446 /* Compare with c/c-decl.cc: finish_struct. */
447 tree t = as_tree ();
448
449 tree fieldlist = NULL;
450 for (unsigned i = 0; i < fields->length (); i++)
451 {
452 field *f = (*fields)[i];
453 tree x = f->as_tree ();
454 DECL_CONTEXT (x) = t;
455 if (DECL_JIT_BIT_FIELD (x))
456 {
457 unsigned HOST_WIDE_INT width = tree_to_uhwi (DECL_INITIAL (x));
458 DECL_SIZE (x) = bitsize_int (width);
459 DECL_BIT_FIELD (x) = 1;
460 }
461 fieldlist = chainon (x, fieldlist);
462 }
463 fieldlist = nreverse (fieldlist);
464 TYPE_FIELDS (t) = fieldlist;
465
466 layout_type (t);
467 }
468
469 /* Construct a playback::type instance (wrapping a tree) for a function
470 type. */
471
472 playback::type *
473 playback::context::
474 new_function_type (type *return_type,
475 const auto_vec<type *> *param_types,
476 int is_variadic)
477 {
478 int i;
479 type *param_type;
480
481 tree *arg_types = (tree *)xcalloc(param_types->length (), sizeof(tree*));
482
483 FOR_EACH_VEC_ELT (*param_types, i, param_type)
484 arg_types[i] = param_type->as_tree ();
485
486 tree fn_type;
487 if (is_variadic)
488 fn_type =
489 build_varargs_function_type_array (return_type->as_tree (),
490 param_types->length (),
491 arg_types);
492 else
493 fn_type = build_function_type_array (return_type->as_tree (),
494 param_types->length (),
495 arg_types);
496 free (arg_types);
497
498 return new type (fn_type);
499 }
500
501 /* Construct a playback::param instance (wrapping a tree). */
502
503 playback::param *
504 playback::context::
505 new_param (location *loc,
506 type *type,
507 const char *name)
508 {
509 gcc_assert (type);
510 gcc_assert (name);
511 tree inner = build_decl (UNKNOWN_LOCATION, PARM_DECL,
512 get_identifier (name), type->as_tree ());
513 if (loc)
514 set_tree_location (inner, loc);
515
516 return new param (this, inner);
517 }
518
519 const char* fn_attribute_to_string (gcc_jit_fn_attribute attr)
520 {
521 switch (attr)
522 {
523 case GCC_JIT_FN_ATTRIBUTE_ALIAS:
524 return "alias";
525 case GCC_JIT_FN_ATTRIBUTE_ALWAYS_INLINE:
526 return "always_inline";
527 case GCC_JIT_FN_ATTRIBUTE_INLINE:
528 return NULL;
529 case GCC_JIT_FN_ATTRIBUTE_NOINLINE:
530 return "noinline";
531 case GCC_JIT_FN_ATTRIBUTE_TARGET:
532 return "target";
533 case GCC_JIT_FN_ATTRIBUTE_USED:
534 return "used";
535 case GCC_JIT_FN_ATTRIBUTE_VISIBILITY:
536 return "visibility";
537 case GCC_JIT_FN_ATTRIBUTE_COLD:
538 return "cold";
539 case GCC_JIT_FN_ATTRIBUTE_RETURNS_TWICE:
540 return "returns_twice";
541 case GCC_JIT_FN_ATTRIBUTE_PURE:
542 return "pure";
543 case GCC_JIT_FN_ATTRIBUTE_CONST:
544 return "const";
545 case GCC_JIT_FN_ATTRIBUTE_WEAK:
546 return "weak";
547 case GCC_JIT_FN_ATTRIBUTE_NONNULL:
548 return "nonnull";
549 case GCC_JIT_FN_ATTRIBUTE_MAX:
550 return NULL;
551 }
552 return NULL;
553 }
554
555 const char* variable_attribute_to_string (gcc_jit_variable_attribute attr)
556 {
557 switch (attr)
558 {
559 case GCC_JIT_VARIABLE_ATTRIBUTE_VISIBILITY:
560 return "visibility";
561 case GCC_JIT_VARIABLE_ATTRIBUTE_MAX:
562 return NULL;
563 }
564 return NULL;
565 }
566
567 /* Construct a playback::function instance. */
568
569 playback::function *
570 playback::context::
571 new_function (location *loc,
572 enum gcc_jit_function_kind kind,
573 type *return_type,
574 const char *name,
575 const auto_vec<param *> *params,
576 int is_variadic,
577 enum built_in_function builtin_id,
578 const std::vector<gcc_jit_fn_attribute> &attributes,
579 const std::vector<std::pair<gcc_jit_fn_attribute,
580 std::string>> &string_attributes,
581 const std::vector<std::pair<gcc_jit_fn_attribute,
582 std::vector<int>>>
583 &int_array_attributes,
584 bool is_target_builtin)
585 {
586 int i;
587 param *param;
588
589 //can return_type be NULL?
590 gcc_assert (name);
591
592 tree *arg_types = (tree *)xcalloc(params->length (), sizeof(tree*));
593 FOR_EACH_VEC_ELT (*params, i, param)
594 arg_types[i] = TREE_TYPE (param->as_tree ());
595
596 tree fn_type;
597 if (is_variadic)
598 fn_type = build_varargs_function_type_array (return_type->as_tree (),
599 params->length (), arg_types);
600 else
601 fn_type = build_function_type_array (return_type->as_tree (),
602 params->length (), arg_types);
603 free (arg_types);
604
605 /* FIXME: this uses input_location: */
606 tree fndecl = build_fn_decl (name, fn_type);
607
608 if (loc)
609 set_tree_location (fndecl, loc);
610
611 tree resdecl = build_decl (UNKNOWN_LOCATION, RESULT_DECL,
612 NULL_TREE, return_type->as_tree ());
613 DECL_ARTIFICIAL (resdecl) = 1;
614 DECL_IGNORED_P (resdecl) = 1;
615 DECL_RESULT (fndecl) = resdecl;
616 DECL_CONTEXT (resdecl) = fndecl;
617
618 tree fn_attributes = NULL_TREE;
619
620 if (is_target_builtin)
621 {
622 tree *decl = target_builtins.get (name);
623 if (decl != NULL)
624 fndecl = *decl;
625 else
626 add_error (loc, "cannot find target builtin %s", name);
627 }
628
629 if (builtin_id)
630 {
631 gcc_assert (loc == NULL);
632 DECL_SOURCE_LOCATION (fndecl) = BUILTINS_LOCATION;
633
634 built_in_class fclass = builtins_manager::get_class (builtin_id);
635 set_decl_built_in_function (fndecl, fclass, builtin_id);
636 set_builtin_decl (builtin_id, fndecl,
637 builtins_manager::implicit_p (builtin_id));
638
639 builtins_manager *bm = get_builtins_manager ();
640 tree attrs = bm->get_attrs_tree (builtin_id);
641 if (attrs)
642 decl_attributes (&fndecl, attrs, ATTR_FLAG_BUILT_IN);
643 else
644 decl_attributes (&fndecl, NULL_TREE, 0);
645 }
646
647 if (kind != GCC_JIT_FUNCTION_IMPORTED)
648 {
649 tree param_decl_list = NULL;
650 FOR_EACH_VEC_ELT (*params, i, param)
651 {
652 param_decl_list = chainon (param->as_tree (), param_decl_list);
653 }
654
655 /* The param list was created in reverse order; fix it: */
656 param_decl_list = nreverse (param_decl_list);
657
658 tree t;
659 for (t = param_decl_list; t; t = DECL_CHAIN (t))
660 {
661 DECL_CONTEXT (t) = fndecl;
662 DECL_ARG_TYPE (t) = TREE_TYPE (t);
663 }
664
665 /* Set it up on DECL_ARGUMENTS */
666 DECL_ARGUMENTS(fndecl) = param_decl_list;
667 }
668
669 if (kind == GCC_JIT_FUNCTION_ALWAYS_INLINE)
670 {
671 DECL_DECLARED_INLINE_P (fndecl) = 1;
672
673 /* Add attribute "always_inline": */
674 fn_attributes = tree_cons (get_identifier ("always_inline"),
675 NULL,
676 fn_attributes);
677 }
678
679 /* All attributes need to be declared in `dummy-frontend.cc` and more
680 specifically in `jit_attribute_table`. */
681 for (auto attr: attributes)
682 {
683 if (attr == GCC_JIT_FN_ATTRIBUTE_INLINE)
684 DECL_DECLARED_INLINE_P (fndecl) = 1;
685
686 const char* attribute = fn_attribute_to_string (attr);
687 if (attribute)
688 {
689 tree ident = get_identifier (attribute);
690 fn_attributes = tree_cons (ident, NULL_TREE, fn_attributes);
691 }
692 }
693
694 for (auto attr: string_attributes)
695 {
696 gcc_jit_fn_attribute& name = std::get<0>(attr);
697 std::string& value = std::get<1>(attr);
698 tree attribute_value = build_tree_list (NULL_TREE,
699 ::build_string (value.length () + 1, value.c_str ()));
700 const char* attribute = fn_attribute_to_string (name);
701 tree ident = attribute ? get_identifier (attribute) : NULL;
702
703 if (ident)
704 fn_attributes = tree_cons (ident, attribute_value, fn_attributes);
705 }
706
707 for (auto attr: int_array_attributes)
708 {
709 gcc_jit_fn_attribute& name = std::get<0>(attr);
710 std::vector<int>& values = std::get<1>(attr);
711
712 const char* attribute = fn_attribute_to_string (name);
713 tree ident = attribute ? get_identifier (attribute) : NULL;
714
715 if (!ident)
716 continue;
717
718 tree tree_list = NULL_TREE;
719 tree *p_tree_list = &tree_list;
720 for (auto value : values)
721 {
722 tree int_value = build_int_cst (integer_type_node, value);
723 *p_tree_list = build_tree_list (NULL, int_value);
724 p_tree_list = &TREE_CHAIN (*p_tree_list);
725 }
726 fn_attributes = tree_cons (ident, tree_list, fn_attributes);
727 }
728
729 decl_attributes (&fndecl, fn_attributes, 0);
730 function *func = new function (this, fndecl, kind);
731 m_functions.safe_push (func);
732 return func;
733 }
734
735 /* In use by new_global and new_global_initialized. */
736
737 tree
738 playback::context::
739 global_new_decl (location *loc,
740 enum gcc_jit_global_kind kind,
741 type *type,
742 const char *name,
743 enum global_var_flags flags,
744 const std::vector<std::pair<gcc_jit_variable_attribute,
745 std::string>> &attributes,
746 bool readonly)
747 {
748 gcc_assert (type);
749 gcc_assert (name);
750
751 tree type_tree = type->as_tree ();
752
753 tree inner = build_decl (UNKNOWN_LOCATION, VAR_DECL,
754 get_identifier (name),
755 type_tree);
756
757 TREE_PUBLIC (inner) = (kind != GCC_JIT_GLOBAL_INTERNAL);
758
759
760 int will_be_init = flags & (GLOBAL_VAR_FLAGS_WILL_BE_RVAL_INIT |
761 GLOBAL_VAR_FLAGS_WILL_BE_BLOB_INIT);
762
763 /* A VAR_DECL with DECL_INITIAL will not end up in .common section. */
764 if (!will_be_init)
765 DECL_COMMON (inner) = 1;
766
767 switch (kind)
768 {
769 default:
770 gcc_unreachable ();
771
772 case GCC_JIT_GLOBAL_EXPORTED:
773 TREE_STATIC (inner) = 1;
774 break;
775
776 case GCC_JIT_GLOBAL_INTERNAL:
777 TREE_STATIC (inner) = 1;
778 break;
779
780 case GCC_JIT_GLOBAL_IMPORTED:
781 DECL_EXTERNAL (inner) = 1;
782 break;
783 }
784
785 if (TYPE_READONLY (type_tree) || readonly)
786 TREE_READONLY (inner) = 1;
787
788 if (loc)
789 set_tree_location (inner, loc);
790
791 set_variable_string_attribute (attributes, inner);
792
793 return inner;
794 }
795
796 void
797 playback::
798 set_variable_string_attribute (
799 const std::vector<std::pair<gcc_jit_variable_attribute,
800 std::string>> &string_attributes,
801 tree decl)
802 {
803 tree var_attributes = NULL_TREE;
804 for (auto attr: string_attributes)
805 {
806 gcc_jit_variable_attribute& name = std::get<0>(attr);
807 std::string& value = std::get<1>(attr);
808 tree attribute_value = build_tree_list (NULL_TREE,
809 ::build_string (value.length () + 1, value.c_str ()));
810 tree ident = get_identifier (variable_attribute_to_string (name));
811 if (ident)
812 var_attributes = tree_cons (ident, attribute_value, var_attributes);
813 }
814 decl_attributes (&decl, var_attributes, 0);
815 }
816
817 /* In use by new_global and new_global_initialized. */
818
819 playback::lvalue *
820 playback::context::
821 global_finalize_lvalue (tree inner)
822 {
823 m_globals.safe_push (inner);
824
825 return new lvalue (this, inner);
826 }
827
828 /* Construct a playback::lvalue instance (wrapping a tree). */
829
830 playback::lvalue *
831 playback::context::
832 new_global (location *loc,
833 enum gcc_jit_global_kind kind,
834 type *type,
835 const char *name,
836 enum global_var_flags flags,
837 const std::vector<std::pair<gcc_jit_variable_attribute,
838 std::string>> &attributes,
839 bool readonly)
840 {
841 tree inner =
842 global_new_decl (loc, kind, type, name, flags, attributes, readonly);
843
844 return global_finalize_lvalue (inner);
845 }
846
847 void
848 playback::context::
849 global_set_init_rvalue (lvalue* variable,
850 rvalue* init)
851 {
852 tree inner = variable->as_tree ();
853
854 /* We need to fold all expressions as much as possible. The code
855 for a DECL_INITIAL only handles some operations,
856 etc addition, minus, 'address of'. See output_addressed_constants ()
857 in varasm.cc. */
858 tree init_tree = init->as_tree ();
859 tree folded = fold_const_var (init_tree);
860
861 if (!TREE_CONSTANT (folded))
862 {
863 tree name = DECL_NAME (inner);
864
865 if (name != NULL_TREE)
866 add_error (NULL,
867 "unable to convert initial value for the global variable %s"
868 " to a compile-time constant",
869 IDENTIFIER_POINTER (name));
870 else
871 add_error (NULL,
872 "unable to convert initial value for global variable"
873 " to a compile-time constant");
874 return;
875 }
876
877 DECL_INITIAL (inner) = folded;
878 }
879
880 playback::rvalue *
881 playback::context::
882 new_ctor (location *loc,
883 type *type,
884 const auto_vec<field*> *fields,
885 const auto_vec<rvalue*> *rvalues)
886 {
887 tree type_tree = type->as_tree ();
888
889 /* Handle empty ctors first. I.e. set everything to 0. */
890 if (rvalues->length () == 0)
891 return new rvalue (this, build_constructor (type_tree, NULL));
892
893 /* Handle arrays (and return). */
894 if (TREE_CODE (type_tree) == ARRAY_TYPE)
895 {
896 int n = rvalues->length ();
897 /* The vec for the constructor node. */
898 vec<constructor_elt, va_gc> *v = NULL;
899 vec_alloc (v, n);
900
901 for (int i = 0; i < n; i++)
902 {
903 rvalue *rv = (*rvalues)[i];
904 /* null rvalues indicate that the element should be zeroed. */
905 if (rv)
906 CONSTRUCTOR_APPEND_ELT (v,
907 build_int_cst (size_type_node, i),
908 rv->as_tree ());
909 else
910 CONSTRUCTOR_APPEND_ELT (v,
911 build_int_cst (size_type_node, i),
912 build_zero_cst (TREE_TYPE (type_tree)));
913 }
914
915 tree ctor = build_constructor (type_tree, v);
916
917 if (loc)
918 set_tree_location (ctor, loc);
919
920 return new rvalue (this, ctor);
921 }
922
923 /* Handle structs and unions. */
924 int n = fields->length ();
925
926 /* The vec for the constructor node. */
927 vec<constructor_elt, va_gc> *v = NULL;
928 vec_alloc (v, n);
929
930 /* Iterate over the fields, building initializations. */
931 for (int i = 0;i < n; i++)
932 {
933 tree field = (*fields)[i]->as_tree ();
934 rvalue *rv = (*rvalues)[i];
935 /* If the value is NULL, it means we should zero the field. */
936 if (rv)
937 CONSTRUCTOR_APPEND_ELT (v, field, rv->as_tree ());
938 else
939 {
940 tree zero_cst = build_zero_cst (TREE_TYPE (field));
941 CONSTRUCTOR_APPEND_ELT (v, field, zero_cst);
942 }
943 }
944
945 tree ctor = build_constructor (type_tree, v);
946
947 if (loc)
948 set_tree_location (ctor, loc);
949
950 return new rvalue (this, build_constructor (type_tree, v));
951 }
952
953 /* Fill 'constructor_elements' with the memory content of
954 'initializer'. Each element of the initializer is of the size of
955 type T. In use by new_global_initialized.*/
956
957 template<typename T>
958 static void
959 load_blob_in_ctor (vec<constructor_elt, va_gc> *&constructor_elements,
960 size_t num_elem,
961 const void *initializer)
962 {
963 /* Loosely based on 'output_init_element' c-typeck.cc:9691. */
964 const T *p = (const T *)initializer;
965 tree node = make_unsigned_type (BITS_PER_UNIT * sizeof (T));
966 for (size_t i = 0; i < num_elem; i++)
967 {
968 constructor_elt celt =
969 { build_int_cst (long_unsigned_type_node, i),
970 build_int_cst (node, p[i]) };
971 vec_safe_push (constructor_elements, celt);
972 }
973 }
974
975 /* Construct an initialized playback::lvalue instance (wrapping a
976 tree). */
977
978 playback::lvalue *
979 playback::context::
980 new_global_initialized (location *loc,
981 enum gcc_jit_global_kind kind,
982 type *type,
983 size_t element_size,
984 size_t initializer_num_elem,
985 const void *initializer,
986 const char *name,
987 enum global_var_flags flags,
988 const std::vector<std::pair<gcc_jit_variable_attribute,
989 std::string>> &attributes,
990 bool readonly)
991 {
992 tree inner = global_new_decl (loc, kind, type, name, flags, attributes, readonly);
993
994 vec<constructor_elt, va_gc> *constructor_elements = NULL;
995
996 switch (element_size)
997 {
998 case 1:
999 load_blob_in_ctor<uint8_t> (constructor_elements, initializer_num_elem,
1000 initializer);
1001 break;
1002 case 2:
1003 load_blob_in_ctor<uint16_t> (constructor_elements, initializer_num_elem,
1004 initializer);
1005 break;
1006 case 4:
1007 load_blob_in_ctor<uint32_t> (constructor_elements, initializer_num_elem,
1008 initializer);
1009 break;
1010 case 8:
1011 load_blob_in_ctor<uint64_t> (constructor_elements, initializer_num_elem,
1012 initializer);
1013 break;
1014 default:
1015 /* This function is serving on sizes returned by 'get_size',
1016 these are all covered by the previous cases. */
1017 gcc_unreachable ();
1018 }
1019 /* Compare with 'pop_init_level' c-typeck.cc:8780. */
1020 tree ctor = build_constructor (type->as_tree (), constructor_elements);
1021 constructor_elements = NULL;
1022
1023 /* Compare with 'store_init_value' c-typeck.cc:7555. */
1024 DECL_INITIAL (inner) = ctor;
1025
1026 return global_finalize_lvalue (inner);
1027 }
1028
1029 /* Implementation of the various
1030 gcc::jit::playback::context::new_rvalue_from_const <HOST_TYPE>
1031 methods.
1032 Each of these constructs a playback::rvalue instance (wrapping a tree).
1033
1034 These specializations are required to be in the same namespace
1035 as the template, hence we now have to enter the gcc::jit::playback
1036 namespace. */
1037
1038 namespace playback
1039 {
1040
1041 /* Specialization of making an rvalue from a const, for host <int>. */
1042
1043 template <>
1044 rvalue *
1045 context::
1046 new_rvalue_from_const <int> (type *type,
1047 int value)
1048 {
1049 // FIXME: type-checking, or coercion?
1050 tree inner_type = type->as_tree ();
1051 if (INTEGRAL_TYPE_P (inner_type))
1052 {
1053 tree inner = build_int_cst (inner_type, value);
1054 return new rvalue (this, inner);
1055 }
1056 else
1057 {
1058 REAL_VALUE_TYPE real_value;
1059 real_from_integer (&real_value, VOIDmode, value, SIGNED);
1060 tree inner = build_real (inner_type, real_value);
1061 return new rvalue (this, inner);
1062 }
1063 }
1064
1065 /* Specialization of making an rvalue from a const, for host <long>. */
1066
1067 template <>
1068 rvalue *
1069 context::
1070 new_rvalue_from_const <long> (type *type,
1071 long value)
1072 {
1073 // FIXME: type-checking, or coercion?
1074 tree inner_type = type->as_tree ();
1075 if (INTEGRAL_TYPE_P (inner_type))
1076 {
1077 tree inner = build_int_cst (inner_type, value);
1078 return new rvalue (this, inner);
1079 }
1080 else
1081 {
1082 REAL_VALUE_TYPE real_value;
1083 real_from_integer (&real_value, VOIDmode, value, SIGNED);
1084 tree inner = build_real (inner_type, real_value);
1085 return new rvalue (this, inner);
1086 }
1087 }
1088
1089 /* Specialization of making an rvalue from a const, for host <double>. */
1090
1091 template <>
1092 rvalue *
1093 context::
1094 new_rvalue_from_const <double> (type *type,
1095 double value)
1096 {
1097 // FIXME: type-checking, or coercion?
1098 tree inner_type = type->as_tree ();
1099
1100 mpfr_t mpf_value;
1101
1102 mpfr_init2 (mpf_value, 64);
1103 mpfr_set_d (mpf_value, value, MPFR_RNDN);
1104
1105 /* We have a "double", we want a REAL_VALUE_TYPE.
1106
1107 realmpfr.cc:real_from_mpfr. */
1108 REAL_VALUE_TYPE real_value;
1109 real_from_mpfr (&real_value, mpf_value, inner_type, MPFR_RNDN);
1110 tree inner = build_real (inner_type, real_value);
1111 return new rvalue (this, inner);
1112 }
1113
1114 /* Specialization of making an rvalue from a const, for host <void *>. */
1115
1116 template <>
1117 rvalue *
1118 context::
1119 new_rvalue_from_const <void *> (type *type,
1120 void *value)
1121 {
1122 tree inner_type = type->as_tree ();
1123 /* FIXME: how to ensure we have a wide enough type? */
1124 tree inner = build_int_cstu (inner_type, (unsigned HOST_WIDE_INT)value);
1125 return new rvalue (this, inner);
1126 }
1127
1128 /* We're done implementing the specializations of
1129 gcc::jit::playback::context::new_rvalue_from_const <T>
1130 so we can exit the gcc::jit::playback namespace. */
1131
1132 } // namespace playback
1133
1134 /* Construct a playback::rvalue instance (wrapping a tree). */
1135
1136 playback::rvalue *
1137 playback::context::
1138 new_sizeof (type *type)
1139 {
1140 tree inner = TYPE_SIZE_UNIT (type->as_tree ());
1141 return new rvalue (this, inner);
1142 }
1143
1144 /* Construct a playback::rvalue instance (wrapping a tree). */
1145
1146 playback::rvalue *
1147 playback::context::
1148 new_alignof (type *type)
1149 {
1150 int alignment = TYPE_ALIGN (type->as_tree ()) / BITS_PER_UNIT;
1151 tree inner = build_int_cst (integer_type_node, alignment);
1152 return new rvalue (this, inner);
1153 }
1154
1155 /* Construct a playback::rvalue instance (wrapping a tree). */
1156
1157 playback::rvalue *
1158 playback::context::
1159 new_string_literal (const char *value)
1160 {
1161 /* Compare with c-family/c-common.cc: fix_string_type. */
1162 size_t len = strlen (value);
1163 tree i_type = build_index_type (size_int (len));
1164 tree a_type = build_array_type (char_type_node, i_type);
1165 /* build_string len parameter must include NUL terminator when
1166 building C strings. */
1167 tree t_str = ::build_string (len + 1, value);
1168 TREE_TYPE (t_str) = a_type;
1169
1170 /* Convert to (const char*), loosely based on
1171 c/c-typeck.cc: array_to_pointer_conversion,
1172 by taking address of start of string. */
1173 tree t_addr = build1 (ADDR_EXPR, m_const_char_ptr, t_str);
1174
1175 return new rvalue (this, t_addr);
1176 }
1177
1178 /* Construct a playback::rvalue instance (wrapping a tree) for a
1179 vector. */
1180
1181 playback::rvalue *
1182 playback::context::new_rvalue_from_vector (location *,
1183 type *type,
1184 const auto_vec<rvalue *> &elements)
1185 {
1186 vec<constructor_elt, va_gc> *v;
1187 vec_alloc (v, elements.length ());
1188 for (unsigned i = 0; i < elements.length (); ++i)
1189 CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, elements[i]->as_tree ());
1190 tree t_ctor = build_constructor (type->as_tree (), v);
1191 return new rvalue (this, t_ctor);
1192 }
1193
1194 /* Construct a playback::rvalue instance (wrapping a tree) for a
1195 vector perm. */
1196
1197 playback::rvalue *
1198 playback::context::new_rvalue_vector_perm (location *loc,
1199 rvalue* elements1,
1200 rvalue* elements2,
1201 rvalue* mask)
1202 {
1203 tree t_elements1 = elements1->as_tree ();
1204 tree t_elements2 = elements2->as_tree ();
1205 tree t_mask = mask->as_tree ();
1206
1207 tree t_vector_perm = build3 (VEC_PERM_EXPR, TREE_TYPE (t_elements1),
1208 t_elements1, t_elements2, t_mask);
1209 if (loc)
1210 set_tree_location (t_vector_perm, loc);
1211 return new rvalue (this, t_vector_perm);
1212 }
1213
1214 /* Coerce a tree expression into a boolean tree expression. */
1215
1216 tree
1217 playback::context::
1218 as_truth_value (tree expr, location *loc)
1219 {
1220 /* Compare to c-typeck.cc:c_objc_common_truthvalue_conversion */
1221 tree typed_zero = fold_build1 (CONVERT_EXPR,
1222 TREE_TYPE (expr),
1223 integer_zero_node);
1224 if (loc)
1225 set_tree_location (typed_zero, loc);
1226
1227 tree type = TREE_TYPE (expr);
1228 expr = fold_build2_loc (UNKNOWN_LOCATION,
1229 NE_EXPR, type, expr, typed_zero);
1230 if (loc)
1231 set_tree_location (expr, loc);
1232
1233 return expr;
1234 }
1235
1236 /* Add a "top-level" basic asm statement (i.e. one outside of any functions)
1237 containing ASM_STMTS.
1238
1239 Compare with c_parser_asm_definition. */
1240
1241 void
1242 playback::context::add_top_level_asm (const char *asm_stmts)
1243 {
1244 tree asm_str = build_string (asm_stmts);
1245 symtab->finalize_toplevel_asm (asm_str);
1246 }
1247
1248 /* Construct a playback::rvalue instance (wrapping a tree) for a
1249 unary op. */
1250
1251 playback::rvalue *
1252 playback::context::
1253 new_unary_op (location *loc,
1254 enum gcc_jit_unary_op op,
1255 type *result_type,
1256 rvalue *a)
1257 {
1258 // FIXME: type-checking, or coercion?
1259 enum tree_code inner_op;
1260
1261 gcc_assert (result_type);
1262 gcc_assert (a);
1263
1264 tree node = a->as_tree ();
1265 node = fold_const_var (node);
1266
1267 tree inner_result = NULL;
1268
1269 switch (op)
1270 {
1271 default:
1272 add_error (loc, "unrecognized (enum gcc_jit_unary_op) value: %i", op);
1273 return NULL;
1274
1275 case GCC_JIT_UNARY_OP_MINUS:
1276 inner_op = NEGATE_EXPR;
1277 break;
1278
1279 case GCC_JIT_UNARY_OP_BITWISE_NEGATE:
1280 inner_op = BIT_NOT_EXPR;
1281 break;
1282
1283 case GCC_JIT_UNARY_OP_LOGICAL_NEGATE:
1284 node = as_truth_value (node, loc);
1285 inner_result = invert_truthvalue (node);
1286 if (loc)
1287 set_tree_location (inner_result, loc);
1288 return new rvalue (this, inner_result);
1289
1290 case GCC_JIT_UNARY_OP_ABS:
1291 inner_op = ABS_EXPR;
1292 break;
1293 }
1294
1295 inner_result = build1 (inner_op,
1296 result_type->as_tree (),
1297 node);
1298
1299 /* Try to fold. */
1300 inner_result = fold (inner_result);
1301
1302 if (loc)
1303 set_tree_location (inner_result, loc);
1304
1305 return new rvalue (this, inner_result);
1306 }
1307
1308 /* Construct a playback::rvalue instance (wrapping a tree) for a
1309 binary op. */
1310
1311 playback::rvalue *
1312 playback::context::
1313 new_binary_op (location *loc,
1314 enum gcc_jit_binary_op op,
1315 type *result_type,
1316 rvalue *a, rvalue *b)
1317 {
1318 // FIXME: type-checking, or coercion?
1319 enum tree_code inner_op;
1320
1321 gcc_assert (result_type);
1322 gcc_assert (a);
1323 gcc_assert (b);
1324
1325 tree node_a = a->as_tree ();
1326 node_a = fold_const_var (node_a);
1327
1328 tree node_b = b->as_tree ();
1329 node_b = fold_const_var (node_b);
1330
1331 switch (op)
1332 {
1333 default:
1334 add_error (loc, "unrecognized (enum gcc_jit_binary_op) value: %i", op);
1335 return NULL;
1336
1337 case GCC_JIT_BINARY_OP_PLUS:
1338 inner_op = PLUS_EXPR;
1339 break;
1340
1341 case GCC_JIT_BINARY_OP_MINUS:
1342 inner_op = MINUS_EXPR;
1343 break;
1344
1345 case GCC_JIT_BINARY_OP_MULT:
1346 inner_op = MULT_EXPR;
1347 break;
1348
1349 case GCC_JIT_BINARY_OP_DIVIDE:
1350 if (FLOAT_TYPE_P (result_type->as_tree ()))
1351 /* Floating-point division: */
1352 inner_op = RDIV_EXPR;
1353 else
1354 /* Truncating to zero: */
1355 inner_op = TRUNC_DIV_EXPR;
1356 break;
1357
1358 case GCC_JIT_BINARY_OP_MODULO:
1359 inner_op = TRUNC_MOD_EXPR;
1360 break;
1361
1362 case GCC_JIT_BINARY_OP_BITWISE_AND:
1363 inner_op = BIT_AND_EXPR;
1364 break;
1365
1366 case GCC_JIT_BINARY_OP_BITWISE_XOR:
1367 inner_op = BIT_XOR_EXPR;
1368 break;
1369
1370 case GCC_JIT_BINARY_OP_BITWISE_OR:
1371 inner_op = BIT_IOR_EXPR;
1372 break;
1373
1374 case GCC_JIT_BINARY_OP_LOGICAL_AND:
1375 node_a = as_truth_value (node_a, loc);
1376 node_b = as_truth_value (node_b, loc);
1377 inner_op = TRUTH_ANDIF_EXPR;
1378 break;
1379
1380 case GCC_JIT_BINARY_OP_LOGICAL_OR:
1381 node_a = as_truth_value (node_a, loc);
1382 node_b = as_truth_value (node_b, loc);
1383 inner_op = TRUTH_ORIF_EXPR;
1384 break;
1385
1386 case GCC_JIT_BINARY_OP_LSHIFT:
1387 inner_op = LSHIFT_EXPR;
1388 break;
1389
1390 case GCC_JIT_BINARY_OP_RSHIFT:
1391 inner_op = RSHIFT_EXPR;
1392 break;
1393 }
1394
1395 tree inner_expr = build2 (inner_op,
1396 result_type->as_tree (),
1397 node_a,
1398 node_b);
1399
1400 /* Try to fold the expression. */
1401 inner_expr = fold (inner_expr);
1402
1403 if (loc)
1404 set_tree_location (inner_expr, loc);
1405
1406 return new rvalue (this, inner_expr);
1407 }
1408
1409 /* Construct a playback::rvalue instance (wrapping a tree) for a
1410 comparison. */
1411
1412 playback::rvalue *
1413 playback::context::
1414 new_comparison (location *loc,
1415 enum gcc_jit_comparison op,
1416 rvalue *a, rvalue *b, type *vec_result_type)
1417 {
1418 // FIXME: type-checking, or coercion?
1419 enum tree_code inner_op;
1420
1421 gcc_assert (a);
1422 gcc_assert (b);
1423
1424 switch (op)
1425 {
1426 default:
1427 add_error (loc, "unrecognized (enum gcc_jit_comparison) value: %i", op);
1428 return NULL;
1429
1430 case GCC_JIT_COMPARISON_EQ:
1431 inner_op = EQ_EXPR;
1432 break;
1433 case GCC_JIT_COMPARISON_NE:
1434 inner_op = NE_EXPR;
1435 break;
1436 case GCC_JIT_COMPARISON_LT:
1437 inner_op = LT_EXPR;
1438 break;
1439 case GCC_JIT_COMPARISON_LE:
1440 inner_op = LE_EXPR;
1441 break;
1442 case GCC_JIT_COMPARISON_GT:
1443 inner_op = GT_EXPR;
1444 break;
1445 case GCC_JIT_COMPARISON_GE:
1446 inner_op = GE_EXPR;
1447 break;
1448 }
1449
1450 tree node_a = a->as_tree ();
1451 node_a = fold_const_var (node_a);
1452 tree node_b = b->as_tree ();
1453 node_b = fold_const_var (node_b);
1454
1455 tree inner_expr;
1456 tree a_type = TREE_TYPE (node_a);
1457 if (VECTOR_TYPE_P (a_type))
1458 {
1459 /* Build a vector comparison. See build_vec_cmp in c-typeck.cc for
1460 reference. */
1461 tree t_vec_result_type = vec_result_type->as_tree ();
1462 tree zero_vec = build_zero_cst (t_vec_result_type);
1463 tree minus_one_vec = build_minus_one_cst (t_vec_result_type);
1464 tree cmp_type = truth_type_for (a_type);
1465 tree cmp = build2 (inner_op, cmp_type, node_a, node_b);
1466 inner_expr = build3 (VEC_COND_EXPR, t_vec_result_type, cmp, minus_one_vec,
1467 zero_vec);
1468 }
1469 else
1470 {
1471 inner_expr = build2 (inner_op,
1472 boolean_type_node,
1473 node_a,
1474 node_b);
1475 }
1476
1477 /* Try to fold. */
1478 inner_expr = fold (inner_expr);
1479
1480 if (loc)
1481 set_tree_location (inner_expr, loc);
1482 return new rvalue (this, inner_expr);
1483 }
1484
1485 /* Construct a playback::rvalue instance (wrapping a tree) for a
1486 function call. */
1487
1488 playback::rvalue *
1489 playback::context::
1490 build_call (location *loc,
1491 tree fn_ptr,
1492 const auto_vec<rvalue *> *args,
1493 bool require_tail_call)
1494 {
1495 vec<tree, va_gc> *tree_args;
1496 vec_alloc (tree_args, args->length ());
1497 for (unsigned i = 0; i < args->length (); i++)
1498 tree_args->quick_push ((*args)[i]->as_tree ());
1499
1500 if (loc)
1501 set_tree_location (fn_ptr, loc);
1502
1503 tree fn = TREE_TYPE (fn_ptr);
1504 tree fn_type = TREE_TYPE (fn);
1505 tree return_type = TREE_TYPE (fn_type);
1506
1507 tree call = build_call_vec (return_type,
1508 fn_ptr, tree_args);
1509
1510 if (require_tail_call)
1511 CALL_EXPR_MUST_TAIL_CALL (call) = 1;
1512
1513 return new rvalue (this, call);
1514
1515 /* see c-typeck.cc: build_function_call
1516 which calls build_function_call_vec
1517
1518 which does lots of checking, then:
1519 result = build_call_array_loc (loc, TREE_TYPE (fntype),
1520 function, nargs, argarray);
1521 which is in tree.cc
1522 (see also build_call_vec)
1523 */
1524 }
1525
1526 /* Construct a playback::rvalue instance (wrapping a tree) for a
1527 call to a specific function. */
1528
1529 playback::rvalue *
1530 playback::context::
1531 new_call (location *loc,
1532 function *func,
1533 const auto_vec<rvalue *> *args,
1534 bool require_tail_call)
1535 {
1536 tree fndecl;
1537
1538 gcc_assert (func);
1539
1540 fndecl = func->as_fndecl ();
1541
1542 tree fntype = TREE_TYPE (fndecl);
1543
1544 tree fn = build1 (ADDR_EXPR, build_pointer_type (fntype), fndecl);
1545
1546 return build_call (loc, fn, args, require_tail_call);
1547 }
1548
1549 /* Construct a playback::rvalue instance (wrapping a tree) for a
1550 call through a function pointer. */
1551
1552 playback::rvalue *
1553 playback::context::
1554 new_call_through_ptr (location *loc,
1555 rvalue *fn_ptr,
1556 const auto_vec<rvalue *> *args,
1557 bool require_tail_call)
1558 {
1559 gcc_assert (fn_ptr);
1560 tree t_fn_ptr = fn_ptr->as_tree ();
1561
1562 return build_call (loc, t_fn_ptr, args, require_tail_call);
1563 }
1564
1565 /* Construct a tree for a cast. */
1566
1567 tree
1568 playback::context::build_cast (playback::location *loc,
1569 playback::rvalue *expr,
1570 playback::type *type_)
1571 {
1572 /* For comparison, see:
1573 - c/c-typeck.cc:build_c_cast
1574 - c/c-convert.cc: convert
1575 - convert.h
1576
1577 Only some kinds of cast are currently supported here. */
1578 tree t_expr = expr->as_tree ();
1579 t_expr = fold_const_var (t_expr);
1580
1581 tree t_dst_type = type_->as_tree ();
1582 tree t_ret = NULL;
1583 t_ret = targetm.convert_to_type (t_dst_type, t_expr);
1584 if (t_ret)
1585 return t_ret;
1586 enum tree_code dst_code = TREE_CODE (t_dst_type);
1587 switch (dst_code)
1588 {
1589 case INTEGER_TYPE:
1590 case ENUMERAL_TYPE:
1591 t_ret = convert_to_integer (t_dst_type, t_expr);
1592 goto maybe_fold;
1593
1594 case BOOLEAN_TYPE:
1595 /* Compare with c_objc_common_truthvalue_conversion and
1596 c_common_truthvalue_conversion. */
1597 /* For now, convert to: (t_expr != 0) */
1598 t_ret = build2 (NE_EXPR, t_dst_type,
1599 t_expr,
1600 build_int_cst (TREE_TYPE (t_expr), 0));
1601 goto maybe_fold;
1602
1603 case REAL_TYPE:
1604 t_ret = convert_to_real (t_dst_type, t_expr);
1605 goto maybe_fold;
1606
1607 case POINTER_TYPE:
1608 t_ret = build1 (NOP_EXPR, t_dst_type, t_expr);
1609 goto maybe_fold;
1610
1611 default:
1612 add_error (loc, "couldn't handle cast during playback");
1613 fprintf (stderr, "input expression:\n");
1614 debug_tree (t_expr);
1615 fprintf (stderr, "requested type:\n");
1616 debug_tree (t_dst_type);
1617 return error_mark_node;
1618
1619 maybe_fold:
1620 if (TREE_CODE (t_ret) != C_MAYBE_CONST_EXPR)
1621 t_ret = fold (t_ret);
1622 return t_ret;
1623 }
1624 }
1625
1626 /* Construct a playback::rvalue instance (wrapping a tree) for a
1627 cast. */
1628
1629 playback::rvalue *
1630 playback::context::
1631 new_cast (playback::location *loc,
1632 playback::rvalue *expr,
1633 playback::type *type_)
1634 {
1635
1636 tree t_cast = build_cast (loc, expr, type_);
1637 if (loc)
1638 set_tree_location (t_cast, loc);
1639 return new rvalue (this, t_cast);
1640 }
1641
1642 /* Construct a playback::rvalue instance (wrapping a tree) for a
1643 bitcast. */
1644
1645 playback::rvalue *
1646 playback::context::
1647 new_bitcast (location *loc,
1648 rvalue *expr,
1649 type *type_)
1650 {
1651 tree expr_size = TYPE_SIZE (expr->get_type ()->as_tree ());
1652 tree type_size = TYPE_SIZE (type_->as_tree ());
1653 tree t_expr = expr->as_tree ();
1654 tree t_dst_type = type_->as_tree ();
1655 if (expr_size != type_size)
1656 {
1657 active_playback_ctxt->add_error (loc,
1658 "bitcast with types of different sizes");
1659 fprintf (stderr, "input expression (size: " HOST_WIDE_INT_PRINT_DEC "):\n",
1660 tree_to_uhwi (expr_size));
1661 debug_tree (t_expr);
1662 fprintf (stderr, "requested type (size: " HOST_WIDE_INT_PRINT_DEC "):\n",
1663 tree_to_uhwi (type_size));
1664 debug_tree (t_dst_type);
1665 }
1666 tree t_bitcast = build1 (VIEW_CONVERT_EXPR, t_dst_type, t_expr);
1667 if (loc)
1668 set_tree_location (t_bitcast, loc);
1669 return new rvalue (this, t_bitcast);
1670 }
1671
1672 /* Construct a playback::lvalue instance (wrapping a tree) for an
1673 array access. */
1674
1675 playback::lvalue *
1676 playback::context::
1677 new_array_access (location *loc,
1678 rvalue *ptr,
1679 rvalue *index)
1680 {
1681 gcc_assert (ptr);
1682 gcc_assert (index);
1683
1684 /* For comparison, see:
1685 c/c-typeck.cc: build_array_ref
1686 c-family/c-common.cc: pointer_int_sum
1687 */
1688 tree t_ptr = ptr->as_tree ();
1689 t_ptr = fold_const_var (t_ptr);
1690 tree t_index = index->as_tree ();
1691 t_index = fold_const_var (t_index);
1692
1693 tree t_type_ptr = TREE_TYPE (t_ptr);
1694 tree t_type_star_ptr = TREE_TYPE (t_type_ptr);
1695
1696 if (TREE_CODE (t_type_ptr) == ARRAY_TYPE)
1697 {
1698 tree t_result = build4 (ARRAY_REF, t_type_star_ptr, t_ptr, t_index,
1699 NULL_TREE, NULL_TREE);
1700 t_result = fold (t_result);
1701 if (loc)
1702 set_tree_location (t_result, loc);
1703 return new lvalue (this, t_result);
1704 }
1705 else
1706 {
1707 /* Convert index to an offset in bytes. */
1708 tree t_sizeof = size_in_bytes (t_type_star_ptr);
1709 t_index = fold_build1 (CONVERT_EXPR, sizetype, t_index);
1710 tree t_offset = fold_build2_loc (UNKNOWN_LOCATION,
1711 MULT_EXPR, sizetype, t_index, t_sizeof);
1712
1713 /* Locate (ptr + offset). */
1714 tree t_address = fold_build2_loc (UNKNOWN_LOCATION,
1715 POINTER_PLUS_EXPR, t_type_ptr, t_ptr, t_offset);
1716
1717 tree t_indirection = fold_build1 (INDIRECT_REF, t_type_star_ptr, t_address);
1718 if (loc)
1719 {
1720 set_tree_location (t_sizeof, loc);
1721 set_tree_location (t_offset, loc);
1722 set_tree_location (t_address, loc);
1723 set_tree_location (t_indirection, loc);
1724 }
1725
1726 return new lvalue (this, t_indirection);
1727 }
1728 }
1729
1730 /* Construct a playback::rvalue instance (wrapping a tree) for a
1731 vector conversion. */
1732
1733 playback::rvalue *
1734 playback::context::
1735 convert_vector (location *loc,
1736 rvalue *vector,
1737 type *type)
1738 {
1739 gcc_assert (vector);
1740 gcc_assert (type);
1741
1742 /* For comparison, see:
1743 c/c-common.cc: c_build_vec_convert
1744 */
1745
1746 tree t_vector = vector->as_tree ();
1747
1748 tree t_result =
1749 build_call_expr_internal_loc (UNKNOWN_LOCATION, IFN_VEC_CONVERT,
1750 type->as_tree (), 1, t_vector);
1751
1752 if (loc)
1753 set_tree_location (t_result, loc);
1754
1755 return new rvalue (this, t_result);
1756 }
1757
1758 /* The following functions come from c-common.h. */
1759 /* Like c_mark_addressable but don't check register qualifier. */
1760 void
1761 common_mark_addressable_vec (tree t)
1762 {
1763 while (handled_component_p (t) || TREE_CODE (t) == C_MAYBE_CONST_EXPR)
1764 {
1765 t = TREE_OPERAND (t, 0);
1766 }
1767 if (!VAR_P (t)
1768 && TREE_CODE (t) != PARM_DECL
1769 && TREE_CODE (t) != COMPOUND_LITERAL_EXPR
1770 && TREE_CODE (t) != TARGET_EXPR)
1771 return;
1772 if (!VAR_P (t) || !DECL_HARD_REGISTER (t))
1773 TREE_ADDRESSABLE (t) = 1;
1774 if (TREE_CODE (t) == COMPOUND_LITERAL_EXPR)
1775 TREE_ADDRESSABLE (COMPOUND_LITERAL_EXPR_DECL (t)) = 1;
1776 else if (TREE_CODE (t) == TARGET_EXPR)
1777 TREE_ADDRESSABLE (TARGET_EXPR_SLOT (t)) = 1;
1778 }
1779
1780 /* Return true if TYPE is a vector type that should be subject to the GNU
1781 vector extensions (as opposed to a vector type that is used only for
1782 the purposes of defining target-specific built-in functions). */
1783
1784 inline bool
1785 gnu_vector_type_p (const_tree type)
1786 {
1787 return TREE_CODE (type) == VECTOR_TYPE && !TYPE_INDIVISIBLE_P (type);
1788 }
1789
1790 /* Return nonzero if REF is an lvalue valid for this language.
1791 Lvalues can be assigned, unless their type has TYPE_READONLY.
1792 Lvalues can have their address taken, unless they have C_DECL_REGISTER. */
1793
1794 bool
1795 lvalue_p (const_tree ref)
1796 {
1797 const enum tree_code code = TREE_CODE (ref);
1798
1799 switch (code)
1800 {
1801 case REALPART_EXPR:
1802 case IMAGPART_EXPR:
1803 case COMPONENT_REF:
1804 return lvalue_p (TREE_OPERAND (ref, 0));
1805
1806 case C_MAYBE_CONST_EXPR:
1807 return lvalue_p (TREE_OPERAND (ref, 1));
1808
1809 case COMPOUND_LITERAL_EXPR:
1810 case STRING_CST:
1811 return true;
1812
1813 case MEM_REF:
1814 case TARGET_MEM_REF:
1815 /* MEM_REFs can appear from -fgimple parsing or folding, so allow them
1816 here as well. */
1817 case INDIRECT_REF:
1818 case ARRAY_REF:
1819 case VAR_DECL:
1820 case PARM_DECL:
1821 case RESULT_DECL:
1822 case ERROR_MARK:
1823 return (TREE_CODE (TREE_TYPE (ref)) != FUNCTION_TYPE
1824 && TREE_CODE (TREE_TYPE (ref)) != METHOD_TYPE);
1825
1826 case BIND_EXPR:
1827 return TREE_CODE (TREE_TYPE (ref)) == ARRAY_TYPE;
1828
1829 default:
1830 return false;
1831 }
1832 }
1833
1834 bool
1835 convert_vector_to_array_for_subscript (tree *vecp)
1836 {
1837 bool ret = false;
1838 if (gnu_vector_type_p (TREE_TYPE (*vecp)))
1839 {
1840 tree type = TREE_TYPE (*vecp);
1841
1842 ret = !lvalue_p (*vecp);
1843
1844 /* We are building an ARRAY_REF so mark the vector as addressable
1845 to not run into the gimplifiers premature setting of DECL_GIMPLE_REG_P
1846 for function parameters. */
1847 /* NOTE: that was the missing piece for making vector access work with
1848 optimizations enabled. */
1849 common_mark_addressable_vec (*vecp);
1850
1851 *vecp = build1 (VIEW_CONVERT_EXPR,
1852 build_array_type_nelts (TREE_TYPE (type),
1853 TYPE_VECTOR_SUBPARTS (type)),
1854 *vecp);
1855 }
1856 return ret;
1857 }
1858
1859 /* Construct a playback::lvalue instance (wrapping a tree) for a
1860 vector access. */
1861
1862 playback::lvalue *
1863 playback::context::
1864 new_vector_access (location *loc,
1865 rvalue *vector,
1866 rvalue *index)
1867 {
1868 gcc_assert (vector);
1869 gcc_assert (index);
1870
1871 /* For comparison, see:
1872 c/c-typeck.cc: build_array_ref
1873 */
1874
1875 tree t_vector = vector->as_tree ();
1876 bool non_lvalue = convert_vector_to_array_for_subscript (&t_vector);
1877 tree type = TREE_TYPE (TREE_TYPE (t_vector));
1878 tree t_result = build4 (ARRAY_REF, type, t_vector, index->as_tree (),
1879 NULL_TREE, NULL_TREE);
1880 if (non_lvalue)
1881 t_result = non_lvalue (t_result);
1882
1883 if (loc)
1884 set_tree_location (t_result, loc);
1885 return new lvalue (this, t_result);
1886 }
1887
1888 /* Construct a tree for a field access. */
1889
1890 tree
1891 playback::context::
1892 new_field_access (location *loc,
1893 tree datum,
1894 field *field)
1895 {
1896 gcc_assert (datum);
1897 gcc_assert (field);
1898
1899 /* Compare with c/c-typeck.cc:lookup_field, build_indirect_ref, and
1900 build_component_ref. */
1901 tree type = TREE_TYPE (datum);
1902 gcc_assert (type);
1903 gcc_assert (TREE_CODE (type) != POINTER_TYPE);
1904
1905 tree t_field = field->as_tree ();
1906 tree ref = build3 (COMPONENT_REF, TREE_TYPE (t_field), datum,
1907 t_field, NULL_TREE);
1908 if (loc)
1909 set_tree_location (ref, loc);
1910 return ref;
1911 }
1912
1913 /* Construct a tree for a dereference. */
1914
1915 tree
1916 playback::context::
1917 new_dereference (tree ptr,
1918 location *loc)
1919 {
1920 gcc_assert (ptr);
1921
1922 tree type = TREE_TYPE (TREE_TYPE(ptr));
1923 tree datum = fold_build1 (INDIRECT_REF, type, ptr);
1924 if (loc)
1925 set_tree_location (datum, loc);
1926 return datum;
1927 }
1928
1929 /* Construct a playback::type instance (wrapping a tree)
1930 with the given alignment. */
1931
1932 playback::type *
1933 playback::type::
1934 get_aligned (size_t alignment_in_bytes) const
1935 {
1936 tree t_new_type = build_variant_type_copy (m_inner);
1937
1938 SET_TYPE_ALIGN (t_new_type, alignment_in_bytes * BITS_PER_UNIT);
1939 TYPE_USER_ALIGN (t_new_type) = 1;
1940
1941 return new type (t_new_type);
1942 }
1943
1944 /* Construct a playback::type instance (wrapping a tree)
1945 for the given vector type. */
1946
1947 playback::type *
1948 playback::type::
1949 get_vector (size_t num_units) const
1950 {
1951 tree t_new_type = build_vector_type (m_inner, num_units);
1952 return new type (t_new_type);
1953 }
1954
1955 /* Construct a playback::lvalue instance (wrapping a tree) for a
1956 field access. */
1957
1958 playback::lvalue *
1959 playback::lvalue::
1960 access_field (location *loc,
1961 field *field)
1962 {
1963 tree datum = as_tree ();
1964 tree ref = get_context ()->new_field_access (loc, datum, field);
1965 if (!ref)
1966 return NULL;
1967 return new lvalue (get_context (), ref);
1968 }
1969
1970 /* Construct a playback::rvalue instance (wrapping a tree) for a
1971 field access. */
1972
1973 playback::rvalue *
1974 playback::rvalue::
1975 access_field (location *loc,
1976 field *field)
1977 {
1978 tree datum = as_tree ();
1979 tree ref = get_context ()->new_field_access (loc, datum, field);
1980 if (!ref)
1981 return NULL;
1982 return new rvalue (get_context (), ref);
1983 }
1984
1985 /* Construct a playback::lvalue instance (wrapping a tree) for a
1986 dereferenced field access. */
1987
1988 playback::lvalue *
1989 playback::rvalue::
1990 dereference_field (location *loc,
1991 field *field)
1992 {
1993 tree ptr = as_tree ();
1994 tree datum = get_context ()->new_dereference (ptr, loc);
1995 if (!datum)
1996 return NULL;
1997 tree ref = get_context ()->new_field_access (loc, datum, field);
1998 if (!ref)
1999 return NULL;
2000 return new lvalue (get_context (), ref);
2001 }
2002
2003 /* Construct a playback::lvalue instance (wrapping a tree) for a
2004 dereference. */
2005
2006 playback::lvalue *
2007 playback::rvalue::
2008 dereference (location *loc)
2009 {
2010 tree ptr = as_tree ();
2011 tree datum = get_context ()->new_dereference (ptr, loc);
2012 return new lvalue (get_context (), datum);
2013 }
2014
2015 /* Mark the lvalue saying that we need to be able to take the
2016 address of it; it should not be allocated in a register.
2017 Compare with e.g. c/c-typeck.cc: c_mark_addressable really_atomic_lvalue.
2018 Returns false if a failure occurred (an error will already have been
2019 added to the active context for this case). */
2020
2021 bool
2022 playback::lvalue::
2023 mark_addressable (location *loc)
2024 {
2025 tree x = as_tree ();
2026
2027 while (1)
2028 switch (TREE_CODE (x))
2029 {
2030 case COMPONENT_REF:
2031 if (DECL_JIT_BIT_FIELD (TREE_OPERAND (x, 1)))
2032 {
2033 gcc_assert (gcc::jit::active_playback_ctxt);
2034 gcc::jit::
2035 active_playback_ctxt->add_error (loc,
2036 "cannot take address of "
2037 "bit-field");
2038 return false;
2039 }
2040 /* fallthrough */
2041 case ADDR_EXPR:
2042 case ARRAY_REF:
2043 case REALPART_EXPR:
2044 case IMAGPART_EXPR:
2045 x = TREE_OPERAND (x, 0);
2046 break;
2047
2048 case COMPOUND_LITERAL_EXPR:
2049 case CONSTRUCTOR:
2050 TREE_ADDRESSABLE (x) = 1;
2051 return true;
2052
2053 case VAR_DECL:
2054 case CONST_DECL:
2055 case PARM_DECL:
2056 case RESULT_DECL:
2057 /* (we don't have a concept of a "register" declaration) */
2058 /* fallthrough */
2059 case FUNCTION_DECL:
2060 TREE_ADDRESSABLE (x) = 1;
2061 /* fallthrough */
2062 default:
2063 return true;
2064 }
2065 }
2066
2067 /* Construct a playback::rvalue instance (wrapping a tree) for an
2068 address-lookup. */
2069
2070 playback::rvalue *
2071 playback::lvalue::
2072 get_address (location *loc)
2073 {
2074 tree t_lvalue = as_tree ();
2075 tree t_thistype = TREE_TYPE (t_lvalue);
2076 tree t_ptrtype = build_pointer_type (t_thistype);
2077 tree ptr = fold_build1 (ADDR_EXPR, t_ptrtype, t_lvalue);
2078 if (loc)
2079 get_context ()->set_tree_location (ptr, loc);
2080 if (mark_addressable (loc))
2081 return new rvalue (get_context (), ptr);
2082 else
2083 return NULL;
2084 }
2085
2086 /* The wrapper subclasses are GC-managed, but can own non-GC memory.
2087 Provide this finalization hook for calling then they are collected,
2088 which calls the finalizer vfunc. This allows them to call "release"
2089 on any vec<> within them. */
2090
2091 static void
2092 wrapper_finalizer (void *ptr)
2093 {
2094 playback::wrapper *wrapper = reinterpret_cast <playback::wrapper *> (ptr);
2095 wrapper->finalizer ();
2096 }
2097
2098 /* gcc::jit::playback::wrapper subclasses are GC-managed:
2099 allocate them using ggc_internal_cleared_alloc. */
2100
2101 void *
2102 playback::wrapper::
2103 operator new (size_t sz)
2104 {
2105 return ggc_internal_cleared_alloc (sz, wrapper_finalizer, 0, 1);
2106
2107 }
2108
2109 /* Constructor for gcc:jit::playback::function. */
2110
2111 playback::function::
2112 function (context *ctxt,
2113 tree fndecl,
2114 enum gcc_jit_function_kind kind)
2115 : m_ctxt(ctxt),
2116 m_inner_fndecl (fndecl),
2117 m_inner_bind_expr (NULL),
2118 m_kind (kind),
2119 m_blocks ()
2120 {
2121 if (m_kind != GCC_JIT_FUNCTION_IMPORTED)
2122 {
2123 /* Create a BIND_EXPR, and within it, a statement list. */
2124 m_stmt_list = alloc_stmt_list ();
2125 m_stmt_iter = tsi_start (m_stmt_list);
2126 m_inner_block = make_node (BLOCK);
2127 m_inner_bind_expr =
2128 build3 (BIND_EXPR, void_type_node, NULL, m_stmt_list, m_inner_block);
2129 }
2130 else
2131 {
2132 m_inner_block = NULL;
2133 m_stmt_list = NULL;
2134 }
2135 }
2136
2137 /* Hand-written GC-marking hook for playback functions. */
2138
2139 void
2140 playback::function::
2141 gt_ggc_mx ()
2142 {
2143 gt_ggc_m_9tree_node (m_inner_fndecl);
2144 gt_ggc_m_9tree_node (m_inner_bind_expr);
2145 gt_ggc_m_9tree_node (m_stmt_list);
2146 gt_ggc_m_9tree_node (m_inner_block);
2147 }
2148
2149 /* Don't leak vec's internal buffer (in non-GC heap) when we are
2150 GC-ed. */
2151
2152 void
2153 playback::function::finalizer ()
2154 {
2155 m_blocks.release ();
2156 }
2157
2158 /* Get the return type of a playback function, in tree form. */
2159
2160 tree
2161 playback::function::
2162 get_return_type_as_tree () const
2163 {
2164 return TREE_TYPE (TREE_TYPE(m_inner_fndecl));
2165 }
2166
2167 /* Construct a new local within this playback::function. */
2168
2169 playback::lvalue *
2170 playback::function::
2171 new_local (location *loc,
2172 type *type,
2173 const char *name,
2174 const std::vector<std::pair<gcc_jit_variable_attribute,
2175 std::string>> &attributes)
2176 {
2177 gcc_assert (type);
2178 tree inner;
2179 if (name)
2180 inner = build_decl (UNKNOWN_LOCATION, VAR_DECL,
2181 get_identifier (name),
2182 type->as_tree ());
2183 else
2184 {
2185 inner = build_decl (UNKNOWN_LOCATION, VAR_DECL,
2186 create_tmp_var_name ("JITTMP"),
2187 type->as_tree ());
2188 DECL_ARTIFICIAL (inner) = 1;
2189 DECL_IGNORED_P (inner) = 1;
2190 DECL_NAMELESS (inner) = 1;
2191 }
2192 DECL_CONTEXT (inner) = this->m_inner_fndecl;
2193
2194 /* Prepend to BIND_EXPR_VARS: */
2195 DECL_CHAIN (inner) = BIND_EXPR_VARS (m_inner_bind_expr);
2196 BIND_EXPR_VARS (m_inner_bind_expr) = inner;
2197
2198 set_variable_string_attribute (attributes, inner);
2199
2200 if (loc)
2201 set_tree_location (inner, loc);
2202 return new lvalue (m_ctxt, inner);
2203 }
2204
2205 /* Construct a new block within this playback::function. */
2206
2207 playback::block *
2208 playback::function::
2209 new_block (const char *name)
2210 {
2211 gcc_assert (m_kind != GCC_JIT_FUNCTION_IMPORTED);
2212
2213 block *result = new playback::block (this, name);
2214 m_blocks.safe_push (result);
2215 return result;
2216 }
2217
2218 /* Construct a playback::rvalue instance wrapping an ADDR_EXPR for
2219 this playback::function. */
2220
2221 playback::rvalue *
2222 playback::function::get_address (location *loc)
2223 {
2224 tree t_fndecl = as_fndecl ();
2225 tree t_fntype = TREE_TYPE (t_fndecl);
2226 tree t_fnptr = build1 (ADDR_EXPR, build_pointer_type (t_fntype), t_fndecl);
2227 if (loc)
2228 m_ctxt->set_tree_location (t_fnptr, loc);
2229 return new rvalue (m_ctxt, t_fnptr);
2230 }
2231
2232 /* Build a statement list for the function as a whole out of the
2233 lists of statements for the individual blocks, building labels
2234 for each block. */
2235
2236 void
2237 playback::function::
2238 build_stmt_list ()
2239 {
2240 int i;
2241 block *b;
2242
2243 JIT_LOG_SCOPE (m_ctxt->get_logger ());
2244
2245 FOR_EACH_VEC_ELT (m_blocks, i, b)
2246 {
2247 int j;
2248 tree stmt;
2249
2250 b->m_label_expr = build1 (LABEL_EXPR,
2251 void_type_node,
2252 b->as_label_decl ());
2253 tsi_link_after (&m_stmt_iter, b->m_label_expr, TSI_CONTINUE_LINKING);
2254
2255 FOR_EACH_VEC_ELT (b->m_stmts, j, stmt)
2256 tsi_link_after (&m_stmt_iter, stmt, TSI_CONTINUE_LINKING);
2257 }
2258 }
2259
2260 /* Finish compiling the given function, potentially running the
2261 garbage-collector.
2262 The function will have a statement list by now.
2263 Amongst other things, this gimplifies the statement list,
2264 and calls cgraph_node::finalize_function on the function. */
2265
2266 void
2267 playback::function::
2268 postprocess ()
2269 {
2270 JIT_LOG_SCOPE (m_ctxt->get_logger ());
2271
2272 if (m_ctxt->get_bool_option (GCC_JIT_BOOL_OPTION_DUMP_INITIAL_TREE))
2273 debug_tree (m_stmt_list);
2274
2275 /* Do we need this to force cgraphunit.cc to output the function? */
2276 if (m_kind == GCC_JIT_FUNCTION_EXPORTED)
2277 {
2278 DECL_EXTERNAL (m_inner_fndecl) = 0;
2279 DECL_PRESERVE_P (m_inner_fndecl) = 1;
2280 }
2281
2282 if (m_kind == GCC_JIT_FUNCTION_INTERNAL
2283 ||m_kind == GCC_JIT_FUNCTION_ALWAYS_INLINE)
2284 {
2285 DECL_EXTERNAL (m_inner_fndecl) = 0;
2286 TREE_PUBLIC (m_inner_fndecl) = 0;
2287 }
2288
2289 if (m_kind != GCC_JIT_FUNCTION_IMPORTED)
2290 {
2291 /* Seem to need this in gimple-low.cc: */
2292 gcc_assert (m_inner_block);
2293 DECL_INITIAL (m_inner_fndecl) = m_inner_block;
2294
2295 /* how to add to function? the following appears to be how to
2296 set the body of a m_inner_fndecl: */
2297 DECL_SAVED_TREE(m_inner_fndecl) = m_inner_bind_expr;
2298
2299 /* Ensure that locals appear in the debuginfo. */
2300 BLOCK_VARS (m_inner_block) = BIND_EXPR_VARS (m_inner_bind_expr);
2301
2302 //debug_tree (m_inner_fndecl);
2303
2304 /* Convert to gimple: */
2305 //printf("about to gimplify_function_tree\n");
2306 gimplify_function_tree (m_inner_fndecl);
2307 //printf("finished gimplify_function_tree\n");
2308
2309 current_function_decl = m_inner_fndecl;
2310 if (m_ctxt->get_bool_option (GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE))
2311 dump_function_to_file (m_inner_fndecl, stderr, TDF_VOPS|TDF_MEMSYMS|TDF_LINENO);
2312 //debug_tree (m_inner_fndecl);
2313
2314 //printf("about to add to cgraph\n");
2315 /* Add to cgraph: */
2316 cgraph_node::finalize_function (m_inner_fndecl, false);
2317 /* This can trigger a collection, so we need to have all of
2318 the funcs as roots. */
2319
2320 current_function_decl = NULL;
2321 }
2322 else
2323 /* Add to cgraph to output aliases: */
2324 rest_of_decl_compilation (m_inner_fndecl, true, 0);
2325 }
2326
2327 /* Don't leak vec's internal buffer (in non-GC heap) when we are
2328 GC-ed. */
2329
2330 void
2331 playback::block::finalizer ()
2332 {
2333 m_stmts.release ();
2334 }
2335
2336 /* Add an eval of the rvalue to the function's statement list. */
2337
2338 void
2339 playback::block::
2340 add_eval (location *loc,
2341 rvalue *rvalue)
2342 {
2343 gcc_assert (rvalue);
2344
2345 if (loc)
2346 set_tree_location (rvalue->as_tree (), loc);
2347
2348 add_stmt (rvalue->as_tree ());
2349 }
2350
2351 /* Add an assignment to the function's statement list. */
2352
2353 void
2354 playback::block::
2355 add_assignment (location *loc,
2356 lvalue *lvalue,
2357 rvalue *rvalue)
2358 {
2359 gcc_assert (lvalue);
2360 gcc_assert (rvalue);
2361
2362 tree t_lvalue = lvalue->as_tree ();
2363 tree t_rvalue = rvalue->as_tree ();
2364 if (TREE_TYPE (t_rvalue) != TREE_TYPE (t_lvalue))
2365 {
2366 t_rvalue = build1 (CONVERT_EXPR,
2367 TREE_TYPE (t_lvalue),
2368 t_rvalue);
2369 if (loc)
2370 set_tree_location (t_rvalue, loc);
2371 }
2372
2373 tree stmt =
2374 build2 (MODIFY_EXPR, TREE_TYPE (t_lvalue),
2375 t_lvalue, t_rvalue);
2376 if (loc)
2377 set_tree_location (stmt, loc);
2378 add_stmt (stmt);
2379 }
2380
2381 /* Add a comment to the function's statement list.
2382 For now this is done by adding a dummy label. */
2383
2384 void
2385 playback::block::
2386 add_comment (location *loc,
2387 const char *text)
2388 {
2389 /* Wrap the text in C-style comment delimiters. */
2390 size_t sz =
2391 (3 /* opening delim */
2392 + strlen (text)
2393 + 3 /* closing delim */
2394 + 1 /* terminator */);
2395 char *wrapped = (char *)ggc_internal_alloc (sz);
2396 snprintf (wrapped, sz, "/* %s */", text);
2397
2398 /* For now we simply implement this by adding a dummy label with a name
2399 containing the given text. */
2400 tree identifier = get_identifier (wrapped);
2401 tree label_decl = build_decl (UNKNOWN_LOCATION, LABEL_DECL,
2402 identifier, void_type_node);
2403 DECL_CONTEXT (label_decl) = m_func->as_fndecl ();
2404
2405 tree label_expr = build1 (LABEL_EXPR, void_type_node, label_decl);
2406 if (loc)
2407 set_tree_location (label_expr, loc);
2408 add_stmt (label_expr);
2409 }
2410
2411 /* Add a conditional jump statement to the function's statement list. */
2412
2413 void
2414 playback::block::
2415 add_conditional (location *loc,
2416 rvalue *boolval,
2417 block *on_true,
2418 block *on_false)
2419 {
2420 gcc_assert (boolval);
2421 gcc_assert (on_true);
2422 gcc_assert (on_false);
2423
2424 /* COND_EXPR wants statement lists for the true/false operands, but we
2425 want labels.
2426 Shim it by creating jumps to the labels */
2427 tree true_jump = build1 (GOTO_EXPR, void_type_node,
2428 on_true->as_label_decl ());
2429 if (loc)
2430 set_tree_location (true_jump, loc);
2431
2432 tree false_jump = build1 (GOTO_EXPR, void_type_node,
2433 on_false->as_label_decl ());
2434 if (loc)
2435 set_tree_location (false_jump, loc);
2436
2437 tree stmt =
2438 build3 (COND_EXPR, void_type_node, boolval->as_tree (),
2439 true_jump, false_jump);
2440 if (loc)
2441 set_tree_location (stmt, loc);
2442 add_stmt (stmt);
2443 }
2444
2445 /* Add an unconditional jump statement to the function's statement list. */
2446
2447 void
2448 playback::block::
2449 add_jump (location *loc,
2450 block *target)
2451 {
2452 gcc_assert (target);
2453
2454 // see c_finish_loop
2455 //tree top = build1 (LABEL_EXPR, void_type_node, NULL_TREE);
2456 //add_stmt (top);
2457
2458 //tree stmt = build_and_jump (&LABEL_EXPR_LABEL (target->label_));
2459 TREE_USED (target->as_label_decl ()) = 1;
2460 tree stmt = build1 (GOTO_EXPR, void_type_node, target->as_label_decl ());
2461 if (loc)
2462 set_tree_location (stmt, loc);
2463 add_stmt (stmt);
2464
2465 /*
2466 from c-typeck.cc:
2467 tree
2468 c_finish_goto_label (location_t loc, tree label)
2469 {
2470 tree decl = lookup_label_for_goto (loc, label);
2471 if (!decl)
2472 return NULL_TREE;
2473 TREE_USED (decl) = 1;
2474 {
2475 tree t = build1 (GOTO_EXPR, void_type_node, decl);
2476 SET_EXPR_LOCATION (t, loc);
2477 return add_stmt (t);
2478 }
2479 }
2480 */
2481
2482 }
2483
2484 /* Add a return statement to the function's statement list. */
2485
2486 void
2487 playback::block::
2488 add_return (location *loc,
2489 rvalue *rvalue)
2490 {
2491 tree modify_retval = NULL;
2492 tree return_type = m_func->get_return_type_as_tree ();
2493 if (rvalue)
2494 {
2495 tree t_lvalue = DECL_RESULT (m_func->as_fndecl ());
2496 tree t_rvalue = rvalue->as_tree ();
2497 if (TREE_TYPE (t_rvalue) != TREE_TYPE (t_lvalue))
2498 t_rvalue = build1 (CONVERT_EXPR,
2499 TREE_TYPE (t_lvalue),
2500 t_rvalue);
2501 modify_retval = build2 (MODIFY_EXPR, return_type,
2502 t_lvalue, t_rvalue);
2503 if (loc)
2504 set_tree_location (modify_retval, loc);
2505 }
2506 tree return_stmt = build1 (RETURN_EXPR, return_type,
2507 modify_retval);
2508 if (loc)
2509 set_tree_location (return_stmt, loc);
2510
2511 add_stmt (return_stmt);
2512 }
2513
2514 /* Helper function for playback::block::add_switch.
2515 Construct a case label for the given range, followed by a goto stmt
2516 to the given block, appending them to stmt list *ptr_t_switch_body. */
2517
2518 static void
2519 add_case (tree *ptr_t_switch_body,
2520 tree t_low_value,
2521 tree t_high_value,
2522 playback::block *dest_block)
2523 {
2524 tree t_label = create_artificial_label (UNKNOWN_LOCATION);
2525 DECL_CONTEXT (t_label) = dest_block->get_function ()->as_fndecl ();
2526
2527 tree t_case_label =
2528 build_case_label (t_low_value, t_high_value, t_label);
2529 append_to_statement_list (t_case_label, ptr_t_switch_body);
2530
2531 tree t_goto_stmt =
2532 build1 (GOTO_EXPR, void_type_node, dest_block->as_label_decl ());
2533 append_to_statement_list (t_goto_stmt, ptr_t_switch_body);
2534 }
2535
2536 /* Add a switch statement to the function's statement list.
2537
2538 We create a switch body, and populate it with case labels, each
2539 followed by a goto to the desired block. */
2540
2541 void
2542 playback::block::
2543 add_switch (location *loc,
2544 rvalue *expr,
2545 block *default_block,
2546 const auto_vec <case_> *cases)
2547 {
2548 /* Compare with:
2549 - c/c-typeck.cc: c_start_case
2550 - c-family/c-common.cc:c_add_case_label
2551 - java/expr.cc:expand_java_switch and expand_java_add_case
2552 We've already rejected overlaps and duplicates in
2553 libgccjit.cc:case_range_validator::validate. */
2554
2555 tree t_expr = expr->as_tree ();
2556 tree t_type = TREE_TYPE (t_expr);
2557
2558 tree t_switch_body = alloc_stmt_list ();
2559
2560 int i;
2561 case_ *c;
2562 FOR_EACH_VEC_ELT (*cases, i, c)
2563 {
2564 tree t_low_value = c->m_min_value->as_tree ();
2565 tree t_high_value = c->m_max_value->as_tree ();
2566 add_case (&t_switch_body, t_low_value, t_high_value, c->m_dest_block);
2567 }
2568 /* Default label. */
2569 add_case (&t_switch_body, NULL_TREE, NULL_TREE, default_block);
2570
2571 tree switch_stmt = build2 (SWITCH_EXPR, t_type, t_expr, t_switch_body);
2572 if (loc)
2573 set_tree_location (switch_stmt, loc);
2574 add_stmt (switch_stmt);
2575 }
2576
2577 /* Convert OPERANDS to a tree-based chain suitable for creating an
2578 extended asm stmt.
2579 Compare with c_parser_asm_operands. */
2580
2581 static tree
2582 build_operand_chain (const auto_vec <playback::asm_operand> *operands)
2583 {
2584 tree result = NULL_TREE;
2585 unsigned i;
2586 playback::asm_operand *asm_op;
2587 FOR_EACH_VEC_ELT (*operands, i, asm_op)
2588 {
2589 tree name = build_string (asm_op->m_asm_symbolic_name);
2590 tree str = build_string (asm_op->m_constraint);
2591 tree value = asm_op->m_expr;
2592 result = chainon (result,
2593 build_tree_list (build_tree_list (name, str),
2594 value));
2595 }
2596 return result;
2597 }
2598
2599 /* Convert CLOBBERS to a tree-based list suitable for creating an
2600 extended asm stmt.
2601 Compare with c_parser_asm_clobbers. */
2602
2603 static tree
2604 build_clobbers (const auto_vec <const char *> *clobbers)
2605 {
2606 tree list = NULL_TREE;
2607 unsigned i;
2608 const char *clobber;
2609 FOR_EACH_VEC_ELT (*clobbers, i, clobber)
2610 {
2611 tree str = build_string (clobber);
2612 list = tree_cons (NULL_TREE, str, list);
2613 }
2614 return list;
2615 }
2616
2617 /* Convert BLOCKS to a tree-based list suitable for creating an
2618 extended asm stmt.
2619 Compare with c_parser_asm_goto_operands. */
2620
2621 static tree
2622 build_goto_operands (const auto_vec <playback::block *> *blocks)
2623 {
2624 tree list = NULL_TREE;
2625 unsigned i;
2626 playback::block *b;
2627 FOR_EACH_VEC_ELT (*blocks, i, b)
2628 {
2629 tree label = b->as_label_decl ();
2630 tree name = build_string (IDENTIFIER_POINTER (DECL_NAME (label)));
2631 TREE_USED (label) = 1;
2632 list = tree_cons (name, label, list);
2633 }
2634 return nreverse (list);
2635 }
2636
2637 /* Add an extended asm statement to this block.
2638
2639 Compare with c_parser_asm_statement (in c/c-parser.cc)
2640 and build_asm_expr (in c/c-typeck.cc). */
2641
2642 void
2643 playback::block::add_extended_asm (location *loc,
2644 const char *asm_template,
2645 bool is_volatile,
2646 bool is_inline,
2647 const auto_vec <asm_operand> *outputs,
2648 const auto_vec <asm_operand> *inputs,
2649 const auto_vec <const char *> *clobbers,
2650 const auto_vec <block *> *goto_blocks)
2651 {
2652 tree t_string = build_string (asm_template);
2653 tree t_outputs = build_operand_chain (outputs);
2654 tree t_inputs = build_operand_chain (inputs);
2655 tree t_clobbers = build_clobbers (clobbers);
2656 tree t_labels = build_goto_operands (goto_blocks);
2657 t_string
2658 = resolve_asm_operand_names (t_string, t_outputs, t_inputs, t_labels);
2659 tree asm_stmt
2660 = build5 (ASM_EXPR, void_type_node,
2661 t_string, t_outputs, t_inputs, t_clobbers, t_labels);
2662
2663 /* asm statements without outputs, including simple ones, are treated
2664 as volatile. */
2665 ASM_VOLATILE_P (asm_stmt) = (outputs->length () == 0);
2666 ASM_BASIC_P (asm_stmt) = 0;
2667 ASM_INLINE_P (asm_stmt) = is_inline;
2668 if (is_volatile)
2669 ASM_VOLATILE_P (asm_stmt) = 1;
2670 if (loc)
2671 set_tree_location (asm_stmt, loc);
2672 add_stmt (asm_stmt);
2673 }
2674
2675 /* Constructor for gcc::jit::playback::block. */
2676
2677 playback::block::
2678 block (function *func,
2679 const char *name)
2680 : m_func (func),
2681 m_stmts ()
2682 {
2683 tree identifier;
2684
2685 gcc_assert (func);
2686 // name can be NULL
2687 if (name)
2688 identifier = get_identifier (name);
2689 else
2690 identifier = NULL;
2691 m_label_decl = build_decl (UNKNOWN_LOCATION, LABEL_DECL,
2692 identifier, void_type_node);
2693 DECL_CONTEXT (m_label_decl) = func->as_fndecl ();
2694 m_label_expr = NULL;
2695 }
2696
2697 // This is basically std::lock_guard but it can call the private lock/unlock
2698 // members of playback::context.
2699 struct playback::context::scoped_lock
2700 {
2701 scoped_lock (context &ctx) : m_ctx (&ctx) { m_ctx->lock (); }
2702 ~scoped_lock () { m_ctx->unlock (); }
2703
2704 context *m_ctx;
2705
2706 // Not movable or copyable.
2707 scoped_lock (scoped_lock &&) = delete;
2708 scoped_lock &operator= (scoped_lock &&) = delete;
2709 };
2710
2711 /* Compile a playback::context:
2712
2713 - Use the context's options to cconstruct command-line options, and
2714 call into the rest of GCC (toplev::main).
2715 - Assuming it succeeds, we have a .s file.
2716 - We then run the "postprocess" vfunc:
2717
2718 (A) In-memory compile ("gcc_jit_context_compile")
2719
2720 For an in-memory compile we have the playback::compile_to_memory
2721 subclass; "postprocess" will convert the .s file to a .so DSO,
2722 and load it in memory (via dlopen), wrapping the result up as
2723 a jit::result and returning it.
2724
2725 (B) Compile to file ("gcc_jit_context_compile_to_file")
2726
2727 When compiling to a file, we have the playback::compile_to_file
2728 subclass; "postprocess" will either copy the .s file to the
2729 destination (for GCC_JIT_OUTPUT_KIND_ASSEMBLER), or invoke
2730 the driver to convert it as necessary, copying the result. */
2731
2732 void
2733 playback::context::
2734 compile ()
2735 {
2736 JIT_LOG_SCOPE (get_logger ());
2737
2738 const char *ctxt_progname;
2739
2740 int keep_intermediates =
2741 get_bool_option (GCC_JIT_BOOL_OPTION_KEEP_INTERMEDIATES);
2742
2743 m_tempdir = new tempdir (get_logger (), keep_intermediates);
2744 if (!m_tempdir->create ())
2745 return;
2746
2747 /* Call into the rest of gcc.
2748 For now, we have to assemble command-line options to pass into
2749 toplev::main, so that they can be parsed. */
2750
2751 /* Pass in user-provided program name as argv0, if any, so that it
2752 makes it into GCC's "progname" global, used in various diagnostics. */
2753 ctxt_progname = get_str_option (GCC_JIT_STR_OPTION_PROGNAME);
2754
2755 if (!ctxt_progname)
2756 ctxt_progname = "libgccjit.so";
2757
2758 auto_vec <recording::requested_dump> requested_dumps;
2759 m_recording_ctxt->get_all_requested_dumps (&requested_dumps);
2760
2761 /* Acquire the JIT mutex and set "this" as the active playback ctxt. */
2762 scoped_lock lock(*this);
2763
2764 auto_string_vec fake_args;
2765 make_fake_args (&fake_args, ctxt_progname, &requested_dumps);
2766 if (errors_occurred ())
2767 return;
2768
2769 /* This runs the compiler. */
2770 toplev toplev (get_timer (), /* external_timer */
2771 false); /* init_signals */
2772 enter_scope ("toplev::main");
2773 if (get_logger ())
2774 for (unsigned i = 0; i < fake_args.length (); i++)
2775 get_logger ()->log ("argv[%i]: %s", i, fake_args[i]);
2776
2777 /* Add a trailing null to argvec; this is not counted in argc. */
2778 fake_args.safe_push (nullptr);
2779 toplev.main (/* The trailing null is not counted in argv. */
2780 fake_args.length () - 1,
2781 const_cast <char **> (fake_args.address ()));
2782 exit_scope ("toplev::main");
2783
2784 /* Extracting dumps makes use of the gcc::dump_manager, hence we
2785 need to do it between toplev::main (which creates the dump manager)
2786 and toplev::finalize (which deletes it). */
2787 extract_any_requested_dumps (&requested_dumps);
2788
2789 /* Clean up the compiler. */
2790 enter_scope ("toplev::finalize");
2791 toplev.finalize ();
2792 exit_scope ("toplev::finalize");
2793
2794 /* Ideally we would release the jit mutex here, but we can't yet since
2795 followup activities use timevars, which are global state. */
2796
2797 if (errors_occurred ())
2798 return;
2799
2800 if (get_bool_option (GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE))
2801 dump_generated_code ();
2802
2803 /* We now have a .s file.
2804
2805 Run any postprocessing steps. This will either convert the .s file to
2806 a .so DSO, and load it in memory (playback::compile_to_memory), or
2807 convert the .s file to the requested output format, and copy it to a
2808 given file (playback::compile_to_file). */
2809 postprocess (ctxt_progname);
2810 }
2811
2812 /* Implementation of class gcc::jit::playback::compile_to_memory,
2813 a subclass of gcc::jit::playback::context. */
2814
2815 /* playback::compile_to_memory's trivial constructor. */
2816
2817 playback::compile_to_memory::compile_to_memory (recording::context *ctxt) :
2818 playback::context (ctxt),
2819 m_result (NULL)
2820 {
2821 JIT_LOG_SCOPE (get_logger ());
2822 }
2823
2824 /* Implementation of the playback::context::process vfunc for compiling
2825 to memory.
2826
2827 Convert the .s file to a .so DSO, and load it in memory (via dlopen),
2828 wrapping the result up as a jit::result and returning it. */
2829
2830 void
2831 playback::compile_to_memory::postprocess (const char *ctxt_progname)
2832 {
2833 JIT_LOG_SCOPE (get_logger ());
2834 convert_to_dso (ctxt_progname);
2835 if (errors_occurred ())
2836 return;
2837 m_result = dlopen_built_dso ();
2838 }
2839
2840 /* Implementation of class gcc::jit::playback::compile_to_file,
2841 a subclass of gcc::jit::playback::context. */
2842
2843 /* playback::compile_to_file's trivial constructor. */
2844
2845 playback::compile_to_file::compile_to_file (recording::context *ctxt,
2846 enum gcc_jit_output_kind output_kind,
2847 const char *output_path) :
2848 playback::context (ctxt),
2849 m_output_kind (output_kind),
2850 m_output_path (output_path)
2851 {
2852 JIT_LOG_SCOPE (get_logger ());
2853 }
2854
2855 /* Implementation of the playback::context::process vfunc for compiling
2856 to a file.
2857
2858 Either copy the .s file to the given destination (for
2859 GCC_JIT_OUTPUT_KIND_ASSEMBLER), or invoke the driver to convert it
2860 as necessary, copying the result. */
2861
2862 void
2863 playback::compile_to_file::postprocess (const char *ctxt_progname)
2864 {
2865 JIT_LOG_SCOPE (get_logger ());
2866
2867 /* The driver takes different actions based on the filename, so
2868 we provide a filename with an appropriate suffix for the
2869 output kind, and then copy it up to the user-provided path,
2870 rather than directly compiling it to the requested output path. */
2871
2872 switch (m_output_kind)
2873 {
2874 default:
2875 gcc_unreachable ();
2876
2877 case GCC_JIT_OUTPUT_KIND_ASSEMBLER:
2878 copy_file (get_tempdir ()->get_path_s_file (),
2879 m_output_path);
2880 /* The .s file is automatically unlinked by tempdir::~tempdir. */
2881 break;
2882
2883 case GCC_JIT_OUTPUT_KIND_OBJECT_FILE:
2884 {
2885 char *tmp_o_path = ::concat (get_tempdir ()->get_path (),
2886 "/fake.o",
2887 NULL);
2888 invoke_driver (ctxt_progname,
2889 get_tempdir ()->get_path_s_file (),
2890 tmp_o_path,
2891 TV_ASSEMBLE,
2892 false, /* bool shared, */
2893 false);/* bool run_linker */
2894 if (!errors_occurred ())
2895 {
2896 copy_file (tmp_o_path,
2897 m_output_path);
2898 get_tempdir ()->add_temp_file (tmp_o_path);
2899 }
2900 else
2901 free (tmp_o_path);
2902 }
2903 break;
2904
2905 case GCC_JIT_OUTPUT_KIND_DYNAMIC_LIBRARY:
2906 invoke_driver (ctxt_progname,
2907 get_tempdir ()->get_path_s_file (),
2908 get_tempdir ()->get_path_so_file (),
2909 TV_ASSEMBLE,
2910 true, /* bool shared, */
2911 true);/* bool run_linker */
2912 if (!errors_occurred ())
2913 copy_file (get_tempdir ()->get_path_so_file (),
2914 m_output_path);
2915 /* The .so file is automatically unlinked by tempdir::~tempdir. */
2916 break;
2917
2918 case GCC_JIT_OUTPUT_KIND_EXECUTABLE:
2919 {
2920 char *tmp_exe_path = ::concat (get_tempdir ()->get_path (),
2921 "/fake.exe",
2922 NULL);
2923 invoke_driver (ctxt_progname,
2924 get_tempdir ()->get_path_s_file (),
2925 tmp_exe_path,
2926 TV_ASSEMBLE,
2927 false, /* bool shared, */
2928 true);/* bool run_linker */
2929 if (!errors_occurred ())
2930 {
2931 copy_file (tmp_exe_path,
2932 m_output_path);
2933 get_tempdir ()->add_temp_file (tmp_exe_path);
2934 }
2935 else
2936 free (tmp_exe_path);
2937 }
2938 break;
2939
2940 }
2941
2942 }
2943
2944 /* Copy SRC_PATH to DST_PATH, preserving permission bits (in particular,
2945 the "executable" bits).
2946
2947 Any errors that occur are reported on the context and hence count as
2948 a failure of the compile.
2949
2950 We can't in general hardlink or use "rename" from the tempdir since
2951 it might be on a different filesystem to the destination. For example,
2952 I get EXDEV: "Invalid cross-device link". */
2953
2954 void
2955 playback::compile_to_file::copy_file (const char *src_path,
2956 const char *dst_path)
2957 {
2958 JIT_LOG_SCOPE (get_logger ());
2959 if (get_logger ())
2960 {
2961 get_logger ()->log ("src_path: %s", src_path);
2962 get_logger ()->log ("dst_path: %s", dst_path);
2963 }
2964
2965 FILE *f_in = NULL;
2966 FILE *f_out = NULL;
2967 size_t total_sz_in = 0;
2968 size_t total_sz_out = 0;
2969 char buf[4096];
2970 size_t sz_in;
2971 struct stat stat_buf;
2972
2973 f_in = fopen (src_path, "rb");
2974 if (!f_in)
2975 {
2976 add_error (NULL,
2977 "unable to open %s for reading: %s",
2978 src_path,
2979 xstrerror (errno));
2980 return;
2981 }
2982
2983 /* Use stat on the filedescriptor to get the mode,
2984 so that we can copy it over (in particular, the
2985 "executable" bits). */
2986 if (fstat (fileno (f_in), &stat_buf) == -1)
2987 {
2988 add_error (NULL,
2989 "unable to fstat %s: %s",
2990 src_path,
2991 xstrerror (errno));
2992 fclose (f_in);
2993 return;
2994 }
2995
2996 f_out = fopen (dst_path, "wb");
2997 if (!f_out)
2998 {
2999 add_error (NULL,
3000 "unable to open %s for writing: %s",
3001 dst_path,
3002 xstrerror (errno));
3003 fclose (f_in);
3004 return;
3005 }
3006
3007 while ( (sz_in = fread (buf, 1, sizeof (buf), f_in)) )
3008 {
3009 total_sz_in += sz_in;
3010 size_t sz_out_remaining = sz_in;
3011 size_t sz_out_so_far = 0;
3012 while (sz_out_remaining)
3013 {
3014 size_t sz_out = fwrite (buf + sz_out_so_far,
3015 1,
3016 sz_out_remaining,
3017 f_out);
3018 gcc_assert (sz_out <= sz_out_remaining);
3019 if (!sz_out)
3020 {
3021 add_error (NULL,
3022 "error writing to %s: %s",
3023 dst_path,
3024 xstrerror (errno));
3025 fclose (f_in);
3026 fclose (f_out);
3027 return;
3028 }
3029 total_sz_out += sz_out;
3030 sz_out_so_far += sz_out;
3031 sz_out_remaining -= sz_out;
3032 }
3033 gcc_assert (sz_out_so_far == sz_in);
3034 }
3035
3036 if (!feof (f_in))
3037 add_error (NULL,
3038 "error reading from %s: %s",
3039 src_path,
3040 xstrerror (errno));
3041
3042 fclose (f_in);
3043
3044 gcc_assert (total_sz_in == total_sz_out);
3045 if (get_logger ())
3046 get_logger ()->log ("total bytes copied: %zu", total_sz_out);
3047
3048 /* fchmod does not exist in Windows. */
3049 #ifndef _WIN32
3050 /* Set the permissions of the copy to those of the original file,
3051 in particular the "executable" bits. */
3052 if (fchmod (fileno (f_out), stat_buf.st_mode) == -1)
3053 add_error (NULL,
3054 "error setting mode of %s: %s",
3055 dst_path,
3056 xstrerror (errno));
3057 #endif
3058
3059 fclose (f_out);
3060 }
3061
3062 /* Helper functions for gcc::jit::playback::context::compile. */
3063
3064 /* This mutex guards gcc::jit::recording::context::compile, so that only
3065 one thread can be accessing the bulk of GCC's state at once. */
3066
3067 static std::mutex jit_mutex;
3068
3069 /* Acquire jit_mutex and set "this" as the active playback ctxt. */
3070
3071 void
3072 playback::context::lock ()
3073 {
3074 auto_timevar tv (get_timer (), TV_JIT_ACQUIRING_MUTEX);
3075
3076 /* Acquire the big GCC mutex. */
3077 JIT_LOG_SCOPE (get_logger ());
3078 jit_mutex.lock ();
3079 gcc_assert (active_playback_ctxt == NULL);
3080 active_playback_ctxt = this;
3081 }
3082
3083 /* Release jit_mutex and clear the active playback ctxt. */
3084
3085 void
3086 playback::context::unlock ()
3087 {
3088 /* Release the big GCC mutex. */
3089 JIT_LOG_SCOPE (get_logger ());
3090 gcc_assert (active_playback_ctxt == this);
3091 active_playback_ctxt = NULL;
3092 jit_mutex.unlock ();
3093 }
3094
3095 /* Callback used by gcc::jit::playback::context::make_fake_args when
3096 invoking driver_get_configure_time_options.
3097 Populate a vec <char * > with the configure-time options. */
3098
3099 static void
3100 append_arg_from_driver (const char *option, void *user_data)
3101 {
3102 gcc_assert (option);
3103 gcc_assert (user_data);
3104 vec <char *> *argvec = static_cast <vec <char *> *> (user_data);
3105 argvec->safe_push (concat ("-", option, NULL));
3106 }
3107
3108 /* Build a fake argv for toplev::main from the options set
3109 by the user on the context . */
3110
3111 void
3112 playback::context::
3113 make_fake_args (vec <char *> *argvec,
3114 const char *ctxt_progname,
3115 vec <recording::requested_dump> *requested_dumps)
3116 {
3117 JIT_LOG_SCOPE (get_logger ());
3118
3119 #define ADD_ARG(arg) argvec->safe_push (xstrdup (arg))
3120 #define ADD_ARG_TAKE_OWNERSHIP(arg) argvec->safe_push (arg)
3121
3122 ADD_ARG (ctxt_progname);
3123 ADD_ARG (get_path_c_file ());
3124 ADD_ARG ("-fPIC");
3125
3126 /* Handle int options: */
3127 switch (get_int_option (GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL))
3128 {
3129 default:
3130 add_error (NULL,
3131 "unrecognized optimization level: %i",
3132 get_int_option (GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL));
3133 return;
3134
3135 case 0:
3136 ADD_ARG ("-O0");
3137 break;
3138
3139 case 1:
3140 ADD_ARG ("-O1");
3141 break;
3142
3143 case 2:
3144 ADD_ARG ("-O2");
3145 break;
3146
3147 case 3:
3148 ADD_ARG ("-O3");
3149 break;
3150 }
3151 /* What about -Os? */
3152
3153 /* Handle bool options: */
3154 if (get_bool_option (GCC_JIT_BOOL_OPTION_DEBUGINFO))
3155 ADD_ARG ("-g");
3156
3157 /* Suppress timing (and other) info. */
3158 if (!get_bool_option (GCC_JIT_BOOL_OPTION_DUMP_SUMMARY))
3159 {
3160 ADD_ARG ("-quiet");
3161 quiet_flag = 1;
3162 }
3163
3164 /* Aggressively garbage-collect, to shake out bugs: */
3165 if (get_bool_option (GCC_JIT_BOOL_OPTION_SELFCHECK_GC))
3166 {
3167 ADD_ARG ("--param=ggc-min-expand=0");
3168 ADD_ARG ("--param=ggc-min-heapsize=0");
3169 }
3170
3171 if (get_bool_option (GCC_JIT_BOOL_OPTION_DUMP_EVERYTHING))
3172 {
3173 ADD_ARG ("-fdump-tree-all");
3174 ADD_ARG ("-fdump-rtl-all");
3175 ADD_ARG ("-fdump-ipa-all");
3176 }
3177
3178 /* Add "-fdump-" options for any calls to
3179 gcc_jit_context_enable_dump. */
3180 {
3181 int i;
3182 recording::requested_dump *d;
3183 FOR_EACH_VEC_ELT (*requested_dumps, i, d)
3184 {
3185 char *arg = concat ("-fdump-", d->m_dumpname, NULL);
3186 ADD_ARG_TAKE_OWNERSHIP (arg);
3187 }
3188 }
3189
3190 /* PR jit/64810: Add any target-specific default options
3191 from OPTION_DEFAULT_SPECS, normally provided by the driver
3192 in the non-jit case.
3193
3194 The target-specific code can define OPTION_DEFAULT_SPECS:
3195 default command options in the form of spec macros for the
3196 driver to expand ().
3197
3198 For cc1 etc, the driver processes OPTION_DEFAULT_SPECS and,
3199 if not overriden, injects the defaults as extra arguments to
3200 cc1 etc.
3201 For the jit case, we need to add these arguments here. The
3202 input format (using the specs language) means that we have to run
3203 part of the driver code here (driver_get_configure_time_options).
3204
3205 To avoid running the spec-expansion code every time, we just do
3206 it the first time (via a function-static flag), saving the result
3207 into a function-static vec.
3208 This flag and vec are global state (i.e. per-process).
3209 They are guarded by the jit mutex. */
3210 {
3211 static bool have_configure_time_options = false;
3212 static vec <char *> configure_time_options;
3213
3214 if (have_configure_time_options)
3215 log ("reusing cached configure-time options");
3216 else
3217 {
3218 have_configure_time_options = true;
3219 log ("getting configure-time options from driver");
3220 driver_get_configure_time_options (append_arg_from_driver,
3221 &configure_time_options);
3222 }
3223
3224 int i;
3225 char *opt;
3226
3227 if (get_logger ())
3228 FOR_EACH_VEC_ELT (configure_time_options, i, opt)
3229 log ("configure_time_options[%i]: %s", i, opt);
3230
3231 /* configure_time_options should now contain the expanded options
3232 from OPTION_DEFAULT_SPECS (if any). */
3233 FOR_EACH_VEC_ELT (configure_time_options, i, opt)
3234 {
3235 gcc_assert (opt);
3236 gcc_assert (opt[0] == '-');
3237 ADD_ARG (opt);
3238 }
3239 }
3240
3241 if (get_timer ())
3242 ADD_ARG ("-ftime-report");
3243
3244 /* Add any user-provided extra options, starting with any from
3245 parent contexts. */
3246 m_recording_ctxt->append_command_line_options (argvec);
3247
3248 #undef ADD_ARG
3249 #undef ADD_ARG_TAKE_OWNERSHIP
3250 }
3251
3252 /* The second half of the implementation of gcc_jit_context_enable_dump.
3253 Iterate through the requested dumps, reading the underlying files
3254 into heap-allocated buffers, writing pointers to the buffers into
3255 the char ** pointers provided by client code.
3256 Client code is responsible for calling free on the results. */
3257
3258 void
3259 playback::context::
3260 extract_any_requested_dumps (vec <recording::requested_dump> *requested_dumps)
3261 {
3262 JIT_LOG_SCOPE (get_logger ());
3263
3264 int i;
3265 recording::requested_dump *d;
3266 FOR_EACH_VEC_ELT (*requested_dumps, i, d)
3267 {
3268 dump_file_info *dfi;
3269 char *filename;
3270 char *content;
3271
3272 dfi = g->get_dumps ()->get_dump_file_info_by_switch (d->m_dumpname);
3273 if (!dfi)
3274 {
3275 add_error (NULL, "unrecognized dump: %s", d->m_dumpname);
3276 continue;
3277 }
3278
3279 filename = g->get_dumps ()->get_dump_file_name (dfi);
3280 content = read_dump_file (filename);
3281 *(d->m_out_ptr) = content;
3282 m_tempdir->add_temp_file (filename);
3283 }
3284 }
3285
3286 /* Helper function for playback::context::extract_any_requested_dumps
3287 (itself for use in implementation of gcc_jit_context_enable_dump).
3288
3289 Attempt to read the complete file at the given path, returning the
3290 bytes found there as a buffer.
3291 The caller is responsible for calling free on the result.
3292 Errors will be reported on the context, and lead to NULL being
3293 returned; an out-of-memory error will terminate the process. */
3294
3295 char *
3296 playback::context::read_dump_file (const char *path)
3297 {
3298 char *result = NULL;
3299 size_t total_sz = 0;
3300 char buf[4096];
3301 size_t sz;
3302 FILE *f_in;
3303
3304 f_in = fopen (path, "r");
3305 if (!f_in)
3306 {
3307 add_error (NULL, "unable to open %s for reading", path);
3308 return NULL;
3309 }
3310
3311 while ( (sz = fread (buf, 1, sizeof (buf), f_in)) )
3312 {
3313 size_t old_total_sz = total_sz;
3314 total_sz += sz;
3315 result = reinterpret_cast <char *> (xrealloc (result, total_sz + 1));
3316 memcpy (result + old_total_sz, buf, sz);
3317 }
3318
3319 if (!feof (f_in))
3320 {
3321 add_error (NULL, "error reading from %s", path);
3322 free (result);
3323 fclose (f_in);
3324 return NULL;
3325 }
3326
3327 fclose (f_in);
3328
3329 if (result)
3330 {
3331 result[total_sz] = '\0';
3332 return result;
3333 }
3334 else
3335 return xstrdup ("");
3336 }
3337
3338 /* Part of playback::context::compile ().
3339
3340 We have a .s file; we want a .so file.
3341 We could reuse parts of gcc/gcc.cc to do this.
3342 For now, just use the driver binary from the install, as
3343 named in gcc-driver-name.h
3344 e.g. "x86_64-unknown-linux-gnu-gcc-5.0.0". */
3345
3346 void
3347 playback::context::
3348 convert_to_dso (const char *ctxt_progname)
3349 {
3350 JIT_LOG_SCOPE (get_logger ());
3351
3352 invoke_driver (ctxt_progname,
3353 m_tempdir->get_path_s_file (),
3354 m_tempdir->get_path_so_file (),
3355 TV_ASSEMBLE,
3356 true, /* bool shared, */
3357 true);/* bool run_linker */
3358 }
3359
3360 static const char * const gcc_driver_name = GCC_DRIVER_NAME;
3361
3362 void
3363 playback::context::
3364 invoke_driver (const char *ctxt_progname,
3365 const char *input_file,
3366 const char *output_file,
3367 timevar_id_t tv_id,
3368 bool shared,
3369 bool run_linker)
3370 {
3371 JIT_LOG_SCOPE (get_logger ());
3372
3373 bool embedded_driver
3374 = !get_inner_bool_option (INNER_BOOL_OPTION_USE_EXTERNAL_DRIVER);
3375
3376 /* Currently this lumps together both assembling and linking into
3377 TV_ASSEMBLE. */
3378 auto_timevar assemble_timevar (get_timer (), tv_id);
3379 auto_string_vec argvec;
3380 #define ADD_ARG(arg) argvec.safe_push (xstrdup (arg))
3381
3382 ADD_ARG (gcc_driver_name);
3383
3384 add_multilib_driver_arguments (&argvec);
3385
3386 if (shared)
3387 ADD_ARG ("-shared");
3388
3389 if (!run_linker)
3390 ADD_ARG ("-c");
3391
3392 ADD_ARG (input_file);
3393 ADD_ARG ("-o");
3394 ADD_ARG (output_file);
3395
3396 /* Don't use the linker plugin.
3397 If running with just a "make" and not a "make install", then we'd
3398 run into
3399 "fatal error: -fuse-linker-plugin, but liblto_plugin.so not found"
3400 libto_plugin is a .la at build time, with it becoming installed with
3401 ".so" suffix: i.e. it doesn't exist with a .so suffix until install
3402 time. */
3403 ADD_ARG ("-fno-use-linker-plugin");
3404
3405 #if defined (DARWIN_X86) || defined (DARWIN_PPC)
3406 /* macOS's linker defaults to treating undefined symbols as errors.
3407 If the context has any imported functions or globals they will be
3408 undefined until the .so is dynamically-linked into the process.
3409 Ensure that the driver passes in "-undefined dynamic_lookup" to the
3410 linker. */
3411 ADD_ARG ("-Wl,-undefined,dynamic_lookup");
3412 #endif
3413
3414 if (0)
3415 ADD_ARG ("-v");
3416
3417 /* Add any user-provided driver extra options. */
3418
3419 m_recording_ctxt->append_driver_options (&argvec);
3420
3421 #undef ADD_ARG
3422
3423 /* pex_one's error-handling requires pname to be non-NULL. */
3424 gcc_assert (ctxt_progname);
3425
3426 if (get_logger ())
3427 for (unsigned i = 0; i < argvec.length (); i++)
3428 get_logger ()->log ("argv[%i]: %s", i, argvec[i]);
3429
3430 if (embedded_driver)
3431 invoke_embedded_driver (&argvec);
3432 else
3433 invoke_external_driver (ctxt_progname, &argvec);
3434 }
3435
3436 void
3437 playback::context::
3438 invoke_embedded_driver (const vec <char *> *argvec)
3439 {
3440 JIT_LOG_SCOPE (get_logger ());
3441 driver d (true, /* can_finalize */
3442 false); /* debug */
3443 int result = d.main (argvec->length (),
3444 const_cast <char **> (argvec->address ()));
3445 d.finalize ();
3446 if (result)
3447 add_error (NULL, "error invoking gcc driver");
3448 }
3449
3450 void
3451 playback::context::
3452 invoke_external_driver (const char *ctxt_progname,
3453 vec <char *> *argvec)
3454 {
3455 JIT_LOG_SCOPE (get_logger ());
3456 const char *errmsg;
3457 int exit_status = 0;
3458 int err = 0;
3459
3460 /* pex argv arrays are NULL-terminated. */
3461 argvec->safe_push (NULL);
3462
3463 errmsg = pex_one (PEX_SEARCH, /* int flags, */
3464 gcc_driver_name,
3465 const_cast <char *const *> (argvec->address ()),
3466 ctxt_progname, /* const char *pname */
3467 NULL, /* const char *outname */
3468 NULL, /* const char *errname */
3469 &exit_status, /* int *status */
3470 &err); /* int *err*/
3471 if (errmsg)
3472 {
3473 add_error (NULL, "error invoking gcc driver: %s", errmsg);
3474 return;
3475 }
3476
3477 /* pex_one can return a NULL errmsg when the executable wasn't
3478 found (or doesn't exist), so trap these cases also. */
3479 if (exit_status || err)
3480 {
3481 add_error (NULL,
3482 "error invoking gcc driver: exit_status: %i err: %i",
3483 exit_status, err);
3484 add_error (NULL,
3485 "whilst attempting to run a driver named: %s",
3486 gcc_driver_name);
3487 add_error (NULL,
3488 "PATH was: %s",
3489 getenv ("PATH"));
3490 return;
3491 }
3492 }
3493
3494 /* Extract the target-specific MULTILIB_DEFAULTS to
3495 multilib_defaults_raw for use by
3496 playback::context::add_multilib_driver_arguments (). */
3497
3498 #ifndef MULTILIB_DEFAULTS
3499 #define MULTILIB_DEFAULTS { "" }
3500 #endif
3501
3502 static const char *const multilib_defaults_raw[] = MULTILIB_DEFAULTS;
3503
3504 /* Helper function for playback::context::invoke_driver ().
3505
3506 32-bit and 64-bit multilib peer builds of libgccjit.so may share
3507 a driver binary. We need to pass in options to the shared driver
3508 to get the appropriate assembler/linker options for this multilib
3509 peer. */
3510
3511 void
3512 playback::context::
3513 add_multilib_driver_arguments (vec <char *> *argvec)
3514 {
3515 JIT_LOG_SCOPE (get_logger ());
3516
3517 /* Add copies of the arguments in multilib_defaults_raw to argvec,
3518 prepending each with a "-". */
3519 for (size_t i = 0; i < ARRAY_SIZE (multilib_defaults_raw); i++)
3520 if (multilib_defaults_raw[i][0])
3521 argvec->safe_push (concat ("-", multilib_defaults_raw[i], NULL));
3522 }
3523
3524 /* Dynamically-link the built DSO file into this process, using dlopen.
3525 Wrap it up within a jit::result *, and return that.
3526 Return NULL if any errors occur, reporting them on this context. */
3527
3528 result *
3529 playback::context::
3530 dlopen_built_dso ()
3531 {
3532 JIT_LOG_SCOPE (get_logger ());
3533 auto_timevar load_timevar (get_timer (), TV_LOAD);
3534 result::handle handle = NULL;
3535 result *result_obj = NULL;
3536
3537 #ifdef _WIN32
3538 /* Clear any existing error. */
3539 SetLastError(0);
3540
3541 handle = LoadLibrary(m_tempdir->get_path_so_file ());
3542 if (GetLastError() != 0) {
3543 print_last_error();
3544 }
3545 #else
3546 const char *error = NULL;
3547 /* Clear any existing error. */
3548 dlerror ();
3549
3550 handle = dlopen (m_tempdir->get_path_so_file (),
3551 RTLD_NOW | RTLD_LOCAL);
3552 if ((error = dlerror()) != NULL) {
3553 add_error (NULL, "%s", error);
3554 }
3555 #endif
3556
3557 if (handle)
3558 {
3559 /* We've successfully dlopened the result; create a
3560 jit::result object to wrap it.
3561
3562 We're done with the tempdir for now, but if the user
3563 has requested debugging, the user's debugger might not
3564 be capable of dealing with the .so file being unlinked
3565 immediately, so keep it around until after the result
3566 is released. We do this by handing over ownership of
3567 the jit::tempdir to the result. See PR jit/64206. */
3568 tempdir *handover_tempdir;
3569 if (get_bool_option (GCC_JIT_BOOL_OPTION_DEBUGINFO))
3570 {
3571 handover_tempdir = m_tempdir;
3572 m_tempdir = NULL;
3573 /* The tempdir will eventually be cleaned up in the
3574 jit::result's dtor. */
3575 log ("GCC_JIT_BOOL_OPTION_DEBUGINFO was set:"
3576 " handing over tempdir to jit::result");
3577 }
3578 else
3579 {
3580 handover_tempdir = NULL;
3581 /* ... and retain ownership of m_tempdir so we clean it
3582 up it the playback::context's dtor. */
3583 log ("GCC_JIT_BOOL_OPTION_DEBUGINFO was not set:"
3584 " retaining ownership of tempdir");
3585 }
3586
3587 result_obj = new result (get_logger (), handle, handover_tempdir);
3588 }
3589 else
3590 result_obj = NULL;
3591
3592 return result_obj;
3593 }
3594
3595 /* Top-level hook for playing back a recording context.
3596
3597 This plays back m_recording_ctxt, and, if no errors
3598 occurred builds statement lists for and then postprocesses
3599 every function in the result. */
3600
3601 void
3602 playback::context::
3603 replay ()
3604 {
3605 JIT_LOG_SCOPE (get_logger ());
3606
3607 init_types ();
3608
3609 /* Replay the recorded events: */
3610 timevar_push (TV_JIT_REPLAY);
3611
3612 /* Ensure that builtins that could be needed during optimization
3613 get created ahead of time. */
3614 builtins_manager *bm = m_recording_ctxt->get_builtins_manager ();
3615 bm->ensure_optimization_builtins_exist ();
3616
3617 m_recording_ctxt->replay_into (this);
3618
3619 /* Clean away the temporary references from recording objects
3620 to playback objects. We have to do this now since the
3621 latter are GC-allocated, but the former don't mark these
3622 refs. Hence we must stop using them before the GC can run. */
3623 m_recording_ctxt->disassociate_from_playback ();
3624
3625 /* The builtins_manager is associated with the recording::context
3626 and might be reused for future compiles on other playback::contexts,
3627 but its m_attributes array is not GTY-labeled and hence will become
3628 nonsense if the GC runs. Purge this state. */
3629 bm->finish_playback ();
3630
3631 timevar_pop (TV_JIT_REPLAY);
3632
3633 if (!errors_occurred ())
3634 {
3635 int i;
3636 function *func;
3637 tree global;
3638 /* No GC can happen yet; process the cached source locations. */
3639 handle_locations ();
3640
3641 /* Finalize globals. See how FORTRAN 95 does it in gfc_be_parse_file()
3642 for a simple reference. */
3643 FOR_EACH_VEC_ELT (m_globals, i, global)
3644 rest_of_decl_compilation (global, true, true);
3645
3646 wrapup_global_declarations (m_globals.address(), m_globals.length());
3647
3648 /* We've now created tree nodes for the stmts in the various blocks
3649 in each function, but we haven't built each function's single stmt
3650 list yet. Do so now. */
3651 FOR_EACH_VEC_ELT (m_functions, i, func)
3652 func->build_stmt_list ();
3653
3654 /* No GC can have happened yet. */
3655
3656 /* Postprocess the functions. This could trigger GC. */
3657 FOR_EACH_VEC_ELT (m_functions, i, func)
3658 {
3659 gcc_assert (func);
3660 func->postprocess ();
3661 }
3662 }
3663 }
3664
3665 /* Dump the generated .s file to stderr. */
3666
3667 void
3668 playback::context::
3669 dump_generated_code ()
3670 {
3671 JIT_LOG_SCOPE (get_logger ());
3672 char buf[4096];
3673 size_t sz;
3674 FILE *f_in = fopen (get_path_s_file (), "r");
3675 if (!f_in)
3676 return;
3677
3678 while ( (sz = fread (buf, 1, sizeof (buf), f_in)) )
3679 fwrite (buf, 1, sz, stderr);
3680
3681 fclose (f_in);
3682 }
3683
3684 /* Get the supposed path of the notional "fake.c" file within the
3685 tempdir. This file doesn't exist, but the rest of the compiler
3686 needs a name. */
3687
3688 const char *
3689 playback::context::
3690 get_path_c_file () const
3691 {
3692 return m_tempdir->get_path_c_file ();
3693 }
3694
3695 /* Get the path of the assembler output file "fake.s" file within the
3696 tempdir. */
3697
3698 const char *
3699 playback::context::
3700 get_path_s_file () const
3701 {
3702 return m_tempdir->get_path_s_file ();
3703 }
3704
3705 /* Get the path of the DSO object file "fake.so" file within the
3706 tempdir. */
3707
3708 const char *
3709 playback::context::
3710 get_path_so_file () const
3711 {
3712 return m_tempdir->get_path_so_file ();
3713 }
3714
3715 /* qsort comparator for comparing pairs of playback::source_line *,
3716 ordering them by line number. */
3717
3718 static int
3719 line_comparator (const void *lhs, const void *rhs)
3720 {
3721 const playback::source_line *line_lhs = \
3722 *static_cast<const playback::source_line * const*> (lhs);
3723 const playback::source_line *line_rhs = \
3724 *static_cast<const playback::source_line * const*> (rhs);
3725 return line_lhs->get_line_num () - line_rhs->get_line_num ();
3726 }
3727
3728 /* qsort comparator for comparing pairs of playback::location *,
3729 ordering them by column number. */
3730
3731 static int
3732 location_comparator (const void *lhs, const void *rhs)
3733 {
3734 const playback::location *loc_lhs = \
3735 *static_cast<const playback::location * const *> (lhs);
3736 const playback::location *loc_rhs = \
3737 *static_cast<const playback::location * const *> (rhs);
3738 return loc_lhs->get_column_num () - loc_rhs->get_column_num ();
3739 }
3740
3741 /* Initialize the NAME_TYPE of the primitive types as well as some
3742 others. */
3743 void
3744 playback::context::
3745 init_types ()
3746 {
3747 /* See lto_init () in lto-lang.cc or void visit (TypeBasic *t) in D's types.cc
3748 for reference. If TYPE_NAME is not set, debug info will not contain types */
3749 #define NAME_TYPE(t,n) \
3750 if (t) \
3751 TYPE_NAME (t) = build_decl (UNKNOWN_LOCATION, TYPE_DECL, \
3752 get_identifier (n), t)
3753
3754 NAME_TYPE (integer_type_node, "int");
3755 NAME_TYPE (char_type_node, "char");
3756 NAME_TYPE (long_integer_type_node, "long int");
3757 NAME_TYPE (unsigned_type_node, "unsigned int");
3758 NAME_TYPE (long_unsigned_type_node, "long unsigned int");
3759 NAME_TYPE (long_long_integer_type_node, "long long int");
3760 NAME_TYPE (long_long_unsigned_type_node, "long long unsigned int");
3761 NAME_TYPE (short_integer_type_node, "short int");
3762 NAME_TYPE (short_unsigned_type_node, "short unsigned int");
3763 if (signed_char_type_node != char_type_node)
3764 NAME_TYPE (signed_char_type_node, "signed char");
3765 if (unsigned_char_type_node != char_type_node)
3766 NAME_TYPE (unsigned_char_type_node, "unsigned char");
3767 NAME_TYPE (float_type_node, "float");
3768 NAME_TYPE (double_type_node, "double");
3769 NAME_TYPE (long_double_type_node, "long double");
3770 NAME_TYPE (void_type_node, "void");
3771 NAME_TYPE (boolean_type_node, "bool");
3772 NAME_TYPE (complex_float_type_node, "complex float");
3773 NAME_TYPE (complex_double_type_node, "complex double");
3774 NAME_TYPE (complex_long_double_type_node, "complex long double");
3775
3776 m_const_char_ptr = build_pointer_type(
3777 build_qualified_type (char_type_node, TYPE_QUAL_CONST));
3778
3779 NAME_TYPE (m_const_char_ptr, "char");
3780 NAME_TYPE (size_type_node, "size_t");
3781 NAME_TYPE (fileptr_type_node, "FILE");
3782 #undef NAME_TYPE
3783 }
3784
3785 /* Our API allows locations to be created in arbitrary orders, but the
3786 linemap API requires locations to be created in ascending order
3787 as if we were tokenizing files.
3788
3789 This hook sorts all of the locations that have been created, and
3790 calls into the linemap API, creating linemap entries in sorted order
3791 for our locations. */
3792
3793 void
3794 playback::context::
3795 handle_locations ()
3796 {
3797 /* Create the source code locations, following the ordering rules
3798 imposed by the linemap API.
3799
3800 line_table is a global. */
3801 JIT_LOG_SCOPE (get_logger ());
3802 int i;
3803 source_file *file;
3804
3805 FOR_EACH_VEC_ELT (m_source_files, i, file)
3806 {
3807 linemap_add (line_table, LC_ENTER, false, file->get_filename (), 0);
3808
3809 /* Sort lines by ascending line numbers. */
3810 file->m_source_lines.qsort (&line_comparator);
3811
3812 int j;
3813 source_line *line;
3814 FOR_EACH_VEC_ELT (file->m_source_lines, j, line)
3815 {
3816 int k;
3817 location *loc;
3818
3819 /* Sort locations in line by ascending column numbers. */
3820 line->m_locations.qsort (&location_comparator);
3821
3822 /* Determine maximum column within this line. */
3823 gcc_assert (line->m_locations.length () > 0);
3824 location *final_column =
3825 line->m_locations[line->m_locations.length () - 1];
3826 int max_col = final_column->get_column_num ();
3827
3828 linemap_line_start (line_table, line->get_line_num (), max_col);
3829 FOR_EACH_VEC_ELT (line->m_locations, k, loc)
3830 {
3831 loc->m_srcloc = \
3832 linemap_position_for_column (line_table, loc->get_column_num ());
3833 }
3834 }
3835
3836 linemap_add (line_table, LC_LEAVE, false, NULL, 0);
3837 }
3838
3839 /* line_table should now be populated; every playback::location should
3840 now have an m_srcloc. */
3841
3842 /* Now assign them to tree nodes as appropriate. */
3843 std::pair<tree, location *> *cached_location;
3844
3845 FOR_EACH_VEC_ELT (m_cached_locations, i, cached_location)
3846 {
3847 tree t = cached_location->first;
3848 location_t srcloc = cached_location->second->m_srcloc;
3849
3850 /* This covers expressions: */
3851 if (CAN_HAVE_LOCATION_P (t))
3852 SET_EXPR_LOCATION (t, srcloc);
3853 else if (CODE_CONTAINS_STRUCT(TREE_CODE(t), TS_DECL_MINIMAL))
3854 DECL_SOURCE_LOCATION (t) = srcloc;
3855 else
3856 {
3857 /* Don't know how to set location on this node. */
3858 }
3859 }
3860 }
3861
3862 /* We handle errors on a playback::context by adding them to the
3863 corresponding recording::context. */
3864
3865 void
3866 playback::context::
3867 add_error (location *loc, const char *fmt, ...)
3868 {
3869 va_list ap;
3870 va_start (ap, fmt);
3871 m_recording_ctxt->add_error_va (loc ? loc->get_recording_loc () : NULL,
3872 fmt, ap);
3873 va_end (ap);
3874 }
3875
3876 /* We handle errors on a playback::context by adding them to the
3877 corresponding recording::context. */
3878
3879 void
3880 playback::context::
3881 add_error_va (location *loc, const char *fmt, va_list ap)
3882 {
3883 m_recording_ctxt->add_error_va (loc ? loc->get_recording_loc () : NULL,
3884 fmt, ap);
3885 }
3886
3887 /* Report a diagnostic up to the jit context as an error,
3888 so that the compilation is treated as a failure.
3889 For now, any kind of diagnostic is treated as an error by the jit
3890 API. */
3891
3892 void
3893 playback::context::
3894 add_diagnostic (const char *text,
3895 const diagnostic_info &diagnostic)
3896 {
3897 /* Get location information (if any) from the diagnostic.
3898 The recording::context::add_error[_va] methods require a
3899 recording::location. We can't lookup the playback::location
3900 from the file/line/column since any playback location instances
3901 may have been garbage-collected away by now, so instead we create
3902 another recording::location directly. */
3903 location_t gcc_loc = diagnostic_location (&diagnostic);
3904 recording::location *rec_loc = NULL;
3905 if (gcc_loc)
3906 {
3907 expanded_location exploc = expand_location (gcc_loc);
3908 if (exploc.file)
3909 rec_loc = m_recording_ctxt->new_location (exploc.file,
3910 exploc.line,
3911 exploc.column,
3912 false);
3913 }
3914
3915 m_recording_ctxt->add_error (rec_loc, "%s", text);
3916 }
3917
3918 /* Dealing with the linemap API. */
3919
3920 /* Construct a playback::location for a recording::location, if it
3921 doesn't exist already. */
3922
3923 playback::location *
3924 playback::context::
3925 new_location (recording::location *rloc,
3926 const char *filename,
3927 int line,
3928 int column)
3929 {
3930 /* Get the source_file for filename, creating if necessary. */
3931 source_file *src_file = get_source_file (filename);
3932 /* Likewise for the line within the file. */
3933 source_line *src_line = src_file->get_source_line (line);
3934 /* Likewise for the column within the line. */
3935 location *loc = src_line->get_location (rloc, column);
3936 return loc;
3937 }
3938
3939 /* Deferred setting of the location for a given tree, by adding the
3940 (tree, playback::location) pair to a list of deferred associations.
3941 We will actually set the location on the tree later on once
3942 the location_t for the playback::location exists. */
3943
3944 void
3945 playback::context::
3946 set_tree_location (tree t, location *loc)
3947 {
3948 gcc_assert (loc);
3949 m_cached_locations.safe_push (std::make_pair (t, loc));
3950 }
3951
3952
3953 /* Construct a playback::source_file for the given source
3954 filename, if it doesn't exist already. */
3955
3956 playback::source_file *
3957 playback::context::
3958 get_source_file (const char *filename)
3959 {
3960 /* Locate the file.
3961 For simplicitly, this is currently a linear search.
3962 Replace with a hash if this shows up in the profile. */
3963 int i;
3964 source_file *file;
3965 tree ident_filename = get_identifier (filename);
3966
3967 FOR_EACH_VEC_ELT (m_source_files, i, file)
3968 if (file->filename_as_tree () == ident_filename)
3969 return file;
3970
3971 /* Not found. */
3972 file = new source_file (ident_filename);
3973 m_source_files.safe_push (file);
3974 return file;
3975 }
3976
3977 /* Constructor for gcc::jit::playback::source_file. */
3978
3979 playback::source_file::source_file (tree filename) :
3980 m_source_lines (),
3981 m_filename (filename)
3982 {
3983 }
3984
3985 /* Don't leak vec's internal buffer (in non-GC heap) when we are
3986 GC-ed. */
3987
3988 void
3989 playback::source_file::finalizer ()
3990 {
3991 m_source_lines.release ();
3992 }
3993
3994 /* Construct a playback::source_line for the given line
3995 within this source file, if one doesn't exist already. */
3996
3997 playback::source_line *
3998 playback::source_file::
3999 get_source_line (int line_num)
4000 {
4001 /* Locate the line.
4002 For simplicitly, this is currently a linear search.
4003 Replace with a hash if this shows up in the profile. */
4004 int i;
4005 source_line *line;
4006
4007 FOR_EACH_VEC_ELT (m_source_lines, i, line)
4008 if (line->get_line_num () == line_num)
4009 return line;
4010
4011 /* Not found. */
4012 line = new source_line (this, line_num);
4013 m_source_lines.safe_push (line);
4014 return line;
4015 }
4016
4017 /* Constructor for gcc::jit::playback::source_line. */
4018
4019 playback::source_line::source_line (source_file *file, int line_num) :
4020 m_locations (),
4021 m_source_file (file),
4022 m_line_num (line_num)
4023 {
4024 }
4025
4026 /* Don't leak vec's internal buffer (in non-GC heap) when we are
4027 GC-ed. */
4028
4029 void
4030 playback::source_line::finalizer ()
4031 {
4032 m_locations.release ();
4033 }
4034
4035 /* Construct a playback::location for the given column
4036 within this line of a specific source file, if one doesn't exist
4037 already. */
4038
4039 playback::location *
4040 playback::source_line::
4041 get_location (recording::location *rloc, int column_num)
4042 {
4043 int i;
4044 location *loc;
4045
4046 /* Another linear search that probably should be a hash table. */
4047 FOR_EACH_VEC_ELT (m_locations, i, loc)
4048 if (loc->get_column_num () == column_num)
4049 return loc;
4050
4051 /* Not found. */
4052 loc = new location (rloc, this, column_num);
4053 m_locations.safe_push (loc);
4054 return loc;
4055 }
4056
4057 /* Constructor for gcc::jit::playback::location. */
4058
4059 playback::location::location (recording::location *loc,
4060 source_line *line,
4061 int column_num) :
4062 m_srcloc (UNKNOWN_LOCATION),
4063 m_recording_loc (loc),
4064 m_line (line),
4065 m_column_num(column_num)
4066 {
4067 }
4068
4069 /* The active gcc::jit::playback::context instance. This is a singleton,
4070 guarded by jit_mutex. */
4071
4072 playback::context *active_playback_ctxt;
4073
4074 } // namespace gcc::jit
4075
4076 } // namespace gcc