Ruby 4.1.0dev (2026-12-01 revision afadaed84ccb23517ffb57fd15f116f2e4a85917)
compile.c (afadaed84ccb23517ffb57fd15f116f2e4a85917)
1/**********************************************************************
2
3 compile.c - ruby node tree -> VM instruction sequence
4
5 $Author$
6 created at: 04/01/01 03:42:15 JST
7
8 Copyright (C) 2004-2007 Koichi Sasada
9
10**********************************************************************/
11
12#include "ruby/internal/config.h"
13#include <math.h>
14
15#ifdef HAVE_DLADDR
16# include <dlfcn.h>
17#endif
18
19#include "encindex.h"
20#include "id_table.h"
21#include "internal.h"
22#include "internal/array.h"
23#include "internal/compile.h"
24#include "internal/coverage.h"
25#include "internal/complex.h"
26#include "internal/encoding.h"
27#include "internal/error.h"
28#include "internal/gc.h"
29#include "internal/hash.h"
30#include "internal/io.h"
31#include "internal/numeric.h"
32#include "internal/object.h"
33#include "internal/rational.h"
34#include "internal/re.h"
35#include "internal/ruby_parser.h"
36#include "internal/st.h"
37#include "internal/symbol.h"
38#include "internal/thread.h"
39#include "internal/variable.h"
40#include "iseq.h"
41#include "ruby/ractor.h"
42#include "ruby/re.h"
43#include "ruby/util.h"
44#include "vm_core.h"
45#include "vm_callinfo.h"
46#include "vm_debug.h"
47#include "yjit.h"
48
49#include "builtin.h"
50#include "insns.inc"
51#include "insns_info.inc"
52
53#define FIXNUM_INC(n, i) ((n)+(INT2FIX(i)&~FIXNUM_FLAG))
54
55typedef struct iseq_link_element {
56 enum {
57 ISEQ_ELEMENT_ANCHOR,
58 ISEQ_ELEMENT_LABEL,
59 ISEQ_ELEMENT_INSN,
60 ISEQ_ELEMENT_ADJUST,
61 ISEQ_ELEMENT_TRACE,
62 } type;
63 struct iseq_link_element *next;
64 struct iseq_link_element *prev;
65} LINK_ELEMENT;
66
67typedef struct iseq_link_anchor {
68 LINK_ELEMENT anchor;
69 LINK_ELEMENT *last;
70} LINK_ANCHOR;
71
72typedef enum {
73 LABEL_RESCUE_NONE,
74 LABEL_RESCUE_BEG,
75 LABEL_RESCUE_END,
76 LABEL_RESCUE_TYPE_MAX
77} LABEL_RESCUE_TYPE;
78
79typedef struct iseq_label_data {
80 LINK_ELEMENT link;
81 int label_no;
82 int position;
83 int sc_state;
84 int sp;
85 int refcnt;
86 unsigned int set: 1;
87 unsigned int rescued: 2;
88 unsigned int unremovable: 1;
89} LABEL;
90
91typedef struct iseq_insn_data {
92 LINK_ELEMENT link;
93 enum ruby_vminsn_type insn_id;
94 int operand_size;
95 int sc_state;
96 VALUE *operands;
97 struct {
98 int line_no;
99 int node_id;
100 rb_event_flag_t events;
101 } insn_info;
102} INSN;
103
104typedef struct iseq_adjust_data {
105 LINK_ELEMENT link;
106 LABEL *label;
107 int line_no;
108} ADJUST;
109
110typedef struct iseq_trace_data {
111 LINK_ELEMENT link;
112 rb_event_flag_t event;
113 long data;
114} TRACE;
115
117 LABEL *begin;
118 LABEL *end;
119 struct ensure_range *next;
120};
121
123 const void *ensure_node;
125 struct ensure_range *erange;
126};
127
128const ID rb_iseq_shared_exc_local_tbl[] = {idERROR_INFO};
129
142
143#ifndef CPDEBUG
144#define CPDEBUG 0
145#endif
146
147#if CPDEBUG >= 0
148#define compile_debug CPDEBUG
149#else
150#define compile_debug ISEQ_COMPILE_DATA(iseq)->option->debug_level
151#endif
152
153#if CPDEBUG
154
155#define compile_debug_print_indent(level) \
156 ruby_debug_print_indent((level), compile_debug, gl_node_level * 2)
157
158#define debugp(header, value) (void) \
159 (compile_debug_print_indent(1) && \
160 ruby_debug_print_value(1, compile_debug, (header), (value)))
161
162#define debugi(header, id) (void) \
163 (compile_debug_print_indent(1) && \
164 ruby_debug_print_id(1, compile_debug, (header), (id)))
165
166#define debugp_param(header, value) (void) \
167 (compile_debug_print_indent(1) && \
168 ruby_debug_print_value(1, compile_debug, (header), (value)))
169
170#define debugp_verbose(header, value) (void) \
171 (compile_debug_print_indent(2) && \
172 ruby_debug_print_value(2, compile_debug, (header), (value)))
173
174#define debugp_verbose_node(header, value) (void) \
175 (compile_debug_print_indent(10) && \
176 ruby_debug_print_value(10, compile_debug, (header), (value)))
177
178#define debug_node_start(node) ((void) \
179 (compile_debug_print_indent(1) && \
180 (ruby_debug_print_node(1, CPDEBUG, "", (const NODE *)(node)), gl_node_level)), \
181 gl_node_level++)
182
183#define debug_node_end() gl_node_level --
184
185#else
186
187#define debugi(header, id) ((void)0)
188#define debugp(header, value) ((void)0)
189#define debugp_verbose(header, value) ((void)0)
190#define debugp_verbose_node(header, value) ((void)0)
191#define debugp_param(header, value) ((void)0)
192#define debug_node_start(node) ((void)0)
193#define debug_node_end() ((void)0)
194#endif
195
196#if CPDEBUG > 1 || CPDEBUG < 0
197#undef printf
198#define printf ruby_debug_printf
199#define debugs if (compile_debug_print_indent(1)) ruby_debug_printf
200#define debug_compile(msg, v) ((void)(compile_debug_print_indent(1) && fputs((msg), stderr)), (v))
201#else
202#define debugs if(0)printf
203#define debug_compile(msg, v) (v)
204#endif
205
206#define LVAR_ERRINFO (1)
207
208/* create new label */
209#define NEW_LABEL(l) new_label_body(iseq, (l))
210#define LABEL_FORMAT "<L%03d>"
211
212#define NEW_ISEQ(node, name, type, line_no) \
213 new_child_iseq(iseq, (node), rb_fstring(name), 0, (type), (line_no))
214
215#define NEW_CHILD_ISEQ(node, name, type, line_no) \
216 new_child_iseq(iseq, (node), rb_fstring(name), iseq, (type), (line_no))
217
218#define NEW_CHILD_ISEQ_WITH_CALLBACK(callback_func, name, type, line_no) \
219 new_child_iseq_with_callback(iseq, (callback_func), (name), iseq, (type), (line_no))
220
221/* add instructions */
222#define ADD_SEQ(seq1, seq2) \
223 APPEND_LIST((seq1), (seq2))
224
225/* add an instruction */
226#define ADD_INSN(seq, line_node, insn) \
227 ADD_ELEM((seq), (LINK_ELEMENT *) new_insn_body(iseq, nd_line(line_node), nd_node_id(line_node), BIN(insn), 0))
228
229/* add an instruction with the given line number and node id */
230#define ADD_SYNTHETIC_INSN(seq, line_no, node_id, insn) \
231 ADD_ELEM((seq), (LINK_ELEMENT *) new_insn_body(iseq, (line_no), (node_id), BIN(insn), 0))
232
233/* insert an instruction before next */
234#define INSERT_BEFORE_INSN(next, line_no, node_id, insn) \
235 ELEM_INSERT_PREV(&(next)->link, (LINK_ELEMENT *) new_insn_body(iseq, line_no, node_id, BIN(insn), 0))
236
237/* insert an instruction after prev */
238#define INSERT_AFTER_INSN(prev, line_no, node_id, insn) \
239 ELEM_INSERT_NEXT(&(prev)->link, (LINK_ELEMENT *) new_insn_body(iseq, line_no, node_id, BIN(insn), 0))
240
241/* add an instruction with some operands (1, 2, 3, 5) */
242#define ADD_INSN1(seq, line_node, insn, op1) \
243 ADD_ELEM((seq), (LINK_ELEMENT *) \
244 new_insn_body(iseq, nd_line(line_node), nd_node_id(line_node), BIN(insn), 1, (VALUE)(op1)))
245
246/* insert an instruction with some operands (1, 2, 3, 5) before next */
247#define INSERT_BEFORE_INSN1(next, line_no, node_id, insn, op1) \
248 ELEM_INSERT_PREV(&(next)->link, (LINK_ELEMENT *) \
249 new_insn_body(iseq, line_no, node_id, BIN(insn), 1, (VALUE)(op1)))
250
251/* insert an instruction with some operands (1, 2, 3, 5) after prev */
252#define INSERT_AFTER_INSN1(prev, line_no, node_id, insn, op1) \
253 ELEM_INSERT_NEXT(&(prev)->link, (LINK_ELEMENT *) \
254 new_insn_body(iseq, line_no, node_id, BIN(insn), 1, (VALUE)(op1)))
255
256#define LABEL_REF(label) ((label)->refcnt++)
257
258/* add an instruction with label operand (alias of ADD_INSN1) */
259#define ADD_INSNL(seq, line_node, insn, label) (ADD_INSN1(seq, line_node, insn, label), LABEL_REF(label))
260
261#define ADD_INSN2(seq, line_node, insn, op1, op2) \
262 ADD_ELEM((seq), (LINK_ELEMENT *) \
263 new_insn_body(iseq, nd_line(line_node), nd_node_id(line_node), BIN(insn), 2, (VALUE)(op1), (VALUE)(op2)))
264
265#define ADD_INSN3(seq, line_node, insn, op1, op2, op3) \
266 ADD_ELEM((seq), (LINK_ELEMENT *) \
267 new_insn_body(iseq, nd_line(line_node), nd_node_id(line_node), BIN(insn), 3, (VALUE)(op1), (VALUE)(op2), (VALUE)(op3)))
268
269/* Specific Insn factory */
270#define ADD_SEND(seq, line_node, id, argc) \
271 ADD_SEND_R((seq), (line_node), (id), (argc), NULL, (VALUE)INT2FIX(0), NULL)
272
273#define ADD_SEND_WITH_FLAG(seq, line_node, id, argc, flag) \
274 ADD_SEND_R((seq), (line_node), (id), (argc), NULL, (VALUE)(flag), NULL)
275
276#define ADD_SEND_WITH_BLOCK(seq, line_node, id, argc, block) \
277 ADD_SEND_R((seq), (line_node), (id), (argc), (block), (VALUE)INT2FIX(0), NULL)
278
279#define ADD_CALL_RECEIVER(seq, line_node) \
280 ADD_INSN((seq), (line_node), putself)
281
282#define ADD_CALL(seq, line_node, id, argc) \
283 ADD_SEND_R((seq), (line_node), (id), (argc), NULL, (VALUE)INT2FIX(VM_CALL_FCALL), NULL)
284
285#define ADD_CALL_WITH_BLOCK(seq, line_node, id, argc, block) \
286 ADD_SEND_R((seq), (line_node), (id), (argc), (block), (VALUE)INT2FIX(VM_CALL_FCALL), NULL)
287
288#define ADD_SEND_R(seq, line_node, id, argc, block, flag, keywords) \
289 ADD_ELEM((seq), (LINK_ELEMENT *) new_insn_send(iseq, nd_line(line_node), nd_node_id(line_node), (id), (VALUE)(argc), (block), (VALUE)(flag), (keywords)))
290
291#define ADD_TRACE(seq, event) \
292 ADD_ELEM((seq), (LINK_ELEMENT *)new_trace_body(iseq, (event), 0))
293#define ADD_TRACE_WITH_DATA(seq, event, data) \
294 ADD_ELEM((seq), (LINK_ELEMENT *)new_trace_body(iseq, (event), (data)))
295
296static void iseq_add_getlocal(rb_iseq_t *iseq, LINK_ANCHOR *const seq, const NODE *const line_node, int idx, int level);
297static void iseq_add_setlocal(rb_iseq_t *iseq, LINK_ANCHOR *const seq, const NODE *const line_node, int idx, int level);
298
299#define ADD_GETLOCAL(seq, line_node, idx, level) iseq_add_getlocal(iseq, (seq), (line_node), (idx), (level))
300#define ADD_SETLOCAL(seq, line_node, idx, level) iseq_add_setlocal(iseq, (seq), (line_node), (idx), (level))
301
302/* add label */
303#define ADD_LABEL(seq, label) \
304 ADD_ELEM((seq), (LINK_ELEMENT *) (label))
305
306#define APPEND_LABEL(seq, before, label) \
307 APPEND_ELEM((seq), (before), (LINK_ELEMENT *) (label))
308
309#define ADD_ADJUST(seq, line_node, label) \
310 ADD_ELEM((seq), (LINK_ELEMENT *) new_adjust_body(iseq, (label), nd_line(line_node)))
311
312#define ADD_ADJUST_RESTORE(seq, label) \
313 ADD_ELEM((seq), (LINK_ELEMENT *) new_adjust_body(iseq, (label), -1))
314
315#define LABEL_UNREMOVABLE(label) \
316 ((label) ? (LABEL_REF(label), (label)->unremovable=1) : 0)
317#define ADD_CATCH_ENTRY(type, ls, le, iseqv, lc) do { \
318 VALUE _e = rb_ary_new3(5, (type), \
319 (VALUE)(ls) | 1, (VALUE)(le) | 1, \
320 (VALUE)(iseqv), (VALUE)(lc) | 1); \
321 LABEL_UNREMOVABLE(ls); \
322 LABEL_REF(le); \
323 LABEL_REF(lc); \
324 if (NIL_P(ISEQ_COMPILE_DATA(iseq)->catch_table_ary)) \
325 RB_OBJ_WRITE(iseq, &ISEQ_COMPILE_DATA(iseq)->catch_table_ary, rb_ary_hidden_new(3)); \
326 rb_ary_push(ISEQ_COMPILE_DATA(iseq)->catch_table_ary, freeze_hide_obj(_e)); \
327} while (0)
328
329/* compile node */
330#define COMPILE(anchor, desc, node) \
331 (debug_compile("== " desc "\n", \
332 iseq_compile_each(iseq, (anchor), (node), 0)))
333
334/* compile node, this node's value will be popped */
335#define COMPILE_POPPED(anchor, desc, node) \
336 (debug_compile("== " desc "\n", \
337 iseq_compile_each(iseq, (anchor), (node), 1)))
338
339/* compile node, which is popped when 'popped' is true */
340#define COMPILE_(anchor, desc, node, popped) \
341 (debug_compile("== " desc "\n", \
342 iseq_compile_each(iseq, (anchor), (node), (popped))))
343
344#define COMPILE_RECV(anchor, desc, node, recv) \
345 (private_recv_p(node) ? \
346 (ADD_INSN(anchor, node, putself), VM_CALL_FCALL) : \
347 COMPILE(anchor, desc, recv) ? 0 : -1)
348
349#define OPERAND_AT(insn, idx) \
350 (((INSN*)(insn))->operands[(idx)])
351
352#define INSN_OF(insn) \
353 (((INSN*)(insn))->insn_id)
354
355#define IS_INSN(link) ((link)->type == ISEQ_ELEMENT_INSN)
356#define IS_LABEL(link) ((link)->type == ISEQ_ELEMENT_LABEL)
357#define IS_ADJUST(link) ((link)->type == ISEQ_ELEMENT_ADJUST)
358#define IS_TRACE(link) ((link)->type == ISEQ_ELEMENT_TRACE)
359#define IS_INSN_ID(iobj, insn) (INSN_OF(iobj) == BIN(insn))
360#define IS_NEXT_INSN_ID(link, insn) \
361 ((link)->next && IS_INSN((link)->next) && IS_INSN_ID((link)->next, insn))
362
363static inline bool
364IS_INDEPENDENT_INSN(LINK_ELEMENT *link)
365{
366 if (!IS_INSN(link)) {
367 return false;
368 }
369
370 enum ruby_vminsn_type type = INSN_OF(link);
371
372 return (
373 type == BIN(putobject) ||
374 type == BIN(putspecialobject) ||
375 type == BIN(putnil) ||
376 type == BIN(putself) ||
377 type == BIN(duphash) ||
378 type == BIN(getinstancevariable) ||
379 type == BIN(getlocal) ||
380 type == BIN(getlocal_WC_0) ||
381 type == BIN(getlocal_WC_1) ||
382 type == BIN(putobject_INT2FIX_0_) ||
383 type == BIN(putobject_INT2FIX_1_) ||
384 type == BIN(opt_getconstant_path)
385 );
386}
387
388/* error */
389#if CPDEBUG > 0
391#endif
392RBIMPL_ATTR_FORMAT(RBIMPL_PRINTF_FORMAT, 3, 4)
393static void
394append_compile_error(const rb_iseq_t *iseq, int line, const char *fmt, ...)
395{
396 VALUE err_info = ISEQ_COMPILE_DATA(iseq)->err_info;
397 VALUE file = rb_iseq_path(iseq);
398 VALUE err = err_info == Qtrue ? Qfalse : err_info;
399 va_list args;
400
401 va_start(args, fmt);
402 err = rb_syntax_error_append(err, file, line, -1, NULL, fmt, args);
403 va_end(args);
404 if (NIL_P(err_info)) {
405 RB_OBJ_WRITE(iseq, &ISEQ_COMPILE_DATA(iseq)->err_info, err);
406 rb_set_errinfo(err);
407 }
408 else if (!err_info) {
409 RB_OBJ_WRITE(iseq, &ISEQ_COMPILE_DATA(iseq)->err_info, Qtrue);
410 }
411 if (compile_debug) {
412 if (SPECIAL_CONST_P(err)) err = rb_eSyntaxError;
413 rb_exc_fatal(err);
414 }
415}
416
417#if 0
418static void
419compile_bug(rb_iseq_t *iseq, int line, const char *fmt, ...)
420{
421 va_list args;
422 va_start(args, fmt);
423 rb_report_bug_valist(rb_iseq_path(iseq), line, fmt, args);
424 va_end(args);
425 abort();
426}
427#endif
428
429#define COMPILE_ERROR append_compile_error
430
431#define ERROR_ARGS_AT(n) iseq, nd_line(n),
432#define ERROR_ARGS ERROR_ARGS_AT(node)
433
434#define EXPECT_NODE(prefix, node, ndtype, errval) \
435do { \
436 const NODE *error_node = (node); \
437 enum node_type error_type = nd_type(error_node); \
438 if (error_type != (ndtype)) { \
439 COMPILE_ERROR(ERROR_ARGS_AT(error_node) \
440 prefix ": " #ndtype " is expected, but %s", \
441 ruby_node_name(error_type)); \
442 return errval; \
443 } \
444} while (0)
445
446#define EXPECT_NODE_NONULL(prefix, parent, ndtype, errval) \
447do { \
448 COMPILE_ERROR(ERROR_ARGS_AT(parent) \
449 prefix ": must be " #ndtype ", but 0"); \
450 return errval; \
451} while (0)
452
453#define UNKNOWN_NODE(prefix, node, errval) \
454do { \
455 const NODE *error_node = (node); \
456 COMPILE_ERROR(ERROR_ARGS_AT(error_node) prefix ": unknown node (%s)", \
457 ruby_node_name(nd_type(error_node))); \
458 return errval; \
459} while (0)
460
461#define COMPILE_OK 1
462#define COMPILE_NG 0
463
464#define CHECK(sub) if (!(sub)) {BEFORE_RETURN;return COMPILE_NG;}
465#define NO_CHECK(sub) (void)(sub)
466#define BEFORE_RETURN
467
468#define DECL_ANCHOR(name) \
469 LINK_ANCHOR name[1] = {{{ISEQ_ELEMENT_ANCHOR,},&name[0].anchor}}
470#define INIT_ANCHOR(name) \
471 ((name->last = &name->anchor)->next = NULL) /* re-initialize */
472
473static inline VALUE
474freeze_hide_obj(VALUE obj)
475{
476 OBJ_FREEZE(obj);
477 RBASIC_CLEAR_CLASS(obj);
478 return obj;
479}
480
481#include "optinsn.inc"
482#if OPT_INSTRUCTIONS_UNIFICATION
483#include "optunifs.inc"
484#endif
485
486/* for debug */
487#if CPDEBUG < 0
488#define ISEQ_ARG iseq,
489#define ISEQ_ARG_DECLARE rb_iseq_t *iseq,
490#else
491#define ISEQ_ARG
492#define ISEQ_ARG_DECLARE
493#endif
494
495#if CPDEBUG
496#define gl_node_level ISEQ_COMPILE_DATA(iseq)->node_level
497#endif
498
499static void dump_disasm_list_with_cursor(const LINK_ELEMENT *link, const LINK_ELEMENT *curr, const LABEL *dest);
500static void dump_disasm_list(const LINK_ELEMENT *elem);
501
502static int insn_data_length(INSN *iobj);
503static int calc_sp_depth(int depth, INSN *iobj);
504
505static INSN *new_insn_body(rb_iseq_t *iseq, int line_no, int node_id, enum ruby_vminsn_type insn_id, int argc, ...);
506static LABEL *new_label_body(rb_iseq_t *iseq, long line);
507static ADJUST *new_adjust_body(rb_iseq_t *iseq, LABEL *label, int line);
508static TRACE *new_trace_body(rb_iseq_t *iseq, rb_event_flag_t event, long data);
509
510
511static int iseq_compile_each(rb_iseq_t *iseq, LINK_ANCHOR *anchor, const NODE *n, int);
512static int iseq_setup(rb_iseq_t *iseq, LINK_ANCHOR *const anchor);
513static int iseq_setup_insn(rb_iseq_t *iseq, LINK_ANCHOR *const anchor);
514static int iseq_optimize(rb_iseq_t *iseq, LINK_ANCHOR *const anchor);
515static int iseq_insns_unification(rb_iseq_t *iseq, LINK_ANCHOR *const anchor);
516
517static int iseq_set_local_table(rb_iseq_t *iseq, const rb_ast_id_table_t *tbl, const NODE *const node_args);
518static int iseq_set_exception_local_table(rb_iseq_t *iseq);
519static int iseq_set_arguments(rb_iseq_t *iseq, LINK_ANCHOR *const anchor, const NODE *const node);
520
521static int iseq_set_sequence(rb_iseq_t *iseq, LINK_ANCHOR *const anchor);
522static int iseq_set_exception_table(rb_iseq_t *iseq);
523static int iseq_set_optargs_table(rb_iseq_t *iseq);
524static int iseq_set_parameters_lvar_state(const rb_iseq_t *iseq);
525
526static int compile_defined_expr(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, VALUE needstr, bool ignore);
527static int compile_hash(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *node, int method_call_keywords, int popped);
528
529/*
530 * To make Array to LinkedList, use link_anchor
531 */
532
533static void
534verify_list(ISEQ_ARG_DECLARE const char *info, LINK_ANCHOR *const anchor)
535{
536#if CPDEBUG
537 int flag = 0;
538 LINK_ELEMENT *list, *plist;
539
540 if (!compile_debug) return;
541
542 list = anchor->anchor.next;
543 plist = &anchor->anchor;
544 while (list) {
545 if (plist != list->prev) {
546 flag += 1;
547 }
548 plist = list;
549 list = list->next;
550 }
551
552 if (anchor->last != plist && anchor->last != 0) {
553 flag |= 0x70000;
554 }
555
556 if (flag != 0) {
557 rb_bug("list verify error: %08x (%s)", flag, info);
558 }
559#endif
560}
561#if CPDEBUG < 0
562#define verify_list(info, anchor) verify_list(iseq, (info), (anchor))
563#endif
564
565static void
566verify_call_cache(rb_iseq_t *iseq)
567{
568#if CPDEBUG
569 VALUE *original = rb_iseq_original_iseq(iseq);
570 size_t i = 0;
571 while (i < ISEQ_BODY(iseq)->iseq_size) {
572 VALUE insn = original[i];
573 const char *types = insn_op_types(insn);
574
575 for (int j=0; types[j]; j++) {
576 if (types[j] == TS_CALLDATA) {
577 struct rb_call_data *cd = (struct rb_call_data *)original[i+j+1];
578 const struct rb_callinfo *ci = cd->ci;
579 const struct rb_callcache *cc = cd->cc;
580 if (cc != vm_cc_empty()) {
581 vm_ci_dump(ci);
582 rb_bug("call cache is not initialized by vm_cc_empty()");
583 }
584 }
585 }
586 i += insn_len(insn);
587 }
588
589 for (unsigned int i=0; i<ISEQ_BODY(iseq)->ci_size; i++) {
590 struct rb_call_data *cd = &ISEQ_BODY(iseq)->call_data[i];
591 const struct rb_callinfo *ci = cd->ci;
592 const struct rb_callcache *cc = cd->cc;
593 if (cc != NULL && cc != vm_cc_empty()) {
594 vm_ci_dump(ci);
595 rb_bug("call cache is not initialized by vm_cc_empty()");
596 }
597 }
598#endif
599}
600
601/*
602 * elem1, elem2 => elem1, elem2, elem
603 */
604static void
605ADD_ELEM(ISEQ_ARG_DECLARE LINK_ANCHOR *const anchor, LINK_ELEMENT *elem)
606{
607 elem->prev = anchor->last;
608 anchor->last->next = elem;
609 anchor->last = elem;
610 verify_list("add", anchor);
611}
612
613/*
614 * elem1, before, elem2 => elem1, before, elem, elem2
615 */
616static void
617APPEND_ELEM(ISEQ_ARG_DECLARE LINK_ANCHOR *const anchor, LINK_ELEMENT *before, LINK_ELEMENT *elem)
618{
619 elem->prev = before;
620 elem->next = before->next;
621 elem->next->prev = elem;
622 before->next = elem;
623 if (before == anchor->last) anchor->last = elem;
624 verify_list("add", anchor);
625}
626#if CPDEBUG < 0
627#define ADD_ELEM(anchor, elem) ADD_ELEM(iseq, (anchor), (elem))
628#define APPEND_ELEM(anchor, before, elem) APPEND_ELEM(iseq, (anchor), (before), (elem))
629#endif
630
631static int
632branch_coverage_valid_p(rb_iseq_t *iseq, int first_line)
633{
634 if (!ISEQ_COVERAGE(iseq)) return 0;
635 if (!ISEQ_BRANCH_COVERAGE(iseq)) return 0;
636 if (first_line <= 0) return 0;
637 return 1;
638}
639
640static VALUE
641setup_branch(const rb_code_location_t *loc, const char *type, VALUE structure, VALUE key)
642{
643 const int first_lineno = loc->beg_pos.lineno, first_column = loc->beg_pos.column;
644 const int last_lineno = loc->end_pos.lineno, last_column = loc->end_pos.column;
645 VALUE branch = rb_ary_hidden_new(6);
646
647 rb_hash_aset(structure, key, branch);
648 rb_ary_push(branch, ID2SYM(rb_intern(type)));
649 rb_ary_push(branch, INT2FIX(first_lineno));
650 rb_ary_push(branch, INT2FIX(first_column));
651 rb_ary_push(branch, INT2FIX(last_lineno));
652 rb_ary_push(branch, INT2FIX(last_column));
653 return branch;
654}
655
656static VALUE
657decl_branch_base(rb_iseq_t *iseq, int node_id, const rb_code_location_t *loc, const char *type)
658{
659 if (!branch_coverage_valid_p(iseq, loc->beg_pos.lineno)) return Qundef;
660
661 /*
662 * A branch base is keyed by [source_hash (in two halves), node_id, first_lineno],
663 * which identifies the branch node stably even across (re-)evals against
664 * the same path.
665 *
666 * if !structure[key]
667 * structure[key] = [type, first_lineno, first_column, last_lineno, last_column, branches = {}]
668 * else
669 * branches = structure[key][5]
670 * end
671 */
672 uint64_t source_hash = ISEQ_BODY(iseq)->source_hash;
673 VALUE key = rb_ary_new_from_args(4,
674 ULONG2NUM((unsigned long)(source_hash >> 32)),
675 ULONG2NUM((unsigned long)(source_hash & 0xffffffff)),
676 INT2FIX(node_id),
677 INT2FIX(loc->beg_pos.lineno));
678 rb_ary_freeze(key);
679
680 VALUE structure = RARRAY_AREF(ISEQ_BRANCH_COVERAGE(iseq), 0);
681 VALUE branch_base = rb_hash_aref(structure, key);
682 VALUE branches;
683
684 if (NIL_P(branch_base)) {
685 branch_base = setup_branch(loc, type, structure, key);
686 branches = rb_hash_new();
687 rb_obj_hide(branches);
688 rb_ary_push(branch_base, branches);
689 }
690 else {
691 branches = RARRAY_AREF(branch_base, 5);
692 }
693
694 return branches;
695}
696
697static NODE
698generate_dummy_line_node(int lineno, int node_id)
699{
700 NODE dummy = { 0 };
701 nd_set_line(&dummy, lineno);
702 nd_set_node_id(&dummy, node_id);
703 return dummy;
704}
705
706static void
707add_trace_branch_coverage(rb_iseq_t *iseq, LINK_ANCHOR *const seq, const rb_code_location_t *loc, int node_id, int branch_id, const char *type, VALUE branches)
708{
709 if (!branch_coverage_valid_p(iseq, loc->beg_pos.lineno)) return;
710
711 /*
712 * if !branches[branch_id]
713 * branches[branch_id] = [type, first_lineno, first_column, last_lineno, last_column, counter_idx]
714 * else
715 * counter_idx= branches[branch_id][5]
716 * end
717 */
718
719 VALUE key = INT2FIX(branch_id);
720 VALUE branch = rb_hash_aref(branches, key);
721 long counter_idx;
722
723 if (NIL_P(branch)) {
724 branch = setup_branch(loc, type, branches, key);
725 VALUE counters = RARRAY_AREF(ISEQ_BRANCH_COVERAGE(iseq), 1);
726 counter_idx = RARRAY_LEN(counters);
727 rb_ary_push(branch, LONG2FIX(counter_idx));
728 rb_ary_push(counters, INT2FIX(0));
729 }
730 else {
731 counter_idx = FIX2LONG(RARRAY_AREF(branch, 5));
732 }
733
734 ADD_TRACE_WITH_DATA(seq, RUBY_EVENT_COVERAGE_BRANCH, counter_idx);
735 ADD_SYNTHETIC_INSN(seq, loc->end_pos.lineno, node_id, nop);
736}
737
738#define ISEQ_LAST_LINE(iseq) (ISEQ_COMPILE_DATA(iseq)->last_line)
739
740static int
741validate_label(st_data_t name, st_data_t label, st_data_t arg)
742{
743 rb_iseq_t *iseq = (rb_iseq_t *)arg;
744 LABEL *lobj = (LABEL *)label;
745 if (!lobj->link.next) {
746 do {
747 COMPILE_ERROR(iseq, lobj->position,
748 "%"PRIsVALUE": undefined label",
749 rb_sym2str((VALUE)name));
750 } while (0);
751 }
752 return ST_CONTINUE;
753}
754
755static void
756validate_labels(rb_iseq_t *iseq, st_table *labels_table)
757{
758 st_foreach(labels_table, validate_label, (st_data_t)iseq);
759 st_free_table(labels_table);
760}
761
762static NODE *
763get_nd_recv(const NODE *node)
764{
765 switch (nd_type(node)) {
766 case NODE_CALL:
767 return RNODE_CALL(node)->nd_recv;
768 case NODE_OPCALL:
769 return RNODE_OPCALL(node)->nd_recv;
770 case NODE_FCALL:
771 return 0;
772 case NODE_QCALL:
773 return RNODE_QCALL(node)->nd_recv;
774 case NODE_VCALL:
775 return 0;
776 case NODE_ATTRASGN:
777 return RNODE_ATTRASGN(node)->nd_recv;
778 case NODE_OP_ASGN1:
779 return RNODE_OP_ASGN1(node)->nd_recv;
780 case NODE_OP_ASGN2:
781 return RNODE_OP_ASGN2(node)->nd_recv;
782 default:
783 rb_bug("unexpected node: %s", ruby_node_name(nd_type(node)));
784 }
785}
786
787static ID
788get_node_call_nd_mid(const NODE *node)
789{
790 switch (nd_type(node)) {
791 case NODE_CALL:
792 return RNODE_CALL(node)->nd_mid;
793 case NODE_OPCALL:
794 return RNODE_OPCALL(node)->nd_mid;
795 case NODE_FCALL:
796 return RNODE_FCALL(node)->nd_mid;
797 case NODE_QCALL:
798 return RNODE_QCALL(node)->nd_mid;
799 case NODE_VCALL:
800 return RNODE_VCALL(node)->nd_mid;
801 case NODE_ATTRASGN:
802 return RNODE_ATTRASGN(node)->nd_mid;
803 default:
804 rb_bug("unexpected node: %s", ruby_node_name(nd_type(node)));
805 }
806}
807
808static NODE *
809get_nd_args(const NODE *node)
810{
811 switch (nd_type(node)) {
812 case NODE_CALL:
813 return RNODE_CALL(node)->nd_args;
814 case NODE_OPCALL:
815 return RNODE_OPCALL(node)->nd_args;
816 case NODE_FCALL:
817 return RNODE_FCALL(node)->nd_args;
818 case NODE_QCALL:
819 return RNODE_QCALL(node)->nd_args;
820 case NODE_VCALL:
821 return 0;
822 case NODE_ATTRASGN:
823 return RNODE_ATTRASGN(node)->nd_args;
824 default:
825 rb_bug("unexpected node: %s", ruby_node_name(nd_type(node)));
826 }
827}
828
829static ID
830get_node_colon_nd_mid(const NODE *node)
831{
832 switch (nd_type(node)) {
833 case NODE_COLON2:
834 return RNODE_COLON2(node)->nd_mid;
835 case NODE_COLON3:
836 return RNODE_COLON3(node)->nd_mid;
837 default:
838 rb_bug("unexpected node: %s", ruby_node_name(nd_type(node)));
839 }
840}
841
842static ID
843get_nd_vid(const NODE *node)
844{
845 switch (nd_type(node)) {
846 case NODE_LASGN:
847 return RNODE_LASGN(node)->nd_vid;
848 case NODE_DASGN:
849 return RNODE_DASGN(node)->nd_vid;
850 case NODE_IASGN:
851 return RNODE_IASGN(node)->nd_vid;
852 case NODE_CVASGN:
853 return RNODE_CVASGN(node)->nd_vid;
854 default:
855 rb_bug("unexpected node: %s", ruby_node_name(nd_type(node)));
856 }
857}
858
859static NODE *
860get_nd_value(const NODE *node)
861{
862 switch (nd_type(node)) {
863 case NODE_LASGN:
864 return RNODE_LASGN(node)->nd_value;
865 case NODE_DASGN:
866 return RNODE_DASGN(node)->nd_value;
867 default:
868 rb_bug("unexpected node: %s", ruby_node_name(nd_type(node)));
869 }
870}
871
872static VALUE
873get_string_value(const NODE *node)
874{
875 switch (nd_type(node)) {
876 case NODE_STR:
877 return RB_OBJ_SET_SHAREABLE(rb_node_str_string_val(node));
878 case NODE_FILE:
879 return RB_OBJ_SET_SHAREABLE(rb_node_file_path_val(node));
880 default:
881 rb_bug("unexpected node: %s", ruby_node_name(nd_type(node)));
882 }
883}
884
885VALUE
886rb_iseq_compile_callback(rb_iseq_t *iseq, const struct rb_iseq_new_with_callback_callback_func * ifunc)
887{
888 DECL_ANCHOR(ret);
889 INIT_ANCHOR(ret);
890
891 (*ifunc->func)(iseq, ret, ifunc->data);
892
893 ADD_SYNTHETIC_INSN(ret, ISEQ_COMPILE_DATA(iseq)->last_line, -1, leave);
894
895 CHECK(iseq_setup_insn(iseq, ret));
896 return iseq_setup(iseq, ret);
897}
898
899static bool drop_unreachable_return(LINK_ANCHOR *ret);
900
901VALUE
902rb_iseq_compile_node(rb_iseq_t *iseq, const NODE *node)
903{
904 DECL_ANCHOR(ret);
905 INIT_ANCHOR(ret);
906
907 if (node == 0) {
908 NO_CHECK(COMPILE(ret, "nil", node));
909 iseq_set_local_table(iseq, 0, 0);
910 }
911 /* assume node is T_NODE */
912 else if (nd_type_p(node, NODE_SCOPE)) {
913 /* iseq type of top, method, class, block */
914 iseq_set_local_table(iseq, RNODE_SCOPE(node)->nd_tbl, (NODE *)RNODE_SCOPE(node)->nd_args);
915 iseq_set_arguments(iseq, ret, (NODE *)RNODE_SCOPE(node)->nd_args);
916 iseq_set_parameters_lvar_state(iseq);
917
918 switch (ISEQ_BODY(iseq)->type) {
919 case ISEQ_TYPE_BLOCK:
920 {
921 LABEL *start = ISEQ_COMPILE_DATA(iseq)->start_label = NEW_LABEL(0);
922 LABEL *end = ISEQ_COMPILE_DATA(iseq)->end_label = NEW_LABEL(0);
923
924 start->rescued = LABEL_RESCUE_BEG;
925 end->rescued = LABEL_RESCUE_END;
926
927 ADD_TRACE(ret, RUBY_EVENT_B_CALL);
928 ADD_SYNTHETIC_INSN(ret, ISEQ_BODY(iseq)->location.first_lineno, -1, nop);
929 ADD_LABEL(ret, start);
930 CHECK(COMPILE(ret, "block body", RNODE_SCOPE(node)->nd_body));
931 ADD_LABEL(ret, end);
932 ADD_TRACE(ret, RUBY_EVENT_B_RETURN);
933 ISEQ_COMPILE_DATA(iseq)->last_line = ISEQ_BODY(iseq)->location.code_location.end_pos.lineno;
934
935 /* wide range catch handler must put at last */
936 ADD_CATCH_ENTRY(CATCH_TYPE_REDO, start, end, NULL, start);
937 ADD_CATCH_ENTRY(CATCH_TYPE_NEXT, start, end, NULL, end);
938 break;
939 }
940 case ISEQ_TYPE_CLASS:
941 {
942 ADD_TRACE(ret, RUBY_EVENT_CLASS);
943 CHECK(COMPILE(ret, "scoped node", RNODE_SCOPE(node)->nd_body));
944 ADD_TRACE(ret, RUBY_EVENT_END);
945 ISEQ_COMPILE_DATA(iseq)->last_line = nd_line(node);
946 break;
947 }
948 case ISEQ_TYPE_METHOD:
949 {
950 ISEQ_COMPILE_DATA(iseq)->root_node = RNODE_SCOPE(node)->nd_body;
951 ADD_TRACE(ret, RUBY_EVENT_CALL);
952 CHECK(COMPILE(ret, "scoped node", RNODE_SCOPE(node)->nd_body));
953 ISEQ_COMPILE_DATA(iseq)->root_node = RNODE_SCOPE(node)->nd_body;
954 ADD_TRACE(ret, RUBY_EVENT_RETURN);
955 ISEQ_COMPILE_DATA(iseq)->last_line = nd_line(node);
956 break;
957 }
958 default: {
959 CHECK(COMPILE(ret, "scoped node", RNODE_SCOPE(node)->nd_body));
960 break;
961 }
962 }
963 }
964 else {
965 const char *m;
966#define INVALID_ISEQ_TYPE(type) \
967 ISEQ_TYPE_##type: m = #type; goto invalid_iseq_type
968 switch (ISEQ_BODY(iseq)->type) {
969 case INVALID_ISEQ_TYPE(METHOD);
970 case INVALID_ISEQ_TYPE(CLASS);
971 case INVALID_ISEQ_TYPE(BLOCK);
972 case INVALID_ISEQ_TYPE(EVAL);
973 case INVALID_ISEQ_TYPE(MAIN);
974 case INVALID_ISEQ_TYPE(TOP);
975#undef INVALID_ISEQ_TYPE /* invalid iseq types end */
976 case ISEQ_TYPE_RESCUE:
977 iseq_set_exception_local_table(iseq);
978 CHECK(COMPILE(ret, "rescue", node));
979 break;
980 case ISEQ_TYPE_ENSURE:
981 iseq_set_exception_local_table(iseq);
982 CHECK(COMPILE_POPPED(ret, "ensure", node));
983 break;
984 case ISEQ_TYPE_PLAIN:
985 CHECK(COMPILE(ret, "ensure", node));
986 break;
987 default:
988 COMPILE_ERROR(ERROR_ARGS "unknown scope: %d", ISEQ_BODY(iseq)->type);
989 return COMPILE_NG;
990 invalid_iseq_type:
991 COMPILE_ERROR(ERROR_ARGS "compile/ISEQ_TYPE_%s should not be reached", m);
992 return COMPILE_NG;
993 }
994 }
995
996 if (ISEQ_BODY(iseq)->type == ISEQ_TYPE_RESCUE || ISEQ_BODY(iseq)->type == ISEQ_TYPE_ENSURE) {
997 NODE dummy_line_node = generate_dummy_line_node(0, -1);
998 ADD_GETLOCAL(ret, &dummy_line_node, LVAR_ERRINFO, 0);
999 ADD_INSN1(ret, &dummy_line_node, throw, INT2FIX(0) /* continue throw */ );
1000 }
1001 else if (!drop_unreachable_return(ret)) {
1002 ADD_SYNTHETIC_INSN(ret, ISEQ_COMPILE_DATA(iseq)->last_line, -1, leave);
1003 }
1004
1005#if OPT_SUPPORT_JOKE
1006 if (ISEQ_COMPILE_DATA(iseq)->labels_table) {
1007 st_table *labels_table = ISEQ_COMPILE_DATA(iseq)->labels_table;
1008 ISEQ_COMPILE_DATA(iseq)->labels_table = 0;
1009 validate_labels(iseq, labels_table);
1010 }
1011#endif
1012 CHECK(iseq_setup_insn(iseq, ret));
1013 return iseq_setup(iseq, ret);
1014}
1015
1016static int
1017rb_iseq_translate_threaded_code(rb_iseq_t *iseq)
1018{
1019#if OPT_DIRECT_THREADED_CODE || OPT_CALL_THREADED_CODE
1020 const void * const *table = rb_vm_get_insns_address_table();
1021 unsigned int i;
1022 VALUE *encoded = (VALUE *)ISEQ_BODY(iseq)->iseq_encoded;
1023
1024 for (i = 0; i < ISEQ_BODY(iseq)->iseq_size; /* */ ) {
1025 int insn = (int)ISEQ_BODY(iseq)->iseq_encoded[i];
1026 int len = insn_len(insn);
1027 encoded[i] = (VALUE)table[insn];
1028 i += len;
1029 }
1030#endif
1031 FL_SET((VALUE)iseq, ISEQ_TRANSLATED);
1032
1033#if USE_YJIT
1034 rb_yjit_live_iseq_count++;
1035 rb_yjit_iseq_alloc_count++;
1036#endif
1037
1038 return COMPILE_OK;
1039}
1040
1041VALUE *
1042rb_iseq_original_iseq(const rb_iseq_t *iseq) /* cold path */
1043{
1044 struct rb_iseq_variable *v = ISEQ_VARIABLE(iseq);
1045 VALUE *original_code = v ? RUBY_ATOMIC_PTR_LOAD(v->original_iseq) : NULL;
1046
1047 if (original_code) return original_code;
1048 original_code = ALLOC_N(VALUE, ISEQ_BODY(iseq)->iseq_size);
1049 MEMCPY(original_code, ISEQ_BODY(iseq)->iseq_encoded, VALUE, ISEQ_BODY(iseq)->iseq_size);
1050
1051 {
1052 unsigned int i;
1053
1054 for (i = 0; i < ISEQ_BODY(iseq)->iseq_size; /* */ ) {
1055 const void *addr = (const void *)original_code[i];
1056 const int insn = rb_vm_insn_addr2insn(addr);
1057
1058 original_code[i] = insn;
1059 i += insn_len(insn);
1060 }
1061 }
1062
1063 /* Concurrent callers can each build a copy; publish only fully
1064 * translated code and keep the first one. */
1065 v = rb_iseq_variable_ensure((rb_iseq_t *)iseq);
1066 VALUE *prev = ATOMIC_PTR_CAS(v->original_iseq,
1067 NULL, original_code);
1068 if (prev) {
1069 SIZED_FREE_N(original_code, ISEQ_BODY(iseq)->iseq_size);
1070 return prev;
1071 }
1072 return original_code;
1073}
1074
1075/*********************************************/
1076/* definition of data structure for compiler */
1077/*********************************************/
1078
1079#if defined(HAVE_TRUE_LONG_LONG) && SIZEOF_LONG_LONG > SIZEOF_VALUE
1080# define ALIGNMENT_SIZE SIZEOF_LONG_LONG
1081#else
1082# define ALIGNMENT_SIZE SIZEOF_VALUE
1083#endif
1084#define PADDING_SIZE_MAX ((size_t)((ALIGNMENT_SIZE) - 1))
1085
1086#define ALIGNMENT_SIZE_OF(type) alignment_size_assert(RUBY_ALIGNOF(type), #type)
1087
1088static inline size_t
1089alignment_size_assert(size_t align, const char *type)
1090{
1091 RUBY_ASSERT((align & (align - 1)) == 0,
1092 "ALIGNMENT_SIZE_OF(%s):%zd == (2 ** N) is expected", type, align);
1093 return align;
1094}
1095
1096/* calculate padding size for aligned memory access */
1097static inline size_t
1098calc_padding(void *ptr, size_t align)
1099{
1100 size_t mis;
1101 size_t padding = 0;
1102
1103 mis = (size_t)ptr & (align - 1);
1104 if (mis > 0) {
1105 padding = align - mis;
1106 }
1107
1108 return padding;
1109}
1110
1111static void *
1112compile_data_alloc_with_arena(struct iseq_compile_data_storage **arena, size_t size, size_t align)
1113{
1114 void *ptr = 0;
1115 struct iseq_compile_data_storage *storage = *arena;
1116 size_t padding = calc_padding((void *)&storage->buff[storage->pos], align);
1117
1118 if (size >= INT_MAX - padding) rb_memerror();
1119 if (storage->pos + size + padding > storage->size) {
1120 unsigned int alloc_size = storage->size;
1121
1122 while (alloc_size < size + PADDING_SIZE_MAX) {
1123 if (alloc_size >= INT_MAX / 2) rb_memerror();
1124 alloc_size *= 2;
1125 }
1126 storage->next = (void *)ALLOC_N(char, alloc_size +
1127 offsetof(struct iseq_compile_data_storage, buff));
1128 storage = *arena = storage->next;
1129 storage->next = 0;
1130 storage->pos = 0;
1131 storage->size = alloc_size;
1132 padding = calc_padding((void *)&storage->buff[storage->pos], align);
1133 }
1134
1135 storage->pos += (int)padding;
1136
1137 ptr = (void *)&storage->buff[storage->pos];
1138 storage->pos += (int)size;
1139 return ptr;
1140}
1141
1142static void *
1143compile_data_alloc(rb_iseq_t *iseq, size_t size, size_t align)
1144{
1145 struct iseq_compile_data_storage ** arena = &ISEQ_COMPILE_DATA(iseq)->node.storage_current;
1146 return compile_data_alloc_with_arena(arena, size, align);
1147}
1148
1149#define compile_data_alloc_type(iseq, type) \
1150 (type *)compile_data_alloc(iseq, sizeof(type), ALIGNMENT_SIZE_OF(type))
1151
1152static inline void *
1153compile_data_alloc2(rb_iseq_t *iseq, size_t elsize, size_t num, size_t align)
1154{
1155 size_t size = rb_size_mul_or_raise(elsize, num, rb_eRuntimeError);
1156 return compile_data_alloc(iseq, size, align);
1157}
1158
1159#define compile_data_alloc2_type(iseq, type, num) \
1160 (type *)compile_data_alloc2(iseq, sizeof(type), num, ALIGNMENT_SIZE_OF(type))
1161
1162static inline void *
1163compile_data_calloc2(rb_iseq_t *iseq, size_t elsize, size_t num, size_t align)
1164{
1165 size_t size = rb_size_mul_or_raise(elsize, num, rb_eRuntimeError);
1166 void *p = compile_data_alloc(iseq, size, align);
1167 memset(p, 0, size);
1168 return p;
1169}
1170
1171#define compile_data_calloc2_type(iseq, type, num) \
1172 (type *)compile_data_calloc2(iseq, sizeof(type), num, ALIGNMENT_SIZE_OF(type))
1173
1174static INSN *
1175compile_data_alloc_insn(rb_iseq_t *iseq)
1176{
1177 struct iseq_compile_data_storage ** arena = &ISEQ_COMPILE_DATA(iseq)->insn.storage_current;
1178 return (INSN *)compile_data_alloc_with_arena(arena, sizeof(INSN), ALIGNMENT_SIZE_OF(INSN));
1179}
1180
1181static LABEL *
1182compile_data_alloc_label(rb_iseq_t *iseq)
1183{
1184 return compile_data_alloc_type(iseq, LABEL);
1185}
1186
1187static ADJUST *
1188compile_data_alloc_adjust(rb_iseq_t *iseq)
1189{
1190 return compile_data_alloc_type(iseq, ADJUST);
1191}
1192
1193static TRACE *
1194compile_data_alloc_trace(rb_iseq_t *iseq)
1195{
1196 return compile_data_alloc_type(iseq, TRACE);
1197}
1198
1199/*
1200 * elem1, elemX => elem1, elem2, elemX
1201 */
1202static void
1203ELEM_INSERT_NEXT(LINK_ELEMENT *elem1, LINK_ELEMENT *elem2)
1204{
1205 elem2->next = elem1->next;
1206 elem2->prev = elem1;
1207 elem1->next = elem2;
1208 if (elem2->next) {
1209 elem2->next->prev = elem2;
1210 }
1211}
1212
1213/*
1214 * elem1, elemX => elemX, elem2, elem1
1215 */
1216static void
1217ELEM_INSERT_PREV(LINK_ELEMENT *elem1, LINK_ELEMENT *elem2)
1218{
1219 elem2->prev = elem1->prev;
1220 elem2->next = elem1;
1221 elem1->prev = elem2;
1222 if (elem2->prev) {
1223 elem2->prev->next = elem2;
1224 }
1225}
1226
1227/*
1228 * elemX, elem1, elemY => elemX, elem2, elemY
1229 */
1230static void
1231ELEM_REPLACE(LINK_ELEMENT *elem1, LINK_ELEMENT *elem2)
1232{
1233 elem2->prev = elem1->prev;
1234 elem2->next = elem1->next;
1235 if (elem1->prev) {
1236 elem1->prev->next = elem2;
1237 }
1238 if (elem1->next) {
1239 elem1->next->prev = elem2;
1240 }
1241}
1242
1243static void
1244ELEM_REMOVE(LINK_ELEMENT *elem)
1245{
1246 elem->prev->next = elem->next;
1247 if (elem->next) {
1248 elem->next->prev = elem->prev;
1249 }
1250}
1251
1252/*
1253 * elem1, elem2 => elem2, elem1
1254 */
1255static void
1256ELEM_SWAP(LINK_ELEMENT *first, LINK_ELEMENT *second)
1257{
1258 RUBY_ASSERT(first->next == second);
1259 RUBY_ASSERT(first == second->prev);
1260
1261 first->prev->next = second;
1262 second->next->prev = first;
1263
1264 first->next = second->next;
1265 second->next = first;
1266
1267 second->prev = first->prev;
1268 first->prev = second;
1269
1270 if (IS_INSN(first) && IS_INSN(second)) {
1271 INSN *first_insn = (INSN*)first;
1272 INSN *second_insn = (INSN*)second;
1273
1274 // [Bug #22299] If both instructions are on the same line and the first one carries
1275 // a line event we need to swap the event as well.
1276 if (first_insn->insn_info.line_no == second_insn->insn_info.line_no) {
1277 rb_event_flag_t mask = (RUBY_EVENT_LINE | RUBY_EVENT_COVERAGE_LINE);
1278 rb_event_flag_t first_events = first_insn->insn_info.events & mask;
1279 rb_event_flag_t second_events = second_insn->insn_info.events & mask;
1280 first_insn->insn_info.events = (first_insn->insn_info.events & ~mask) | second_events;
1281 second_insn->insn_info.events = (second_insn->insn_info.events & ~mask) | first_events;
1282 }
1283 }
1284}
1285
1286static LINK_ELEMENT *
1287FIRST_ELEMENT(const LINK_ANCHOR *const anchor)
1288{
1289 return anchor->anchor.next;
1290}
1291
1292static LINK_ELEMENT *
1293LAST_ELEMENT(LINK_ANCHOR *const anchor)
1294{
1295 return anchor->last;
1296}
1297
1298static LINK_ELEMENT *
1299ELEM_FIRST_INSN(LINK_ELEMENT *elem)
1300{
1301 while (elem) {
1302 switch (elem->type) {
1303 case ISEQ_ELEMENT_INSN:
1304 case ISEQ_ELEMENT_ADJUST:
1305 return elem;
1306 default:
1307 elem = elem->next;
1308 }
1309 }
1310 return NULL;
1311}
1312
1313static int
1314LIST_INSN_SIZE_ONE(const LINK_ANCHOR *const anchor)
1315{
1316 LINK_ELEMENT *first_insn = ELEM_FIRST_INSN(FIRST_ELEMENT(anchor));
1317 if (first_insn != NULL &&
1318 ELEM_FIRST_INSN(first_insn->next) == NULL) {
1319 return TRUE;
1320 }
1321 else {
1322 return FALSE;
1323 }
1324}
1325
1326static int
1327LIST_INSN_SIZE_ZERO(const LINK_ANCHOR *const anchor)
1328{
1329 if (ELEM_FIRST_INSN(FIRST_ELEMENT(anchor)) == NULL) {
1330 return TRUE;
1331 }
1332 else {
1333 return FALSE;
1334 }
1335}
1336
1337/*
1338 * anc1: e1, e2, e3
1339 * anc2: e4, e5
1340 *#=>
1341 * anc1: e1, e2, e3, e4, e5
1342 * anc2: e4, e5 (broken)
1343 */
1344static void
1345APPEND_LIST(ISEQ_ARG_DECLARE LINK_ANCHOR *const anc1, LINK_ANCHOR *const anc2)
1346{
1347 if (anc2->anchor.next) {
1348 /* LINK_ANCHOR must not loop */
1349 RUBY_ASSERT(anc2->last != &anc2->anchor);
1350 anc1->last->next = anc2->anchor.next;
1351 anc2->anchor.next->prev = anc1->last;
1352 anc1->last = anc2->last;
1353 }
1354 else {
1355 RUBY_ASSERT(anc2->last == &anc2->anchor);
1356 }
1357 verify_list("append", anc1);
1358}
1359#if CPDEBUG < 0
1360#define APPEND_LIST(anc1, anc2) APPEND_LIST(iseq, (anc1), (anc2))
1361#endif
1362
1363#if CPDEBUG && 0
1364static void
1365debug_list(ISEQ_ARG_DECLARE LINK_ANCHOR *const anchor, LINK_ELEMENT *cur)
1366{
1367 LINK_ELEMENT *list = FIRST_ELEMENT(anchor);
1368 printf("----\n");
1369 printf("anch: %p, frst: %p, last: %p\n", (void *)&anchor->anchor,
1370 (void *)anchor->anchor.next, (void *)anchor->last);
1371 while (list) {
1372 printf("curr: %p, next: %p, prev: %p, type: %d\n", (void *)list, (void *)list->next,
1373 (void *)list->prev, (int)list->type);
1374 list = list->next;
1375 }
1376 printf("----\n");
1377
1378 dump_disasm_list_with_cursor(anchor->anchor.next, cur, 0);
1379 verify_list("debug list", anchor);
1380}
1381#if CPDEBUG < 0
1382#define debug_list(anc, cur) debug_list(iseq, (anc), (cur))
1383#endif
1384#else
1385#define debug_list(anc, cur) ((void)0)
1386#endif
1387
1388static TRACE *
1389new_trace_body(rb_iseq_t *iseq, rb_event_flag_t event, long data)
1390{
1391 TRACE *trace = compile_data_alloc_trace(iseq);
1392
1393 trace->link.type = ISEQ_ELEMENT_TRACE;
1394 trace->link.next = NULL;
1395 trace->event = event;
1396 trace->data = data;
1397
1398 return trace;
1399}
1400
1401static LABEL *
1402new_label_body(rb_iseq_t *iseq, long line)
1403{
1404 LABEL *labelobj = compile_data_alloc_label(iseq);
1405
1406 labelobj->link.type = ISEQ_ELEMENT_LABEL;
1407 labelobj->link.next = 0;
1408
1409 labelobj->label_no = ISEQ_COMPILE_DATA(iseq)->label_no++;
1410 labelobj->sc_state = 0;
1411 labelobj->sp = -1;
1412 labelobj->refcnt = 0;
1413 labelobj->set = 0;
1414 labelobj->rescued = LABEL_RESCUE_NONE;
1415 labelobj->unremovable = 0;
1416 labelobj->position = -1;
1417 return labelobj;
1418}
1419
1420static ADJUST *
1421new_adjust_body(rb_iseq_t *iseq, LABEL *label, int line)
1422{
1423 ADJUST *adjust = compile_data_alloc_adjust(iseq);
1424 adjust->link.type = ISEQ_ELEMENT_ADJUST;
1425 adjust->link.next = 0;
1426 adjust->label = label;
1427 adjust->line_no = line;
1428 LABEL_UNREMOVABLE(label);
1429 return adjust;
1430}
1431
1432static void
1433iseq_insn_each_markable_object(INSN *insn, void (*func)(VALUE *, VALUE), VALUE data)
1434{
1435 const char *types = insn_op_types(insn->insn_id);
1436 for (int j = 0; types[j]; j++) {
1437 char type = types[j];
1438 switch (type) {
1439 case TS_CDHASH:
1440 case TS_ISEQ:
1441 case TS_VALUE:
1442 case TS_CALLDATA: // ci is stored.
1443 func(&OPERAND_AT(insn, j), data);
1444 break;
1445 default:
1446 break;
1447 }
1448 }
1449}
1450
1451static void
1452iseq_insn_each_object_write_barrier(VALUE * obj, VALUE iseq)
1453{
1454 RB_OBJ_WRITTEN(iseq, Qundef, *obj);
1456 RBASIC_CLASS(*obj) == 0 || // hidden
1457 RB_OBJ_SHAREABLE_P(*obj));
1458}
1459
1460static INSN *
1461new_insn_core(rb_iseq_t *iseq, int line_no, int node_id, int insn_id, int argc, VALUE *argv)
1462{
1463 INSN *iobj = compile_data_alloc_insn(iseq);
1464
1465 /* printf("insn_id: %d, line: %d\n", insn_id, nd_line(line_node)); */
1466
1467 iobj->link.type = ISEQ_ELEMENT_INSN;
1468 iobj->link.next = 0;
1469 iobj->insn_id = insn_id;
1470 iobj->insn_info.line_no = line_no;
1471 iobj->insn_info.node_id = node_id;
1472 iobj->insn_info.events = 0;
1473 iobj->operands = argv;
1474 iobj->operand_size = argc;
1475 iobj->sc_state = 0;
1476
1477 iseq_insn_each_markable_object(iobj, iseq_insn_each_object_write_barrier, (VALUE)iseq);
1478
1479 return iobj;
1480}
1481
1482static INSN *
1483new_insn_body(rb_iseq_t *iseq, int line_no, int node_id, enum ruby_vminsn_type insn_id, int argc, ...)
1484{
1485 VALUE *operands = 0;
1486 va_list argv;
1487 if (argc > 0) {
1488 int i;
1489 va_start(argv, argc);
1490 operands = compile_data_alloc2_type(iseq, VALUE, argc);
1491 for (i = 0; i < argc; i++) {
1492 VALUE v = va_arg(argv, VALUE);
1493 operands[i] = v;
1494 }
1495 va_end(argv);
1496 }
1497 return new_insn_core(iseq, line_no, node_id, insn_id, argc, operands);
1498}
1499
1500static INSN *
1501insn_replace_with_operands(rb_iseq_t *iseq, INSN *iobj, enum ruby_vminsn_type insn_id, int argc, ...)
1502{
1503 VALUE *operands = 0;
1504 va_list argv;
1505 if (argc > 0) {
1506 int i;
1507 va_start(argv, argc);
1508 operands = compile_data_alloc2_type(iseq, VALUE, argc);
1509 for (i = 0; i < argc; i++) {
1510 VALUE v = va_arg(argv, VALUE);
1511 operands[i] = v;
1512 }
1513 va_end(argv);
1514 }
1515
1516 iobj->insn_id = insn_id;
1517 iobj->operand_size = argc;
1518 iobj->operands = operands;
1519 iseq_insn_each_markable_object(iobj, iseq_insn_each_object_write_barrier, (VALUE)iseq);
1520
1521 return iobj;
1522}
1523
1524static const struct rb_callinfo *
1525new_callinfo(rb_iseq_t *iseq, ID mid, int argc, unsigned int flag, struct rb_callinfo_kwarg *kw_arg, int has_blockiseq)
1526{
1527 VM_ASSERT(argc >= 0);
1528
1529 if (kw_arg) {
1530 flag |= VM_CALL_KWARG;
1531 argc += kw_arg->keyword_len;
1532 }
1533
1534 if (!(flag & (VM_CALL_ARGS_SPLAT | VM_CALL_ARGS_BLOCKARG | VM_CALL_KWARG | VM_CALL_KW_SPLAT | VM_CALL_FORWARDING))
1535 && !has_blockiseq) {
1536 flag |= VM_CALL_ARGS_SIMPLE;
1537 }
1538
1539 ISEQ_BODY(iseq)->ci_size++;
1540 const struct rb_callinfo *ci = vm_ci_new(mid, flag, argc, kw_arg);
1541 RB_OBJ_WRITTEN(iseq, Qundef, ci);
1542 return ci;
1543}
1544
1545static INSN *
1546new_insn_send(rb_iseq_t *iseq, int line_no, int node_id, ID id, VALUE argc, const rb_iseq_t *blockiseq, VALUE flag, struct rb_callinfo_kwarg *keywords)
1547{
1548 VALUE *operands = compile_data_calloc2_type(iseq, VALUE, 2);
1549 VALUE ci = (VALUE)new_callinfo(iseq, id, FIX2INT(argc), FIX2INT(flag), keywords, blockiseq != NULL);
1550 operands[0] = ci;
1551 operands[1] = (VALUE)blockiseq;
1552 if (blockiseq) {
1553 RB_OBJ_WRITTEN(iseq, Qundef, blockiseq);
1554 }
1555
1556 INSN *insn;
1557
1558 if (vm_ci_flag((struct rb_callinfo *)ci) & VM_CALL_FORWARDING) {
1559 insn = new_insn_core(iseq, line_no, node_id, BIN(sendforward), 2, operands);
1560 }
1561 else {
1562 insn = new_insn_core(iseq, line_no, node_id, BIN(send), 2, operands);
1563 }
1564
1565 RB_OBJ_WRITTEN(iseq, Qundef, ci);
1566 RB_GC_GUARD(ci);
1567 return insn;
1568}
1569
1570static rb_iseq_t *
1571new_child_iseq(rb_iseq_t *iseq, const NODE *const node,
1572 VALUE name, const rb_iseq_t *parent, enum rb_iseq_type type, int line_no)
1573{
1574 rb_iseq_t *ret_iseq;
1575 VALUE ast_value = rb_ruby_ast_new(node);
1576
1577 // The child AST wrapper does not carry the source hash, so copy it from
1578 // the enclosing iseq before compiling, for grandchildren to inherit it.
1579 if (ISEQ_BODY(iseq)->source_hash) {
1580 rb_ast_t *child_ast = rb_ruby_ast_data_get(ast_value);
1581 child_ast->body.source_hash = ISEQ_BODY(iseq)->source_hash;
1582 child_ast->body.has_source_hash = 1;
1583 }
1584
1585 debugs("[new_child_iseq]> ---------------------------------------\n");
1586 int isolated_depth = ISEQ_COMPILE_DATA(iseq)->isolated_depth;
1587 ret_iseq = rb_iseq_new_with_opt(ast_value, name,
1588 rb_iseq_path(iseq), rb_iseq_realpath(iseq),
1589 line_no, parent,
1590 isolated_depth ? isolated_depth + 1 : 0,
1591 type, ISEQ_COMPILE_DATA(iseq)->option,
1592 ISEQ_SCRIPT_LINES(iseq));
1593 debugs("[new_child_iseq]< ---------------------------------------\n");
1594 return ret_iseq;
1595}
1596
1597static rb_iseq_t *
1598new_child_iseq_with_callback(rb_iseq_t *iseq, const struct rb_iseq_new_with_callback_callback_func *ifunc,
1599 VALUE name, const rb_iseq_t *parent, enum rb_iseq_type type, int line_no)
1600{
1601 rb_iseq_t *ret_iseq;
1602
1603 debugs("[new_child_iseq_with_callback]> ---------------------------------------\n");
1604 ret_iseq = rb_iseq_new_with_callback(ifunc, name,
1605 rb_iseq_path(iseq), rb_iseq_realpath(iseq),
1606 line_no, parent, type, ISEQ_COMPILE_DATA(iseq)->option);
1607 debugs("[new_child_iseq_with_callback]< ---------------------------------------\n");
1608 return ret_iseq;
1609}
1610
1611static void
1612set_catch_except_p(rb_iseq_t *iseq)
1613{
1614 RUBY_ASSERT(ISEQ_COMPILE_DATA(iseq));
1615 ISEQ_COMPILE_DATA(iseq)->catch_except_p = true;
1616 if (ISEQ_BODY(iseq)->parent_iseq != NULL) {
1617 if (ISEQ_COMPILE_DATA(ISEQ_BODY(iseq)->parent_iseq)) {
1618 set_catch_except_p((rb_iseq_t *) ISEQ_BODY(iseq)->parent_iseq);
1619 }
1620 }
1621}
1622
1623/* Set body->catch_except_p to true if the ISeq may catch an exception. If it is false,
1624 JIT-ed code may be optimized. If we are extremely conservative, we should set true
1625 if catch table exists. But we want to optimize while loop, which always has catch
1626 table entries for break/next/redo.
1627
1628 So this function sets true for limited ISeqs with break/next/redo catch table entries
1629 whose child ISeq would really raise an exception. */
1630static void
1631update_catch_except_flags(rb_iseq_t *iseq, struct rb_iseq_constant_body *body)
1632{
1633 unsigned int pos;
1634 size_t i;
1635 int insn;
1636 const struct iseq_catch_table *ct = body->catch_table;
1637
1638 /* This assumes that a block has parent_iseq which may catch an exception from the block, and that
1639 BREAK/NEXT/REDO catch table entries are used only when `throw` insn is used in the block. */
1640 pos = 0;
1641 while (pos < body->iseq_size) {
1642 insn = rb_vm_insn_decode(body->iseq_encoded[pos]);
1643 if (insn == BIN(throw)) {
1644 set_catch_except_p(iseq);
1645 break;
1646 }
1647 pos += insn_len(insn);
1648 }
1649
1650 if (ct == NULL)
1651 return;
1652
1653 for (i = 0; i < ct->size; i++) {
1654 const struct iseq_catch_table_entry *entry =
1655 UNALIGNED_MEMBER_PTR(ct, entries[i]);
1656 if (entry->type != CATCH_TYPE_BREAK
1657 && entry->type != CATCH_TYPE_NEXT
1658 && entry->type != CATCH_TYPE_REDO) {
1659 RUBY_ASSERT(ISEQ_COMPILE_DATA(iseq));
1660 ISEQ_COMPILE_DATA(iseq)->catch_except_p = true;
1661 break;
1662 }
1663 }
1664}
1665
1666static void
1667iseq_insert_nop_between_end_and_cont(rb_iseq_t *iseq)
1668{
1669 VALUE catch_table_ary = ISEQ_COMPILE_DATA(iseq)->catch_table_ary;
1670 if (NIL_P(catch_table_ary)) return;
1671 unsigned int i, tlen = (unsigned int)RARRAY_LEN(catch_table_ary);
1672 const VALUE *tptr = RARRAY_CONST_PTR(catch_table_ary);
1673 for (i = 0; i < tlen; i++) {
1674 const VALUE *ptr = RARRAY_CONST_PTR(tptr[i]);
1675 LINK_ELEMENT *end = (LINK_ELEMENT *)(ptr[2] & ~1);
1676 LINK_ELEMENT *cont = (LINK_ELEMENT *)(ptr[4] & ~1);
1677 LINK_ELEMENT *e;
1678
1679 enum rb_catch_type ct = (enum rb_catch_type)(ptr[0] & 0xffff);
1680
1681 if (ct != CATCH_TYPE_BREAK
1682 && ct != CATCH_TYPE_NEXT
1683 && ct != CATCH_TYPE_REDO) {
1684
1685 for (e = end; e && (IS_LABEL(e) || IS_TRACE(e)); e = e->next) {
1686 if (e == cont) {
1687 INSN *nop = new_insn_core(iseq, 0, -1, BIN(nop), 0, 0);
1688 ELEM_INSERT_NEXT(end, &nop->link);
1689 break;
1690 }
1691 }
1692 }
1693 }
1694
1695 RB_GC_GUARD(catch_table_ary);
1696}
1697
1698static int
1699iseq_setup_insn(rb_iseq_t *iseq, LINK_ANCHOR *const anchor)
1700{
1701 if (RTEST(ISEQ_COMPILE_DATA(iseq)->err_info))
1702 return COMPILE_NG;
1703
1704 /* debugs("[compile step 2] (iseq_array_to_linkedlist)\n"); */
1705
1706 if (compile_debug > 5)
1707 dump_disasm_list(FIRST_ELEMENT(anchor));
1708
1709 debugs("[compile step 3.1 (iseq_optimize)]\n");
1710 iseq_optimize(iseq, anchor);
1711
1712 if (compile_debug > 5)
1713 dump_disasm_list(FIRST_ELEMENT(anchor));
1714
1715 if (ISEQ_COMPILE_DATA(iseq)->option->instructions_unification) {
1716 debugs("[compile step 3.2 (iseq_insns_unification)]\n");
1717 iseq_insns_unification(iseq, anchor);
1718 if (compile_debug > 5)
1719 dump_disasm_list(FIRST_ELEMENT(anchor));
1720 }
1721
1722 debugs("[compile step 3.4 (iseq_insert_nop_between_end_and_cont)]\n");
1723 iseq_insert_nop_between_end_and_cont(iseq);
1724 if (compile_debug > 5)
1725 dump_disasm_list(FIRST_ELEMENT(anchor));
1726
1727 return COMPILE_OK;
1728}
1729
1730static int
1731iseq_setup(rb_iseq_t *iseq, LINK_ANCHOR *const anchor)
1732{
1733 if (RTEST(ISEQ_COMPILE_DATA(iseq)->err_info))
1734 return COMPILE_NG;
1735
1736 debugs("[compile step 4.1 (iseq_set_sequence)]\n");
1737 if (!iseq_set_sequence(iseq, anchor)) return COMPILE_NG;
1738 if (compile_debug > 5)
1739 dump_disasm_list(FIRST_ELEMENT(anchor));
1740
1741 debugs("[compile step 4.2 (iseq_set_exception_table)]\n");
1742 if (!iseq_set_exception_table(iseq)) return COMPILE_NG;
1743
1744 debugs("[compile step 4.3 (set_optargs_table)] \n");
1745 if (!iseq_set_optargs_table(iseq)) return COMPILE_NG;
1746
1747 debugs("[compile step 5 (iseq_translate_threaded_code)] \n");
1748 if (!rb_iseq_translate_threaded_code(iseq)) return COMPILE_NG;
1749
1750 debugs("[compile step 6 (update_catch_except_flags)] \n");
1751 RUBY_ASSERT(ISEQ_COMPILE_DATA(iseq));
1752 update_catch_except_flags(iseq, ISEQ_BODY(iseq));
1753
1754 debugs("[compile step 6.1 (remove unused catch tables)] \n");
1755 RUBY_ASSERT(ISEQ_COMPILE_DATA(iseq));
1756 if (!ISEQ_COMPILE_DATA(iseq)->catch_except_p && ISEQ_BODY(iseq)->catch_table) {
1757 ruby_xfree_sized(ISEQ_BODY(iseq)->catch_table, iseq_catch_table_bytes(ISEQ_BODY(iseq)->catch_table->size));
1758 ISEQ_BODY(iseq)->catch_table = NULL;
1759 }
1760
1761 if (compile_debug > 1) {
1762 VALUE str = rb_iseq_disasm(iseq);
1763 printf("%s\n", StringValueCStr(str));
1764 }
1765 verify_call_cache(iseq);
1766 debugs("[compile step: finish]\n");
1767
1768 return COMPILE_OK;
1769}
1770
1771static int
1772iseq_set_exception_local_table(rb_iseq_t *iseq)
1773{
1774 ISEQ_BODY(iseq)->local_table_size = numberof(rb_iseq_shared_exc_local_tbl);
1775 ISEQ_BODY(iseq)->local_table = rb_iseq_shared_exc_local_tbl;
1776 ISEQ_BODY(iseq)->lvar_states.list = NULL; // $! is read-only, so don't need lvar_states
1777 return COMPILE_OK;
1778}
1779
1780static int
1781get_lvar_level(const rb_iseq_t *iseq)
1782{
1783 int lev = 0;
1784 while (iseq != ISEQ_BODY(iseq)->local_iseq) {
1785 lev++;
1786 iseq = ISEQ_BODY(iseq)->parent_iseq;
1787 }
1788 return lev;
1789}
1790
1791static int
1792get_dyna_var_idx_at_raw(const rb_iseq_t *iseq, ID id)
1793{
1794 unsigned int i;
1795
1796 for (i = 0; i < ISEQ_BODY(iseq)->local_table_size; i++) {
1797 if (ISEQ_BODY(iseq)->local_table[i] == id) {
1798 return (int)i;
1799 }
1800 }
1801 return -1;
1802}
1803
1804static int
1805get_local_var_idx(const rb_iseq_t *iseq, ID id)
1806{
1807 int idx = get_dyna_var_idx_at_raw(ISEQ_BODY(iseq)->local_iseq, id);
1808
1809 if (idx < 0) {
1810 COMPILE_ERROR(iseq, ISEQ_LAST_LINE(iseq),
1811 "get_local_var_idx: %d", idx);
1812 }
1813
1814 return idx;
1815}
1816
1817static int
1818get_dyna_var_idx(const rb_iseq_t *iseq, ID id, int *level, int *ls)
1819{
1820 int lv = 0, idx = -1;
1821 const rb_iseq_t *const topmost_iseq = iseq;
1822
1823 while (iseq) {
1824 idx = get_dyna_var_idx_at_raw(iseq, id);
1825 if (idx >= 0) {
1826 break;
1827 }
1828 iseq = ISEQ_BODY(iseq)->parent_iseq;
1829 lv++;
1830 }
1831
1832 if (idx < 0) {
1833 COMPILE_ERROR(topmost_iseq, ISEQ_LAST_LINE(topmost_iseq),
1834 "get_dyna_var_idx: -1");
1835 }
1836
1837 *level = lv;
1838 *ls = ISEQ_BODY(iseq)->local_table_size;
1839 return idx;
1840}
1841
1842static int
1843iseq_local_block_param_p(const rb_iseq_t *iseq, unsigned int idx, unsigned int level)
1844{
1845 const struct rb_iseq_constant_body *body;
1846 while (level > 0) {
1847 iseq = ISEQ_BODY(iseq)->parent_iseq;
1848 level--;
1849 }
1850 body = ISEQ_BODY(iseq);
1851 if (body->local_iseq == iseq && /* local variables */
1852 body->param.flags.has_block &&
1853 body->local_table_size - body->param.block_start == idx) {
1854 return TRUE;
1855 }
1856 else {
1857 return FALSE;
1858 }
1859}
1860
1861static int
1862iseq_block_param_id_p(const rb_iseq_t *iseq, ID id, int *pidx, int *plevel)
1863{
1864 int level, ls;
1865 int idx = get_dyna_var_idx(iseq, id, &level, &ls);
1866 if (iseq_local_block_param_p(iseq, ls - idx, level)) {
1867 *pidx = ls - idx;
1868 *plevel = level;
1869 return TRUE;
1870 }
1871 else {
1872 return FALSE;
1873 }
1874}
1875
1876static void
1877access_outer_variables(const rb_iseq_t *iseq, int level, ID id, bool write)
1878{
1879 int isolated_depth = ISEQ_COMPILE_DATA(iseq)->isolated_depth;
1880
1881 if (isolated_depth && level >= isolated_depth) {
1882 if (id == rb_intern("yield")) {
1883 COMPILE_ERROR(iseq, ISEQ_LAST_LINE(iseq), "can not yield from isolated Proc");
1884 }
1885 else {
1886 COMPILE_ERROR(iseq, ISEQ_LAST_LINE(iseq), "can not access variable '%s' from isolated Proc", rb_id2name(id));
1887 }
1888 }
1889
1890 for (int i=0; i<level; i++) {
1891 VALUE val;
1892 struct rb_id_table *ovs = ISEQ_BODY(iseq)->outer_variables;
1893
1894 if (!ovs) {
1895 ovs = ISEQ_BODY(iseq)->outer_variables = rb_id_table_create(8);
1896 }
1897
1898 if (rb_id_table_lookup(ISEQ_BODY(iseq)->outer_variables, id, &val)) {
1899 if (write && !val) {
1900 rb_id_table_insert(ISEQ_BODY(iseq)->outer_variables, id, Qtrue);
1901 }
1902 }
1903 else {
1904 rb_id_table_insert(ISEQ_BODY(iseq)->outer_variables, id, RBOOL(write));
1905 }
1906
1907 iseq = ISEQ_BODY(iseq)->parent_iseq;
1908 }
1909}
1910
1911static ID
1912iseq_lvar_id(const rb_iseq_t *iseq, int idx, int level)
1913{
1914 for (int i=0; i<level; i++) {
1915 iseq = ISEQ_BODY(iseq)->parent_iseq;
1916 }
1917
1918 ID id = ISEQ_BODY(iseq)->local_table[ISEQ_BODY(iseq)->local_table_size - idx];
1919 // fprintf(stderr, "idx:%d level:%d ID:%s\n", idx, level, rb_id2name(id));
1920 return id;
1921}
1922
1923static void
1924update_lvar_state(const rb_iseq_t *iseq, int level, int idx)
1925{
1926 for (int i=0; i<level; i++) {
1927 iseq = ISEQ_BODY(iseq)->parent_iseq;
1928 }
1929
1930 uint8_t *states = iseq_lvar_states(ISEQ_BODY(iseq));
1931 int table_idx = ISEQ_BODY(iseq)->local_table_size - idx;
1932 switch (iseq_lvar_state_get(states, table_idx)) {
1933 case lvar_uninitialized:
1934 iseq_lvar_state_set(states, table_idx, lvar_initialized);
1935 break;
1936 case lvar_initialized:
1937 iseq_lvar_state_set(states, table_idx, lvar_reassigned);
1938 break;
1939 case lvar_reassigned:
1940 /* nothing */
1941 break;
1942 default:
1943 rb_bug("unreachable");
1944 }
1945}
1946
1947static int
1948iseq_set_parameters_lvar_state(const rb_iseq_t *iseq)
1949{
1950 uint8_t *states = iseq_lvar_states(ISEQ_BODY(iseq));
1951
1952 for (unsigned int i=0; i<ISEQ_BODY(iseq)->param.size; i++) {
1953 iseq_lvar_state_set(states, i, lvar_initialized);
1954 }
1955
1956 int lead_num = ISEQ_BODY(iseq)->param.lead_num;
1957 int opt_num = ISEQ_BODY(iseq)->param.opt_num;
1958 for (int i=0; i<opt_num; i++) {
1959 iseq_lvar_state_set(states, lead_num + i, lvar_uninitialized);
1960 }
1961
1962 return COMPILE_OK;
1963}
1964
1965static void
1966iseq_add_getlocal(rb_iseq_t *iseq, LINK_ANCHOR *const seq, const NODE *const line_node, int idx, int level)
1967{
1968 if (iseq_local_block_param_p(iseq, idx, level)) {
1969 ADD_INSN2(seq, line_node, getblockparam, INT2FIX((idx) + VM_ENV_DATA_SIZE - 1), INT2FIX(level));
1970 }
1971 else {
1972 ADD_INSN2(seq, line_node, getlocal, INT2FIX((idx) + VM_ENV_DATA_SIZE - 1), INT2FIX(level));
1973 }
1974 if (level > 0) access_outer_variables(iseq, level, iseq_lvar_id(iseq, idx, level), Qfalse);
1975}
1976
1977static void
1978iseq_add_setlocal(rb_iseq_t *iseq, LINK_ANCHOR *const seq, const NODE *const line_node, int idx, int level)
1979{
1980 if (iseq_local_block_param_p(iseq, idx, level)) {
1981 ADD_INSN2(seq, line_node, setblockparam, INT2FIX((idx) + VM_ENV_DATA_SIZE - 1), INT2FIX(level));
1982 }
1983 else {
1984 ADD_INSN2(seq, line_node, setlocal, INT2FIX((idx) + VM_ENV_DATA_SIZE - 1), INT2FIX(level));
1985 }
1986 update_lvar_state(iseq, level, idx);
1987 if (level > 0) access_outer_variables(iseq, level, iseq_lvar_id(iseq, idx, level), Qtrue);
1988}
1989
1990
1991
1992static void
1993iseq_calc_param_size(rb_iseq_t *iseq)
1994{
1995 struct rb_iseq_constant_body *const body = ISEQ_BODY(iseq);
1996 if (body->param.flags.has_opt ||
1997 body->param.flags.has_post ||
1998 body->param.flags.has_rest ||
1999 body->param.flags.has_block ||
2000 body->param.flags.has_kw ||
2001 body->param.flags.has_kwrest) {
2002
2003 if (body->param.flags.has_block) {
2004 body->param.size = body->param.block_start + 1;
2005 }
2006 else if (body->param.flags.has_kwrest) {
2007 body->param.size = body->param.keyword->rest_start + 1;
2008 }
2009 else if (body->param.flags.has_kw) {
2010 body->param.size = body->param.keyword->bits_start + 1;
2011 }
2012 else if (body->param.flags.has_post) {
2013 body->param.size = rb_iseq_param_post_start(body) + body->param.post_num;
2014 }
2015 else if (body->param.flags.has_rest) {
2016 body->param.size = rb_iseq_param_rest_start(body) + 1;
2017 }
2018 else if (body->param.flags.has_opt) {
2019 body->param.size = body->param.lead_num + body->param.opt_num;
2020 }
2021 else {
2023 }
2024 }
2025 else {
2026 body->param.size = body->param.lead_num;
2027 }
2028}
2029
2030static int
2031iseq_set_arguments_keywords(rb_iseq_t *iseq, LINK_ANCHOR *const optargs,
2032 const struct rb_args_info *args, int arg_size)
2033{
2034 const rb_node_kw_arg_t *node = args->kw_args;
2035 struct rb_iseq_constant_body *const body = ISEQ_BODY(iseq);
2036 struct rb_iseq_param_keyword *keyword;
2037 const VALUE default_values = rb_ary_hidden_new(1);
2038 const VALUE complex_mark = rb_str_tmp_new(0);
2039 int kw = 0, rkw = 0, i;
2040
2041 body->param.flags.has_kw = TRUE;
2042 body->param.keyword = keyword = ZALLOC_N(struct rb_iseq_param_keyword, 1);
2043
2044 while (node) {
2045 kw++;
2046 if (get_nd_value(node->nd_body) == NODE_SPECIAL_REQUIRED_KEYWORD) {
2047 rkw++;
2048 }
2049 node = node->nd_next;
2050 }
2051 if (kw > VM_CALL_KW_LEN_MAX) {
2052 COMPILE_ERROR(ERROR_ARGS_AT(RNODE(args->kw_args)) "too many keyword parameters (%d, maximum is %d)",
2053 kw, (int)VM_CALL_KW_LEN_MAX);
2054 }
2055 arg_size += kw;
2056 keyword->bits_start = arg_size++;
2057 keyword->num = kw;
2058 keyword->required_num = rkw;
2059 keyword->table = &body->local_table[keyword->bits_start - keyword->num];
2060
2061 if (RNODE_DVAR(args->kw_rest_arg)->nd_vid != 0) {
2062 ID kw_id = ISEQ_BODY(iseq)->local_table[arg_size];
2063 keyword->rest_start = arg_size++;
2064 body->param.flags.has_kwrest = TRUE;
2065
2066 if (kw_id == idPow) body->param.flags.anon_kwrest = TRUE;
2067 }
2068
2069 node = args->kw_args;
2070 while (node) {
2071 const NODE *val_node = get_nd_value(node->nd_body);
2072 VALUE dv;
2073
2074 if (val_node != NODE_SPECIAL_REQUIRED_KEYWORD) {
2075 switch (nd_type(val_node)) {
2076 case NODE_SYM:
2077 dv = rb_node_sym_string_val(val_node);
2078 break;
2079 case NODE_REGX:
2080 dv = rb_node_regx_string_val(val_node);
2081 break;
2082 case NODE_LINE:
2083 dv = rb_node_line_lineno_val(val_node);
2084 break;
2085 case NODE_INTEGER:
2086 dv = rb_node_integer_literal_val(val_node);
2087 break;
2088 case NODE_FLOAT:
2089 dv = rb_node_float_literal_val(val_node);
2090 break;
2091 case NODE_RATIONAL:
2092 dv = rb_node_rational_literal_val(val_node);
2093 break;
2094 case NODE_IMAGINARY:
2095 dv = rb_node_imaginary_literal_val(val_node);
2096 break;
2097 case NODE_ENCODING:
2098 dv = rb_node_encoding_val(val_node);
2099 break;
2100 case NODE_NIL:
2101 dv = Qnil;
2102 break;
2103 case NODE_TRUE:
2104 dv = Qtrue;
2105 break;
2106 case NODE_FALSE:
2107 dv = Qfalse;
2108 break;
2109 default:
2110 NO_CHECK(COMPILE_POPPED(optargs, "kwarg", RNODE(node))); /* nd_type_p(node, NODE_KW_ARG) */
2111 dv = complex_mark;
2112 }
2113
2114 rb_ary_push(default_values, dv);
2115 }
2116
2117 node = node->nd_next;
2118 }
2119
2120 if (RARRAY_LEN(default_values)) {
2121 VALUE *dvs = ALLOC_N(VALUE, RARRAY_LEN(default_values));
2122
2123 for (i = 0; i < RARRAY_LEN(default_values); i++) {
2124 VALUE dv = RARRAY_AREF(default_values, i);
2125 if (dv == complex_mark) dv = Qundef;
2127 RB_OBJ_WRITE(iseq, &dvs[i], dv);
2128 }
2129
2130 keyword->default_values = dvs;
2131 }
2132 return arg_size;
2133}
2134
2135static void
2136iseq_set_use_block(rb_iseq_t *iseq)
2137{
2138 struct rb_iseq_constant_body *const body = ISEQ_BODY(iseq);
2139 if (!body->param.flags.use_block) {
2140 body->param.flags.use_block = 1;
2141
2142 rb_vm_t *vm = GET_VM();
2143
2144 if (!rb_warning_category_enabled_p(RB_WARN_CATEGORY_STRICT_UNUSED_BLOCK)) {
2145 st_data_t key = (st_data_t)rb_intern_str(body->location.label); // String -> ID
2146 set_insert(&vm->unused_block_warning_table, key);
2147 }
2148 }
2149}
2150
2151static int
2152iseq_set_arguments(rb_iseq_t *iseq, LINK_ANCHOR *const optargs, const NODE *const node_args)
2153{
2154 debugs("iseq_set_arguments: %s\n", node_args ? "" : "0");
2155
2156 if (node_args) {
2157 struct rb_iseq_constant_body *const body = ISEQ_BODY(iseq);
2158 const struct rb_args_info *const args = &RNODE_ARGS(node_args)->nd_ainfo;
2159 ID rest_id = 0;
2160 int last_comma = 0;
2161 ID block_id = 0;
2162 int arg_size;
2163
2164 EXPECT_NODE("iseq_set_arguments", node_args, NODE_ARGS, COMPILE_NG);
2165
2166 body->param.lead_num = arg_size = (int)args->pre_args_num;
2167 if (body->param.lead_num > 0) body->param.flags.has_lead = TRUE;
2168 debugs(" - argc: %d\n", body->param.lead_num);
2169
2170 rest_id = args->rest_arg;
2171 if (rest_id == NODE_SPECIAL_EXCESSIVE_COMMA) {
2172 last_comma = 1;
2173 rest_id = 0;
2174 }
2175 block_id = args->block_arg;
2176
2177 bool optimized_forward = (args->forwarding && args->pre_args_num == 0 && !args->opt_args);
2178
2179 if (optimized_forward) {
2180 rest_id = 0;
2181 block_id = 0;
2182 }
2183
2184 if (args->opt_args) {
2185 const rb_node_opt_arg_t *node = args->opt_args;
2186 LABEL *label;
2187 VALUE labels = rb_ary_hidden_new(1);
2188 VALUE *opt_table;
2189 int i = 0, j;
2190
2191 while (node) {
2192 label = NEW_LABEL(nd_line(RNODE(node)));
2193 rb_ary_push(labels, (VALUE)label | 1);
2194 ADD_LABEL(optargs, label);
2195 NO_CHECK(COMPILE_POPPED(optargs, "optarg", node->nd_body));
2196 node = node->nd_next;
2197 i += 1;
2198 }
2199
2200 /* last label */
2201 label = NEW_LABEL(nd_line(node_args));
2202 rb_ary_push(labels, (VALUE)label | 1);
2203 ADD_LABEL(optargs, label);
2204
2205 opt_table = ALLOC_N(VALUE, i+1);
2206
2207 MEMCPY(opt_table, RARRAY_CONST_PTR(labels), VALUE, i+1);
2208 for (j = 0; j < i+1; j++) {
2209 opt_table[j] &= ~1;
2210 }
2211 rb_ary_clear(labels);
2212
2213 body->param.flags.has_opt = TRUE;
2214 body->param.opt_num = i;
2215 body->param.opt_table = opt_table;
2216 arg_size += i;
2217 }
2218
2219 if (rest_id) {
2220 RUBY_ASSERT(rb_iseq_param_rest_start(body) == arg_size);
2221 arg_size++;
2222 body->param.flags.has_rest = TRUE;
2223 if (rest_id == '*') body->param.flags.anon_rest = TRUE;
2224 }
2225
2226 if (args->first_post_arg) {
2227 RUBY_ASSERT(rb_iseq_param_post_start(body) == arg_size);
2228 body->param.post_num = args->post_args_num;
2229 body->param.flags.has_post = TRUE;
2230 arg_size += args->post_args_num;
2231 }
2232
2233 if (args->kw_args) {
2234 arg_size = iseq_set_arguments_keywords(iseq, optargs, args, arg_size);
2235 }
2236 else if (args->kw_rest_arg && !optimized_forward) {
2237 ID kw_id = ISEQ_BODY(iseq)->local_table[arg_size];
2238 struct rb_iseq_param_keyword *keyword = ZALLOC_N(struct rb_iseq_param_keyword, 1);
2239 keyword->rest_start = arg_size++;
2240 body->param.keyword = keyword;
2241 body->param.flags.has_kwrest = TRUE;
2242
2243 static ID anon_kwrest = 0;
2244 if (!anon_kwrest) anon_kwrest = rb_intern("**");
2245 if (kw_id == anon_kwrest) body->param.flags.anon_kwrest = TRUE;
2246 }
2247 else if (args->no_kwarg) {
2248 body->param.flags.accepts_no_kwarg = TRUE;
2249 }
2250
2251 if (args->no_blockarg) {
2252 body->param.flags.accepts_no_block = TRUE;
2253 }
2254 else if (block_id) {
2255 body->param.block_start = arg_size++;
2256 body->param.flags.has_block = TRUE;
2257 iseq_set_use_block(iseq);
2258 }
2259
2260 // Only optimize specifically methods like this: `foo(...)`
2261 if (optimized_forward) {
2262 body->param.flags.use_block = 1;
2263 body->param.flags.forwardable = TRUE;
2264 arg_size = 1;
2265 }
2266
2267 iseq_calc_param_size(iseq);
2268 body->param.size = arg_size;
2269
2270 if (args->pre_init) { /* m_init */
2271 NO_CHECK(COMPILE_POPPED(optargs, "init arguments (m)", args->pre_init));
2272 }
2273 if (args->post_init) { /* p_init */
2274 NO_CHECK(COMPILE_POPPED(optargs, "init arguments (p)", args->post_init));
2275 }
2276
2277 if (body->type == ISEQ_TYPE_BLOCK) {
2278 if (body->param.flags.has_opt == FALSE &&
2279 body->param.flags.has_post == FALSE &&
2280 body->param.flags.has_rest == FALSE &&
2281 body->param.flags.has_kw == FALSE &&
2282 body->param.flags.has_kwrest == FALSE) {
2283
2284 if (body->param.lead_num == 1 && last_comma == 0) {
2285 /* {|a|} */
2286 body->param.flags.ambiguous_param0 = TRUE;
2287 }
2288 }
2289 }
2290 }
2291
2292 return COMPILE_OK;
2293}
2294
2295static int
2296iseq_set_local_table(rb_iseq_t *iseq, const rb_ast_id_table_t *tbl, const NODE *const node_args)
2297{
2298 unsigned int size = tbl ? tbl->size : 0;
2299 unsigned int offset = 0;
2300
2301 if (node_args) {
2302 struct rb_args_info *args = &RNODE_ARGS(node_args)->nd_ainfo;
2303
2304 // If we have a function that only has `...` as the parameter,
2305 // then its local table should only be `...`
2306 // FIXME: I think this should be fixed in the AST rather than special case here.
2307 if (args->forwarding && args->pre_args_num == 0 && !args->opt_args) {
2308 CHECK(size >= 3);
2309 size -= 3;
2310 offset += 3;
2311 }
2312 }
2313
2314 if (size > 0) {
2315 ID *ids = ALLOC_N(ID, size);
2316 MEMCPY(ids, tbl->ids + offset, ID, size);
2317 ISEQ_BODY(iseq)->local_table = ids;
2318
2319 if (ISEQ_LVAR_STATES_EMBED_P(size)) {
2320 /* states are embedded in the body; zero them out */
2321 memset(ISEQ_BODY(iseq)->lvar_states.single, 0, sizeof(ISEQ_BODY(iseq)->lvar_states.single));
2322 }
2323 else {
2324 ISEQ_BODY(iseq)->lvar_states.list = ZALLOC_N(uint8_t, ISEQ_LVAR_STATES_BUFLEN(size));
2325 }
2326 }
2327 ISEQ_BODY(iseq)->local_table_size = size;
2328
2329 debugs("iseq_set_local_table: %u\n", ISEQ_BODY(iseq)->local_table_size);
2330 return COMPILE_OK;
2331}
2332
2333int
2334rb_iseq_cdhash_cmp(VALUE val, VALUE lit)
2335{
2336 int tval, tlit;
2337
2338 if (val == lit) {
2339 return 0;
2340 }
2341 else if ((tlit = OBJ_BUILTIN_TYPE(lit)) == -1) {
2342 return val != lit;
2343 }
2344 else if ((tval = OBJ_BUILTIN_TYPE(val)) == -1) {
2345 return -1;
2346 }
2347 else if (tlit != tval) {
2348 return -1;
2349 }
2350 else if (tlit == T_SYMBOL) {
2351 return val != lit;
2352 }
2353 else if (tlit == T_STRING) {
2354 return rb_str_hash_cmp(lit, val);
2355 }
2356 else if (tlit == T_BIGNUM) {
2357 long x = FIX2LONG(rb_big_cmp(lit, val));
2358
2359 /* Given lit and val are both Bignum, x must be -1, 0, 1.
2360 * There is no need to call rb_fix2int here. */
2361 RUBY_ASSERT((x == 1) || (x == 0) || (x == -1));
2362 return (int)x;
2363 }
2364 else if (tlit == T_FLOAT) {
2365 return rb_float_cmp(lit, val);
2366 }
2367 else if (tlit == T_RATIONAL) {
2368 const struct RRational *rat1 = RRATIONAL(val);
2369 const struct RRational *rat2 = RRATIONAL(lit);
2370 return rb_iseq_cdhash_cmp(rat1->num, rat2->num) || rb_iseq_cdhash_cmp(rat1->den, rat2->den);
2371 }
2372 else if (tlit == T_COMPLEX) {
2373 const struct RComplex *comp1 = RCOMPLEX(val);
2374 const struct RComplex *comp2 = RCOMPLEX(lit);
2375 return rb_iseq_cdhash_cmp(comp1->real, comp2->real) || rb_iseq_cdhash_cmp(comp1->imag, comp2->imag);
2376 }
2377 else if (tlit == T_REGEXP) {
2378 return rb_reg_equal(val, lit) ? 0 : -1;
2379 }
2380 else {
2382 }
2383}
2384
2385st_index_t
2386rb_iseq_cdhash_hash(VALUE a)
2387{
2388 switch (OBJ_BUILTIN_TYPE(a)) {
2389 case -1:
2390 case T_SYMBOL:
2391 return (st_index_t)a;
2392 case T_STRING:
2393 return rb_str_hash(a);
2394 case T_BIGNUM:
2395 return FIX2LONG(rb_big_hash(a));
2396 case T_FLOAT:
2397 return rb_dbl_long_hash(RFLOAT_VALUE(a));
2398 case T_RATIONAL:
2399 return rb_rational_hash(a);
2400 case T_COMPLEX:
2401 return rb_complex_hash(a);
2402 case T_REGEXP:
2403 return NUM2LONG(rb_reg_hash(a));
2404 default:
2406 }
2407}
2408
2409static const struct st_hash_type cdhash_type = {
2410 rb_iseq_cdhash_cmp,
2411 rb_iseq_cdhash_hash,
2412};
2413
2414static VALUE
2415cdhash_new(size_t size)
2416{
2417 VALUE cdhash = rb_imemo_cdhash_new(size, &cdhash_type);
2418 RB_OBJ_SET_SHAREABLE(cdhash);
2419 return cdhash;
2420}
2421
2422static void
2423cdhash_aset(VALUE cdhash, VALUE key, VALUE val)
2424{
2425 st_table *tbl = rb_imemo_cdhash_tbl(cdhash);
2426 st_insert(tbl, key, val);
2427 RB_OBJ_WRITTEN(cdhash, Qundef, key);
2428}
2429
2430static void
2431cdhash_aset_if_missing(VALUE cdhash, VALUE key, VALUE val)
2432{
2433 st_table *tbl = rb_imemo_cdhash_tbl(cdhash);
2434 VALUE dontcare;
2435 if (!st_lookup(tbl, key, &dontcare)) {
2436 st_insert(tbl, key, val);
2437 RB_OBJ_WRITTEN(cdhash, Qundef, key);
2438 }
2439}
2440
2442 VALUE hash;
2443 int pos;
2444 int len;
2445};
2446
2447static int
2448cdhash_set_label_check_i(st_data_t key, st_data_t value, st_data_t argp, int error)
2449{
2450 return ST_REPLACE;
2451}
2452
2453static int
2454cdhash_set_label_replace_i(st_data_t *key, st_data_t *value, st_data_t ptr, int existing)
2455{
2456 struct cdhash_set_label_struct *data = (struct cdhash_set_label_struct *)ptr;
2457 LABEL *lobj = (LABEL *)(*value & ~1);
2458 *value = lobj->position - (data->pos+data->len);
2459 return ST_CONTINUE;
2460}
2461
2462static inline VALUE
2463get_ivar_ic_value(rb_iseq_t *iseq,ID id)
2464{
2465 return INT2FIX(ISEQ_BODY(iseq)->ivc_size++);
2466}
2467
2468static inline VALUE
2469get_cvar_ic_value(rb_iseq_t *iseq,ID id)
2470{
2471 VALUE val;
2472 struct rb_id_table *tbl = ISEQ_COMPILE_DATA(iseq)->ivar_cache_table;
2473 if (tbl) {
2474 if (rb_id_table_lookup(tbl,id,&val)) {
2475 return val;
2476 }
2477 }
2478 else {
2479 tbl = rb_id_table_create(1);
2480 ISEQ_COMPILE_DATA(iseq)->ivar_cache_table = tbl;
2481 }
2482 val = INT2FIX(ISEQ_BODY(iseq)->icvarc_size++);
2483 rb_id_table_insert(tbl,id,val);
2484 return val;
2485}
2486
2487#define BADINSN_DUMP(anchor, list, dest) \
2488 dump_disasm_list_with_cursor(FIRST_ELEMENT(anchor), list, dest)
2489
2490#define BADINSN_ERROR \
2491 (SIZED_FREE_N(generated_iseq, generated_iseq_size), \
2492 BADINSN_DUMP(anchor, list, NULL), \
2493 COMPILE_ERROR)
2494
2495static int
2496fix_sp_depth(rb_iseq_t *iseq, LINK_ANCHOR *const anchor)
2497{
2498 int stack_max = 0, sp = 0, line = 0;
2499 LINK_ELEMENT *list;
2500
2501 for (list = FIRST_ELEMENT(anchor); list; list = list->next) {
2502 if (IS_LABEL(list)) {
2503 LABEL *lobj = (LABEL *)list;
2504 lobj->set = TRUE;
2505 }
2506 }
2507
2508 for (list = FIRST_ELEMENT(anchor); list; list = list->next) {
2509 switch (list->type) {
2510 case ISEQ_ELEMENT_INSN:
2511 {
2512 int j, len, insn;
2513 const char *types;
2514 VALUE *operands;
2515 INSN *iobj = (INSN *)list;
2516
2517 /* update sp */
2518 sp = calc_sp_depth(sp, iobj);
2519 if (sp < 0) {
2520 BADINSN_DUMP(anchor, list, NULL);
2521 COMPILE_ERROR(iseq, iobj->insn_info.line_no,
2522 "argument stack underflow (%d)", sp);
2523 return -1;
2524 }
2525 if (sp > stack_max) {
2526 stack_max = sp;
2527 }
2528
2529 line = iobj->insn_info.line_no;
2530 /* fprintf(stderr, "insn: %-16s, sp: %d\n", insn_name(iobj->insn_id), sp); */
2531 operands = iobj->operands;
2532 insn = iobj->insn_id;
2533 types = insn_op_types(insn);
2534 len = insn_len(insn);
2535
2536 /* operand check */
2537 if (iobj->operand_size != len - 1) {
2538 /* printf("operand size miss! (%d, %d)\n", iobj->operand_size, len); */
2539 BADINSN_DUMP(anchor, list, NULL);
2540 COMPILE_ERROR(iseq, iobj->insn_info.line_no,
2541 "operand size miss! (%d for %d)",
2542 iobj->operand_size, len - 1);
2543 return -1;
2544 }
2545
2546 for (j = 0; types[j]; j++) {
2547 if (types[j] == TS_OFFSET) {
2548 /* label(destination position) */
2549 LABEL *lobj = (LABEL *)operands[j];
2550 if (!lobj->set) {
2551 BADINSN_DUMP(anchor, list, NULL);
2552 COMPILE_ERROR(iseq, iobj->insn_info.line_no,
2553 "unknown label: "LABEL_FORMAT, lobj->label_no);
2554 return -1;
2555 }
2556 if (lobj->sp == -1) {
2557 lobj->sp = sp;
2558 }
2559 else if (lobj->sp != sp) {
2560 VALUE path = rb_iseq_path(iseq);
2561 debugs("%.*s:%d: sp inconsistency found but ignored (" LABEL_FORMAT " sp: %d, calculated sp: %d)\n",
2562 RSTRING_LENINT(path), RSTRING_PTR(path), line,
2563 lobj->label_no, lobj->sp, sp);
2564 }
2565 }
2566 }
2567 break;
2568 }
2569 case ISEQ_ELEMENT_LABEL:
2570 {
2571 LABEL *lobj = (LABEL *)list;
2572 if (lobj->sp == -1) {
2573 lobj->sp = sp;
2574 }
2575 else {
2576 if (lobj->sp != sp) {
2577 VALUE path = rb_iseq_path(iseq);
2578 debugs("%.*s:%d: sp inconsistency found but ignored (" LABEL_FORMAT " sp: %d, calculated sp: %d)\n",
2579 RSTRING_LENINT(path), RSTRING_PTR(path), line,
2580 lobj->label_no, lobj->sp, sp);
2581 }
2582 sp = lobj->sp;
2583 }
2584 break;
2585 }
2586 case ISEQ_ELEMENT_TRACE:
2587 {
2588 /* ignore */
2589 break;
2590 }
2591 case ISEQ_ELEMENT_ADJUST:
2592 {
2593 ADJUST *adjust = (ADJUST *)list;
2594 int orig_sp = sp;
2595
2596 sp = adjust->label ? adjust->label->sp : 0;
2597 if (adjust->line_no != -1 && orig_sp - sp < 0) {
2598 BADINSN_DUMP(anchor, list, NULL);
2599 COMPILE_ERROR(iseq, adjust->line_no,
2600 "iseq_set_sequence: adjust bug %d < %d",
2601 orig_sp, sp);
2602 return -1;
2603 }
2604 break;
2605 }
2606 default:
2607 BADINSN_DUMP(anchor, list, NULL);
2608 COMPILE_ERROR(iseq, line, "unknown list type: %d", list->type);
2609 return -1;
2610 }
2611 }
2612 return stack_max;
2613}
2614
2615static void
2616add_node_id(uint8_t *node_ids, unsigned int *node_ids_size, int node_id, int *prev_node_id)
2617{
2618 int delta = node_id - *prev_node_id;
2619 uint32_t zz = ((uint32_t)delta << 1) ^ (uint32_t)(delta >> 31);
2620 *prev_node_id = node_id;
2621 do {
2622 uint8_t byte = zz & 0x7f;
2623 zz >>= 7;
2624 node_ids[(*node_ids_size)++] = zz ? (byte | 0x80) : byte;
2625 } while (zz);
2626}
2627
2628static int
2629add_insn_info(struct iseq_insn_info_entry *insns_info, unsigned int *positions,
2630 int insns_info_index, int code_index, const INSN *iobj)
2631{
2632 if (insns_info_index == 0 ||
2633 insns_info[insns_info_index-1].line_no != iobj->insn_info.line_no ||
2634 insns_info[insns_info_index-1].events != iobj->insn_info.events) {
2635 insns_info[insns_info_index].line_no = iobj->insn_info.line_no;
2636 insns_info[insns_info_index].events = iobj->insn_info.events;
2637 positions[insns_info_index] = code_index;
2638 return TRUE;
2639 }
2640 return FALSE;
2641}
2642
2643static int
2644add_adjust_info(struct iseq_insn_info_entry *insns_info, unsigned int *positions,
2645 int insns_info_index, int code_index, const ADJUST *adjust)
2646{
2647 insns_info[insns_info_index].line_no = adjust->line_no;
2648 insns_info[insns_info_index].events = 0;
2649 positions[insns_info_index] = code_index;
2650 return TRUE;
2651}
2652
2653struct ic_site {
2654 rb_const_path_t path;
2655 unsigned int index;
2656};
2657
2658static unsigned int
2659dedup_const_path_ics(struct ic_site *sites, unsigned int count)
2660{
2661 unsigned int distinct = 0;
2662
2663 if (count <= 32) {
2664 for (unsigned int i = 0; i < count; i++) {
2665 unsigned int j;
2666 for (j = 0; j < i; j++) {
2667 if (sites[i].path == sites[j].path) {
2668 break;
2669 }
2670 }
2671
2672 if (j == i) { // no match
2673 sites[i].index = distinct++;
2674 }
2675 else { // match
2676 sites[i].index = sites[j].index;
2677 }
2678 }
2679 }
2680 else {
2681 st_table table;
2682 st_init_existing_numtable_with_size(&table, count);
2683
2684 for (unsigned int i = 0; i < count; i++) {
2685 st_data_t index;
2686 if (!st_lookup(&table, (st_data_t)sites[i].path, &index)) {
2687 index = distinct++;
2688 st_insert(&table, (st_data_t)sites[i].path, index);
2689 }
2690 sites[i].index = (unsigned int)index;
2691 }
2692 st_free_embedded_table(&table);
2693 }
2694
2695 return distinct;
2696}
2697
2701static int
2702iseq_set_sequence(rb_iseq_t *iseq, LINK_ANCHOR *const anchor)
2703{
2704 struct iseq_insn_info_entry *insns_info;
2705 struct rb_iseq_constant_body *const body = ISEQ_BODY(iseq);
2706 LINK_ELEMENT *list;
2707 VALUE *generated_iseq;
2708 rb_event_flag_t events = 0;
2709 long data = 0;
2710
2711 int insn_num, code_index, insns_info_index, sp = 0;
2712 VALUE ic_site_buf = 0;
2713 unsigned int ic_site_count = 0, ic_site_cursor = 0;
2714 struct ic_site *ic_sites = ALLOCV_N(struct ic_site, ic_site_buf, body->ic_size);
2715 int stack_max = fix_sp_depth(iseq, anchor);
2716
2717 if (stack_max < 0) return COMPILE_NG;
2718
2719 /* fix label position */
2720 insn_num = code_index = 0;
2721 for (list = FIRST_ELEMENT(anchor); list; list = list->next) {
2722 switch (list->type) {
2723 case ISEQ_ELEMENT_INSN:
2724 {
2725 INSN *iobj = (INSN *)list;
2726 /* update sp */
2727 sp = calc_sp_depth(sp, iobj);
2728 insn_num++;
2729 if (iobj->insn_id == BIN(opt_getconstant_path)) {
2730 if (UNLIKELY(ic_site_count >= body->ic_size)) {
2731 COMPILE_ERROR(iseq, iobj->insn_info.line_no,
2732 "iseq_set_sequence: ic_index overflow: size: %d", body->ic_size);
2733 return COMPILE_NG;
2734 }
2735 ic_sites[ic_site_count++].path = (rb_const_path_t)OPERAND_AT(iobj, 0);
2736 }
2737 events = iobj->insn_info.events |= events;
2738 if (ISEQ_COVERAGE(iseq)) {
2739 if (ISEQ_LINE_COVERAGE(iseq) && (events & RUBY_EVENT_COVERAGE_LINE) &&
2740 !(rb_get_coverage_mode() & COVERAGE_TARGET_ONESHOT_LINES)) {
2741 int line = iobj->insn_info.line_no - 1;
2742 if (line >= 0 && line < RARRAY_LEN(ISEQ_LINE_COVERAGE(iseq))) {
2743 RARRAY_ASET(ISEQ_LINE_COVERAGE(iseq), line, INT2FIX(0));
2744 }
2745 }
2746 if (ISEQ_BRANCH_COVERAGE(iseq) && (events & RUBY_EVENT_COVERAGE_BRANCH)) {
2747 while (RARRAY_LEN(ISEQ_PC2BRANCHINDEX(iseq)) <= code_index) {
2748 rb_ary_push(ISEQ_PC2BRANCHINDEX(iseq), Qnil);
2749 }
2750 RARRAY_ASET(ISEQ_PC2BRANCHINDEX(iseq), code_index, INT2FIX(data));
2751 }
2752 }
2753 code_index += insn_data_length(iobj);
2754 events = 0;
2755 data = 0;
2756 break;
2757 }
2758 case ISEQ_ELEMENT_LABEL:
2759 {
2760 LABEL *lobj = (LABEL *)list;
2761 lobj->position = code_index;
2762 if (lobj->sp != sp) {
2763 VALUE path = rb_iseq_path(iseq);
2764 debugs("%.*s: sp inconsistency found but ignored (" LABEL_FORMAT " sp: %d, calculated sp: %d)\n",
2765 RSTRING_LENINT(path), RSTRING_PTR(path),
2766 lobj->label_no, lobj->sp, sp);
2767 }
2768 sp = lobj->sp;
2769 break;
2770 }
2771 case ISEQ_ELEMENT_TRACE:
2772 {
2773 TRACE *trace = (TRACE *)list;
2774 events |= trace->event;
2775 if (trace->event & RUBY_EVENT_COVERAGE_BRANCH) data = trace->data;
2776 break;
2777 }
2778 case ISEQ_ELEMENT_ADJUST:
2779 {
2780 ADJUST *adjust = (ADJUST *)list;
2781 int orig_sp = sp;
2782 /* A restore changes the stack depth even though it emits no
2783 * instructions. */
2784 sp = adjust->label ? adjust->label->sp : 0;
2785 if (adjust->line_no != -1 && orig_sp > sp) {
2786 if (orig_sp - sp > 1) code_index++; /* 1 operand */
2787 code_index++; /* insn */
2788 insn_num++;
2789 }
2790 break;
2791 }
2792 default: break;
2793 }
2794 }
2795
2796 body->ic_size = dedup_const_path_ics(ic_sites, ic_site_count);
2797
2798 /* make instruction sequence */
2799 const int generated_iseq_size = code_index;
2800 generated_iseq = ALLOC_N(VALUE, code_index);
2801
2802 VALUE insns_info_buf;
2803 insns_info = ALLOCV_N(struct iseq_insn_info_entry, insns_info_buf, insn_num);
2804
2805 VALUE positions_buf;
2806 unsigned int *positions = ALLOCV_N(unsigned int, positions_buf, insn_num);
2807 VALUE node_ids_buf;
2808 uint8_t *node_ids = ALLOCV_N(uint8_t, node_ids_buf, (size_t)insn_num * 5);
2809 unsigned int node_ids_size = 0;
2810 int prev_node_id = 0;
2811 if (ISEQ_IS_SIZE(body)) {
2812 body->is_entries = ZALLOC_N(union iseq_inline_storage_entry, ISEQ_IS_SIZE(body));
2813 }
2814 else {
2815 body->is_entries = NULL;
2816 }
2817
2818 if (body->ci_size) {
2819 body->call_data = ZALLOC_N(struct rb_call_data, body->ci_size);
2820 }
2821 else {
2822 body->call_data = NULL;
2823 }
2824 ISEQ_COMPILE_DATA(iseq)->ci_index = 0;
2825
2826 // Calculate the bitmask buffer size.
2827 // Round the generated_iseq size up to the nearest multiple
2828 // of the number of bits in an unsigned long.
2829
2830 // Allocate enough room for the bitmask list
2831 iseq_bits_t * mark_offset_bits;
2832 int code_size = code_index;
2833
2834 bool needs_bitmap = false;
2835
2836 const size_t mark_offset_bits_size = ISEQ_MBITS_BUFLEN(code_index);
2837 if (mark_offset_bits_size == 1) {
2838 mark_offset_bits = &ISEQ_COMPILE_DATA(iseq)->mark_bits.single;
2839 ISEQ_COMPILE_DATA(iseq)->is_single_mark_bit = true;
2840 }
2841 else {
2842 mark_offset_bits = ZALLOC_N(iseq_bits_t, mark_offset_bits_size);
2843 ISEQ_COMPILE_DATA(iseq)->mark_bits.list = mark_offset_bits;
2844 ISEQ_COMPILE_DATA(iseq)->is_single_mark_bit = false;
2845 }
2846
2847 ISEQ_COMPILE_DATA(iseq)->iseq_encoded = (void *)generated_iseq;
2848 ISEQ_COMPILE_DATA(iseq)->iseq_size = code_index;
2849
2850 list = FIRST_ELEMENT(anchor);
2851 insns_info_index = code_index = sp = 0;
2852
2853 while (list) {
2854 switch (list->type) {
2855 case ISEQ_ELEMENT_INSN:
2856 {
2857 int j, len, insn;
2858 const char *types;
2859 VALUE *operands;
2860 INSN *iobj = (INSN *)list;
2861
2862 /* update sp */
2863 sp = calc_sp_depth(sp, iobj);
2864 /* fprintf(stderr, "insn: %-16s, sp: %d\n", insn_name(iobj->insn_id), sp); */
2865 operands = iobj->operands;
2866 insn = iobj->insn_id;
2867 generated_iseq[code_index] = insn;
2868 types = insn_op_types(insn);
2869 len = insn_len(insn);
2870
2871 for (j = 0; types[j]; j++) {
2872 char type = types[j];
2873
2874 /* printf("--> [%c - (%d-%d)]\n", type, k, j); */
2875 switch (type) {
2876 case TS_OFFSET:
2877 {
2878 /* label(destination position) */
2879 LABEL *lobj = (LABEL *)operands[j];
2880 generated_iseq[code_index + 1 + j] = lobj->position - (code_index + len);
2881 break;
2882 }
2883 case TS_CDHASH:
2884 {
2885 VALUE map = operands[j];
2886 struct cdhash_set_label_struct data;
2887 data.hash = map;
2888 data.pos = code_index;
2889 data.len = len;
2890 st_foreach_with_replace(rb_imemo_cdhash_tbl(map), cdhash_set_label_check_i, cdhash_set_label_replace_i, (VALUE)&data);
2891
2892 generated_iseq[code_index + 1 + j] = map;
2893 ISEQ_MBITS_SET(mark_offset_bits, code_index + 1 + j);
2894 RB_OBJ_WRITTEN(iseq, Qundef, map);
2895 needs_bitmap = true;
2896 break;
2897 }
2898 case TS_LINDEX:
2899 case TS_NUM: /* ulong */
2900 generated_iseq[code_index + 1 + j] = FIX2INT(operands[j]);
2901 break;
2902 case TS_ISEQ: /* iseq */
2903 case TS_VALUE: /* VALUE */
2904 {
2905 VALUE v = operands[j];
2906 generated_iseq[code_index + 1 + j] = v;
2907 /* to mark ruby object */
2908 if (!SPECIAL_CONST_P(v)) {
2909 RB_OBJ_WRITTEN(iseq, Qundef, v);
2910 ISEQ_MBITS_SET(mark_offset_bits, code_index + 1 + j);
2911 needs_bitmap = true;
2912 }
2913 break;
2914 }
2915 /* [ TS_IVC | TS_ICVARC | TS_IC ] */
2916 case TS_IC: /* inline cache: constants */
2917 {
2918 const struct ic_site *site = &ic_sites[ic_site_cursor++];
2919 IC ic = &ISEQ_IS_ENTRY_START(body, type)[site->index].ic_cache;
2920 ic->const_path = site->path;
2921
2922 generated_iseq[code_index + 1 + j] = (VALUE)ic;
2923 }
2924 break;
2925 case TS_IVC: /* inline ivar cache */
2926 {
2927 unsigned int ic_index = FIX2UINT(operands[j]);
2928
2929 IVC cache = ((IVC)&body->is_entries[ic_index]);
2930
2931 if (insn == BIN(setinstancevariable)) {
2932 cache->iv_set_name = SYM2ID(operands[j - 1]);
2933 cache->value = IVAR_CACHE_INIT;
2934 }
2935 else {
2936 cache->iv_set_name = 0;
2937 cache->value = rb_getivar_cache_pack(ROOT_SHAPE_ID, ATTR_INDEX_NOT_SET);
2938 }
2939 }
2940 case TS_ICVARC: /* inline cvar cache */
2941 {
2942 unsigned int ic_index = FIX2UINT(operands[j]);
2943 IC ic = &ISEQ_IS_ENTRY_START(body, type)[ic_index].ic_cache;
2944 if (UNLIKELY(ic_index >= ISEQ_IS_SIZE(body))) {
2945 BADINSN_DUMP(anchor, &iobj->link, 0);
2946 COMPILE_ERROR(iseq, iobj->insn_info.line_no,
2947 "iseq_set_sequence: ic_index overflow: index: %d, size: %d",
2948 ic_index, ISEQ_IS_SIZE(body));
2949 }
2950 generated_iseq[code_index + 1 + j] = (VALUE)ic;
2951
2952 break;
2953 }
2954 case TS_CALLDATA:
2955 {
2956 const struct rb_callinfo *source_ci = (const struct rb_callinfo *)operands[j];
2957 RUBY_ASSERT(ISEQ_COMPILE_DATA(iseq)->ci_index <= body->ci_size);
2958 struct rb_call_data *cd = &body->call_data[ISEQ_COMPILE_DATA(iseq)->ci_index++];
2959 cd->ci = source_ci;
2960 cd->cc = vm_cc_empty();
2961 generated_iseq[code_index + 1 + j] = (VALUE)cd;
2962 break;
2963 }
2964 case TS_ID: /* ID */
2965 generated_iseq[code_index + 1 + j] = SYM2ID(operands[j]);
2966 break;
2967 case TS_FUNCPTR:
2968 generated_iseq[code_index + 1 + j] = operands[j];
2969 break;
2970 case TS_BUILTIN:
2971 generated_iseq[code_index + 1 + j] = operands[j];
2972 break;
2973 default:
2974 BADINSN_ERROR(iseq, iobj->insn_info.line_no,
2975 "unknown operand type: %c", type);
2976 return COMPILE_NG;
2977 }
2978 }
2979 if (add_insn_info(insns_info, positions, insns_info_index, code_index, iobj)) insns_info_index++;
2980 add_node_id(node_ids, &node_ids_size, iobj->insn_info.node_id, &prev_node_id);
2981 code_index += len;
2982 break;
2983 }
2984 case ISEQ_ELEMENT_LABEL:
2985 {
2986 LABEL *lobj = (LABEL *)list;
2987 if (lobj->sp != sp) {
2988 VALUE path = rb_iseq_path(iseq);
2989 debugs("%.*s: sp inconsistency found but ignored (" LABEL_FORMAT " sp: %d, calculated sp: %d)\n",
2990 RSTRING_LENINT(path), RSTRING_PTR(path),
2991 lobj->label_no, lobj->sp, sp);
2992 }
2993 sp = lobj->sp;
2994 break;
2995 }
2996 case ISEQ_ELEMENT_ADJUST:
2997 {
2998 ADJUST *adjust = (ADJUST *)list;
2999 int orig_sp = sp;
3000
3001 if (adjust->label) {
3002 sp = adjust->label->sp;
3003 }
3004 else {
3005 sp = 0;
3006 }
3007
3008 if (adjust->line_no != -1) {
3009 const int diff = orig_sp - sp;
3010 if (diff > 0) {
3011 if (insns_info_index == 0) {
3012 COMPILE_ERROR(iseq, adjust->line_no,
3013 "iseq_set_sequence: adjust bug (ISEQ_ELEMENT_ADJUST must not be the first in iseq)");
3014 }
3015 if (add_adjust_info(insns_info, positions, insns_info_index, code_index, adjust)) insns_info_index++;
3016 add_node_id(node_ids, &node_ids_size, -1, &prev_node_id);
3017 }
3018 if (diff > 1) {
3019 generated_iseq[code_index++] = BIN(adjuststack);
3020 generated_iseq[code_index++] = orig_sp - sp;
3021 }
3022 else if (diff == 1) {
3023 generated_iseq[code_index++] = BIN(pop);
3024 }
3025 else if (diff < 0) {
3026 int label_no = adjust->label ? adjust->label->label_no : -1;
3027 SIZED_FREE_N(generated_iseq, generated_iseq_size);
3028 if (ISEQ_MBITS_BUFLEN(code_size) > 1) {
3029 SIZED_FREE_N(mark_offset_bits, ISEQ_MBITS_BUFLEN(code_index));
3030 }
3031 debug_list(anchor, list);
3032 COMPILE_ERROR(iseq, adjust->line_no,
3033 "iseq_set_sequence: adjust bug to %d %d < %d",
3034 label_no, orig_sp, sp);
3035 return COMPILE_NG;
3036 }
3037 }
3038 break;
3039 }
3040 default:
3041 /* ignore */
3042 break;
3043 }
3044 list = list->next;
3045 }
3046
3047 body->iseq_encoded = (void *)generated_iseq;
3048 body->iseq_size = code_index;
3049 body->stack_max = stack_max;
3050
3051 if (ISEQ_COMPILE_DATA(iseq)->is_single_mark_bit) {
3052 body->mark_bits.single = ISEQ_COMPILE_DATA(iseq)->mark_bits.single;
3053 }
3054 else {
3055 if (needs_bitmap) {
3056 body->mark_bits.list = mark_offset_bits;
3057 }
3058 else {
3059 body->mark_bits.list = NULL;
3060 ISEQ_COMPILE_DATA(iseq)->mark_bits.list = NULL;
3061 SIZED_FREE_N(mark_offset_bits, mark_offset_bits_size);
3062 }
3063 }
3064
3065 body->insns_info = rb_iseq_insn_info_new(body->iseq_size, insns_info, positions, insns_info_index, node_ids, node_ids_size);
3066 ALLOCV_END(node_ids_buf);
3067 ALLOCV_END(insns_info_buf);
3068 ALLOCV_END(positions_buf);
3069
3070 ALLOCV_END(ic_site_buf);
3071 return COMPILE_OK;
3072}
3073
3074static int
3075label_get_position(LABEL *lobj)
3076{
3077 return lobj->position;
3078}
3079
3080static int
3081label_get_sp(LABEL *lobj)
3082{
3083 return lobj->sp;
3084}
3085
3086static int
3087iseq_set_exception_table(rb_iseq_t *iseq)
3088{
3089 const VALUE *tptr, *ptr;
3090 unsigned int tlen, i, table_size = 0;
3091 struct iseq_catch_table_entry *entry;
3092
3093 ISEQ_BODY(iseq)->catch_table = NULL;
3094
3095 VALUE catch_table_ary = ISEQ_COMPILE_DATA(iseq)->catch_table_ary;
3096 if (NIL_P(catch_table_ary)) return COMPILE_OK;
3097 tlen = (int)RARRAY_LEN(catch_table_ary);
3098 tptr = RARRAY_CONST_PTR(catch_table_ary);
3099
3100 if (tlen > 0) {
3101 struct iseq_catch_table *table = xmalloc(iseq_catch_table_bytes(tlen));
3102 table->size = tlen;
3103
3104 for (i = 0; i < table->size; i++) {
3105 ptr = RARRAY_CONST_PTR(tptr[i]);
3106 int start = label_get_position((LABEL *)(ptr[1] & ~1));
3107 int end = label_get_position((LABEL *)(ptr[2] & ~1));
3108 int cont = 0;
3109 int sp = 0;
3110 if (start < 0 || end < 0) {
3111 if ((ptr[0] & 0xffff) != CATCH_TYPE_ENSURE) continue;
3112 if (start < 0) start = 0;
3113 if (end < 0) end = 0;
3114 }
3115 if (ptr[4]) {
3116 LABEL *lobj = (LABEL *)(ptr[4] & ~1);
3117 cont = label_get_position(lobj);
3118 if (cont < 0) continue;
3119 sp = label_get_sp(lobj);
3120 }
3121
3122 entry = UNALIGNED_MEMBER_PTR(table, entries[table_size++]);
3123 entry->type = (enum rb_catch_type)(ptr[0] & 0xffff);
3124 entry->start = (unsigned int)start;
3125 entry->end = (unsigned int)end;
3126 entry->iseq = (rb_iseq_t *)ptr[3];
3127 RB_OBJ_WRITTEN(iseq, Qundef, entry->iseq);
3128
3129 /* stack depth */
3130 if (ptr[4]) {
3131 entry->cont = (unsigned int)cont;
3132 entry->sp = sp;
3133
3134 /* TODO: Dirty Hack! Fix me */
3135 if (entry->type == CATCH_TYPE_RESCUE ||
3136 entry->type == CATCH_TYPE_BREAK ||
3137 entry->type == CATCH_TYPE_NEXT) {
3138 RUBY_ASSERT(entry->sp > 0);
3139 entry->sp--;
3140 }
3141 }
3142 else {
3143 entry->cont = 0;
3144 }
3145 }
3146 table->size = table_size;
3147 if (table_size == 0) {
3148 ruby_xfree_sized(table, iseq_catch_table_bytes(tlen));
3149 table = NULL;
3150 }
3151 else if (table_size < tlen) {
3152 table = ruby_xrealloc(table, iseq_catch_table_bytes(table_size));
3153 }
3154 ISEQ_BODY(iseq)->catch_table = table;
3155 RB_OBJ_WRITE(iseq, &ISEQ_COMPILE_DATA(iseq)->catch_table_ary, 0); /* free */
3156 }
3157
3158 RB_GC_GUARD(catch_table_ary);
3159
3160 return COMPILE_OK;
3161}
3162
3163/*
3164 * set optional argument table
3165 * def foo(a, b=expr1, c=expr2)
3166 * =>
3167 * b:
3168 * expr1
3169 * c:
3170 * expr2
3171 */
3172static int
3173iseq_set_optargs_table(rb_iseq_t *iseq)
3174{
3175 int i;
3176 VALUE *opt_table = (VALUE *)ISEQ_BODY(iseq)->param.opt_table;
3177
3178 if (ISEQ_BODY(iseq)->param.flags.has_opt) {
3179 for (i = 0; i < ISEQ_BODY(iseq)->param.opt_num + 1; i++) {
3180 opt_table[i] = label_get_position((LABEL *)opt_table[i]);
3181 }
3182 }
3183 return COMPILE_OK;
3184}
3185
3186static LINK_ELEMENT *
3187get_destination_insn(INSN *iobj)
3188{
3189 LABEL *lobj = (LABEL *)OPERAND_AT(iobj, 0);
3190 LINK_ELEMENT *list;
3191 rb_event_flag_t events = 0;
3192
3193 list = lobj->link.next;
3194 while (list) {
3195 switch (list->type) {
3196 case ISEQ_ELEMENT_INSN:
3197 case ISEQ_ELEMENT_ADJUST:
3198 goto found;
3199 case ISEQ_ELEMENT_LABEL:
3200 /* ignore */
3201 break;
3202 case ISEQ_ELEMENT_TRACE:
3203 {
3204 TRACE *trace = (TRACE *)list;
3205 events |= trace->event;
3206 }
3207 break;
3208 default: break;
3209 }
3210 list = list->next;
3211 }
3212 found:
3213 if (list && IS_INSN(list)) {
3214 INSN *iobj = (INSN *)list;
3215 iobj->insn_info.events |= events;
3216 }
3217 return list;
3218}
3219
3220static LINK_ELEMENT *
3221get_next_insn(INSN *iobj)
3222{
3223 LINK_ELEMENT *list = iobj->link.next;
3224
3225 while (list) {
3226 if (IS_INSN(list) || IS_ADJUST(list)) {
3227 return list;
3228 }
3229 list = list->next;
3230 }
3231 return 0;
3232}
3233
3234static LINK_ELEMENT *
3235get_prev_insn(INSN *iobj)
3236{
3237 LINK_ELEMENT *list = iobj->link.prev;
3238
3239 while (list) {
3240 if (IS_INSN(list) || IS_ADJUST(list)) {
3241 return list;
3242 }
3243 list = list->prev;
3244 }
3245 return 0;
3246}
3247
3248static void
3249unref_destination(INSN *iobj, int pos)
3250{
3251 LABEL *lobj = (LABEL *)OPERAND_AT(iobj, pos);
3252 --lobj->refcnt;
3253 if (!lobj->refcnt) ELEM_REMOVE(&lobj->link);
3254}
3255
3256static bool
3257replace_destination(INSN *dobj, INSN *nobj)
3258{
3259 VALUE n = OPERAND_AT(nobj, 0);
3260 LABEL *dl = (LABEL *)OPERAND_AT(dobj, 0);
3261 LABEL *nl = (LABEL *)n;
3262 if (dl == nl) return false;
3263 --dl->refcnt;
3264 ++nl->refcnt;
3265 OPERAND_AT(dobj, 0) = n;
3266 if (!dl->refcnt) ELEM_REMOVE(&dl->link);
3267 return true;
3268}
3269
3270static LABEL*
3271find_destination(INSN *i)
3272{
3273 int pos, len = insn_len(i->insn_id);
3274 for (pos = 0; pos < len; ++pos) {
3275 if (insn_op_types(i->insn_id)[pos] == TS_OFFSET) {
3276 return (LABEL *)OPERAND_AT(i, pos);
3277 }
3278 }
3279 return 0;
3280}
3281
3283 const unsigned int capacity;
3284 unsigned int gen;
3285 int *counts;
3286 unsigned int *stamps;
3287};
3288
3289static int
3290unreachable_unref_count(const struct unreachable_unref *unref, const LABEL *lab)
3291{
3292 unsigned int no = (unsigned int)lab->label_no;
3293 return unref->stamps[no] == unref->gen ? unref->counts[no] : 0;
3294}
3295
3296static void
3297unreachable_unref_increment(const struct unreachable_unref *unref, const LABEL *lab)
3298{
3299 unsigned int no = (unsigned int)lab->label_no;
3300 if (unref->stamps[no] != unref->gen) {
3301 unref->stamps[no] = unref->gen;
3302 unref->counts[no] = 0;
3303 }
3304 unref->counts[no]++;
3305}
3306
3307static int
3308remove_unreachable_chunk(rb_iseq_t *iseq, struct unreachable_unref *unref, LINK_ELEMENT *i)
3309{
3310 LINK_ELEMENT *first = i, *end, *scan, *pending_end = 0;
3311 LABEL *pending = 0;
3312
3313 if (!i) return 0;
3314 if (++unref->gen == 0) {
3315 /* The stamp wrapped around, so every stale stamp became ambiguous. */
3316 MEMZERO(unref->stamps, unsigned int, unref->capacity);
3317 unref->gen = 1;
3318 }
3319
3320 end = i;
3321 scan = i;
3322 do {
3323 LABEL *lab;
3324 if (IS_INSN(scan)) {
3325 if (IS_INSN_ID(scan, leave)) {
3326 if (pending) break;
3327 end = scan;
3328 break;
3329 }
3330 else if ((lab = find_destination((INSN *)scan)) != 0) {
3331 unreachable_unref_increment(unref, lab);
3332 if (lab == pending && lab->refcnt <= unreachable_unref_count(unref, lab)) {
3333 pending = 0;
3334 }
3335 }
3336 }
3337 else if (IS_LABEL(scan)) {
3338 lab = (LABEL *)scan;
3339 if (lab->unremovable) {
3340 if (pending) break;
3341 return 0;
3342 }
3343 if (lab->refcnt > unreachable_unref_count(unref, lab)) {
3344 if (pending) break;
3345 pending = lab;
3346 pending_end = (scan == first) ? 0 : end;
3347 }
3348 continue;
3349 }
3350 else if (IS_ADJUST(scan)) {
3351 if (pending) break;
3352 return 0;
3353 }
3354 if (!pending) end = scan;
3355 } while ((scan = scan->next) != 0);
3356
3357 if (pending) {
3358 if (!pending_end) return 0;
3359 end = pending_end;
3360 }
3361 i = first;
3362 do {
3363 if (IS_INSN(i)) {
3364 struct rb_iseq_constant_body *body = ISEQ_BODY(iseq);
3365 VALUE insn = INSN_OF(i);
3366 int pos, len = insn_len(insn);
3367 for (pos = 0; pos < len; ++pos) {
3368 switch (insn_op_types(insn)[pos]) {
3369 case TS_OFFSET:
3370 unref_destination((INSN *)i, pos);
3371 break;
3372 case TS_CALLDATA:
3373 --(body->ci_size);
3374 break;
3375 }
3376 }
3377 }
3378 ELEM_REMOVE(i);
3379 } while ((i != end) && (i = i->next) != 0);
3380 return 1;
3381}
3382
3383static int
3384iseq_pop_newarray(rb_iseq_t *iseq, INSN *iobj)
3385{
3386 switch (OPERAND_AT(iobj, 0)) {
3387 case INT2FIX(0): /* empty array */
3388 ELEM_REMOVE(&iobj->link);
3389 return TRUE;
3390 case INT2FIX(1): /* single element array */
3391 ELEM_REMOVE(&iobj->link);
3392 return FALSE;
3393 default:
3394 iobj->insn_id = BIN(adjuststack);
3395 return TRUE;
3396 }
3397}
3398
3399static int
3400is_frozen_putstring(INSN *insn, VALUE *op)
3401{
3402 if (IS_INSN_ID(insn, dupstring) || IS_INSN_ID(insn, dupchilledstring)) {
3403 *op = OPERAND_AT(insn, 0);
3404 return 1;
3405 }
3406 else if (IS_INSN_ID(insn, putobject)) { /* frozen_string_literal */
3407 *op = OPERAND_AT(insn, 0);
3408 return RB_TYPE_P(*op, T_STRING);
3409 }
3410 return 0;
3411}
3412
3413static int
3414insn_has_label_before(LINK_ELEMENT *elem)
3415{
3416 LINK_ELEMENT *prev = elem->prev;
3417 while (prev) {
3418 if (prev->type == ISEQ_ELEMENT_LABEL) {
3419 LABEL *label = (LABEL *)prev;
3420 if (label->refcnt > 0) {
3421 return 1;
3422 }
3423 }
3424 else if (prev->type == ISEQ_ELEMENT_INSN) {
3425 break;
3426 }
3427 prev = prev->prev;
3428 }
3429 return 0;
3430}
3431
3432static int
3433optimize_checktype(rb_iseq_t *iseq, INSN *iobj)
3434{
3435 /*
3436 * putobject obj
3437 * dup
3438 * checktype T_XXX
3439 * branchif l1
3440 * l2:
3441 * ...
3442 * l1:
3443 *
3444 * => obj is a T_XXX
3445 *
3446 * putobject obj (T_XXX)
3447 * jump L1
3448 * L1:
3449 *
3450 * => obj is not a T_XXX
3451 *
3452 * putobject obj (T_XXX)
3453 * jump L2
3454 * L2:
3455 */
3456 int line, node_id;
3457 INSN *niobj, *ciobj, *dup = 0;
3458 LABEL *dest = 0;
3459 VALUE type;
3460
3461 switch (INSN_OF(iobj)) {
3462 case BIN(dupstring):
3463 case BIN(dupchilledstring):
3465 break;
3466 case BIN(putnil):
3467 type = INT2FIX(T_NIL);
3468 break;
3469 case BIN(putobject):
3470 type = INT2FIX(TYPE(OPERAND_AT(iobj, 0)));
3471 break;
3472 default: return FALSE;
3473 }
3474
3475 ciobj = (INSN *)get_next_insn(iobj);
3476 if (IS_INSN_ID(ciobj, jump)) {
3477 ciobj = (INSN *)get_next_insn((INSN*)OPERAND_AT(ciobj, 0));
3478 }
3479 if (IS_INSN_ID(ciobj, dup)) {
3480 ciobj = (INSN *)get_next_insn(dup = ciobj);
3481 }
3482 if (!ciobj || !IS_INSN_ID(ciobj, checktype)) return FALSE;
3483 niobj = (INSN *)get_next_insn(ciobj);
3484 if (!niobj) {
3485 /* TODO: putobject true/false */
3486 return FALSE;
3487 }
3488 switch (INSN_OF(niobj)) {
3489 case BIN(branchif):
3490 if (OPERAND_AT(ciobj, 0) == type) {
3491 dest = (LABEL *)OPERAND_AT(niobj, 0);
3492 }
3493 break;
3494 case BIN(branchunless):
3495 if (OPERAND_AT(ciobj, 0) != type) {
3496 dest = (LABEL *)OPERAND_AT(niobj, 0);
3497 }
3498 break;
3499 default:
3500 return FALSE;
3501 }
3502 line = ciobj->insn_info.line_no;
3503 node_id = ciobj->insn_info.node_id;
3504 if (!dest) {
3505 if (niobj->link.next && IS_LABEL(niobj->link.next)) {
3506 dest = (LABEL *)niobj->link.next; /* reuse label */
3507 }
3508 else {
3509 dest = NEW_LABEL(line);
3510 ELEM_INSERT_NEXT(&niobj->link, &dest->link);
3511 }
3512 }
3513 INSERT_AFTER_INSN1(iobj, line, node_id, jump, dest);
3514 LABEL_REF(dest);
3515 if (!dup) INSERT_AFTER_INSN(iobj, line, node_id, pop);
3516 return TRUE;
3517}
3518
3519static const struct rb_callinfo *
3520ci_flag_set(const rb_iseq_t *iseq, const struct rb_callinfo *ci, unsigned int add)
3521{
3522 const struct rb_callinfo *nci = vm_ci_new(vm_ci_mid(ci),
3523 vm_ci_flag(ci) | add,
3524 vm_ci_argc(ci),
3525 vm_ci_kwarg(ci));
3526 RB_OBJ_WRITTEN(iseq, ci, nci);
3527 return nci;
3528}
3529
3530static const struct rb_callinfo *
3531ci_argc_set(const rb_iseq_t *iseq, const struct rb_callinfo *ci, int argc)
3532{
3533 const struct rb_callinfo *nci = vm_ci_new(vm_ci_mid(ci),
3534 vm_ci_flag(ci),
3535 argc,
3536 vm_ci_kwarg(ci));
3537 RB_OBJ_WRITTEN(iseq, ci, nci);
3538 return nci;
3539}
3540
3541#define vm_ci_simple(ci) (vm_ci_flag(ci) & VM_CALL_ARGS_SIMPLE)
3542
3543static VALUE
3544iseq_reg_compile(rb_iseq_t *iseq, VALUE str, int options, const char *sourcefile, int sourceline)
3545{
3546 VALUE errinfo = rb_errinfo();
3547 VALUE re = rb_reg_compile(str, options, sourcefile, sourceline);
3548 if (NIL_P(re)) {
3549 VALUE message = rb_attr_get(rb_errinfo(), idMesg);
3550 rb_set_errinfo(errinfo);
3551 COMPILE_ERROR(iseq, sourceline, "%" PRIsVALUE, message);
3552 }
3553 else {
3555 }
3556 return re;
3557}
3558
3559static int
3560iseq_peephole_optimize(rb_iseq_t *iseq, struct unreachable_unref *unref, LINK_ELEMENT *list, const int do_tailcallopt)
3561{
3562 INSN *const iobj = (INSN *)list;
3563
3564 again:
3565 optimize_checktype(iseq, iobj);
3566
3567 if (IS_INSN_ID(iobj, jump)) {
3568 INSN *niobj, *diobj, *piobj;
3569 diobj = (INSN *)get_destination_insn(iobj);
3570 niobj = (INSN *)get_next_insn(iobj);
3571
3572 if (diobj == niobj) {
3573 /*
3574 * jump LABEL
3575 * LABEL:
3576 * =>
3577 * LABEL:
3578 */
3579 unref_destination(iobj, 0);
3580 ELEM_REMOVE(&iobj->link);
3581 return COMPILE_OK;
3582 }
3583 else if (iobj != diobj && IS_INSN(&diobj->link) &&
3584 IS_INSN_ID(diobj, jump) &&
3585 OPERAND_AT(iobj, 0) != OPERAND_AT(diobj, 0) &&
3586 diobj->insn_info.events == 0) {
3587 /*
3588 * useless jump elimination:
3589 * jump LABEL1
3590 * ...
3591 * LABEL1:
3592 * jump LABEL2
3593 *
3594 * => in this case, first jump instruction should jump to
3595 * LABEL2 directly
3596 */
3597 if (replace_destination(iobj, diobj)) {
3598 remove_unreachable_chunk(iseq, unref, iobj->link.next);
3599 goto again;
3600 }
3601 }
3602 else if (IS_INSN_ID(diobj, leave)) {
3603 /*
3604 * jump LABEL
3605 * ...
3606 * LABEL:
3607 * leave
3608 * =>
3609 * leave
3610 * ...
3611 * LABEL:
3612 * leave
3613 */
3614 /* replace */
3615 unref_destination(iobj, 0);
3616 iobj->insn_id = BIN(leave);
3617 iobj->operand_size = 0;
3618 iobj->insn_info = diobj->insn_info;
3619 goto again;
3620 }
3621 else if (IS_INSN(iobj->link.prev) &&
3622 (piobj = (INSN *)iobj->link.prev) &&
3623 (IS_INSN_ID(piobj, branchif) ||
3624 IS_INSN_ID(piobj, branchunless))) {
3625 INSN *pdiobj = (INSN *)get_destination_insn(piobj);
3626 if (niobj == pdiobj) {
3627 int refcnt = IS_LABEL(piobj->link.next) ?
3628 ((LABEL *)piobj->link.next)->refcnt : 0;
3629 /*
3630 * useless jump elimination (if/unless destination):
3631 * if L1
3632 * jump L2
3633 * L1:
3634 * ...
3635 * L2:
3636 *
3637 * ==>
3638 * unless L2
3639 * L1:
3640 * ...
3641 * L2:
3642 */
3643 piobj->insn_id = (IS_INSN_ID(piobj, branchif))
3644 ? BIN(branchunless) : BIN(branchif);
3645 if (replace_destination(piobj, iobj) && refcnt <= 1) {
3646 ELEM_REMOVE(&iobj->link);
3647 }
3648 else {
3649 /* TODO: replace other branch destinations too */
3650 }
3651 return COMPILE_OK;
3652 }
3653 else if (diobj == pdiobj) {
3654 /*
3655 * useless jump elimination (if/unless before jump):
3656 * L1:
3657 * ...
3658 * if L1
3659 * jump L1
3660 *
3661 * ==>
3662 * L1:
3663 * ...
3664 * pop
3665 * jump L1
3666 */
3667 INSN *popiobj = new_insn_core(iseq, iobj->insn_info.line_no, iobj->insn_info.node_id, BIN(pop), 0, 0);
3668 ELEM_REPLACE(&piobj->link, &popiobj->link);
3669 }
3670 }
3671 if (remove_unreachable_chunk(iseq, unref, iobj->link.next)) {
3672 goto again;
3673 }
3674 }
3675
3676 /*
3677 * dupstring "beg"
3678 * dupstring "end"
3679 * newrange excl
3680 *
3681 * ==>
3682 *
3683 * putobject "beg".."end"
3684 */
3685 if (IS_INSN_ID(iobj, newrange)) {
3686 INSN *const range = iobj;
3687 INSN *beg, *end;
3688 VALUE str_beg, str_end;
3689
3690 if ((end = (INSN *)get_prev_insn(range)) != 0 &&
3691 is_frozen_putstring(end, &str_end) &&
3692 (beg = (INSN *)get_prev_insn(end)) != 0 &&
3693 is_frozen_putstring(beg, &str_beg) &&
3694 !(insn_has_label_before(&beg->link) || insn_has_label_before(&end->link))) {
3695 int excl = FIX2INT(OPERAND_AT(range, 0));
3696 VALUE lit_range = RB_OBJ_SET_SHAREABLE(rb_range_new(str_beg, str_end, excl));
3697
3698 ELEM_REMOVE(&beg->link);
3699 ELEM_REMOVE(&end->link);
3700 range->insn_id = BIN(putobject);
3701 OPERAND_AT(range, 0) = lit_range;
3702 RB_OBJ_WRITTEN(iseq, Qundef, lit_range);
3703 }
3704 }
3705
3706 if (IS_INSN_ID(iobj, leave)) {
3707 remove_unreachable_chunk(iseq, unref, iobj->link.next);
3708 }
3709
3710 /*
3711 * ...
3712 * duparray [...]
3713 * concatarray | concattoarray
3714 * =>
3715 * ...
3716 * putobject [...]
3717 * concatarray | concattoarray
3718 */
3719 if (IS_INSN_ID(iobj, duparray)) {
3720 LINK_ELEMENT *next = iobj->link.next;
3721 if (IS_INSN(next) && (IS_INSN_ID(next, concatarray) || IS_INSN_ID(next, concattoarray))) {
3722 iobj->insn_id = BIN(putobject);
3723 }
3724 }
3725
3726 /*
3727 * duparray [...]
3728 * send <calldata!mid:freeze, argc:0, ARGS_SIMPLE>, nil
3729 * =>
3730 * opt_ary_freeze [...], <calldata!mid:freeze, argc:0, ARGS_SIMPLE>
3731 */
3732 if (IS_INSN_ID(iobj, duparray)) {
3733 LINK_ELEMENT *next = iobj->link.next;
3734 if (IS_INSN(next) && (IS_INSN_ID(next, send))) {
3735 const struct rb_callinfo *ci = (struct rb_callinfo *)OPERAND_AT(next, 0);
3736 const rb_iseq_t *blockiseq = (rb_iseq_t *)OPERAND_AT(next, 1);
3737
3738 if (vm_ci_simple(ci) && vm_ci_argc(ci) == 0 && blockiseq == NULL && vm_ci_mid(ci) == idFreeze) {
3739 VALUE ary = iobj->operands[0];
3741
3742 insn_replace_with_operands(iseq, iobj, BIN(opt_ary_freeze), 2, ary, (VALUE)ci);
3743 ELEM_REMOVE(next);
3744 }
3745 }
3746 }
3747
3748 /*
3749 * duphash {...}
3750 * send <calldata!mid:freeze, argc:0, ARGS_SIMPLE>, nil
3751 * =>
3752 * opt_hash_freeze {...}, <calldata!mid:freeze, argc:0, ARGS_SIMPLE>
3753 */
3754 if (IS_INSN_ID(iobj, duphash)) {
3755 LINK_ELEMENT *next = iobj->link.next;
3756 if (IS_INSN(next) && (IS_INSN_ID(next, send))) {
3757 const struct rb_callinfo *ci = (struct rb_callinfo *)OPERAND_AT(next, 0);
3758 const rb_iseq_t *blockiseq = (rb_iseq_t *)OPERAND_AT(next, 1);
3759
3760 if (vm_ci_simple(ci) && vm_ci_argc(ci) == 0 && blockiseq == NULL && vm_ci_mid(ci) == idFreeze) {
3761 VALUE hash = iobj->operands[0];
3762 rb_obj_reveal(hash, rb_cHash);
3764
3765 insn_replace_with_operands(iseq, iobj, BIN(opt_hash_freeze), 2, hash, (VALUE)ci);
3766 ELEM_REMOVE(next);
3767 }
3768 }
3769 }
3770
3771 /*
3772 * newarray 0
3773 * send <calldata!mid:freeze, argc:0, ARGS_SIMPLE>, nil
3774 * =>
3775 * opt_ary_freeze [], <calldata!mid:freeze, argc:0, ARGS_SIMPLE>
3776 */
3777 if (IS_INSN_ID(iobj, newarray) && iobj->operands[0] == INT2FIX(0)) {
3778 LINK_ELEMENT *next = iobj->link.next;
3779 if (IS_INSN(next) && (IS_INSN_ID(next, send))) {
3780 const struct rb_callinfo *ci = (struct rb_callinfo *)OPERAND_AT(next, 0);
3781 const rb_iseq_t *blockiseq = (rb_iseq_t *)OPERAND_AT(next, 1);
3782
3783 if (vm_ci_simple(ci) && vm_ci_argc(ci) == 0 && blockiseq == NULL && vm_ci_mid(ci) == idFreeze) {
3784 insn_replace_with_operands(iseq, iobj, BIN(opt_ary_freeze), 2, rb_cArray_empty_frozen, (VALUE)ci);
3785 ELEM_REMOVE(next);
3786 }
3787 }
3788 }
3789
3790 /*
3791 * newhash 0
3792 * send <calldata!mid:freeze, argc:0, ARGS_SIMPLE>, nil
3793 * =>
3794 * opt_hash_freeze {}, <calldata!mid:freeze, argc:0, ARGS_SIMPLE>
3795 */
3796 if (IS_INSN_ID(iobj, newhash) && iobj->operands[0] == INT2FIX(0)) {
3797 LINK_ELEMENT *next = iobj->link.next;
3798 if (IS_INSN(next) && (IS_INSN_ID(next, send))) {
3799 const struct rb_callinfo *ci = (struct rb_callinfo *)OPERAND_AT(next, 0);
3800 const rb_iseq_t *blockiseq = (rb_iseq_t *)OPERAND_AT(next, 1);
3801
3802 if (vm_ci_simple(ci) && vm_ci_argc(ci) == 0 && blockiseq == NULL && vm_ci_mid(ci) == idFreeze) {
3803 insn_replace_with_operands(iseq, iobj, BIN(opt_hash_freeze), 2, rb_cHash_empty_frozen, (VALUE)ci);
3804 ELEM_REMOVE(next);
3805 }
3806 }
3807 }
3808
3809 if (IS_INSN_ID(iobj, branchif) ||
3810 IS_INSN_ID(iobj, branchnil) ||
3811 IS_INSN_ID(iobj, branchunless)) {
3812 /*
3813 * if L1
3814 * ...
3815 * L1:
3816 * jump L2
3817 * =>
3818 * if L2
3819 */
3820 INSN *nobj = (INSN *)get_destination_insn(iobj);
3821
3822 /* This jump-jump optimization may ignore line events on the jump
3823 * instruction being skipped. For example, the Line 2 TracePoint
3824 * event would otherwise never fire in the following code:
3825 *
3826 * 1: raise if 1 == 2
3827 * 2: while true
3828 * 3: break
3829 * 4: end
3830 *
3831 * Do not skip a jump that carries a line event. This applies even
3832 * when coverage is disabled because TracePoint consumes the same
3833 * event. [Bug #15980]
3834 */
3835 int stop_optimization =
3836 nobj->link.type == ISEQ_ELEMENT_INSN &&
3837 (nobj->insn_info.events & (RUBY_EVENT_LINE | RUBY_EVENT_COVERAGE_LINE));
3838 if (!stop_optimization) {
3839 INSN *pobj = (INSN *)iobj->link.prev;
3840 int prev_dup = 0;
3841 if (pobj) {
3842 if (!IS_INSN(&pobj->link))
3843 pobj = 0;
3844 else if (IS_INSN_ID(pobj, dup))
3845 prev_dup = 1;
3846 }
3847
3848 for (;;) {
3849 if (IS_INSN(&nobj->link) && IS_INSN_ID(nobj, jump)) {
3850 if (!replace_destination(iobj, nobj)) break;
3851 }
3852 else if (prev_dup && IS_INSN(&nobj->link) && IS_INSN_ID(nobj, dup) &&
3853 !!(nobj = (INSN *)nobj->link.next) &&
3854 IS_INSN(&nobj->link) &&
3855 /* basic blocks, with no labels in the middle */
3856 nobj->insn_id == iobj->insn_id) {
3857 /*
3858 * dup
3859 * if L1
3860 * ...
3861 * L1:
3862 * dup
3863 * if L2
3864 * =>
3865 * dup
3866 * if L2
3867 * ...
3868 * L1:
3869 * dup
3870 * if L2
3871 */
3872 if (!replace_destination(iobj, nobj)) break;
3873 }
3874 else if (pobj) {
3875 /*
3876 * putnil
3877 * if L1
3878 * =>
3879 * # nothing
3880 *
3881 * putobject true
3882 * if L1
3883 * =>
3884 * jump L1
3885 *
3886 * dupstring ".."
3887 * if L1
3888 * =>
3889 * jump L1
3890 *
3891 * dupstring ".."
3892 * dup
3893 * if L1
3894 * =>
3895 * dupstring ".."
3896 * jump L1
3897 *
3898 */
3899 int cond;
3900 if (prev_dup && IS_INSN(pobj->link.prev)) {
3901 pobj = (INSN *)pobj->link.prev;
3902 }
3903 if (IS_INSN_ID(pobj, putobject)) {
3904 cond = (IS_INSN_ID(iobj, branchif) ?
3905 OPERAND_AT(pobj, 0) != Qfalse :
3906 IS_INSN_ID(iobj, branchunless) ?
3907 OPERAND_AT(pobj, 0) == Qfalse :
3908 FALSE);
3909 }
3910 else if (IS_INSN_ID(pobj, dupstring) ||
3911 IS_INSN_ID(pobj, duparray) ||
3912 IS_INSN_ID(pobj, newarray)) {
3913 cond = IS_INSN_ID(iobj, branchif);
3914 }
3915 else if (IS_INSN_ID(pobj, putnil)) {
3916 cond = !IS_INSN_ID(iobj, branchif);
3917 }
3918 else break;
3919 if (prev_dup || !IS_INSN_ID(pobj, newarray)) {
3920 ELEM_REMOVE(iobj->link.prev);
3921 }
3922 else if (!iseq_pop_newarray(iseq, pobj)) {
3923 pobj = new_insn_core(iseq, pobj->insn_info.line_no, pobj->insn_info.node_id, BIN(pop), 0, NULL);
3924 ELEM_INSERT_PREV(&iobj->link, &pobj->link);
3925 }
3926 if (cond) {
3927 if (prev_dup) {
3928 pobj = new_insn_core(iseq, pobj->insn_info.line_no, pobj->insn_info.node_id, BIN(putnil), 0, NULL);
3929 ELEM_INSERT_NEXT(&iobj->link, &pobj->link);
3930 }
3931 iobj->insn_id = BIN(jump);
3932 goto again;
3933 }
3934 else {
3935 unref_destination(iobj, 0);
3936 ELEM_REMOVE(&iobj->link);
3937 }
3938 break;
3939 }
3940 else break;
3941 {
3942 LINK_ELEMENT *dest = get_destination_insn(nobj);
3943 if (!dest || !IS_INSN(dest)) break;
3944 nobj = (INSN *)dest;
3945 }
3946 }
3947 }
3948 }
3949
3950 if (IS_INSN_ID(iobj, pop)) {
3951 /*
3952 * putself / putnil / putobject obj / dupstring "..."
3953 * pop
3954 * =>
3955 * # do nothing
3956 */
3957 LINK_ELEMENT *prev = iobj->link.prev;
3958 if (IS_INSN(prev)) {
3959 enum ruby_vminsn_type previ = ((INSN *)prev)->insn_id;
3960 if (previ == BIN(putobject) || previ == BIN(putnil) ||
3961 previ == BIN(putself) || previ == BIN(dupstring) ||
3962 previ == BIN(dupchilledstring) ||
3963 previ == BIN(dup) ||
3964 previ == BIN(getlocal) ||
3965 previ == BIN(getblockparam) ||
3966 previ == BIN(getblockparamproxy) ||
3967 previ == BIN(getinstancevariable) ||
3968 previ == BIN(duparray)) {
3969 /* just push operand or static value and pop soon, no
3970 * side effects */
3971 ELEM_REMOVE(prev);
3972 ELEM_REMOVE(&iobj->link);
3973 }
3974 else if (previ == BIN(newarray) && iseq_pop_newarray(iseq, (INSN*)prev)) {
3975 ELEM_REMOVE(&iobj->link);
3976 }
3977 else if (previ == BIN(concatarray)) {
3978 INSN *piobj = (INSN *)prev;
3979 INSERT_BEFORE_INSN1(piobj, piobj->insn_info.line_no, piobj->insn_info.node_id, splatarray, Qfalse);
3980 INSN_OF(piobj) = BIN(pop);
3981 }
3982 else if (previ == BIN(concatstrings)) {
3983 if (OPERAND_AT(prev, 0) == INT2FIX(1)) {
3984 ELEM_REMOVE(prev);
3985 }
3986 else {
3987 ELEM_REMOVE(&iobj->link);
3988 INSN_OF(prev) = BIN(adjuststack);
3989 }
3990 }
3991 }
3992 }
3993
3994 if (IS_INSN_ID(iobj, newarray) ||
3995 IS_INSN_ID(iobj, duparray) ||
3996 IS_INSN_ID(iobj, concatarray) ||
3997 IS_INSN_ID(iobj, splatarray) ||
3998 0) {
3999 /*
4000 * newarray N
4001 * splatarray
4002 * =>
4003 * newarray N
4004 * newarray always puts an array
4005 */
4006 LINK_ELEMENT *next = iobj->link.next;
4007 if (IS_INSN(next) && IS_INSN_ID(next, splatarray)) {
4008 /* remove splatarray following always-array insn */
4009 ELEM_REMOVE(next);
4010 }
4011 }
4012
4013 if (IS_INSN_ID(iobj, newarray)) {
4014 LINK_ELEMENT *next = iobj->link.next;
4015 if (IS_INSN(next) && IS_INSN_ID(next, expandarray) &&
4016 OPERAND_AT(next, 1) == INT2FIX(0)) {
4017 VALUE op1, op2;
4018 op1 = OPERAND_AT(iobj, 0);
4019 op2 = OPERAND_AT(next, 0);
4020 ELEM_REMOVE(next);
4021
4022 if (op1 == op2) {
4023 /*
4024 * newarray 2
4025 * expandarray 2, 0
4026 * =>
4027 * swap
4028 */
4029 if (op1 == INT2FIX(2)) {
4030 INSN_OF(iobj) = BIN(swap);
4031 iobj->operand_size = 0;
4032 }
4033 /*
4034 * newarray X
4035 * expandarray X, 0
4036 * =>
4037 * opt_reverse X
4038 */
4039 else {
4040 INSN_OF(iobj) = BIN(opt_reverse);
4041 }
4042 }
4043 else {
4044 long diff = FIX2LONG(op1) - FIX2LONG(op2);
4045 INSN_OF(iobj) = BIN(opt_reverse);
4046 OPERAND_AT(iobj, 0) = OPERAND_AT(next, 0);
4047
4048 if (op1 > op2) {
4049 /* X > Y
4050 * newarray X
4051 * expandarray Y, 0
4052 * =>
4053 * pop * (Y-X)
4054 * opt_reverse Y
4055 */
4056 for (; diff > 0; diff--) {
4057 INSERT_BEFORE_INSN(iobj, iobj->insn_info.line_no, iobj->insn_info.node_id, pop);
4058 }
4059 }
4060 else { /* (op1 < op2) */
4061 /* X < Y
4062 * newarray X
4063 * expandarray Y, 0
4064 * =>
4065 * putnil * (Y-X)
4066 * opt_reverse Y
4067 */
4068 for (; diff < 0; diff++) {
4069 INSERT_BEFORE_INSN(iobj, iobj->insn_info.line_no, iobj->insn_info.node_id, putnil);
4070 }
4071 }
4072 }
4073 }
4074 }
4075
4076 if (IS_INSN_ID(iobj, duparray)) {
4077 LINK_ELEMENT *next = iobj->link.next;
4078 /*
4079 * duparray obj
4080 * expandarray X, 0
4081 * =>
4082 * putobject obj
4083 * expandarray X, 0
4084 */
4085 if (IS_INSN(next) && IS_INSN_ID(next, expandarray)) {
4086 INSN_OF(iobj) = BIN(putobject);
4087 }
4088 }
4089
4090 if (IS_INSN_ID(iobj, anytostring)) {
4091 LINK_ELEMENT *next = iobj->link.next;
4092 /*
4093 * anytostring
4094 * concatstrings 1
4095 * =>
4096 * anytostring
4097 */
4098 if (IS_INSN(next) && IS_INSN_ID(next, concatstrings) &&
4099 OPERAND_AT(next, 0) == INT2FIX(1)) {
4100 ELEM_REMOVE(next);
4101 }
4102 }
4103
4104 if (IS_INSN_ID(iobj, dupstring) || IS_INSN_ID(iobj, dupchilledstring) ||
4105 (IS_INSN_ID(iobj, putobject) && RB_TYPE_P(OPERAND_AT(iobj, 0), T_STRING))) {
4106 /*
4107 * dupstring ""
4108 * concatstrings N
4109 * =>
4110 * concatstrings N-1
4111 */
4112 if (IS_NEXT_INSN_ID(&iobj->link, concatstrings) &&
4113 RSTRING_LEN(OPERAND_AT(iobj, 0)) == 0) {
4114 INSN *next = (INSN *)iobj->link.next;
4115 if ((OPERAND_AT(next, 0) = FIXNUM_INC(OPERAND_AT(next, 0), -1)) == INT2FIX(1)) {
4116 ELEM_REMOVE(&next->link);
4117 }
4118 ELEM_REMOVE(&iobj->link);
4119 }
4120 if (IS_NEXT_INSN_ID(&iobj->link, toregexp)) {
4121 INSN *next = (INSN *)iobj->link.next;
4122 if (OPERAND_AT(next, 1) == INT2FIX(1)) {
4123 VALUE src = OPERAND_AT(iobj, 0);
4124 int opt = (int)FIX2LONG(OPERAND_AT(next, 0));
4125 VALUE path = rb_iseq_path(iseq);
4126 int line = iobj->insn_info.line_no;
4127 VALUE re = iseq_reg_compile(iseq, src, opt, RSTRING_PTR(path), line);
4128 /* The folded operand is a Regexp, so the instruction must be
4129 * putobject: dupstring/dupchilledstring would resurrect the
4130 * Regexp as a String at run time (e.g. for a /o regexp whose
4131 * interpolation folds to a constant, such as /#{"a"}/o). */
4132 iobj->insn_id = BIN(putobject);
4133 RB_OBJ_WRITE(iseq, &OPERAND_AT(iobj, 0), re);
4134 ELEM_REMOVE(iobj->link.next);
4135 }
4136 }
4137 }
4138
4139 if (IS_INSN_ID(iobj, concatstrings)) {
4140 /*
4141 * concatstrings N
4142 * concatstrings M
4143 * =>
4144 * concatstrings N+M-1
4145 */
4146 LINK_ELEMENT *next = iobj->link.next;
4147 INSN *jump = 0;
4148 if (IS_INSN(next) && IS_INSN_ID(next, jump))
4149 next = get_destination_insn(jump = (INSN *)next);
4150 if (IS_INSN(next) && IS_INSN_ID(next, concatstrings)) {
4151 int n = FIX2INT(OPERAND_AT(iobj, 0)) + FIX2INT(OPERAND_AT(next, 0)) - 1;
4152 OPERAND_AT(iobj, 0) = INT2FIX(n);
4153 if (jump) {
4154 LABEL *label = ((LABEL *)OPERAND_AT(jump, 0));
4155 if (!--label->refcnt) {
4156 ELEM_REMOVE(&label->link);
4157 }
4158 else {
4159 label = NEW_LABEL(0);
4160 OPERAND_AT(jump, 0) = (VALUE)label;
4161 }
4162 label->refcnt++;
4163 ELEM_INSERT_NEXT(next, &label->link);
4164 CHECK(iseq_peephole_optimize(iseq, unref, get_next_insn(jump), do_tailcallopt));
4165 }
4166 else {
4167 ELEM_REMOVE(next);
4168 }
4169 }
4170 }
4171
4172 if (do_tailcallopt &&
4173 (IS_INSN_ID(iobj, send) ||
4174 IS_INSN_ID(iobj, invokesuper))) {
4175 /*
4176 * send ...
4177 * leave
4178 * =>
4179 * send ..., ... | VM_CALL_TAILCALL, ...
4180 * leave # unreachable
4181 */
4182 INSN *piobj = NULL;
4183 if (iobj->link.next) {
4184 LINK_ELEMENT *next = iobj->link.next;
4185 do {
4186 if (!IS_INSN(next)) {
4187 next = next->next;
4188 continue;
4189 }
4190 switch (INSN_OF(next)) {
4191 case BIN(nop):
4192 next = next->next;
4193 break;
4194 case BIN(jump):
4195 /* if cond
4196 * return tailcall
4197 * end
4198 */
4199 next = get_destination_insn((INSN *)next);
4200 break;
4201 case BIN(leave):
4202 piobj = iobj;
4203 /* fall through */
4204 default:
4205 next = NULL;
4206 break;
4207 }
4208 } while (next);
4209 }
4210
4211 if (piobj) {
4212 const struct rb_callinfo *ci = (struct rb_callinfo *)OPERAND_AT(piobj, 0);
4213 if (IS_INSN_ID(piobj, send) ||
4214 IS_INSN_ID(piobj, invokesuper)) {
4215 if (OPERAND_AT(piobj, 1) == 0) { /* no blockiseq */
4216 ci = ci_flag_set(iseq, ci, VM_CALL_TAILCALL);
4217 OPERAND_AT(piobj, 0) = (VALUE)ci;
4218 RB_OBJ_WRITTEN(iseq, Qundef, ci);
4219 }
4220 }
4221 else {
4222 ci = ci_flag_set(iseq, ci, VM_CALL_TAILCALL);
4223 OPERAND_AT(piobj, 0) = (VALUE)ci;
4224 RB_OBJ_WRITTEN(iseq, Qundef, ci);
4225 }
4226 }
4227 }
4228
4229 if (IS_INSN_ID(iobj, dup)) {
4230 if (IS_NEXT_INSN_ID(&iobj->link, setlocal)) {
4231 LINK_ELEMENT *set1 = iobj->link.next, *set2 = NULL;
4232
4233 /*
4234 * dup
4235 * setlocal x, y
4236 * setlocal x, y
4237 * =>
4238 * dup
4239 * setlocal x, y
4240 */
4241 if (IS_NEXT_INSN_ID(set1, setlocal)) {
4242 set2 = set1->next;
4243 if (OPERAND_AT(set1, 0) == OPERAND_AT(set2, 0) &&
4244 OPERAND_AT(set1, 1) == OPERAND_AT(set2, 1)) {
4245 ELEM_REMOVE(set1);
4246 ELEM_REMOVE(&iobj->link);
4247 }
4248 }
4249
4250 /*
4251 * dup
4252 * setlocal x, y
4253 * dup
4254 * setlocal x, y
4255 * =>
4256 * dup
4257 * setlocal x, y
4258 */
4259 else if (IS_NEXT_INSN_ID(set1, dup) &&
4260 IS_NEXT_INSN_ID(set1->next, setlocal)) {
4261 set2 = set1->next->next;
4262 if (OPERAND_AT(set1, 0) == OPERAND_AT(set2, 0) &&
4263 OPERAND_AT(set1, 1) == OPERAND_AT(set2, 1)) {
4264 ELEM_REMOVE(set1->next);
4265 ELEM_REMOVE(set2);
4266 }
4267 }
4268 }
4269 }
4270
4271 /*
4272 * getlocal x, y
4273 * dup
4274 * setlocal x, y
4275 * =>
4276 * dup
4277 */
4278 if (IS_INSN_ID(iobj, getlocal)) {
4279 LINK_ELEMENT *niobj = &iobj->link;
4280 if (IS_NEXT_INSN_ID(niobj, dup)) {
4281 niobj = niobj->next;
4282 }
4283 if (IS_NEXT_INSN_ID(niobj, setlocal)) {
4284 LINK_ELEMENT *set1 = niobj->next;
4285 if (OPERAND_AT(iobj, 0) == OPERAND_AT(set1, 0) &&
4286 OPERAND_AT(iobj, 1) == OPERAND_AT(set1, 1)) {
4287 ELEM_REMOVE(set1);
4288 ELEM_REMOVE(niobj);
4289 }
4290 }
4291 }
4292
4293 /*
4294 * opt_invokebuiltin_delegate
4295 * trace
4296 * leave
4297 * =>
4298 * opt_invokebuiltin_delegate_leave
4299 * trace
4300 * leave
4301 */
4302 if (IS_INSN_ID(iobj, opt_invokebuiltin_delegate)) {
4303 if (IS_TRACE(iobj->link.next)) {
4304 if (IS_NEXT_INSN_ID(iobj->link.next, leave)) {
4305 iobj->insn_id = BIN(opt_invokebuiltin_delegate_leave);
4306 const struct rb_builtin_function *bf = (const struct rb_builtin_function *)iobj->operands[0];
4307 if (iobj == (INSN *)list && bf->argc == 0 && (ISEQ_BODY(iseq)->builtin_attrs & BUILTIN_ATTR_LEAF)) {
4308 ISEQ_BODY(iseq)->builtin_attrs |= BUILTIN_ATTR_SINGLE_NOARG_LEAF;
4309 }
4310 }
4311 }
4312 }
4313
4314 /*
4315 * getblockparam
4316 * branchif / branchunless
4317 * =>
4318 * getblockparamproxy
4319 * branchif / branchunless
4320 */
4321 if (IS_INSN_ID(iobj, getblockparam)) {
4322 if (IS_NEXT_INSN_ID(&iobj->link, branchif) || IS_NEXT_INSN_ID(&iobj->link, branchunless)) {
4323 iobj->insn_id = BIN(getblockparamproxy);
4324 }
4325 }
4326
4327 if (IS_INSN_ID(iobj, splatarray) && OPERAND_AT(iobj, 0) == false) {
4328 LINK_ELEMENT *niobj = &iobj->link;
4329 if (IS_NEXT_INSN_ID(niobj, duphash)) {
4330 niobj = niobj->next;
4331 LINK_ELEMENT *siobj;
4332 unsigned int set_flags = 0, unset_flags = 0;
4333
4334 /*
4335 * Eliminate hash allocation for f(*a, kw: 1)
4336 *
4337 * splatarray false
4338 * duphash
4339 * send ARGS_SPLAT|KW_SPLAT|KW_SPLAT_MUT and not ARGS_BLOCKARG
4340 * =>
4341 * splatarray false
4342 * putobject
4343 * send ARGS_SPLAT|KW_SPLAT
4344 */
4345 if (IS_NEXT_INSN_ID(niobj, send)) {
4346 siobj = niobj->next;
4347 set_flags = VM_CALL_ARGS_SPLAT|VM_CALL_KW_SPLAT|VM_CALL_KW_SPLAT_MUT;
4348 unset_flags = VM_CALL_ARGS_BLOCKARG;
4349 }
4350 /*
4351 * Eliminate hash allocation for f(*a, kw: 1, &{arg,lvar,@iv})
4352 *
4353 * splatarray false
4354 * duphash
4355 * getlocal / getinstancevariable / getblockparamproxy
4356 * send ARGS_SPLAT|KW_SPLAT|KW_SPLAT_MUT|ARGS_BLOCKARG
4357 * =>
4358 * splatarray false
4359 * putobject
4360 * getlocal / getinstancevariable / getblockparamproxy
4361 * send ARGS_SPLAT|KW_SPLAT|ARGS_BLOCKARG
4362 */
4363 else if ((IS_NEXT_INSN_ID(niobj, getlocal) || IS_NEXT_INSN_ID(niobj, getinstancevariable) ||
4364 IS_NEXT_INSN_ID(niobj, getblockparamproxy)) && (IS_NEXT_INSN_ID(niobj->next, send))) {
4365 siobj = niobj->next->next;
4366 set_flags = VM_CALL_ARGS_SPLAT|VM_CALL_KW_SPLAT|VM_CALL_KW_SPLAT_MUT|VM_CALL_ARGS_BLOCKARG;
4367 }
4368
4369 if (set_flags) {
4370 const struct rb_callinfo *ci = (const struct rb_callinfo *)OPERAND_AT(siobj, 0);
4371 unsigned int flags = vm_ci_flag(ci);
4372 if ((flags & set_flags) == set_flags && !(flags & unset_flags)) {
4373 ((INSN*)niobj)->insn_id = BIN(putobject);
4374 RB_OBJ_WRITE(iseq, &OPERAND_AT(niobj, 0), RB_OBJ_SET_SHAREABLE(rb_hash_freeze(rb_hash_resurrect(OPERAND_AT(niobj, 0)))));
4375
4376 const struct rb_callinfo *nci = vm_ci_new(vm_ci_mid(ci),
4377 flags & ~VM_CALL_KW_SPLAT_MUT, vm_ci_argc(ci), vm_ci_kwarg(ci));
4378 RB_OBJ_WRITTEN(iseq, ci, nci);
4379 OPERAND_AT(siobj, 0) = (VALUE)nci;
4380 }
4381 }
4382 }
4383 }
4384
4385 /*
4386 * putself / (or any other independent instruction)
4387 * putnil / (or any other independent instruction)
4388 * swap
4389 * =>
4390 * putnil / (or any other independent instruction)
4391 * putself / (or any other independent instruction)
4392 */
4393 if (IS_NEXT_INSN_ID(&iobj->link, swap)) {
4394 LINK_ELEMENT *second = &iobj->link;
4395 LINK_ELEMENT *first = second->prev;
4396 LINK_ELEMENT *swap = second->next;
4397
4398 if (IS_INDEPENDENT_INSN(first) && IS_INDEPENDENT_INSN(second)) {
4399 ELEM_REMOVE(swap);
4400 ELEM_SWAP(first, second);
4401 }
4402 }
4403
4404 return COMPILE_OK;
4405}
4406
4407static int
4408insn_set_specialized_instruction(rb_iseq_t *iseq, INSN *iobj, int insn_id)
4409{
4410 if (insn_id == BIN(opt_neq)) {
4411 VALUE original_ci = iobj->operands[0];
4412 VALUE new_ci = (VALUE)new_callinfo(iseq, idEq, 1, 0, NULL, FALSE);
4413 insn_replace_with_operands(iseq, iobj, insn_id, 2, new_ci, original_ci);
4414 }
4415 else {
4416 iobj->insn_id = insn_id;
4417 iobj->operand_size = insn_len(insn_id) - 1;
4418 }
4419 iobj->insn_info.events |= RUBY_EVENT_C_CALL | RUBY_EVENT_C_RETURN;
4420
4421 return COMPILE_OK;
4422}
4423
4424static int
4425iseq_specialized_instruction(rb_iseq_t *iseq, INSN *iobj)
4426{
4427 if (IS_INSN_ID(iobj, newarray) && iobj->link.next &&
4428 IS_INSN(iobj->link.next)) {
4429 /*
4430 * [a, b, ...].max/min -> a, b, c, opt_newarray_send max/min
4431 */
4432 INSN *niobj = (INSN *)iobj->link.next;
4433 if (IS_INSN_ID(niobj, send)) {
4434 const struct rb_callinfo *ci = (struct rb_callinfo *)OPERAND_AT(niobj, 0);
4435 if (vm_ci_simple(ci) && vm_ci_argc(ci) == 0) {
4436 VALUE method = INT2FIX(0);
4437 switch (vm_ci_mid(ci)) {
4438 case idMax:
4439 method = INT2FIX(VM_OPT_NEWARRAY_SEND_MAX);
4440 break;
4441 case idMin:
4442 method = INT2FIX(VM_OPT_NEWARRAY_SEND_MIN);
4443 break;
4444 case idHash:
4445 method = INT2FIX(VM_OPT_NEWARRAY_SEND_HASH);
4446 break;
4447 }
4448
4449 if (method != INT2FIX(0)) {
4450 VALUE num = iobj->operands[0];
4451 insn_replace_with_operands(iseq, iobj, BIN(opt_newarray_send), 2, num, method);
4452 ELEM_REMOVE(&niobj->link);
4453 return COMPILE_OK;
4454 }
4455 }
4456 }
4457 else if ((IS_INSN_ID(niobj, dupstring) || IS_INSN_ID(niobj, dupchilledstring) ||
4458 (IS_INSN_ID(niobj, putobject) && RB_TYPE_P(OPERAND_AT(niobj, 0), T_STRING))) &&
4459 IS_NEXT_INSN_ID(&niobj->link, send)) {
4460 const struct rb_callinfo *ci = (struct rb_callinfo *)OPERAND_AT((INSN *)niobj->link.next, 0);
4461 if (vm_ci_simple(ci) && vm_ci_argc(ci) == 1 && vm_ci_mid(ci) == idPack) {
4462 VALUE num = iobj->operands[0];
4463 insn_replace_with_operands(iseq, iobj, BIN(opt_newarray_send), 2, FIXNUM_INC(num, 1), INT2FIX(VM_OPT_NEWARRAY_SEND_PACK));
4464 ELEM_REMOVE(&iobj->link);
4465 ELEM_REMOVE(niobj->link.next);
4466 ELEM_INSERT_NEXT(&niobj->link, &iobj->link);
4467 return COMPILE_OK;
4468 }
4469 }
4470 // newarray n, dupchilledstring "E", getlocal b, send :pack with {buffer: b}
4471 // -> dupchilledstring "E", getlocal b, opt_newarray_send n+2, :pack, :buffer
4472 else if ((IS_INSN_ID(niobj, dupstring) || IS_INSN_ID(niobj, dupchilledstring) ||
4473 (IS_INSN_ID(niobj, putobject) && RB_TYPE_P(OPERAND_AT(niobj, 0), T_STRING))) &&
4474 IS_NEXT_INSN_ID(&niobj->link, getlocal) &&
4475 (niobj->link.next && IS_NEXT_INSN_ID(niobj->link.next, send))) {
4476 const struct rb_callinfo *ci = (struct rb_callinfo *)OPERAND_AT((INSN *)(niobj->link.next)->next, 0);
4477 const struct rb_callinfo_kwarg *kwarg = vm_ci_kwarg(ci);
4478 if (vm_ci_mid(ci) == idPack && vm_ci_argc(ci) == 2 &&
4479 (kwarg && kwarg->keyword_len == 1 && kwarg->keywords[0] == rb_id2sym(idBuffer))) {
4480 VALUE num = iobj->operands[0];
4481 insn_replace_with_operands(iseq, iobj, BIN(opt_newarray_send), 2, FIXNUM_INC(num, 2), INT2FIX(VM_OPT_NEWARRAY_SEND_PACK_BUFFER));
4482 // Remove the "send" insn.
4483 ELEM_REMOVE((niobj->link.next)->next);
4484 // Remove the modified insn from its original "newarray" position...
4485 ELEM_REMOVE(&iobj->link);
4486 // and insert it after the buffer insn.
4487 ELEM_INSERT_NEXT(niobj->link.next, &iobj->link);
4488 return COMPILE_OK;
4489 }
4490 }
4491
4492 // Break the "else if" chain since some prior checks abort after sub-ifs.
4493 // We already found "newarray". To match `[...].include?(arg)` we look for
4494 // the instruction(s) representing the argument followed by a "send".
4495 if ((IS_INSN_ID(niobj, dupstring) || IS_INSN_ID(niobj, dupchilledstring) ||
4496 IS_INSN_ID(niobj, putobject) ||
4497 IS_INSN_ID(niobj, putself) ||
4498 IS_INSN_ID(niobj, getlocal) ||
4499 IS_INSN_ID(niobj, getinstancevariable)) &&
4500 IS_NEXT_INSN_ID(&niobj->link, send)) {
4501
4502 LINK_ELEMENT *sendobj = &(niobj->link); // Below we call ->next;
4503 const struct rb_callinfo *ci;
4504 // Allow any number (0 or more) of simple method calls on the argument
4505 // (as in `[...].include?(arg.method1.method2)`.
4506 do {
4507 sendobj = sendobj->next;
4508 ci = (struct rb_callinfo *)OPERAND_AT(sendobj, 0);
4509 } while (vm_ci_simple(ci) && vm_ci_argc(ci) == 0 && IS_NEXT_INSN_ID(sendobj, send));
4510
4511 // If this send is for .include? with one arg we can do our opt.
4512 if (vm_ci_simple(ci) && vm_ci_argc(ci) == 1 && vm_ci_mid(ci) == idIncludeP) {
4513 VALUE num = iobj->operands[0];
4514 INSN *sendins = (INSN *)sendobj;
4515 insn_replace_with_operands(iseq, sendins, BIN(opt_newarray_send), 2, FIXNUM_INC(num, 1), INT2FIX(VM_OPT_NEWARRAY_SEND_INCLUDE_P));
4516 // Remove the original "newarray" insn.
4517 ELEM_REMOVE(&iobj->link);
4518 return COMPILE_OK;
4519 }
4520 }
4521 }
4522
4523 /*
4524 * duparray [...]
4525 * some insn for the arg...
4526 * send <calldata!mid:include?, argc:1, ARGS_SIMPLE>, nil
4527 * =>
4528 * arg insn...
4529 * opt_duparray_send [...], :include?, 1
4530 */
4531 if (IS_INSN_ID(iobj, duparray) && iobj->link.next && IS_INSN(iobj->link.next)) {
4532 INSN *niobj = (INSN *)iobj->link.next;
4533 if ((IS_INSN_ID(niobj, getlocal) ||
4534 IS_INSN_ID(niobj, getinstancevariable) ||
4535 IS_INSN_ID(niobj, putself) ||
4536 IS_INSN_ID(niobj, putobject) ||
4537 IS_INSN_ID(niobj, putnil)) &&
4538 IS_NEXT_INSN_ID(&niobj->link, send)) {
4539
4540 LINK_ELEMENT *sendobj = &(niobj->link); // Below we call ->next;
4541 const struct rb_callinfo *ci;
4542 // Allow any number (0 or more) of simple method calls on the argument
4543 // (as in `[...].include?(arg.method1.method2)`.
4544 do {
4545 sendobj = sendobj->next;
4546 ci = (struct rb_callinfo *)OPERAND_AT(sendobj, 0);
4547 } while (vm_ci_simple(ci) && vm_ci_argc(ci) == 0 && IS_NEXT_INSN_ID(sendobj, send));
4548
4549 if (vm_ci_simple(ci) && vm_ci_argc(ci) == 1 && vm_ci_mid(ci) == idIncludeP) {
4550 // Move the array arg from duparray to opt_duparray_send.
4551 VALUE ary = iobj->operands[0];
4553
4554 INSN *sendins = (INSN *)sendobj;
4555 insn_replace_with_operands(iseq, sendins, BIN(opt_duparray_send), 3, ary, rb_id2sym(idIncludeP), INT2FIX(1));
4556
4557 // Remove the duparray insn.
4558 ELEM_REMOVE(&iobj->link);
4559 return COMPILE_OK;
4560 }
4561 }
4562 }
4563
4564
4565 if (IS_INSN_ID(iobj, send)) {
4566 const struct rb_callinfo *ci = (struct rb_callinfo *)OPERAND_AT(iobj, 0);
4567 const rb_iseq_t *blockiseq = (rb_iseq_t *)OPERAND_AT(iobj, 1);
4568
4569#define SP_INSN(opt) insn_set_specialized_instruction(iseq, iobj, BIN(opt_##opt))
4570 if (vm_ci_simple(ci)) {
4571 switch (vm_ci_argc(ci)) {
4572 case 0:
4573 switch (vm_ci_mid(ci)) {
4574 case idLength: SP_INSN(length); return COMPILE_OK;
4575 case idSize: SP_INSN(size); return COMPILE_OK;
4576 case idEmptyP: SP_INSN(empty_p);return COMPILE_OK;
4577 case idNilP: SP_INSN(nil_p); return COMPILE_OK;
4578 case idSucc: SP_INSN(succ); return COMPILE_OK;
4579 case idNot: SP_INSN(not); return COMPILE_OK;
4580 }
4581 break;
4582 case 1:
4583 switch (vm_ci_mid(ci)) {
4584 case idPLUS: SP_INSN(plus); return COMPILE_OK;
4585 case idMINUS: SP_INSN(minus); return COMPILE_OK;
4586 case idMULT: SP_INSN(mult); return COMPILE_OK;
4587 case idDIV: SP_INSN(div); return COMPILE_OK;
4588 case idMOD: SP_INSN(mod); return COMPILE_OK;
4589 case idEq: SP_INSN(eq); return COMPILE_OK;
4590 case idNeq: SP_INSN(neq); return COMPILE_OK;
4591 case idEqTilde:SP_INSN(regexpmatch2);return COMPILE_OK;
4592 case idLT: SP_INSN(lt); return COMPILE_OK;
4593 case idLE: SP_INSN(le); return COMPILE_OK;
4594 case idGT: SP_INSN(gt); return COMPILE_OK;
4595 case idGE: SP_INSN(ge); return COMPILE_OK;
4596 case idLTLT: SP_INSN(ltlt); return COMPILE_OK;
4597 case idAREF: SP_INSN(aref); return COMPILE_OK;
4598 case idAnd: SP_INSN(and); return COMPILE_OK;
4599 case idOr: SP_INSN(or); return COMPILE_OK;
4600 }
4601 break;
4602 case 2:
4603 switch (vm_ci_mid(ci)) {
4604 case idASET: SP_INSN(aset); return COMPILE_OK;
4605 }
4606 break;
4607 }
4608 }
4609
4610 if ((vm_ci_flag(ci) & (VM_CALL_ARGS_BLOCKARG | VM_CALL_FORWARDING)) == 0 && blockiseq == NULL) {
4611 iobj->insn_id = BIN(opt_send_without_block);
4612 iobj->operand_size = insn_len(iobj->insn_id) - 1;
4613 }
4614 }
4615#undef SP_INSN
4616
4617 return COMPILE_OK;
4618}
4619
4620static inline int
4621tailcallable_p(rb_iseq_t *iseq)
4622{
4623 switch (ISEQ_BODY(iseq)->type) {
4624 case ISEQ_TYPE_TOP:
4625 case ISEQ_TYPE_EVAL:
4626 case ISEQ_TYPE_MAIN:
4627 /* not tail callable because cfp will be over popped */
4628 case ISEQ_TYPE_RESCUE:
4629 case ISEQ_TYPE_ENSURE:
4630 /* rescue block can't tail call because of errinfo */
4631 return FALSE;
4632 default:
4633 return TRUE;
4634 }
4635}
4636
4637static int
4638iseq_optimize(rb_iseq_t *iseq, LINK_ANCHOR *const anchor)
4639{
4640 LINK_ELEMENT *list;
4641 const int do_peepholeopt = ISEQ_COMPILE_DATA(iseq)->option->peephole_optimization;
4642 const int do_tailcallopt = tailcallable_p(iseq) &&
4643 ISEQ_COMPILE_DATA(iseq)->option->tailcall_optimization;
4644 const int do_si = ISEQ_COMPILE_DATA(iseq)->option->specialized_instruction;
4645 const int do_ou = ISEQ_COMPILE_DATA(iseq)->option->operands_unification;
4646 const int do_without_ints = ISEQ_BODY(iseq)->builtin_attrs & BUILTIN_ATTR_WITHOUT_INTERRUPTS;
4647 int rescue_level = 0;
4648 int tailcallopt = do_tailcallopt;
4649
4650 list = FIRST_ELEMENT(anchor);
4651
4652 int do_block_optimization = 0;
4653 LABEL * block_loop_label = NULL;
4654
4655 int nlabels = ISEQ_COMPILE_DATA(iseq)->label_no;
4656 VALUE unref_counts_buf = 0, unref_stamps_buf = 0;
4658 .capacity = nlabels,
4659 .gen = 0,
4660 .counts = ALLOCV_N(int, unref_counts_buf, nlabels),
4661 .stamps = ALLOCV_N(unsigned int, unref_stamps_buf, nlabels),
4662 };
4663 MEMZERO(unreachable_unref.counts, int, nlabels);
4664 MEMZERO(unreachable_unref.stamps, unsigned int, nlabels);
4665
4666 // If we're optimizing a block
4667 if (ISEQ_BODY(iseq)->type == ISEQ_TYPE_BLOCK) {
4668 do_block_optimization = 1;
4669
4670 // If the block starts with a nop and a label,
4671 // record the label so we can detect if it's a jump target
4672 LINK_ELEMENT * le = FIRST_ELEMENT(anchor)->next;
4673 if (IS_INSN(le) && IS_INSN_ID((INSN *)le, nop) && IS_LABEL(le->next)) {
4674 block_loop_label = (LABEL *)le->next;
4675 }
4676 }
4677
4678 while (list) {
4679 if (IS_INSN(list)) {
4680 if (do_peepholeopt) {
4681 iseq_peephole_optimize(iseq, &unreachable_unref, list, tailcallopt);
4682 }
4683 if (do_si) {
4684 iseq_specialized_instruction(iseq, (INSN *)list);
4685 }
4686 if (do_ou) {
4687 insn_operands_unification((INSN *)list);
4688 }
4689
4690 if (do_without_ints) {
4691 INSN *item = (INSN *)list;
4692 if (IS_INSN_ID(item, jump)) {
4693 item->insn_id = BIN(jump_without_ints);
4694 }
4695 else if (IS_INSN_ID(item, branchif)) {
4696 item->insn_id = BIN(branchif_without_ints);
4697 }
4698 else if (IS_INSN_ID(item, branchunless)) {
4699 item->insn_id = BIN(branchunless_without_ints);
4700 }
4701 else if (IS_INSN_ID(item, branchnil)) {
4702 item->insn_id = BIN(branchnil_without_ints);
4703 }
4704 }
4705
4706 if (do_block_optimization) {
4707 INSN * item = (INSN *)list;
4708 // Give up if there is a throw
4709 if (IS_INSN_ID(item, throw)) {
4710 do_block_optimization = 0;
4711 }
4712 else {
4713 // If the instruction has a jump target, check if the
4714 // jump target is the block loop label
4715 const char *types = insn_op_types(item->insn_id);
4716 for (int j = 0; types[j]; j++) {
4717 if (types[j] == TS_OFFSET) {
4718 // If the jump target is equal to the block loop
4719 // label, then we can't do the optimization because
4720 // the leading `nop` instruction fires the block
4721 // entry tracepoint
4722 LABEL * target = (LABEL *)OPERAND_AT(item, j);
4723 if (target == block_loop_label) {
4724 do_block_optimization = 0;
4725 }
4726 }
4727 }
4728 }
4729 }
4730 }
4731 if (IS_LABEL(list)) {
4732 switch (((LABEL *)list)->rescued) {
4733 case LABEL_RESCUE_BEG:
4734 rescue_level++;
4735 tailcallopt = FALSE;
4736 break;
4737 case LABEL_RESCUE_END:
4738 if (!--rescue_level) tailcallopt = do_tailcallopt;
4739 break;
4740 }
4741 }
4742 list = list->next;
4743 }
4744
4745 if (do_block_optimization) {
4746 LINK_ELEMENT * le = FIRST_ELEMENT(anchor)->next;
4747 if (IS_INSN(le) && IS_INSN_ID((INSN *)le, nop)) {
4748 ELEM_REMOVE(le);
4749 }
4750 }
4751
4752 ALLOCV_END(unref_counts_buf);
4753 ALLOCV_END(unref_stamps_buf);
4754 return COMPILE_OK;
4755}
4756
4757#if OPT_INSTRUCTIONS_UNIFICATION
4758static INSN *
4759new_unified_insn(rb_iseq_t *iseq,
4760 int insn_id, int size, LINK_ELEMENT *seq_list)
4761{
4762 INSN *iobj = 0;
4763 LINK_ELEMENT *list = seq_list;
4764 int i, argc = 0;
4765 VALUE *operands = 0, *ptr = 0;
4766
4767
4768 /* count argc */
4769 for (i = 0; i < size; i++) {
4770 iobj = (INSN *)list;
4771 argc += iobj->operand_size;
4772 list = list->next;
4773 }
4774
4775 if (argc > 0) {
4776 ptr = operands = compile_data_alloc2_type(iseq, VALUE, argc);
4777 }
4778
4779 /* copy operands */
4780 list = seq_list;
4781 for (i = 0; i < size; i++) {
4782 iobj = (INSN *)list;
4783 MEMCPY(ptr, iobj->operands, VALUE, iobj->operand_size);
4784 ptr += iobj->operand_size;
4785 list = list->next;
4786 }
4787
4788 return new_insn_core(iseq, iobj->insn_info.line_no, iobj->insn_info.node_id, insn_id, argc, operands);
4789}
4790#endif
4791
4792/*
4793 * This scheme can get more performance if do this optimize with
4794 * label address resolving.
4795 * It's future work (if compile time was bottle neck).
4796 */
4797static int
4798iseq_insns_unification(rb_iseq_t *iseq, LINK_ANCHOR *const anchor)
4799{
4800#if OPT_INSTRUCTIONS_UNIFICATION
4801 LINK_ELEMENT *list;
4802 INSN *iobj, *niobj;
4803 int id, k;
4804 intptr_t j;
4805
4806 list = FIRST_ELEMENT(anchor);
4807 while (list) {
4808 if (IS_INSN(list)) {
4809 iobj = (INSN *)list;
4810 id = iobj->insn_id;
4811 if (unified_insns_data[id] != 0) {
4812 const int *const *entry = unified_insns_data[id];
4813 for (j = 1; j < (intptr_t)entry[0]; j++) {
4814 const int *unified = entry[j];
4815 LINK_ELEMENT *li = list->next;
4816 for (k = 2; k < unified[1]; k++) {
4817 if (!IS_INSN(li) ||
4818 ((INSN *)li)->insn_id != unified[k]) {
4819 goto miss;
4820 }
4821 li = li->next;
4822 }
4823 /* matched */
4824 niobj =
4825 new_unified_insn(iseq, unified[0], unified[1] - 1,
4826 list);
4827
4828 /* insert to list */
4829 niobj->link.prev = (LINK_ELEMENT *)iobj->link.prev;
4830 niobj->link.next = li;
4831 if (li) {
4832 li->prev = (LINK_ELEMENT *)niobj;
4833 }
4834
4835 list->prev->next = (LINK_ELEMENT *)niobj;
4836 list = (LINK_ELEMENT *)niobj;
4837 break;
4838 miss:;
4839 }
4840 }
4841 }
4842 list = list->next;
4843 }
4844#endif
4845 return COMPILE_OK;
4846}
4847
4848static int
4849all_string_result_p(const NODE *node)
4850{
4851 if (!node) return FALSE;
4852 switch (nd_type(node)) {
4853 case NODE_STR: case NODE_DSTR: case NODE_FILE:
4854 return TRUE;
4855 case NODE_IF: case NODE_UNLESS:
4856 if (!RNODE_IF(node)->nd_body || !RNODE_IF(node)->nd_else) return FALSE;
4857 if (all_string_result_p(RNODE_IF(node)->nd_body))
4858 return all_string_result_p(RNODE_IF(node)->nd_else);
4859 return FALSE;
4860 case NODE_AND: case NODE_OR:
4861 if (!RNODE_AND(node)->nd_2nd)
4862 return all_string_result_p(RNODE_AND(node)->nd_1st);
4863 if (!all_string_result_p(RNODE_AND(node)->nd_1st))
4864 return FALSE;
4865 return all_string_result_p(RNODE_AND(node)->nd_2nd);
4866 default:
4867 return FALSE;
4868 }
4869}
4870
4872 rb_iseq_t *const iseq;
4873 LINK_ANCHOR *const ret;
4874 VALUE lit;
4875 const NODE *lit_node;
4876 int cnt;
4877 int dregx;
4878};
4879
4880static int
4881append_dstr_fragment(struct dstr_ctxt *args, const NODE *const node, rb_parser_string_t *str)
4882{
4883 VALUE s = rb_str_new_mutable_parser_string(str);
4884 if (args->dregx) {
4885 VALUE error = rb_reg_check_preprocess(s);
4886 if (!NIL_P(error)) {
4887 COMPILE_ERROR(args->iseq, nd_line(node), "%" PRIsVALUE, error);
4888 return COMPILE_NG;
4889 }
4890 }
4891 if (NIL_P(args->lit)) {
4892 args->lit = s;
4893 args->lit_node = node;
4894 }
4895 else {
4896 rb_str_buf_append(args->lit, s);
4897 }
4898 return COMPILE_OK;
4899}
4900
4901static void
4902flush_dstr_fragment(struct dstr_ctxt *args)
4903{
4904 if (!NIL_P(args->lit)) {
4905 rb_iseq_t *iseq = args->iseq;
4906 VALUE lit = args->lit;
4907 args->lit = Qnil;
4908 lit = rb_fstring(lit);
4909 ADD_INSN1(args->ret, args->lit_node, putobject, lit);
4910 RB_OBJ_WRITTEN(args->iseq, Qundef, lit);
4911 args->cnt++;
4912 }
4913}
4914
4915static int
4916compile_dstr_fragments_0(struct dstr_ctxt *args, const NODE *const node)
4917{
4918 const struct RNode_LIST *list = RNODE_DSTR(node)->nd_next;
4919 rb_parser_string_t *str = RNODE_DSTR(node)->string;
4920
4921 if (str) {
4922 CHECK(append_dstr_fragment(args, node, str));
4923 }
4924
4925 while (list) {
4926 const NODE *const head = list->nd_head;
4927 if (nd_type_p(head, NODE_STR)) {
4928 CHECK(append_dstr_fragment(args, node, RNODE_STR(head)->string));
4929 }
4930 else if (nd_type_p(head, NODE_DSTR)) {
4931 CHECK(compile_dstr_fragments_0(args, head));
4932 }
4933 else {
4934 flush_dstr_fragment(args);
4935 rb_iseq_t *iseq = args->iseq;
4936 CHECK(COMPILE(args->ret, "each string", head));
4937 args->cnt++;
4938 }
4939 list = (struct RNode_LIST *)list->nd_next;
4940 }
4941 return COMPILE_OK;
4942}
4943
4944static int
4945compile_dstr_fragments(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int *cntp, int dregx)
4946{
4947 struct dstr_ctxt args = {
4948 .iseq = iseq, .ret = ret,
4949 .lit = Qnil, .lit_node = NULL,
4950 .cnt = 0, .dregx = dregx,
4951 };
4952 CHECK(compile_dstr_fragments_0(&args, node));
4953 flush_dstr_fragment(&args);
4954
4955 *cntp = args.cnt;
4956
4957 return COMPILE_OK;
4958}
4959
4960static int
4961compile_block(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *node, int popped)
4962{
4963 while (node && nd_type_p(node, NODE_BLOCK)) {
4964 CHECK(COMPILE_(ret, "BLOCK body", RNODE_BLOCK(node)->nd_head,
4965 (RNODE_BLOCK(node)->nd_next ? 1 : popped)));
4966 node = RNODE_BLOCK(node)->nd_next;
4967 }
4968 if (node) {
4969 CHECK(COMPILE_(ret, "BLOCK next", RNODE_BLOCK(node)->nd_next, popped));
4970 }
4971 return COMPILE_OK;
4972}
4973
4974static void
4975compile_file_path(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int frozen_string_literal)
4976{
4977 ADD_INSN1(ret, node, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
4978 ADD_INSN1(ret, node, putobject, INT2FIX(frozen_string_literal));
4979 ADD_SEND(ret, node, id_core_iseq_path, INT2FIX(1));
4980}
4981
4982static int
4983compile_dstr(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node)
4984{
4985 int cnt;
4986 if (!RNODE_DSTR(node)->nd_next) {
4987 VALUE lit = rb_node_dstr_string_val(node);
4988 ADD_INSN1(ret, node, dupstring, lit);
4990 RB_OBJ_WRITTEN(iseq, Qundef, lit);
4991 }
4992 else {
4993 CHECK(compile_dstr_fragments(iseq, ret, node, &cnt, FALSE));
4994 ADD_INSN1(ret, node, concatstrings, INT2FIX(cnt));
4995 }
4996 return COMPILE_OK;
4997}
4998
4999static int
5000compile_dregx(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped)
5001{
5002 int cnt;
5003 int cflag = (int)RNODE_DREGX(node)->as.nd_cflag;
5004
5005 if (!RNODE_DREGX(node)->nd_next) {
5006 if (!popped) {
5007 VALUE src = rb_node_dregx_string_val(node);
5008 VALUE match = iseq_reg_compile(iseq, src, cflag, NULL, 0);
5009 ADD_INSN1(ret, node, putobject, match);
5010 RB_OBJ_WRITTEN(iseq, Qundef, match);
5011 }
5012 return COMPILE_OK;
5013 }
5014
5015 CHECK(compile_dstr_fragments(iseq, ret, node, &cnt, TRUE));
5016 ADD_INSN2(ret, node, toregexp, INT2FIX(cflag), INT2FIX(cnt));
5017
5018 if (popped) {
5019 ADD_INSN(ret, node, pop);
5020 }
5021
5022 return COMPILE_OK;
5023}
5024
5025static int
5026compile_flip_flop(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int again,
5027 LABEL *then_label, LABEL *else_label)
5028{
5029 const int line = nd_line(node);
5030 LABEL *lend = NEW_LABEL(line);
5031 rb_num_t cnt = ISEQ_FLIP_CNT_INCREMENT(ISEQ_BODY(iseq)->local_iseq)
5032 + VM_SVAR_FLIPFLOP_START;
5033 VALUE key = INT2FIX(cnt);
5034
5035 ADD_INSN2(ret, node, getspecial, key, INT2FIX(0));
5036 ADD_INSNL(ret, node, branchif, lend);
5037
5038 /* *flip == 0 */
5039 CHECK(COMPILE(ret, "flip2 beg", RNODE_FLIP2(node)->nd_beg));
5040 ADD_INSNL(ret, node, branchunless, else_label);
5041 ADD_INSN1(ret, node, putobject, Qtrue);
5042 ADD_INSN1(ret, node, setspecial, key);
5043 if (!again) {
5044 ADD_INSNL(ret, node, jump, then_label);
5045 }
5046
5047 /* *flip == 1 */
5048 ADD_LABEL(ret, lend);
5049 CHECK(COMPILE(ret, "flip2 end", RNODE_FLIP2(node)->nd_end));
5050 ADD_INSNL(ret, node, branchunless, then_label);
5051 ADD_INSN1(ret, node, putobject, Qfalse);
5052 ADD_INSN1(ret, node, setspecial, key);
5053 ADD_INSNL(ret, node, jump, then_label);
5054
5055 return COMPILE_OK;
5056}
5057
5058static int
5059compile_branch_condition(rb_iseq_t *iseq, LINK_ANCHOR *ret, const NODE *cond,
5060 LABEL *then_label, LABEL *else_label);
5061
5062#define COMPILE_SINGLE 2
5063static int
5064compile_logical(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *cond,
5065 LABEL *then_label, LABEL *else_label)
5066{
5067 DECL_ANCHOR(seq);
5068 INIT_ANCHOR(seq);
5069 LABEL *label = NEW_LABEL(nd_line(cond));
5070 if (!then_label) then_label = label;
5071 else if (!else_label) else_label = label;
5072
5073 CHECK(compile_branch_condition(iseq, seq, cond, then_label, else_label));
5074
5075 if (LIST_INSN_SIZE_ONE(seq)) {
5076 INSN *insn = (INSN *)ELEM_FIRST_INSN(FIRST_ELEMENT(seq));
5077 if (insn->insn_id == BIN(jump) && (LABEL *)(insn->operands[0]) == label)
5078 return COMPILE_OK;
5079 }
5080 if (!label->refcnt) {
5081 return COMPILE_SINGLE;
5082 }
5083 ADD_LABEL(seq, label);
5084 ADD_SEQ(ret, seq);
5085 return COMPILE_OK;
5086}
5087
5088static int
5089compile_branch_condition(rb_iseq_t *iseq, LINK_ANCHOR *ret, const NODE *cond,
5090 LABEL *then_label, LABEL *else_label)
5091{
5092 int ok;
5093 DECL_ANCHOR(ignore);
5094
5095 again:
5096 switch (nd_type(cond)) {
5097 case NODE_AND:
5098 CHECK(ok = compile_logical(iseq, ret, RNODE_AND(cond)->nd_1st, NULL, else_label));
5099 cond = RNODE_AND(cond)->nd_2nd;
5100 if (ok == COMPILE_SINGLE) {
5101 ADD_INSNL(ret, cond, jump, else_label);
5102 INIT_ANCHOR(ignore);
5103 ret = ignore;
5104 then_label = NEW_LABEL(nd_line(cond));
5105 }
5106 goto again;
5107 case NODE_OR:
5108 CHECK(ok = compile_logical(iseq, ret, RNODE_OR(cond)->nd_1st, then_label, NULL));
5109 cond = RNODE_OR(cond)->nd_2nd;
5110 if (ok == COMPILE_SINGLE) {
5111 ADD_INSNL(ret, cond, jump, then_label);
5112 INIT_ANCHOR(ignore);
5113 ret = ignore;
5114 else_label = NEW_LABEL(nd_line(cond));
5115 }
5116 goto again;
5117 case NODE_SYM:
5118 case NODE_LINE:
5119 case NODE_FILE:
5120 case NODE_ENCODING:
5121 case NODE_INTEGER: /* NODE_INTEGER is always true */
5122 case NODE_FLOAT: /* NODE_FLOAT is always true */
5123 case NODE_RATIONAL: /* NODE_RATIONAL is always true */
5124 case NODE_IMAGINARY: /* NODE_IMAGINARY is always true */
5125 case NODE_TRUE:
5126 case NODE_STR:
5127 case NODE_REGX:
5128 case NODE_ZLIST:
5129 case NODE_LAMBDA:
5130 /* printf("useless condition eliminate (%s)\n", ruby_node_name(nd_type(cond))); */
5131 ADD_INSNL(ret, cond, jump, then_label);
5132 return COMPILE_OK;
5133 case NODE_FALSE:
5134 case NODE_NIL:
5135 /* printf("useless condition eliminate (%s)\n", ruby_node_name(nd_type(cond))); */
5136 ADD_INSNL(ret, cond, jump, else_label);
5137 return COMPILE_OK;
5138 case NODE_LIST:
5139 case NODE_ARGSCAT:
5140 case NODE_DREGX:
5141 case NODE_DSTR:
5142 CHECK(COMPILE_POPPED(ret, "branch condition", cond));
5143 ADD_INSNL(ret, cond, jump, then_label);
5144 return COMPILE_OK;
5145 case NODE_FLIP2:
5146 CHECK(compile_flip_flop(iseq, ret, cond, TRUE, then_label, else_label));
5147 return COMPILE_OK;
5148 case NODE_FLIP3:
5149 CHECK(compile_flip_flop(iseq, ret, cond, FALSE, then_label, else_label));
5150 return COMPILE_OK;
5151 case NODE_DEFINED:
5152 CHECK(compile_defined_expr(iseq, ret, cond, Qfalse, ret == ignore));
5153 break;
5154 default:
5155 {
5156 DECL_ANCHOR(cond_seq);
5157 INIT_ANCHOR(cond_seq);
5158
5159 CHECK(COMPILE(cond_seq, "branch condition", cond));
5160
5161 if (LIST_INSN_SIZE_ONE(cond_seq)) {
5162 INSN *insn = (INSN *)ELEM_FIRST_INSN(FIRST_ELEMENT(cond_seq));
5163 if (insn->insn_id == BIN(putobject)) {
5164 if (RTEST(insn->operands[0])) {
5165 ADD_INSNL(ret, cond, jump, then_label);
5166 // maybe unreachable
5167 return COMPILE_OK;
5168 }
5169 else {
5170 ADD_INSNL(ret, cond, jump, else_label);
5171 return COMPILE_OK;
5172 }
5173 }
5174 }
5175 ADD_SEQ(ret, cond_seq);
5176 }
5177 break;
5178 }
5179
5180 ADD_INSNL(ret, cond, branchunless, else_label);
5181 ADD_INSNL(ret, cond, jump, then_label);
5182 return COMPILE_OK;
5183}
5184
5185#define HASH_BRACE 1
5186
5187static int
5188keyword_node_p(const NODE *const node)
5189{
5190 return nd_type_p(node, NODE_HASH) && (RNODE_HASH(node)->nd_brace & HASH_BRACE) != HASH_BRACE;
5191}
5192
5193static VALUE
5194get_symbol_value(rb_iseq_t *iseq, const NODE *node)
5195{
5196 switch (nd_type(node)) {
5197 case NODE_SYM:
5198 return rb_node_sym_string_val(node);
5199 default:
5200 UNKNOWN_NODE("get_symbol_value", node, Qnil);
5201 }
5202}
5203
5204static VALUE
5205node_hash_unique_key_index(rb_iseq_t *iseq, rb_node_hash_t *node_hash, int *count_ptr)
5206{
5207 NODE *node = node_hash->nd_head;
5208 VALUE hash = rb_hash_new();
5209 VALUE ary = rb_ary_new();
5210
5211 for (int i = 0; node != NULL; i++, node = RNODE_LIST(RNODE_LIST(node)->nd_next)->nd_next) {
5212 VALUE key = get_symbol_value(iseq, RNODE_LIST(node)->nd_head);
5213 VALUE idx = rb_hash_aref(hash, key);
5214 if (!NIL_P(idx)) {
5215 rb_ary_store(ary, FIX2INT(idx), Qfalse);
5216 (*count_ptr)--;
5217 }
5218 rb_hash_aset(hash, key, INT2FIX(i));
5219 rb_ary_store(ary, i, Qtrue);
5220 (*count_ptr)++;
5221 }
5222
5223 return ary;
5224}
5225
5226static int
5227compile_keyword_arg(rb_iseq_t *iseq, LINK_ANCHOR *const ret,
5228 const NODE *const root_node,
5229 struct rb_callinfo_kwarg **const kw_arg_ptr,
5230 unsigned int *flag)
5231{
5232 RUBY_ASSERT(nd_type_p(root_node, NODE_HASH));
5233 RUBY_ASSERT(kw_arg_ptr != NULL);
5234
5235 if (RNODE_HASH(root_node)->nd_head && nd_type_p(RNODE_HASH(root_node)->nd_head, NODE_LIST)) {
5236 const NODE *node = RNODE_HASH(root_node)->nd_head;
5237 int seen_nodes = 0;
5238
5239 while (node) {
5240 const NODE *key_node = RNODE_LIST(node)->nd_head;
5241 seen_nodes++;
5242
5243 RUBY_ASSERT(nd_type_p(node, NODE_LIST));
5244 if (key_node && nd_type_p(key_node, NODE_SYM)) {
5245 /* can be keywords */
5246 }
5247 else {
5248 if (flag) {
5249 *flag |= VM_CALL_KW_SPLAT;
5250 if (seen_nodes > 1 || RNODE_LIST(RNODE_LIST(node)->nd_next)->nd_next) {
5251 /* A new hash will be created for the keyword arguments
5252 * in this case, so mark the method as passing mutable
5253 * keyword splat.
5254 */
5255 *flag |= VM_CALL_KW_SPLAT_MUT;
5256 }
5257 }
5258 return FALSE;
5259 }
5260 node = RNODE_LIST(node)->nd_next; /* skip value node */
5261 node = RNODE_LIST(node)->nd_next;
5262 }
5263
5264 /* may be keywords */
5265 node = RNODE_HASH(root_node)->nd_head;
5266 {
5267 int len = 0;
5268 VALUE key_index = node_hash_unique_key_index(iseq, RNODE_HASH(root_node), &len);
5269
5270 if (len > VM_CALL_KW_LEN_MAX) {
5271 COMPILE_ERROR(ERROR_ARGS_AT(root_node) "too many keyword arguments (%d, maximum is %d)",
5272 len, (int)VM_CALL_KW_LEN_MAX);
5273 }
5274
5275 struct rb_callinfo_kwarg *kw_arg =
5276 rb_xmalloc_mul_add(len, sizeof(VALUE), sizeof(struct rb_callinfo_kwarg));
5277 VALUE *keywords = kw_arg->keywords;
5278 int i = 0;
5279 int j = 0;
5280 kw_arg->references = 0;
5281 kw_arg->keyword_len = len;
5282
5283 *kw_arg_ptr = kw_arg;
5284
5285 for (i=0; node != NULL; i++, node = RNODE_LIST(RNODE_LIST(node)->nd_next)->nd_next) {
5286 const NODE *key_node = RNODE_LIST(node)->nd_head;
5287 const NODE *val_node = RNODE_LIST(RNODE_LIST(node)->nd_next)->nd_head;
5288 int popped = TRUE;
5289 if (rb_ary_entry(key_index, i)) {
5290 keywords[j] = get_symbol_value(iseq, key_node);
5291 j++;
5292 popped = FALSE;
5293 }
5294 NO_CHECK(COMPILE_(ret, "keyword values", val_node, popped));
5295 }
5296 RUBY_ASSERT(j == len);
5297 return TRUE;
5298 }
5299 }
5300 return FALSE;
5301}
5302
5303static int
5304compile_args(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *node, NODE **kwnode_ptr)
5305{
5306 int len = 0;
5307
5308 for (; node; len++, node = RNODE_LIST(node)->nd_next) {
5309 if (CPDEBUG > 0) {
5310 EXPECT_NODE("compile_args", node, NODE_LIST, -1);
5311 }
5312
5313 if (RNODE_LIST(node)->nd_next == NULL && keyword_node_p(RNODE_LIST(node)->nd_head)) { /* last node is kwnode */
5314 *kwnode_ptr = RNODE_LIST(node)->nd_head;
5315 }
5316 else {
5317 RUBY_ASSERT(!keyword_node_p(RNODE_LIST(node)->nd_head));
5318 NO_CHECK(COMPILE_(ret, "array element", RNODE_LIST(node)->nd_head, FALSE));
5319 }
5320 }
5321
5322 return len;
5323}
5324
5325static inline bool
5326frozen_string_literal_p(const rb_iseq_t *iseq)
5327{
5328 return ISEQ_COMPILE_DATA(iseq)->option->frozen_string_literal > 0;
5329}
5330
5331static inline bool
5332static_literal_node_p(const NODE *node, const rb_iseq_t *iseq, bool hash_key)
5333{
5334 switch (nd_type(node)) {
5335 case NODE_SYM:
5336 case NODE_REGX:
5337 case NODE_LINE:
5338 case NODE_ENCODING:
5339 case NODE_INTEGER:
5340 case NODE_FLOAT:
5341 case NODE_RATIONAL:
5342 case NODE_IMAGINARY:
5343 case NODE_NIL:
5344 case NODE_TRUE:
5345 case NODE_FALSE:
5346 return TRUE;
5347 case NODE_STR:
5348 return hash_key || frozen_string_literal_p(iseq);
5349 default:
5350 return FALSE;
5351 }
5352}
5353
5354static inline VALUE
5355static_literal_value(const NODE *node, rb_iseq_t *iseq)
5356{
5357 switch (nd_type(node)) {
5358 case NODE_INTEGER:
5359 {
5360 VALUE lit = rb_node_integer_literal_val(node);
5361 if (!SPECIAL_CONST_P(lit)) RB_OBJ_SET_SHAREABLE(lit);
5362 return lit;
5363 }
5364 case NODE_FLOAT:
5365 {
5366 VALUE lit = rb_node_float_literal_val(node);
5367 if (!SPECIAL_CONST_P(lit)) RB_OBJ_SET_SHAREABLE(lit);
5368 return lit;
5369 }
5370 case NODE_RATIONAL:
5371 return rb_ractor_make_shareable(rb_node_rational_literal_val(node));
5372 case NODE_IMAGINARY:
5373 return rb_ractor_make_shareable(rb_node_imaginary_literal_val(node));
5374 case NODE_NIL:
5375 return Qnil;
5376 case NODE_TRUE:
5377 return Qtrue;
5378 case NODE_FALSE:
5379 return Qfalse;
5380 case NODE_SYM:
5381 return rb_node_sym_string_val(node);
5382 case NODE_REGX:
5383 return RB_OBJ_SET_SHAREABLE(rb_node_regx_string_val(node));
5384 case NODE_LINE:
5385 return rb_node_line_lineno_val(node);
5386 case NODE_ENCODING:
5387 return rb_node_encoding_val(node);
5388 case NODE_FILE:
5389 case NODE_STR:
5390 if (ISEQ_COMPILE_DATA(iseq)->option->debug_frozen_string_literal || RTEST(ruby_debug)) {
5391 VALUE lit = get_string_value(node);
5392 VALUE str = rb_str_with_debug_created_info(lit, rb_iseq_path(iseq), (int)nd_line(node));
5394 return str;
5395 }
5396 else {
5397 return get_string_value(node);
5398 }
5399 default:
5400 rb_bug("unexpected node: %s", ruby_node_name(nd_type(node)));
5401 }
5402}
5403
5404static int
5405compile_array(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *node, int popped, bool first_chunk)
5406{
5407 const NODE *line_node = node;
5408
5409 if (nd_type_p(node, NODE_ZLIST)) {
5410 if (!popped) {
5411 ADD_INSN1(ret, line_node, newarray, INT2FIX(0));
5412 }
5413 return 0;
5414 }
5415
5416 EXPECT_NODE("compile_array", node, NODE_LIST, -1);
5417
5418 if (popped) {
5419 for (; node; node = RNODE_LIST(node)->nd_next) {
5420 NO_CHECK(COMPILE_(ret, "array element", RNODE_LIST(node)->nd_head, popped));
5421 }
5422 return 1;
5423 }
5424
5425 /* Compilation of an array literal.
5426 * The following code is essentially the same as:
5427 *
5428 * for (int count = 0; node; count++; node->nd_next) {
5429 * compile(node->nd_head);
5430 * }
5431 * ADD_INSN(newarray, count);
5432 *
5433 * However, there are three points.
5434 *
5435 * - The code above causes stack overflow for a big string literal.
5436 * The following limits the stack length up to max_stack_len.
5437 *
5438 * [x1,x2,...,x10000] =>
5439 * push x1 ; push x2 ; ...; push x256; newarray 256;
5440 * push x257; push x258; ...; push x512; pushtoarray 256;
5441 * push x513; push x514; ...; push x768; pushtoarray 256;
5442 * ...
5443 *
5444 * - Long subarray can be optimized by pre-allocating a hidden array.
5445 *
5446 * [1,2,3,...,100] =>
5447 * duparray [1,2,3,...,100]
5448 *
5449 * [x, 1,2,3,...,100, z] =>
5450 * push x; newarray 1;
5451 * putobject [1,2,3,...,100] (<- hidden array); concattoarray;
5452 * push z; pushtoarray 1;
5453 *
5454 * - If the last element is a keyword, pushtoarraykwsplat should be emitted
5455 * to only push it onto the array if it is not empty
5456 * (Note: a keyword is NODE_HASH which is not static_literal_node_p.)
5457 *
5458 * [1,2,3,**kw] =>
5459 * putobject 1; putobject 2; putobject 3; newarray 3; ...; pushtoarraykwsplat kw
5460 */
5461
5462 const int max_stack_len = 0x100;
5463 const int min_tmp_ary_len = 0x40;
5464 int stack_len = 0;
5465
5466 /* Either create a new array, or push to the existing array */
5467#define FLUSH_CHUNK \
5468 if (stack_len) { \
5469 if (first_chunk) ADD_INSN1(ret, line_node, newarray, INT2FIX(stack_len)); \
5470 else ADD_INSN1(ret, line_node, pushtoarray, INT2FIX(stack_len)); \
5471 first_chunk = FALSE; \
5472 stack_len = 0; \
5473 }
5474
5475 while (node) {
5476 int count = 1;
5477
5478 /* pre-allocation check (this branch can be omittable) */
5479 if (static_literal_node_p(RNODE_LIST(node)->nd_head, iseq, false)) {
5480 /* count the elements that are optimizable */
5481 const NODE *node_tmp = RNODE_LIST(node)->nd_next;
5482 for (; node_tmp && static_literal_node_p(RNODE_LIST(node_tmp)->nd_head, iseq, false); node_tmp = RNODE_LIST(node_tmp)->nd_next)
5483 count++;
5484
5485 if ((first_chunk && stack_len == 0 && !node_tmp) || count >= min_tmp_ary_len) {
5486 /* The literal contains only optimizable elements, or the subarray is long enough */
5487 VALUE ary = rb_ary_hidden_new(count);
5488
5489 /* Create a hidden array */
5490 for (; count; count--, node = RNODE_LIST(node)->nd_next)
5491 rb_ary_push(ary, static_literal_value(RNODE_LIST(node)->nd_head, iseq));
5493
5494 /* Emit optimized code */
5495 FLUSH_CHUNK;
5496 if (first_chunk) {
5497 ADD_INSN1(ret, line_node, duparray, ary);
5498 first_chunk = FALSE;
5499 }
5500 else {
5501 ADD_INSN1(ret, line_node, putobject, ary);
5502 ADD_INSN(ret, line_node, concattoarray);
5503 }
5505 RB_OBJ_WRITTEN(iseq, Qundef, ary);
5506 }
5507 }
5508
5509 /* Base case: Compile "count" elements */
5510 for (; count; count--, node = RNODE_LIST(node)->nd_next) {
5511 if (CPDEBUG > 0) {
5512 EXPECT_NODE("compile_array", node, NODE_LIST, -1);
5513 }
5514
5515 if (!RNODE_LIST(node)->nd_next && keyword_node_p(RNODE_LIST(node)->nd_head)) {
5516 /* Create array or push existing non-keyword elements onto array */
5517 if (stack_len == 0 && first_chunk) {
5518 ADD_INSN1(ret, line_node, newarray, INT2FIX(0));
5519 }
5520 else {
5521 FLUSH_CHUNK;
5522 }
5523 NO_CHECK(COMPILE_(ret, "array element", RNODE_LIST(node)->nd_head, 0));
5524 ADD_INSN(ret, line_node, pushtoarraykwsplat);
5525 return 1;
5526 }
5527 else {
5528 NO_CHECK(COMPILE_(ret, "array element", RNODE_LIST(node)->nd_head, 0));
5529 stack_len++;
5530 }
5531
5532 /* If there are many pushed elements, flush them to avoid stack overflow */
5533 if (stack_len >= max_stack_len) FLUSH_CHUNK;
5534 }
5535 }
5536
5537 FLUSH_CHUNK;
5538#undef FLUSH_CHUNK
5539 return 1;
5540}
5541
5542static inline int
5543static_literal_node_pair_p(const NODE *node, const rb_iseq_t *iseq)
5544{
5545 return RNODE_LIST(node)->nd_head && static_literal_node_p(RNODE_LIST(node)->nd_head, iseq, true) && static_literal_node_p(RNODE_LIST(RNODE_LIST(node)->nd_next)->nd_head, iseq, false);
5546}
5547
5548static int
5549compile_hash(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *node, int method_call_keywords, int popped)
5550{
5551 const NODE *line_node = node;
5552
5553 node = RNODE_HASH(node)->nd_head;
5554
5555 if (!node || nd_type_p(node, NODE_ZLIST)) {
5556 if (!popped) {
5557 ADD_INSN1(ret, line_node, newhash, INT2FIX(0));
5558 }
5559 return 0;
5560 }
5561
5562 EXPECT_NODE("compile_hash", node, NODE_LIST, -1);
5563
5564 if (popped) {
5565 for (; node; node = RNODE_LIST(node)->nd_next) {
5566 NO_CHECK(COMPILE_(ret, "hash element", RNODE_LIST(node)->nd_head, popped));
5567 }
5568 return 1;
5569 }
5570
5571 /* Compilation of a hash literal (or keyword arguments).
5572 * This is very similar to compile_array, but there are some differences:
5573 *
5574 * - It contains key-value pairs. So we need to take every two elements.
5575 * We can assume that the length is always even.
5576 *
5577 * - Merging is done by a method call (id_core_hash_merge_bang_ptr).
5578 * Sometimes we need to insert the receiver, so "anchor" is needed.
5579 * In addition, a method call is much slower than concatarray.
5580 * So it pays only when the subsequence is really long.
5581 * (min_tmp_hash_len must be much larger than min_tmp_ary_len.)
5582 *
5583 * - We need to handle keyword splat: **kw.
5584 * For **kw, the key part (node->nd_head) is NULL, and the value part
5585 * (node->nd_next->nd_head) is "kw".
5586 * The code is a bit difficult to avoid hash allocation for **{}.
5587 */
5588
5589 const int max_stack_len = 0x100;
5590 const int min_tmp_hash_len = 0x800;
5591 int stack_len = 0;
5592 int first_chunk = 1;
5593 DECL_ANCHOR(anchor);
5594 INIT_ANCHOR(anchor);
5595
5596 /* Convert pushed elements to a hash, and merge if needed */
5597#define FLUSH_CHUNK() \
5598 if (stack_len) { \
5599 if (first_chunk) { \
5600 APPEND_LIST(ret, anchor); \
5601 ADD_INSN1(ret, line_node, newhash, INT2FIX(stack_len)); \
5602 } \
5603 else { \
5604 ADD_INSN1(ret, line_node, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE)); \
5605 ADD_INSN(ret, line_node, swap); \
5606 APPEND_LIST(ret, anchor); \
5607 ADD_SEND(ret, line_node, id_core_hash_merge_bang_ptr, INT2FIX(stack_len + 1)); \
5608 } \
5609 INIT_ANCHOR(anchor); \
5610 first_chunk = stack_len = 0; \
5611 }
5612
5613 while (node) {
5614 int count = 1;
5615
5616 /* pre-allocation check (this branch can be omittable) */
5617 if (static_literal_node_pair_p(node, iseq)) {
5618 /* count the elements that are optimizable */
5619 const NODE *node_tmp = RNODE_LIST(RNODE_LIST(node)->nd_next)->nd_next;
5620 for (; node_tmp && static_literal_node_pair_p(node_tmp, iseq); node_tmp = RNODE_LIST(RNODE_LIST(node_tmp)->nd_next)->nd_next)
5621 count++;
5622
5623 if ((first_chunk && stack_len == 0 && !node_tmp) || count >= min_tmp_hash_len) {
5624 /* The literal contains only optimizable elements, or the subsequence is long enough */
5625 VALUE ary = rb_ary_hidden_new(count);
5626
5627 /* Create a hidden hash */
5628 for (; count; count--, node = RNODE_LIST(RNODE_LIST(node)->nd_next)->nd_next) {
5629 VALUE elem[2];
5630 elem[0] = static_literal_value(RNODE_LIST(node)->nd_head, iseq);
5631 if (!RB_SPECIAL_CONST_P(elem[0])) RB_OBJ_SET_FROZEN_SHAREABLE(elem[0]);
5632 elem[1] = static_literal_value(RNODE_LIST(RNODE_LIST(node)->nd_next)->nd_head, iseq);
5633 if (!RB_SPECIAL_CONST_P(elem[1])) RB_OBJ_SET_FROZEN_SHAREABLE(elem[1]);
5634 rb_ary_cat(ary, elem, 2);
5635 }
5636 VALUE hash = rb_hash_alloc_fixed_size(Qfalse, RARRAY_LEN(ary) / 2);
5637 rb_hash_bulk_insert(RARRAY_LEN(ary), RARRAY_CONST_PTR(ary), hash);
5638 RB_GC_GUARD(ary);
5639 hash = RB_OBJ_SET_FROZEN_SHAREABLE(hash);
5640
5641 /* Emit optimized code */
5642 FLUSH_CHUNK();
5643 if (first_chunk) {
5644 ADD_INSN1(ret, line_node, duphash, hash);
5645 first_chunk = 0;
5646 }
5647 else {
5648 ADD_INSN1(ret, line_node, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
5649 ADD_INSN(ret, line_node, swap);
5650
5651 ADD_INSN1(ret, line_node, putobject, hash);
5652
5653 ADD_SEND(ret, line_node, id_core_hash_merge_bang_kwd, INT2FIX(2));
5654 }
5655 RB_OBJ_WRITTEN(iseq, Qundef, hash);
5656 }
5657 }
5658
5659 /* Base case: Compile "count" elements */
5660 for (; count; count--, node = RNODE_LIST(RNODE_LIST(node)->nd_next)->nd_next) {
5661
5662 if (CPDEBUG > 0) {
5663 EXPECT_NODE("compile_hash", node, NODE_LIST, -1);
5664 }
5665
5666 if (RNODE_LIST(node)->nd_head) {
5667 /* Normal key-value pair */
5668 NO_CHECK(COMPILE_(anchor, "hash key element", RNODE_LIST(node)->nd_head, 0));
5669 NO_CHECK(COMPILE_(anchor, "hash value element", RNODE_LIST(RNODE_LIST(node)->nd_next)->nd_head, 0));
5670 stack_len += 2;
5671
5672 /* If there are many pushed elements, flush them to avoid stack overflow */
5673 if (stack_len >= max_stack_len) FLUSH_CHUNK();
5674 }
5675 else {
5676 /* kwsplat case: foo(..., **kw, ...) */
5677 FLUSH_CHUNK();
5678
5679 const NODE *kw = RNODE_LIST(RNODE_LIST(node)->nd_next)->nd_head;
5680 int empty_kw = nd_type_p(kw, NODE_HASH) && (!RNODE_HASH(kw)->nd_head); /* foo( ..., **{}, ...) */
5681 int first_kw = first_chunk && stack_len == 0; /* foo(1,2,3, **kw, ...) */
5682 int last_kw = !RNODE_LIST(RNODE_LIST(node)->nd_next)->nd_next; /* foo( ..., **kw) */
5683 int only_kw = last_kw && first_kw; /* foo(1,2,3, **kw) */
5684
5685 empty_kw = empty_kw || nd_type_p(kw, NODE_NIL); /* foo( ..., **nil, ...) */
5686 if (empty_kw) {
5687 if (only_kw && method_call_keywords) {
5688 /* **{} appears at the only keyword argument in method call,
5689 * so it won't be modified.
5690 * kw is a special NODE_LIT that contains a special empty hash,
5691 * so this emits: putobject {}.
5692 * This is only done for method calls and not for literal hashes,
5693 * because literal hashes should always result in a new hash.
5694 */
5695 NO_CHECK(COMPILE(ret, "keyword splat", kw));
5696 }
5697 else if (first_kw) {
5698 /* **{} appears as the first keyword argument, so it may be modified.
5699 * We need to create a fresh hash object.
5700 */
5701 ADD_INSN1(ret, line_node, newhash, INT2FIX(0));
5702 }
5703 /* Any empty keyword splats that are not the first can be ignored.
5704 * since merging an empty hash into the existing hash is the same
5705 * as not merging it. */
5706 }
5707 else {
5708 if (only_kw && method_call_keywords) {
5709 /* **kw is only keyword argument in method call.
5710 * Use directly. This will be not be flagged as mutable.
5711 * This is only done for method calls and not for literal hashes,
5712 * because literal hashes should always result in a new hash.
5713 */
5714 NO_CHECK(COMPILE(ret, "keyword splat", kw));
5715 }
5716 else {
5717 /* There is more than one keyword argument, or this is not a method
5718 * call. In that case, we need to add an empty hash (if first keyword),
5719 * or merge the hash to the accumulated hash (if not the first keyword).
5720 */
5721 ADD_INSN1(ret, line_node, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
5722 if (first_kw) ADD_INSN1(ret, line_node, newhash, INT2FIX(0));
5723 else ADD_INSN(ret, line_node, swap);
5724
5725 NO_CHECK(COMPILE(ret, "keyword splat", kw));
5726
5727 ADD_SEND(ret, line_node, id_core_hash_merge_bang_kwd, INT2FIX(2));
5728 }
5729 }
5730
5731 first_chunk = 0;
5732 }
5733 }
5734 }
5735
5736 FLUSH_CHUNK();
5737#undef FLUSH_CHUNK
5738 return 1;
5739}
5740
5741static VALUE
5742rb_node_case_when_optimizable_literal(const NODE *const node)
5743{
5744 switch (nd_type(node)) {
5745 case NODE_INTEGER:
5746 return rb_node_integer_literal_val(node);
5747 case NODE_FLOAT: {
5748 VALUE v = rb_node_float_literal_val(node);
5749 double ival;
5750
5751 if (modf(RFLOAT_VALUE(v), &ival) == 0.0) {
5752 return FIXABLE(ival) ? LONG2FIX((long)ival) : rb_dbl2big(ival);
5753 }
5754 return v;
5755 }
5756 case NODE_RATIONAL:
5757 case NODE_IMAGINARY:
5758 return Qundef;
5759 case NODE_NIL:
5760 return Qnil;
5761 case NODE_TRUE:
5762 return Qtrue;
5763 case NODE_FALSE:
5764 return Qfalse;
5765 case NODE_SYM:
5766 return rb_node_sym_string_val(node);
5767 case NODE_LINE:
5768 return rb_node_line_lineno_val(node);
5769 case NODE_STR:
5770 return rb_node_str_string_val(node);
5771 }
5772 return Qundef;
5773}
5774
5775static int
5776when_vals(rb_iseq_t *iseq, LINK_ANCHOR *const cond_seq, const NODE *vals,
5777 LABEL *l1, int only_special_literals, VALUE literals)
5778{
5779 while (vals) {
5780 const NODE *val = RNODE_LIST(vals)->nd_head;
5781 VALUE lit = rb_node_case_when_optimizable_literal(val);
5782
5783 if (UNDEF_P(lit)) {
5784 only_special_literals = 0;
5785 }
5786 else {
5787 cdhash_aset_if_missing(literals, lit, (VALUE)(l1));
5788 }
5789
5790 if (nd_type_p(val, NODE_STR)) {
5791 debugp_param("nd_lit", get_string_value(val));
5792 lit = get_string_value(val);
5793 ADD_INSN1(cond_seq, val, putobject, lit);
5794 RB_OBJ_WRITTEN(iseq, Qundef, lit);
5795 }
5796 else {
5797 if (!COMPILE(cond_seq, "when cond", val)) return -1;
5798 }
5799
5800 // Emit pattern === target
5801 ADD_INSN1(cond_seq, vals, topn, INT2FIX(1));
5802 ADD_CALL(cond_seq, vals, idEqq, INT2FIX(1));
5803 ADD_INSNL(cond_seq, val, branchif, l1);
5804 vals = RNODE_LIST(vals)->nd_next;
5805 }
5806 return only_special_literals;
5807}
5808
5809static int
5810when_splat_vals(rb_iseq_t *iseq, LINK_ANCHOR *const cond_seq, const NODE *vals,
5811 LABEL *l1, int only_special_literals, VALUE literals)
5812{
5813 const NODE *line_node = vals;
5814
5815 switch (nd_type(vals)) {
5816 case NODE_LIST:
5817 if (when_vals(iseq, cond_seq, vals, l1, only_special_literals, literals) < 0)
5818 return COMPILE_NG;
5819 break;
5820 case NODE_SPLAT:
5821 ADD_INSN (cond_seq, line_node, dup);
5822 CHECK(COMPILE(cond_seq, "when splat", RNODE_SPLAT(vals)->nd_head));
5823 ADD_INSN1(cond_seq, line_node, splatarray, Qfalse);
5824 ADD_INSN1(cond_seq, line_node, checkmatch, INT2FIX(VM_CHECKMATCH_TYPE_CASE | VM_CHECKMATCH_ARRAY));
5825 ADD_INSNL(cond_seq, line_node, branchif, l1);
5826 break;
5827 case NODE_ARGSCAT:
5828 CHECK(when_splat_vals(iseq, cond_seq, RNODE_ARGSCAT(vals)->nd_head, l1, only_special_literals, literals));
5829 CHECK(when_splat_vals(iseq, cond_seq, RNODE_ARGSCAT(vals)->nd_body, l1, only_special_literals, literals));
5830 break;
5831 case NODE_ARGSPUSH:
5832 CHECK(when_splat_vals(iseq, cond_seq, RNODE_ARGSPUSH(vals)->nd_head, l1, only_special_literals, literals));
5833 ADD_INSN (cond_seq, line_node, dup);
5834 CHECK(COMPILE(cond_seq, "when argspush body", RNODE_ARGSPUSH(vals)->nd_body));
5835 ADD_INSN1(cond_seq, line_node, checkmatch, INT2FIX(VM_CHECKMATCH_TYPE_CASE));
5836 ADD_INSNL(cond_seq, line_node, branchif, l1);
5837 break;
5838 default:
5839 ADD_INSN (cond_seq, line_node, dup);
5840 CHECK(COMPILE(cond_seq, "when val", vals));
5841 ADD_INSN1(cond_seq, line_node, splatarray, Qfalse);
5842 ADD_INSN1(cond_seq, line_node, checkmatch, INT2FIX(VM_CHECKMATCH_TYPE_CASE | VM_CHECKMATCH_ARRAY));
5843 ADD_INSNL(cond_seq, line_node, branchif, l1);
5844 break;
5845 }
5846 return COMPILE_OK;
5847}
5848
5849/* Multiple Assignment Handling
5850 *
5851 * In order to handle evaluation of multiple assignment such that the left hand side
5852 * is evaluated before the right hand side, we need to process the left hand side
5853 * and see if there are any attributes that need to be assigned, or constants set
5854 * on explicit objects. If so, we add instructions to evaluate the receiver of
5855 * any assigned attributes or constants before we process the right hand side.
5856 *
5857 * For a multiple assignment such as:
5858 *
5859 * l1.m1, l2[0] = r3, r4
5860 *
5861 * We start off evaluating l1 and l2, then we evaluate r3 and r4, then we
5862 * assign the result of r3 to l1.m1, and then the result of r4 to l2.m2.
5863 * On the VM stack, this looks like:
5864 *
5865 * self # putself
5866 * l1 # send
5867 * l1, self # putself
5868 * l1, l2 # send
5869 * l1, l2, 0 # putobject 0
5870 * l1, l2, 0, [r3, r4] # after evaluation of RHS
5871 * l1, l2, 0, [r3, r4], r4, r3 # expandarray
5872 * l1, l2, 0, [r3, r4], r4, r3, l1 # topn 5
5873 * l1, l2, 0, [r3, r4], r4, l1, r3 # swap
5874 * l1, l2, 0, [r3, r4], r4, m1= # send
5875 * l1, l2, 0, [r3, r4], r4 # pop
5876 * l1, l2, 0, [r3, r4], r4, l2 # topn 3
5877 * l1, l2, 0, [r3, r4], r4, l2, 0 # topn 3
5878 * l1, l2, 0, [r3, r4], r4, l2, 0, r4 # topn 2
5879 * l1, l2, 0, [r3, r4], r4, []= # send
5880 * l1, l2, 0, [r3, r4], r4 # pop
5881 * l1, l2, 0, [r3, r4] # pop
5882 * [r3, r4], l2, 0, [r3, r4] # setn 3
5883 * [r3, r4], l2, 0 # pop
5884 * [r3, r4], l2 # pop
5885 * [r3, r4] # pop
5886 *
5887 * This is made more complex when you have to handle splats, post args,
5888 * and arbitrary levels of nesting. You need to keep track of the total
5889 * number of attributes to set, and for each attribute, how many entries
5890 * are on the stack before the final attribute, in order to correctly
5891 * calculate the topn value to use to get the receiver of the attribute
5892 * setter method.
5893 *
5894 * A brief description of the VM stack for simple multiple assignment
5895 * with no splat (rhs_array will not be present if the return value of
5896 * the multiple assignment is not needed):
5897 *
5898 * lhs_attr1, lhs_attr2, ..., rhs_array, ..., rhs_arg2, rhs_arg1
5899 *
5900 * For multiple assignment with splats, while processing the part before
5901 * the splat (splat+post here is an array of the splat and the post arguments):
5902 *
5903 * lhs_attr1, lhs_attr2, ..., rhs_array, splat+post, ..., rhs_arg2, rhs_arg1
5904 *
5905 * When processing the splat and post arguments:
5906 *
5907 * lhs_attr1, lhs_attr2, ..., rhs_array, ..., post_arg2, post_arg1, splat
5908 *
5909 * When processing nested multiple assignment, existing values on the stack
5910 * are kept. So for:
5911 *
5912 * (l1.m1, l2.m2), l3.m3, l4* = [r1, r2], r3, r4
5913 *
5914 * The stack layout would be the following before processing the nested
5915 * multiple assignment:
5916 *
5917 * l1, l2, [[r1, r2], r3, r4], [r4], r3, [r1, r2]
5918 *
5919 * In order to handle this correctly, we need to keep track of the nesting
5920 * level for each attribute assignment, as well as the attribute number
5921 * (left hand side attributes are processed left to right) and number of
5922 * arguments to pass to the setter method. struct masgn_lhs_node tracks
5923 * this information.
5924 *
5925 * We also need to track information for the entire multiple assignment, such
5926 * as the total number of arguments, and the current nesting level, to
5927 * handle both nested multiple assignment as well as cases where the
5928 * rhs is not needed. We also need to keep track of all attribute
5929 * assignments in this, which we do using a linked listed. struct masgn_state
5930 * tracks this information.
5931 */
5932
5934 INSN *before_insn;
5935 struct masgn_lhs_node *next;
5936 const NODE *line_node;
5937 int argn;
5938 int num_args;
5939 int lhs_pos;
5940};
5941
5943 struct masgn_lhs_node *first_memo;
5944 struct masgn_lhs_node *last_memo;
5945 int lhs_level;
5946 int num_args;
5947 bool nested;
5948};
5949
5950static int
5951add_masgn_lhs_node(struct masgn_state *state, int lhs_pos, const NODE *line_node, int argc, INSN *before_insn)
5952{
5953 if (!state) {
5954 rb_bug("no masgn_state");
5955 }
5956
5957 struct masgn_lhs_node *memo;
5958 memo = malloc(sizeof(struct masgn_lhs_node));
5959 if (!memo) {
5960 return COMPILE_NG;
5961 }
5962
5963 memo->before_insn = before_insn;
5964 memo->line_node = line_node;
5965 memo->argn = state->num_args + 1;
5966 memo->num_args = argc;
5967 state->num_args += argc;
5968 memo->lhs_pos = lhs_pos;
5969 memo->next = NULL;
5970 if (!state->first_memo) {
5971 state->first_memo = memo;
5972 }
5973 else {
5974 state->last_memo->next = memo;
5975 }
5976 state->last_memo = memo;
5977
5978 return COMPILE_OK;
5979}
5980
5981static int compile_massign0(rb_iseq_t *iseq, LINK_ANCHOR *const pre, LINK_ANCHOR *const rhs, LINK_ANCHOR *const lhs, LINK_ANCHOR *const post, const NODE *const node, struct masgn_state *state, int popped);
5982
5983static int
5984compile_massign_lhs(rb_iseq_t *iseq, LINK_ANCHOR *const pre, LINK_ANCHOR *const rhs, LINK_ANCHOR *const lhs, LINK_ANCHOR *const post, const NODE *const node, struct masgn_state *state, int lhs_pos)
5985{
5986 switch (nd_type(node)) {
5987 case NODE_ATTRASGN: {
5988 INSN *iobj;
5989 const NODE *line_node = node;
5990
5991 CHECK(COMPILE_POPPED(pre, "masgn lhs (NODE_ATTRASGN)", node));
5992
5993 bool safenav_call = false;
5994 LINK_ELEMENT *insn_element = LAST_ELEMENT(pre);
5995 iobj = (INSN *)get_prev_insn((INSN *)insn_element); /* send insn */
5996 ASSUME(iobj);
5997 ELEM_REMOVE(insn_element);
5998 if (!IS_INSN_ID(iobj, send)) {
5999 safenav_call = true;
6000 iobj = (INSN *)get_prev_insn(iobj);
6001 ELEM_INSERT_NEXT(&iobj->link, insn_element);
6002 }
6003 (pre->last = iobj->link.prev)->next = 0;
6004
6005 const struct rb_callinfo *ci = (struct rb_callinfo *)OPERAND_AT(iobj, 0);
6006 int argc = vm_ci_argc(ci) + 1;
6007 ci = ci_argc_set(iseq, ci, argc);
6008 OPERAND_AT(iobj, 0) = (VALUE)ci;
6009 RB_OBJ_WRITTEN(iseq, Qundef, ci);
6010
6011 if (argc == 1) {
6012 ADD_INSN(lhs, line_node, swap);
6013 }
6014 else {
6015 ADD_INSN1(lhs, line_node, topn, INT2FIX(argc));
6016 }
6017
6018 if (!add_masgn_lhs_node(state, lhs_pos, line_node, argc, (INSN *)LAST_ELEMENT(lhs))) {
6019 return COMPILE_NG;
6020 }
6021
6022 iobj->link.prev = lhs->last;
6023 lhs->last->next = &iobj->link;
6024 for (lhs->last = &iobj->link; lhs->last->next; lhs->last = lhs->last->next);
6025 if (vm_ci_flag(ci) & VM_CALL_ARGS_SPLAT) {
6026 int argc = vm_ci_argc(ci);
6027 bool dupsplat = false;
6028 ci = ci_argc_set(iseq, ci, argc - 1);
6029 if (!(vm_ci_flag(ci) & VM_CALL_ARGS_SPLAT_MUT)) {
6030 /* Given h[*a], _ = ary
6031 * setup_args sets VM_CALL_ARGS_SPLAT and not VM_CALL_ARGS_SPLAT_MUT
6032 * `a` must be dupped, because it will be appended with ary[0]
6033 * Since you are dupping `a`, you can set VM_CALL_ARGS_SPLAT_MUT
6034 */
6035 dupsplat = true;
6036 ci = ci_flag_set(iseq, ci, VM_CALL_ARGS_SPLAT_MUT);
6037 }
6038 OPERAND_AT(iobj, 0) = (VALUE)ci;
6039 RB_OBJ_WRITTEN(iseq, Qundef, ci);
6040
6041 /* Given: h[*a], h[*b, 1] = ary
6042 * h[*a] uses splatarray false and does not set VM_CALL_ARGS_SPLAT_MUT,
6043 * so this uses splatarray true on a to dup it before using pushtoarray
6044 * h[*b, 1] uses splatarray true and sets VM_CALL_ARGS_SPLAT_MUT,
6045 * so you can use pushtoarray directly
6046 */
6047 int line_no = nd_line(line_node);
6048 int node_id = nd_node_id(line_node);
6049
6050 if (dupsplat) {
6051 INSERT_BEFORE_INSN(iobj, line_no, node_id, swap);
6052 INSERT_BEFORE_INSN1(iobj, line_no, node_id, splatarray, Qtrue);
6053 INSERT_BEFORE_INSN(iobj, line_no, node_id, swap);
6054 }
6055 INSERT_BEFORE_INSN1(iobj, line_no, node_id, pushtoarray, INT2FIX(1));
6056 }
6057 if (!safenav_call) {
6058 ADD_INSN(lhs, line_node, pop);
6059 if (argc != 1) {
6060 ADD_INSN(lhs, line_node, pop);
6061 }
6062 }
6063 for (int i=0; i < argc; i++) {
6064 ADD_INSN(post, line_node, pop);
6065 }
6066 break;
6067 }
6068 case NODE_MASGN: {
6069 DECL_ANCHOR(nest_rhs);
6070 INIT_ANCHOR(nest_rhs);
6071 DECL_ANCHOR(nest_lhs);
6072 INIT_ANCHOR(nest_lhs);
6073
6074 int prev_level = state->lhs_level;
6075 bool prev_nested = state->nested;
6076 state->nested = 1;
6077 state->lhs_level = lhs_pos - 1;
6078 CHECK(compile_massign0(iseq, pre, nest_rhs, nest_lhs, post, node, state, 1));
6079 state->lhs_level = prev_level;
6080 state->nested = prev_nested;
6081
6082 ADD_SEQ(lhs, nest_rhs);
6083 ADD_SEQ(lhs, nest_lhs);
6084 break;
6085 }
6086 case NODE_CDECL:
6087 if (!RNODE_CDECL(node)->nd_vid) {
6088 /* Special handling only needed for expr::C, not for C */
6089 INSN *iobj;
6090
6091 CHECK(COMPILE_POPPED(pre, "masgn lhs (NODE_CDECL)", node));
6092
6093 LINK_ELEMENT *insn_element = LAST_ELEMENT(pre);
6094 iobj = (INSN *)insn_element; /* setconstant insn */
6095 ELEM_REMOVE((LINK_ELEMENT *)get_prev_insn((INSN *)get_prev_insn(iobj)));
6096 ELEM_REMOVE((LINK_ELEMENT *)get_prev_insn(iobj));
6097 ELEM_REMOVE(insn_element);
6098 pre->last = iobj->link.prev;
6099 ADD_ELEM(lhs, (LINK_ELEMENT *)iobj);
6100
6101 if (!add_masgn_lhs_node(state, lhs_pos, node, 1, (INSN *)LAST_ELEMENT(lhs))) {
6102 return COMPILE_NG;
6103 }
6104
6105 ADD_INSN(post, node, pop);
6106 break;
6107 }
6108 /* Fallthrough */
6109 default: {
6110 DECL_ANCHOR(anchor);
6111 INIT_ANCHOR(anchor);
6112 CHECK(COMPILE_POPPED(anchor, "masgn lhs", node));
6113 ELEM_REMOVE(FIRST_ELEMENT(anchor));
6114 ADD_SEQ(lhs, anchor);
6115 }
6116 }
6117
6118 return COMPILE_OK;
6119}
6120
6121static int
6122compile_massign_opt_lhs(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *lhsn)
6123{
6124 if (lhsn) {
6125 CHECK(compile_massign_opt_lhs(iseq, ret, RNODE_LIST(lhsn)->nd_next));
6126 CHECK(compile_massign_lhs(iseq, ret, ret, ret, ret, RNODE_LIST(lhsn)->nd_head, NULL, 0));
6127 }
6128 return COMPILE_OK;
6129}
6130
6131static int
6132compile_massign_opt(rb_iseq_t *iseq, LINK_ANCHOR *const ret,
6133 const NODE *rhsn, const NODE *orig_lhsn)
6134{
6135 VALUE mem[64];
6136 const int memsize = numberof(mem);
6137 int memindex = 0;
6138 int llen = 0, rlen = 0;
6139 int i;
6140 const NODE *lhsn = orig_lhsn;
6141
6142#define MEMORY(v) { \
6143 int i; \
6144 if (memindex == memsize) return 0; \
6145 for (i=0; i<memindex; i++) { \
6146 if (mem[i] == (v)) return 0; \
6147 } \
6148 mem[memindex++] = (v); \
6149}
6150
6151 if (rhsn == 0 || !nd_type_p(rhsn, NODE_LIST)) {
6152 return 0;
6153 }
6154
6155 while (lhsn) {
6156 const NODE *ln = RNODE_LIST(lhsn)->nd_head;
6157 switch (nd_type(ln)) {
6158 case NODE_LASGN:
6159 case NODE_DASGN:
6160 case NODE_IASGN:
6161 case NODE_CVASGN:
6162 MEMORY(get_nd_vid(ln));
6163 break;
6164 default:
6165 return 0;
6166 }
6167 lhsn = RNODE_LIST(lhsn)->nd_next;
6168 llen++;
6169 }
6170
6171 while (rhsn) {
6172 if (llen <= rlen) {
6173 NO_CHECK(COMPILE_POPPED(ret, "masgn val (popped)", RNODE_LIST(rhsn)->nd_head));
6174 }
6175 else {
6176 NO_CHECK(COMPILE(ret, "masgn val", RNODE_LIST(rhsn)->nd_head));
6177 }
6178 rhsn = RNODE_LIST(rhsn)->nd_next;
6179 rlen++;
6180 }
6181
6182 if (llen > rlen) {
6183 for (i=0; i<llen-rlen; i++) {
6184 ADD_INSN(ret, orig_lhsn, putnil);
6185 }
6186 }
6187
6188 compile_massign_opt_lhs(iseq, ret, orig_lhsn);
6189 return 1;
6190}
6191
6192static int
6193compile_massign0(rb_iseq_t *iseq, LINK_ANCHOR *const pre, LINK_ANCHOR *const rhs, LINK_ANCHOR *const lhs, LINK_ANCHOR *const post, const NODE *const node, struct masgn_state *state, int popped)
6194{
6195 const NODE *rhsn = RNODE_MASGN(node)->nd_value;
6196 const NODE *splatn = RNODE_MASGN(node)->nd_args;
6197 const NODE *lhsn = RNODE_MASGN(node)->nd_head;
6198 const NODE *lhsn_count = lhsn;
6199 int lhs_splat = (splatn && NODE_NAMED_REST_P(splatn)) ? 1 : 0;
6200
6201 int llen = 0;
6202 int lpos = 0;
6203
6204 while (lhsn_count) {
6205 llen++;
6206 lhsn_count = RNODE_LIST(lhsn_count)->nd_next;
6207 }
6208 while (lhsn) {
6209 CHECK(compile_massign_lhs(iseq, pre, rhs, lhs, post, RNODE_LIST(lhsn)->nd_head, state, (llen - lpos) + lhs_splat + state->lhs_level));
6210 lpos++;
6211 lhsn = RNODE_LIST(lhsn)->nd_next;
6212 }
6213
6214 if (lhs_splat) {
6215 if (nd_type_p(splatn, NODE_POSTARG)) {
6216 /*a, b, *r, p1, p2 */
6217 const NODE *postn = RNODE_POSTARG(splatn)->nd_2nd;
6218 const NODE *restn = RNODE_POSTARG(splatn)->nd_1st;
6219 int plen = (int)RNODE_LIST(postn)->as.nd_alen;
6220 int ppos = 0;
6221 int flag = 0x02 | (NODE_NAMED_REST_P(restn) ? 0x01 : 0x00);
6222
6223 ADD_INSN2(lhs, splatn, expandarray, INT2FIX(plen), INT2FIX(flag));
6224
6225 if (NODE_NAMED_REST_P(restn)) {
6226 CHECK(compile_massign_lhs(iseq, pre, rhs, lhs, post, restn, state, 1 + plen + state->lhs_level));
6227 }
6228 while (postn) {
6229 CHECK(compile_massign_lhs(iseq, pre, rhs, lhs, post, RNODE_LIST(postn)->nd_head, state, (plen - ppos) + state->lhs_level));
6230 ppos++;
6231 postn = RNODE_LIST(postn)->nd_next;
6232 }
6233 }
6234 else {
6235 /* a, b, *r */
6236 CHECK(compile_massign_lhs(iseq, pre, rhs, lhs, post, splatn, state, 1 + state->lhs_level));
6237 }
6238 }
6239
6240 if (!state->nested) {
6241 NO_CHECK(COMPILE(rhs, "normal masgn rhs", rhsn));
6242 }
6243
6244 if (!popped) {
6245 ADD_INSN(rhs, node, dup);
6246 }
6247 ADD_INSN2(rhs, node, expandarray, INT2FIX(llen), INT2FIX(lhs_splat));
6248 return COMPILE_OK;
6249}
6250
6251static int
6252compile_massign(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped)
6253{
6254 if (!popped || RNODE_MASGN(node)->nd_args || !compile_massign_opt(iseq, ret, RNODE_MASGN(node)->nd_value, RNODE_MASGN(node)->nd_head)) {
6255 struct masgn_state state;
6256 state.lhs_level = popped ? 0 : 1;
6257 state.nested = 0;
6258 state.num_args = 0;
6259 state.first_memo = NULL;
6260 state.last_memo = NULL;
6261
6262 DECL_ANCHOR(pre);
6263 INIT_ANCHOR(pre);
6264 DECL_ANCHOR(rhs);
6265 INIT_ANCHOR(rhs);
6266 DECL_ANCHOR(lhs);
6267 INIT_ANCHOR(lhs);
6268 DECL_ANCHOR(post);
6269 INIT_ANCHOR(post);
6270 int ok = compile_massign0(iseq, pre, rhs, lhs, post, node, &state, popped);
6271
6272 struct masgn_lhs_node *memo = state.first_memo, *tmp_memo;
6273 while (memo) {
6274 VALUE topn_arg = INT2FIX((state.num_args - memo->argn) + memo->lhs_pos);
6275 for (int i = 0; i < memo->num_args; i++) {
6276 INSERT_BEFORE_INSN1(memo->before_insn, nd_line(memo->line_node), nd_node_id(memo->line_node), topn, topn_arg);
6277 }
6278 tmp_memo = memo->next;
6279 free(memo);
6280 memo = tmp_memo;
6281 }
6282 CHECK(ok);
6283
6284 ADD_SEQ(ret, pre);
6285 ADD_SEQ(ret, rhs);
6286 ADD_SEQ(ret, lhs);
6287 if (!popped && state.num_args >= 1) {
6288 /* make sure rhs array is returned before popping */
6289 ADD_INSN1(ret, node, setn, INT2FIX(state.num_args));
6290 }
6291 ADD_SEQ(ret, post);
6292 }
6293 return COMPILE_OK;
6294}
6295
6296static size_t
6297constant_path_size(const NODE *node, bool *absolute)
6298{
6299 size_t size = 1;
6300 while (true) {
6301 switch (nd_type(node)) {
6302 case NODE_CONST:
6303 return size;
6304 case NODE_COLON3:
6305 *absolute = true;
6306 return size;
6307 case NODE_COLON2:
6308 node = RNODE_COLON2(node)->nd_head;
6309 size++;
6310 break;
6311 default:
6312 return 0;
6313 }
6314 }
6315}
6316
6317static rb_const_path_t
6318compile_const_path(rb_iseq_t *iseq, const NODE *node)
6319{
6320 bool absolute = false;
6321 size_t size = constant_path_size(node, &absolute);
6322 if (size == 0) {
6323 return 0;
6324 }
6325
6326 VALUE buf_v;
6327 ID *ids = ALLOCV_N(ID, buf_v, size);
6328
6329 for (size_t i = size; i > 0; i--) {
6330 switch (nd_type(node)) {
6331 case NODE_CONST:
6332 ids[i - 1] = RNODE_CONST(node)->nd_vid;
6333 break;
6334 case NODE_COLON3:
6335 ids[i - 1] = RNODE_COLON3(node)->nd_mid;
6336 break;
6337 default:
6338 ids[i - 1] = RNODE_COLON2(node)->nd_mid;
6339 node = RNODE_COLON2(node)->nd_head;
6340 break;
6341 }
6342 }
6343 rb_const_path_t const_path = rb_const_path_from_ids(absolute, ids, size);
6344 ALLOCV_END(buf_v);
6345 return const_path;
6346}
6347
6348static int
6349compile_const_prefix(rb_iseq_t *iseq, const NODE *const node,
6350 LINK_ANCHOR *const pref, LINK_ANCHOR *const body)
6351{
6352 switch (nd_type(node)) {
6353 case NODE_CONST:
6354 debugi("compile_const_prefix - colon", RNODE_CONST(node)->nd_vid);
6355 ADD_INSN1(body, node, putobject, Qtrue);
6356 ADD_INSN1(body, node, getconstant, ID2SYM(RNODE_CONST(node)->nd_vid));
6357 break;
6358 case NODE_COLON3:
6359 debugi("compile_const_prefix - colon3", RNODE_COLON3(node)->nd_mid);
6360 ADD_INSN(body, node, pop);
6361 ADD_INSN1(body, node, putobject, rb_cObject);
6362 ADD_INSN1(body, node, putobject, Qtrue);
6363 ADD_INSN1(body, node, getconstant, ID2SYM(RNODE_COLON3(node)->nd_mid));
6364 break;
6365 case NODE_COLON2:
6366 CHECK(compile_const_prefix(iseq, RNODE_COLON2(node)->nd_head, pref, body));
6367 debugi("compile_const_prefix - colon2", RNODE_COLON2(node)->nd_mid);
6368 ADD_INSN1(body, node, putobject, Qfalse);
6369 ADD_INSN1(body, node, getconstant, ID2SYM(RNODE_COLON2(node)->nd_mid));
6370 break;
6371 default:
6372 CHECK(COMPILE(pref, "const colon2 prefix", node));
6373 break;
6374 }
6375 return COMPILE_OK;
6376}
6377
6378static int
6379cpath_const_p(const NODE *node)
6380{
6381 switch (nd_type(node)) {
6382 case NODE_CONST:
6383 case NODE_COLON3:
6384 return TRUE;
6385 case NODE_COLON2:
6386 if (RNODE_COLON2(node)->nd_head) {
6387 return cpath_const_p(RNODE_COLON2(node)->nd_head);
6388 }
6389 return TRUE;
6390 default:
6391 return FALSE;
6392 }
6393}
6394
6395static int
6396compile_cpath(LINK_ANCHOR *const ret, rb_iseq_t *iseq, const NODE *cpath)
6397{
6398 if (nd_type_p(cpath, NODE_COLON3)) {
6399 /* toplevel class ::Foo */
6400 ADD_INSN1(ret, cpath, putobject, rb_cObject);
6401 return VM_DEFINECLASS_FLAG_SCOPED;
6402 }
6403 else if (nd_type_p(cpath, NODE_COLON2) && RNODE_COLON2(cpath)->nd_head) {
6404 /* Bar::Foo or expr::Foo */
6405 NO_CHECK(COMPILE(ret, "nd_else->nd_head", RNODE_COLON2(cpath)->nd_head));
6406 int flags = VM_DEFINECLASS_FLAG_SCOPED;
6407 if (!cpath_const_p(RNODE_COLON2(cpath)->nd_head)) {
6408 flags |= VM_DEFINECLASS_FLAG_DYNAMIC_CREF;
6409 }
6410 return flags;
6411 }
6412 else {
6413 /* class at cbase Foo */
6414 ADD_INSN1(ret, cpath, putspecialobject,
6415 INT2FIX(VM_SPECIAL_OBJECT_CONST_BASE));
6416 return 0;
6417 }
6418}
6419
6420static inline int
6421private_recv_p(const NODE *node)
6422{
6423 NODE *recv = get_nd_recv(node);
6424 if (recv && nd_type_p(recv, NODE_SELF)) {
6425 return RNODE_SELF(recv)->nd_state != 0;
6426 }
6427 return 0;
6428}
6429
6430static void
6431defined_expr(rb_iseq_t *iseq, LINK_ANCHOR *const ret,
6432 const NODE *const node, LABEL **lfinish, VALUE needstr, bool ignore);
6433
6434static int
6435compile_call(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, const enum node_type type, const NODE *const line_node, int popped, bool assume_receiver);
6436
6437static void
6438defined_expr0(rb_iseq_t *iseq, LINK_ANCHOR *const ret,
6439 const NODE *const node, LABEL **lfinish, VALUE needstr,
6440 bool keep_result)
6441{
6442 enum defined_type expr_type = DEFINED_NOT_DEFINED;
6443 enum node_type type;
6444 const int line = nd_line(node);
6445 const NODE *line_node = node;
6446
6447 switch (type = nd_type(node)) {
6448
6449 /* easy literals */
6450 case NODE_NIL:
6451 expr_type = DEFINED_NIL;
6452 break;
6453 case NODE_SELF:
6454 expr_type = DEFINED_SELF;
6455 break;
6456 case NODE_TRUE:
6457 expr_type = DEFINED_TRUE;
6458 break;
6459 case NODE_FALSE:
6460 expr_type = DEFINED_FALSE;
6461 break;
6462
6463 case NODE_HASH:
6464 case NODE_LIST:{
6465 const NODE *vals = (nd_type(node) == NODE_HASH) ? RNODE_HASH(node)->nd_head : node;
6466
6467 if (vals) {
6468 do {
6469 if (RNODE_LIST(vals)->nd_head) {
6470 defined_expr0(iseq, ret, RNODE_LIST(vals)->nd_head, lfinish, Qfalse, false);
6471
6472 if (!lfinish[1]) {
6473 lfinish[1] = NEW_LABEL(line);
6474 }
6475 ADD_INSNL(ret, line_node, branchunless, lfinish[1]);
6476 }
6477 } while ((vals = RNODE_LIST(vals)->nd_next) != NULL);
6478 }
6479 }
6480 /* fall through */
6481 case NODE_STR:
6482 case NODE_SYM:
6483 case NODE_REGX:
6484 case NODE_LINE:
6485 case NODE_FILE:
6486 case NODE_ENCODING:
6487 case NODE_INTEGER:
6488 case NODE_FLOAT:
6489 case NODE_RATIONAL:
6490 case NODE_IMAGINARY:
6491 case NODE_ZLIST:
6492 case NODE_AND:
6493 case NODE_OR:
6494 default:
6495 expr_type = DEFINED_EXPR;
6496 break;
6497
6498 case NODE_SPLAT:
6499 defined_expr0(iseq, ret, RNODE_LIST(node)->nd_head, lfinish, Qfalse, false);
6500 if (!lfinish[1]) {
6501 lfinish[1] = NEW_LABEL(line);
6502 }
6503 ADD_INSNL(ret, line_node, branchunless, lfinish[1]);
6504 expr_type = DEFINED_EXPR;
6505 break;
6506
6507 /* variables */
6508 case NODE_LVAR:
6509 case NODE_DVAR:
6510 expr_type = DEFINED_LVAR;
6511 break;
6512
6513#define PUSH_VAL(type) (needstr == Qfalse ? Qtrue : rb_iseq_defined_string(type))
6514 case NODE_IVAR:
6515 ADD_INSN3(ret, line_node, definedivar,
6516 ID2SYM(RNODE_IVAR(node)->nd_vid), get_ivar_ic_value(iseq,RNODE_IVAR(node)->nd_vid), PUSH_VAL(DEFINED_IVAR));
6517 return;
6518
6519 case NODE_GVAR:
6520 ADD_INSN(ret, line_node, putnil);
6521 ADD_INSN3(ret, line_node, defined, INT2FIX(DEFINED_GVAR),
6522 ID2SYM(RNODE_GVAR(node)->nd_vid), PUSH_VAL(DEFINED_GVAR));
6523 return;
6524
6525 case NODE_CVAR:
6526 ADD_INSN(ret, line_node, putnil);
6527 ADD_INSN3(ret, line_node, defined, INT2FIX(DEFINED_CVAR),
6528 ID2SYM(RNODE_CVAR(node)->nd_vid), PUSH_VAL(DEFINED_CVAR));
6529 return;
6530
6531 case NODE_CONST:
6532 ADD_INSN(ret, line_node, putnil);
6533 ADD_INSN3(ret, line_node, defined, INT2FIX(DEFINED_CONST),
6534 ID2SYM(RNODE_CONST(node)->nd_vid), PUSH_VAL(DEFINED_CONST));
6535 return;
6536 case NODE_COLON2:
6537 if (!lfinish[1]) {
6538 lfinish[1] = NEW_LABEL(line);
6539 }
6540 defined_expr0(iseq, ret, RNODE_COLON2(node)->nd_head, lfinish, Qfalse, false);
6541 ADD_INSNL(ret, line_node, branchunless, lfinish[1]);
6542 NO_CHECK(COMPILE(ret, "defined/colon2#nd_head", RNODE_COLON2(node)->nd_head));
6543
6544 if (rb_is_const_id(RNODE_COLON2(node)->nd_mid)) {
6545 ADD_INSN3(ret, line_node, defined, INT2FIX(DEFINED_CONST_FROM),
6546 ID2SYM(RNODE_COLON2(node)->nd_mid), PUSH_VAL(DEFINED_CONST));
6547 }
6548 else {
6549 ADD_INSN3(ret, line_node, defined, INT2FIX(DEFINED_METHOD),
6550 ID2SYM(RNODE_COLON2(node)->nd_mid), PUSH_VAL(DEFINED_METHOD));
6551 }
6552 return;
6553 case NODE_COLON3:
6554 ADD_INSN1(ret, line_node, putobject, rb_cObject);
6555 ADD_INSN3(ret, line_node, defined,
6556 INT2FIX(DEFINED_CONST_FROM), ID2SYM(RNODE_COLON3(node)->nd_mid), PUSH_VAL(DEFINED_CONST));
6557 return;
6558
6559 /* method dispatch */
6560 case NODE_CALL:
6561 case NODE_OPCALL:
6562 case NODE_VCALL:
6563 case NODE_FCALL:
6564 case NODE_ATTRASGN:{
6565 const int explicit_receiver =
6566 (type == NODE_CALL || type == NODE_OPCALL ||
6567 (type == NODE_ATTRASGN && !private_recv_p(node)));
6568
6569 if (get_nd_args(node) || explicit_receiver) {
6570 if (!lfinish[1]) {
6571 lfinish[1] = NEW_LABEL(line);
6572 }
6573 if (!lfinish[2]) {
6574 lfinish[2] = NEW_LABEL(line);
6575 }
6576 }
6577 if (get_nd_args(node)) {
6578 defined_expr0(iseq, ret, get_nd_args(node), lfinish, Qfalse, false);
6579 ADD_INSNL(ret, line_node, branchunless, lfinish[1]);
6580 }
6581 if (explicit_receiver) {
6582 defined_expr0(iseq, ret, get_nd_recv(node), lfinish, Qfalse, true);
6583 switch (nd_type(get_nd_recv(node))) {
6584 case NODE_CALL:
6585 case NODE_OPCALL:
6586 case NODE_VCALL:
6587 case NODE_FCALL:
6588 case NODE_ATTRASGN:
6589 ADD_INSNL(ret, line_node, branchunless, lfinish[2]);
6590 compile_call(iseq, ret, get_nd_recv(node), nd_type(get_nd_recv(node)), line_node, 0, true);
6591 break;
6592 default:
6593 ADD_INSNL(ret, line_node, branchunless, lfinish[1]);
6594 NO_CHECK(COMPILE(ret, "defined/recv", get_nd_recv(node)));
6595 break;
6596 }
6597 if (keep_result) {
6598 ADD_INSN(ret, line_node, dup);
6599 }
6600 ADD_INSN3(ret, line_node, defined, INT2FIX(DEFINED_METHOD),
6601 ID2SYM(get_node_call_nd_mid(node)), PUSH_VAL(DEFINED_METHOD));
6602 }
6603 else {
6604 ADD_INSN(ret, line_node, putself);
6605 if (keep_result) {
6606 ADD_INSN(ret, line_node, dup);
6607 }
6608 ADD_INSN3(ret, line_node, defined, INT2FIX(DEFINED_FUNC),
6609 ID2SYM(get_node_call_nd_mid(node)), PUSH_VAL(DEFINED_METHOD));
6610 }
6611 return;
6612 }
6613
6614 case NODE_YIELD:
6615 ADD_INSN(ret, line_node, putnil);
6616 ADD_INSN3(ret, line_node, defined, INT2FIX(DEFINED_YIELD), 0,
6617 PUSH_VAL(DEFINED_YIELD));
6618 iseq_set_use_block(ISEQ_BODY(iseq)->local_iseq);
6619 return;
6620
6621 case NODE_BACK_REF:
6622 case NODE_NTH_REF:
6623 ADD_INSN(ret, line_node, putnil);
6624 ADD_INSN3(ret, line_node, defined, INT2FIX(DEFINED_REF),
6625 INT2FIX((RNODE_BACK_REF(node)->nd_nth << 1) | (type == NODE_BACK_REF)),
6626 PUSH_VAL(DEFINED_GVAR));
6627 return;
6628
6629 case NODE_SUPER:
6630 case NODE_ZSUPER:
6631 ADD_INSN(ret, line_node, putnil);
6632 ADD_INSN3(ret, line_node, defined, INT2FIX(DEFINED_ZSUPER), 0,
6633 PUSH_VAL(DEFINED_ZSUPER));
6634 return;
6635
6636#undef PUSH_VAL
6637 case NODE_OP_ASGN1:
6638 case NODE_OP_ASGN2:
6639 case NODE_OP_ASGN_OR:
6640 case NODE_OP_ASGN_AND:
6641 case NODE_MASGN:
6642 case NODE_LASGN:
6643 case NODE_DASGN:
6644 case NODE_GASGN:
6645 case NODE_IASGN:
6646 case NODE_CDECL:
6647 case NODE_CVASGN:
6648 case NODE_OP_CDECL:
6649 expr_type = DEFINED_ASGN;
6650 break;
6651 }
6652
6653 RUBY_ASSERT(expr_type != DEFINED_NOT_DEFINED);
6654
6655 if (needstr != Qfalse) {
6656 VALUE str = rb_iseq_defined_string(expr_type);
6657 ADD_INSN1(ret, line_node, putobject, str);
6658 }
6659 else {
6660 ADD_INSN1(ret, line_node, putobject, Qtrue);
6661 }
6662}
6663
6664static void
6665build_defined_rescue_iseq(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const void *unused)
6666{
6667 ADD_SYNTHETIC_INSN(ret, 0, -1, putnil);
6668 iseq_set_exception_local_table(iseq);
6669}
6670
6671static void
6672defined_expr(rb_iseq_t *iseq, LINK_ANCHOR *const ret,
6673 const NODE *const node, LABEL **lfinish, VALUE needstr, bool ignore)
6674{
6675 LINK_ELEMENT *lcur = ret->last;
6676 defined_expr0(iseq, ret, node, lfinish, needstr, false);
6677 if (lfinish[1]) {
6678 int line = nd_line(node);
6679 LABEL *lstart = NEW_LABEL(line);
6680 LABEL *lend = NEW_LABEL(line);
6681 const rb_iseq_t *rescue;
6683 rb_iseq_new_with_callback_new_callback(build_defined_rescue_iseq, NULL);
6684 rescue = NEW_CHILD_ISEQ_WITH_CALLBACK(ifunc,
6685 rb_str_concat(rb_str_new2("defined guard in "),
6686 ISEQ_BODY(iseq)->location.label),
6687 ISEQ_TYPE_RESCUE, 0);
6688 lstart->rescued = LABEL_RESCUE_BEG;
6689 lend->rescued = LABEL_RESCUE_END;
6690 APPEND_LABEL(ret, lcur, lstart);
6691 ADD_LABEL(ret, lend);
6692 if (!ignore) {
6693 ADD_CATCH_ENTRY(CATCH_TYPE_RESCUE, lstart, lend, rescue, lfinish[1]);
6694 }
6695 }
6696}
6697
6698static int
6699compile_defined_expr(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, VALUE needstr, bool ignore)
6700{
6701 const int line = nd_line(node);
6702 const NODE *line_node = node;
6703 if (!RNODE_DEFINED(node)->nd_head) {
6704 VALUE str = rb_iseq_defined_string(DEFINED_NIL);
6705 ADD_INSN1(ret, line_node, putobject, str);
6706 }
6707 else {
6708 LABEL *lfinish[3];
6709 LINK_ELEMENT *last = ret->last;
6710 lfinish[0] = NEW_LABEL(line);
6711 lfinish[1] = 0;
6712 lfinish[2] = 0;
6713 defined_expr(iseq, ret, RNODE_DEFINED(node)->nd_head, lfinish, needstr, ignore);
6714 if (lfinish[1]) {
6715 ELEM_INSERT_NEXT(last, &new_insn_body(iseq, nd_line(line_node), nd_node_id(line_node), BIN(putnil), 0)->link);
6716 ADD_INSN(ret, line_node, swap);
6717 if (lfinish[2]) {
6718 ADD_LABEL(ret, lfinish[2]);
6719 }
6720 ADD_INSN(ret, line_node, pop);
6721 ADD_LABEL(ret, lfinish[1]);
6722 }
6723 ADD_LABEL(ret, lfinish[0]);
6724 }
6725 return COMPILE_OK;
6726}
6727
6728static VALUE
6729make_name_for_block(const rb_iseq_t *orig_iseq)
6730{
6731 int level = 1;
6732 const rb_iseq_t *iseq = orig_iseq;
6733
6734 if (ISEQ_BODY(orig_iseq)->parent_iseq != 0) {
6735 while (ISEQ_BODY(orig_iseq)->local_iseq != iseq) {
6736 if (ISEQ_BODY(iseq)->type == ISEQ_TYPE_BLOCK) {
6737 level++;
6738 }
6739 iseq = ISEQ_BODY(iseq)->parent_iseq;
6740 }
6741 }
6742
6743 if (level == 1) {
6744 return rb_sprintf("block in %"PRIsVALUE, ISEQ_BODY(iseq)->location.label);
6745 }
6746 else {
6747 return rb_sprintf("block (%d levels) in %"PRIsVALUE, level, ISEQ_BODY(iseq)->location.label);
6748 }
6749}
6750
6751static void
6752push_ensure_entry(rb_iseq_t *iseq,
6754 struct ensure_range *er, const void *const node)
6755{
6756 enl->ensure_node = node;
6757 enl->prev = ISEQ_COMPILE_DATA(iseq)->ensure_node_stack; /* prev */
6758 enl->erange = er;
6759 ISEQ_COMPILE_DATA(iseq)->ensure_node_stack = enl;
6760}
6761
6762static void
6763add_ensure_range(rb_iseq_t *iseq, struct ensure_range *erange,
6764 LABEL *lstart, LABEL *lend)
6765{
6766 struct ensure_range *ne =
6767 compile_data_alloc_type(iseq, struct ensure_range);
6768
6769 while (erange->next != 0) {
6770 erange = erange->next;
6771 }
6772 ne->next = 0;
6773 ne->begin = lend;
6774 ne->end = erange->end;
6775 erange->end = lstart;
6776
6777 erange->next = ne;
6778}
6779
6780static bool
6781has_ensure_iseq(const rb_iseq_t *iseq)
6782{
6784 for (e = ISEQ_COMPILE_DATA(iseq)->ensure_node_stack; e; e = e->prev) {
6785 if (e->ensure_node) return true;
6786 }
6787 return false;
6788}
6789
6790static bool
6791can_add_ensure_iseq(const rb_iseq_t *iseq)
6792{
6793 return !ISEQ_COMPILE_DATA(iseq)->in_rescue || !has_ensure_iseq(iseq);
6794}
6795
6796static bool
6797can_inline_return(const rb_iseq_t *iseq, enum rb_iseq_type type)
6798{
6799 return type == ISEQ_TYPE_METHOD &&
6800 ((!ISEQ_COMPILE_DATA(iseq)->in_rescue && !ISEQ_COMPILE_DATA(iseq)->redo_label) || !has_ensure_iseq(iseq));
6801}
6802
6803static void
6804add_ensure_iseq(LINK_ANCHOR *const ret, rb_iseq_t *iseq, int is_return)
6805{
6806 RUBY_ASSERT(can_add_ensure_iseq(iseq));
6807
6809 ISEQ_COMPILE_DATA(iseq)->ensure_node_stack;
6810 struct iseq_compile_data_ensure_node_stack *prev_enlp = enlp;
6811 DECL_ANCHOR(ensure);
6812
6813 INIT_ANCHOR(ensure);
6814 while (enlp) {
6815 if (enlp->erange != NULL) {
6816 DECL_ANCHOR(ensure_part);
6817 LABEL *lstart = NEW_LABEL(0);
6818 LABEL *lend = NEW_LABEL(0);
6819 INIT_ANCHOR(ensure_part);
6820
6821 add_ensure_range(iseq, enlp->erange, lstart, lend);
6822
6823 ISEQ_COMPILE_DATA(iseq)->ensure_node_stack = enlp->prev;
6824 ADD_LABEL(ensure_part, lstart);
6825 NO_CHECK(COMPILE_POPPED(ensure_part, "ensure part", enlp->ensure_node));
6826 ADD_LABEL(ensure_part, lend);
6827 ADD_SEQ(ensure, ensure_part);
6828 }
6829 else {
6830 if (!is_return) {
6831 break;
6832 }
6833 }
6834 enlp = enlp->prev;
6835 }
6836 ISEQ_COMPILE_DATA(iseq)->ensure_node_stack = prev_enlp;
6837 ADD_SEQ(ret, ensure);
6838}
6839
6840#if RUBY_DEBUG
6841static int
6842check_keyword(const NODE *node)
6843{
6844 /* This check is essentially a code clone of compile_keyword_arg. */
6845
6846 if (nd_type_p(node, NODE_LIST)) {
6847 while (RNODE_LIST(node)->nd_next) {
6848 node = RNODE_LIST(node)->nd_next;
6849 }
6850 node = RNODE_LIST(node)->nd_head;
6851 }
6852
6853 return keyword_node_p(node);
6854}
6855#endif
6856
6857static bool
6858keyword_node_single_splat_p(NODE *kwnode)
6859{
6860 RUBY_ASSERT(keyword_node_p(kwnode));
6861
6862 NODE *node = RNODE_HASH(kwnode)->nd_head;
6863 return RNODE_LIST(node)->nd_head == NULL &&
6864 RNODE_LIST(RNODE_LIST(node)->nd_next)->nd_next == NULL;
6865}
6866
6867static void
6868compile_single_keyword_splat_mutable(rb_iseq_t *iseq, LINK_ANCHOR *const args, const NODE *argn,
6869 NODE *kwnode, unsigned int *flag_ptr)
6870{
6871 if (flag_ptr) *flag_ptr |= VM_CALL_KW_SPLAT_MUT;
6872 ADD_INSN1(args, argn, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
6873 ADD_INSN1(args, argn, newhash, INT2FIX(0));
6874 compile_hash(iseq, args, kwnode, TRUE, FALSE);
6875 ADD_SEND(args, argn, id_core_hash_merge_kwd, INT2FIX(2));
6876}
6877
6878#define SPLATARRAY_FALSE 0
6879#define SPLATARRAY_TRUE 1
6880#define DUP_SINGLE_KW_SPLAT 2
6881
6882static int
6883setup_args_core(rb_iseq_t *iseq, LINK_ANCHOR *const args, const NODE *argn,
6884 unsigned int *dup_rest, unsigned int *flag_ptr, struct rb_callinfo_kwarg **kwarg_ptr)
6885{
6886 if (!argn) return 0;
6887
6888 NODE *kwnode = NULL;
6889
6890 switch (nd_type(argn)) {
6891 case NODE_LIST: {
6892 // f(x, y, z)
6893 int len = compile_args(iseq, args, argn, &kwnode);
6894 RUBY_ASSERT(flag_ptr == NULL || (*flag_ptr & VM_CALL_ARGS_SPLAT) == 0);
6895
6896 if (kwnode) {
6897 if (kwarg_ptr && compile_keyword_arg(iseq, args, kwnode, kwarg_ptr, flag_ptr)) {
6898 len -= 1;
6899 }
6900 else {
6901 if (keyword_node_single_splat_p(kwnode) && (*dup_rest & DUP_SINGLE_KW_SPLAT)) {
6902 compile_single_keyword_splat_mutable(iseq, args, argn, kwnode, flag_ptr);
6903 }
6904 else {
6905 compile_hash(iseq, args, kwnode, TRUE, FALSE);
6906 }
6907 }
6908 }
6909
6910 return len;
6911 }
6912 case NODE_SPLAT: {
6913 // f(*a)
6914 NO_CHECK(COMPILE(args, "args (splat)", RNODE_SPLAT(argn)->nd_head));
6915 ADD_INSN1(args, argn, splatarray, RBOOL(*dup_rest & SPLATARRAY_TRUE));
6916 if (*dup_rest & SPLATARRAY_TRUE) *dup_rest &= ~SPLATARRAY_TRUE;
6917 if (flag_ptr) *flag_ptr |= VM_CALL_ARGS_SPLAT;
6918 RUBY_ASSERT(flag_ptr == NULL || (*flag_ptr & VM_CALL_KW_SPLAT) == 0);
6919 return 1;
6920 }
6921 case NODE_ARGSCAT: {
6922 if (flag_ptr) *flag_ptr |= VM_CALL_ARGS_SPLAT;
6923 int argc = setup_args_core(iseq, args, RNODE_ARGSCAT(argn)->nd_head, dup_rest, NULL, NULL);
6924 bool args_pushed = false;
6925
6926 if (nd_type_p(RNODE_ARGSCAT(argn)->nd_body, NODE_LIST)) {
6927 int rest_len = compile_args(iseq, args, RNODE_ARGSCAT(argn)->nd_body, &kwnode);
6928 if (kwnode) rest_len--;
6929 ADD_INSN1(args, argn, pushtoarray, INT2FIX(rest_len));
6930 args_pushed = true;
6931 }
6932 else {
6933 RUBY_ASSERT(!check_keyword(RNODE_ARGSCAT(argn)->nd_body));
6934 NO_CHECK(COMPILE(args, "args (cat: splat)", RNODE_ARGSCAT(argn)->nd_body));
6935 }
6936
6937 if (nd_type_p(RNODE_ARGSCAT(argn)->nd_head, NODE_LIST)) {
6938 ADD_INSN1(args, argn, splatarray, RBOOL(*dup_rest & SPLATARRAY_TRUE));
6939 if (*dup_rest & SPLATARRAY_TRUE) *dup_rest &= ~SPLATARRAY_TRUE;
6940 argc += 1;
6941 }
6942 else if (!args_pushed) {
6943 ADD_INSN(args, argn, concattoarray);
6944 }
6945
6946 // f(..., *a, ..., k1:1, ...) #=> f(..., *[*a, ...], **{k1:1, ...})
6947 if (kwnode) {
6948 // kwsplat
6949 if (flag_ptr) *flag_ptr |= VM_CALL_KW_SPLAT;
6950 compile_hash(iseq, args, kwnode, TRUE, FALSE);
6951 argc += 1;
6952 }
6953
6954 return argc;
6955 }
6956 case NODE_ARGSPUSH: {
6957 if (flag_ptr) *flag_ptr |= VM_CALL_ARGS_SPLAT;
6958 int argc = setup_args_core(iseq, args, RNODE_ARGSPUSH(argn)->nd_head, dup_rest, NULL, NULL);
6959
6960 if (nd_type_p(RNODE_ARGSPUSH(argn)->nd_body, NODE_LIST)) {
6961 int rest_len = compile_args(iseq, args, RNODE_ARGSPUSH(argn)->nd_body, &kwnode);
6962 if (kwnode) rest_len--;
6963 ADD_INSN1(args, argn, newarray, INT2FIX(rest_len));
6964 ADD_INSN1(args, argn, pushtoarray, INT2FIX(1));
6965 }
6966 else {
6967 if (keyword_node_p(RNODE_ARGSPUSH(argn)->nd_body)) {
6968 kwnode = RNODE_ARGSPUSH(argn)->nd_body;
6969 }
6970 else {
6971 NO_CHECK(COMPILE(args, "args (cat: splat)", RNODE_ARGSPUSH(argn)->nd_body));
6972 ADD_INSN1(args, argn, pushtoarray, INT2FIX(1));
6973 }
6974 }
6975
6976 if (kwnode) {
6977 // f(*a, k:1)
6978 if (flag_ptr) *flag_ptr |= VM_CALL_KW_SPLAT;
6979 if (!keyword_node_single_splat_p(kwnode)) {
6980 if (flag_ptr) *flag_ptr |= VM_CALL_KW_SPLAT_MUT;
6981 compile_hash(iseq, args, kwnode, TRUE, FALSE);
6982 }
6983 else if (*dup_rest & DUP_SINGLE_KW_SPLAT) {
6984 compile_single_keyword_splat_mutable(iseq, args, argn, kwnode, flag_ptr);
6985 }
6986 else {
6987 compile_hash(iseq, args, kwnode, TRUE, FALSE);
6988 }
6989 argc += 1;
6990 }
6991
6992 return argc;
6993 }
6994 default: {
6995 UNKNOWN_NODE("setup_arg", argn, Qnil);
6996 }
6997 }
6998}
6999
7000static void
7001setup_args_splat_mut(unsigned int *flag, int dup_rest, int initial_dup_rest)
7002{
7003 if ((*flag & VM_CALL_ARGS_SPLAT) && dup_rest != initial_dup_rest) {
7004 *flag |= VM_CALL_ARGS_SPLAT_MUT;
7005 }
7006}
7007
7008static bool
7009setup_args_dup_rest_p(const NODE *argn)
7010{
7011 switch(nd_type(argn)) {
7012 case NODE_LVAR:
7013 case NODE_DVAR:
7014 case NODE_GVAR:
7015 case NODE_IVAR:
7016 case NODE_CVAR:
7017 case NODE_CONST:
7018 case NODE_COLON3:
7019 case NODE_INTEGER:
7020 case NODE_FLOAT:
7021 case NODE_RATIONAL:
7022 case NODE_IMAGINARY:
7023 case NODE_STR:
7024 case NODE_SYM:
7025 case NODE_REGX:
7026 case NODE_SELF:
7027 case NODE_NIL:
7028 case NODE_TRUE:
7029 case NODE_FALSE:
7030 case NODE_LAMBDA:
7031 case NODE_NTH_REF:
7032 case NODE_BACK_REF:
7033 return false;
7034 case NODE_COLON2:
7035 return setup_args_dup_rest_p(RNODE_COLON2(argn)->nd_head);
7036 case NODE_LIST:
7037 while (argn) {
7038 if (setup_args_dup_rest_p(RNODE_LIST(argn)->nd_head)) {
7039 return true;
7040 }
7041 argn = RNODE_LIST(argn)->nd_next;
7042 }
7043 return false;
7044 default:
7045 return true;
7046 }
7047}
7048
7049static VALUE
7050setup_args(rb_iseq_t *iseq, LINK_ANCHOR *const args, const NODE *argn,
7051 unsigned int *flag, struct rb_callinfo_kwarg **keywords)
7052{
7053 VALUE ret;
7054 unsigned int dup_rest = SPLATARRAY_TRUE, initial_dup_rest;
7055 RUBY_ASSERT(flag);
7056
7057 if (argn) {
7058 const NODE *check_arg = nd_type_p(argn, NODE_BLOCK_PASS) ?
7059 RNODE_BLOCK_PASS(argn)->nd_head : argn;
7060
7061 if (check_arg) {
7062 switch(nd_type(check_arg)) {
7063 case(NODE_SPLAT):
7064 // avoid caller side array allocation for f(*arg)
7065 dup_rest = SPLATARRAY_FALSE;
7066 break;
7067 case(NODE_ARGSCAT):
7068 // avoid caller side array allocation for f(1, *arg)
7069 dup_rest = !nd_type_p(RNODE_ARGSCAT(check_arg)->nd_head, NODE_LIST);
7070 break;
7071 case(NODE_ARGSPUSH):
7072 // avoid caller side array allocation for f(*arg, **hash) and f(1, *arg, **hash)
7073 dup_rest = !((nd_type_p(RNODE_ARGSPUSH(check_arg)->nd_head, NODE_SPLAT) ||
7074 (nd_type_p(RNODE_ARGSPUSH(check_arg)->nd_head, NODE_ARGSCAT) &&
7075 nd_type_p(RNODE_ARGSCAT(RNODE_ARGSPUSH(check_arg)->nd_head)->nd_head, NODE_LIST))) &&
7076 nd_type_p(RNODE_ARGSPUSH(check_arg)->nd_body, NODE_HASH) &&
7077 !RNODE_HASH(RNODE_ARGSPUSH(check_arg)->nd_body)->nd_brace);
7078
7079 if (dup_rest == SPLATARRAY_FALSE) {
7080 // require allocation for keyword key/value/splat that may modify splatted argument
7081 NODE *node = RNODE_HASH(RNODE_ARGSPUSH(check_arg)->nd_body)->nd_head;
7082 while (node) {
7083 NODE *key_node = RNODE_LIST(node)->nd_head;
7084 if (key_node && setup_args_dup_rest_p(key_node)) {
7085 dup_rest = SPLATARRAY_TRUE;
7086 break;
7087 }
7088
7089 node = RNODE_LIST(node)->nd_next;
7090 NODE *value_node = RNODE_LIST(node)->nd_head;
7091 if (setup_args_dup_rest_p(value_node)) {
7092 dup_rest = SPLATARRAY_TRUE;
7093 break;
7094 }
7095
7096 node = RNODE_LIST(node)->nd_next;
7097 }
7098 }
7099 break;
7100 default:
7101 break;
7102 }
7103 }
7104
7105 if (check_arg != argn && setup_args_dup_rest_p(RNODE_BLOCK_PASS(argn)->nd_body)) {
7106 // for block pass that may modify splatted argument, dup rest and kwrest if given
7107 dup_rest = SPLATARRAY_TRUE | DUP_SINGLE_KW_SPLAT;
7108 }
7109 }
7110 initial_dup_rest = dup_rest;
7111
7112 if (argn && nd_type_p(argn, NODE_BLOCK_PASS)) {
7113 DECL_ANCHOR(arg_block);
7114 INIT_ANCHOR(arg_block);
7115
7116 if (RNODE_BLOCK_PASS(argn)->forwarding && ISEQ_BODY(ISEQ_BODY(iseq)->local_iseq)->param.flags.forwardable) {
7117 int idx = ISEQ_BODY(ISEQ_BODY(iseq)->local_iseq)->local_table_size;// - get_local_var_idx(iseq, idDot3);
7118
7119 RUBY_ASSERT(nd_type_p(RNODE_BLOCK_PASS(argn)->nd_head, NODE_ARGSPUSH));
7120 const NODE * arg_node =
7121 RNODE_ARGSPUSH(RNODE_BLOCK_PASS(argn)->nd_head)->nd_head;
7122
7123 int argc = 0;
7124
7125 // Only compile leading args:
7126 // foo(x, y, ...)
7127 // ^^^^
7128 if (nd_type_p(arg_node, NODE_ARGSCAT)) {
7129 argc += setup_args_core(iseq, args, RNODE_ARGSCAT(arg_node)->nd_head, &dup_rest, flag, keywords);
7130 }
7131
7132 *flag |= VM_CALL_FORWARDING;
7133
7134 ADD_GETLOCAL(args, argn, idx, get_lvar_level(iseq));
7135 setup_args_splat_mut(flag, dup_rest, initial_dup_rest);
7136 return INT2FIX(argc);
7137 }
7138 else {
7139 *flag |= VM_CALL_ARGS_BLOCKARG;
7140
7141 NO_CHECK(COMPILE(arg_block, "block", RNODE_BLOCK_PASS(argn)->nd_body));
7142 }
7143
7144 if (LIST_INSN_SIZE_ONE(arg_block)) {
7145 LINK_ELEMENT *elem = FIRST_ELEMENT(arg_block);
7146 if (IS_INSN(elem)) {
7147 INSN *iobj = (INSN *)elem;
7148 if (iobj->insn_id == BIN(getblockparam)) {
7149 iobj->insn_id = BIN(getblockparamproxy);
7150 }
7151 }
7152 }
7153 ret = INT2FIX(setup_args_core(iseq, args, RNODE_BLOCK_PASS(argn)->nd_head, &dup_rest, flag, keywords));
7154 ADD_SEQ(args, arg_block);
7155 }
7156 else {
7157 ret = INT2FIX(setup_args_core(iseq, args, argn, &dup_rest, flag, keywords));
7158 }
7159 setup_args_splat_mut(flag, dup_rest, initial_dup_rest);
7160 return ret;
7161}
7162
7163static void
7164build_postexe_iseq(rb_iseq_t *iseq, LINK_ANCHOR *ret, const void *ptr)
7165{
7166 const NODE *body = ptr;
7167 int line = nd_line(body);
7168 VALUE argc = INT2FIX(0);
7169 const rb_iseq_t *block = NEW_CHILD_ISEQ(body, make_name_for_block(ISEQ_BODY(iseq)->parent_iseq), ISEQ_TYPE_BLOCK, line);
7170
7171 ADD_INSN1(ret, body, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
7172 ADD_CALL_WITH_BLOCK(ret, body, id_core_set_postexe, argc, block);
7173 RB_OBJ_WRITTEN(iseq, Qundef, (VALUE)block);
7174 iseq_set_local_table(iseq, 0, 0);
7175}
7176
7177static void
7178compile_named_capture_assign(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node)
7179{
7180 const NODE *vars;
7181 LINK_ELEMENT *last;
7182 int line = nd_line(node);
7183 const NODE *line_node = node;
7184 LABEL *fail_label = NEW_LABEL(line), *end_label = NEW_LABEL(line);
7185
7186#if !(defined(NAMED_CAPTURE_BY_SVAR) && NAMED_CAPTURE_BY_SVAR-0)
7187 ADD_INSN1(ret, line_node, getglobal, ID2SYM(idBACKREF));
7188#else
7189 ADD_INSN2(ret, line_node, getspecial, INT2FIX(1) /* '~' */, INT2FIX(0));
7190#endif
7191 ADD_INSN(ret, line_node, dup);
7192 ADD_INSNL(ret, line_node, branchunless, fail_label);
7193
7194 for (vars = node; vars; vars = RNODE_BLOCK(vars)->nd_next) {
7195 INSN *cap;
7196 if (RNODE_BLOCK(vars)->nd_next) {
7197 ADD_INSN(ret, line_node, dup);
7198 }
7199 last = ret->last;
7200 NO_CHECK(COMPILE_POPPED(ret, "capture", RNODE_BLOCK(vars)->nd_head));
7201 last = last->next; /* putobject :var */
7202 cap = new_insn_send(iseq, nd_line(line_node), nd_node_id(line_node), idAREF, INT2FIX(1),
7203 NULL, INT2FIX(0), NULL);
7204 ELEM_INSERT_PREV(last->next, (LINK_ELEMENT *)cap);
7205#if !defined(NAMED_CAPTURE_SINGLE_OPT) || NAMED_CAPTURE_SINGLE_OPT-0
7206 if (!RNODE_BLOCK(vars)->nd_next && vars == node) {
7207 /* only one name */
7208 DECL_ANCHOR(nom);
7209
7210 INIT_ANCHOR(nom);
7211 ADD_INSNL(nom, line_node, jump, end_label);
7212 ADD_LABEL(nom, fail_label);
7213# if 0 /* $~ must be MatchData or nil */
7214 ADD_INSN(nom, line_node, pop);
7215 ADD_INSN(nom, line_node, putnil);
7216# endif
7217 ADD_LABEL(nom, end_label);
7218 (nom->last->next = cap->link.next)->prev = nom->last;
7219 (cap->link.next = nom->anchor.next)->prev = &cap->link;
7220 return;
7221 }
7222#endif
7223 }
7224 ADD_INSNL(ret, line_node, jump, end_label);
7225 ADD_LABEL(ret, fail_label);
7226 ADD_INSN(ret, line_node, pop);
7227 for (vars = node; vars; vars = RNODE_BLOCK(vars)->nd_next) {
7228 last = ret->last;
7229 NO_CHECK(COMPILE_POPPED(ret, "capture", RNODE_BLOCK(vars)->nd_head));
7230 last = last->next; /* putobject :var */
7231 ((INSN*)last)->insn_id = BIN(putnil);
7232 ((INSN*)last)->operand_size = 0;
7233 }
7234 ADD_LABEL(ret, end_label);
7235}
7236
7237static int
7238optimizable_range_item_p(const NODE *n)
7239{
7240 if (!n) return FALSE;
7241 switch (nd_type(n)) {
7242 case NODE_LINE:
7243 return TRUE;
7244 case NODE_INTEGER:
7245 return TRUE;
7246 case NODE_NIL:
7247 return TRUE;
7248 default:
7249 return FALSE;
7250 }
7251}
7252
7253static VALUE
7254optimized_range_item(const NODE *n)
7255{
7256 switch (nd_type(n)) {
7257 case NODE_LINE:
7258 return rb_node_line_lineno_val(n);
7259 case NODE_INTEGER:
7260 return rb_node_integer_literal_val(n);
7261 case NODE_FLOAT:
7262 return rb_node_float_literal_val(n);
7263 case NODE_RATIONAL:
7264 return rb_node_rational_literal_val(n);
7265 case NODE_IMAGINARY:
7266 return rb_node_imaginary_literal_val(n);
7267 case NODE_NIL:
7268 return Qnil;
7269 default:
7270 rb_bug("unexpected node: %s", ruby_node_name(nd_type(n)));
7271 }
7272}
7273
7274static int
7275compile_if(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped, const enum node_type type)
7276{
7277 const NODE *const node_body = type == NODE_IF ? RNODE_IF(node)->nd_body : RNODE_UNLESS(node)->nd_else;
7278 const NODE *const node_else = type == NODE_IF ? RNODE_IF(node)->nd_else : RNODE_UNLESS(node)->nd_body;
7279
7280 const int line = nd_line(node);
7281 const NODE *line_node = node;
7282 DECL_ANCHOR(cond_seq);
7283 LABEL *then_label, *else_label, *end_label;
7284 VALUE branches = Qfalse;
7285
7286 INIT_ANCHOR(cond_seq);
7287 then_label = NEW_LABEL(line);
7288 else_label = NEW_LABEL(line);
7289 end_label = 0;
7290
7291 NODE *cond = RNODE_IF(node)->nd_cond;
7292 if (nd_type(cond) == NODE_BLOCK) {
7293 cond = RNODE_BLOCK(cond)->nd_head;
7294 }
7295
7296 CHECK(compile_branch_condition(iseq, cond_seq, cond, then_label, else_label));
7297 ADD_SEQ(ret, cond_seq);
7298
7299 if (then_label->refcnt && else_label->refcnt) {
7300 branches = decl_branch_base(iseq, nd_node_id(node), nd_code_loc(node), type == NODE_IF ? "if" : "unless");
7301 }
7302
7303 if (then_label->refcnt) {
7304 ADD_LABEL(ret, then_label);
7305
7306 DECL_ANCHOR(then_seq);
7307 INIT_ANCHOR(then_seq);
7308 CHECK(COMPILE_(then_seq, "then", node_body, popped));
7309
7310 if (else_label->refcnt) {
7311 const NODE *const coverage_node = node_body ? node_body : node;
7312 add_trace_branch_coverage(
7313 iseq,
7314 ret,
7315 nd_code_loc(coverage_node),
7316 nd_node_id(coverage_node),
7317 0,
7318 type == NODE_IF ? "then" : "else",
7319 branches);
7320 end_label = NEW_LABEL(line);
7321 ADD_INSNL(then_seq, line_node, jump, end_label);
7322 if (!popped) {
7323 ADD_INSN(then_seq, line_node, pop);
7324 }
7325 }
7326 ADD_SEQ(ret, then_seq);
7327 }
7328
7329 if (else_label->refcnt) {
7330 ADD_LABEL(ret, else_label);
7331
7332 DECL_ANCHOR(else_seq);
7333 INIT_ANCHOR(else_seq);
7334 CHECK(COMPILE_(else_seq, "else", node_else, popped));
7335
7336 if (then_label->refcnt) {
7337 const NODE *const coverage_node = node_else ? node_else : node;
7338 add_trace_branch_coverage(
7339 iseq,
7340 ret,
7341 nd_code_loc(coverage_node),
7342 nd_node_id(coverage_node),
7343 1,
7344 type == NODE_IF ? "else" : "then",
7345 branches);
7346 }
7347 ADD_SEQ(ret, else_seq);
7348 }
7349
7350 if (end_label) {
7351 ADD_LABEL(ret, end_label);
7352 }
7353
7354 return COMPILE_OK;
7355}
7356
7357static int
7358compile_case(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const orig_node, int popped)
7359{
7360 const NODE *vals;
7361 const NODE *node = orig_node;
7362 LABEL *endlabel, *elselabel;
7363 DECL_ANCHOR(head);
7364 DECL_ANCHOR(body_seq);
7365 DECL_ANCHOR(cond_seq);
7366 int only_special_literals = 1;
7367 VALUE literals = cdhash_new(0);
7368 int line;
7369 enum node_type type;
7370 const NODE *line_node;
7371 VALUE branches = Qfalse;
7372 int branch_id = 0;
7373
7374 INIT_ANCHOR(head);
7375 INIT_ANCHOR(body_seq);
7376 INIT_ANCHOR(cond_seq);
7377
7378 CHECK(COMPILE(head, "case base", RNODE_CASE(node)->nd_head));
7379
7380 branches = decl_branch_base(iseq, nd_node_id(node), nd_code_loc(node), "case");
7381
7382 node = RNODE_CASE(node)->nd_body;
7383 EXPECT_NODE("NODE_CASE", node, NODE_WHEN, COMPILE_NG);
7384 type = nd_type(node);
7385 line = nd_line(node);
7386 line_node = node;
7387
7388 endlabel = NEW_LABEL(line);
7389 elselabel = NEW_LABEL(line);
7390
7391 ADD_SEQ(ret, head); /* case VAL */
7392
7393 while (type == NODE_WHEN) {
7394 LABEL *l1;
7395
7396 l1 = NEW_LABEL(line);
7397 ADD_LABEL(body_seq, l1);
7398 ADD_INSN(body_seq, line_node, pop);
7399
7400 const NODE *const coverage_node = RNODE_WHEN(node)->nd_body ? RNODE_WHEN(node)->nd_body : node;
7401 add_trace_branch_coverage(
7402 iseq,
7403 body_seq,
7404 nd_code_loc(coverage_node),
7405 nd_node_id(coverage_node),
7406 branch_id++,
7407 "when",
7408 branches);
7409
7410 CHECK(COMPILE_(body_seq, "when body", RNODE_WHEN(node)->nd_body, popped));
7411 ADD_INSNL(body_seq, line_node, jump, endlabel);
7412
7413 vals = RNODE_WHEN(node)->nd_head;
7414 if (vals) {
7415 switch (nd_type(vals)) {
7416 case NODE_LIST:
7417 only_special_literals = when_vals(iseq, cond_seq, vals, l1, only_special_literals, literals);
7418 if (only_special_literals < 0) return COMPILE_NG;
7419 break;
7420 case NODE_SPLAT:
7421 case NODE_ARGSCAT:
7422 case NODE_ARGSPUSH:
7423 only_special_literals = 0;
7424 CHECK(when_splat_vals(iseq, cond_seq, vals, l1, only_special_literals, literals));
7425 break;
7426 default:
7427 UNKNOWN_NODE("NODE_CASE", vals, COMPILE_NG);
7428 }
7429 }
7430 else {
7431 EXPECT_NODE_NONULL("NODE_CASE", node, NODE_LIST, COMPILE_NG);
7432 }
7433
7434 node = RNODE_WHEN(node)->nd_next;
7435 if (!node) {
7436 break;
7437 }
7438 type = nd_type(node);
7439 line = nd_line(node);
7440 line_node = node;
7441 }
7442 /* else */
7443 if (node) {
7444 ADD_LABEL(cond_seq, elselabel);
7445 ADD_INSN(cond_seq, line_node, pop);
7446 add_trace_branch_coverage(iseq, cond_seq, nd_code_loc(node), nd_node_id(node), branch_id, "else", branches);
7447 CHECK(COMPILE_(cond_seq, "else", node, popped));
7448 ADD_INSNL(cond_seq, line_node, jump, endlabel);
7449 }
7450 else {
7451 debugs("== else (implicit)\n");
7452 ADD_LABEL(cond_seq, elselabel);
7453 ADD_INSN(cond_seq, orig_node, pop);
7454 add_trace_branch_coverage(iseq, cond_seq, nd_code_loc(orig_node), nd_node_id(orig_node), branch_id, "else", branches);
7455 if (!popped) {
7456 ADD_INSN(cond_seq, orig_node, putnil);
7457 }
7458 ADD_INSNL(cond_seq, orig_node, jump, endlabel);
7459 }
7460
7461 if (only_special_literals && ISEQ_COMPILE_DATA(iseq)->option->specialized_instruction) {
7462 ADD_INSN(ret, orig_node, dup);
7463 ADD_INSN2(ret, orig_node, opt_case_dispatch, literals, elselabel);
7464 RB_OBJ_WRITTEN(iseq, Qundef, literals);
7465 LABEL_REF(elselabel);
7466 }
7467
7468 ADD_SEQ(ret, cond_seq);
7469 ADD_SEQ(ret, body_seq);
7470 ADD_LABEL(ret, endlabel);
7471 return COMPILE_OK;
7472}
7473
7474static int
7475compile_case2(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const orig_node, int popped)
7476{
7477 const NODE *vals;
7478 const NODE *val;
7479 const NODE *node = RNODE_CASE2(orig_node)->nd_body;
7480 LABEL *endlabel;
7481 DECL_ANCHOR(body_seq);
7482 VALUE branches = Qfalse;
7483 int branch_id = 0;
7484
7485 branches = decl_branch_base(iseq, nd_node_id(orig_node), nd_code_loc(orig_node), "case");
7486
7487 INIT_ANCHOR(body_seq);
7488 endlabel = NEW_LABEL(nd_line(node));
7489
7490 while (node && nd_type_p(node, NODE_WHEN)) {
7491 const int line = nd_line(node);
7492 LABEL *l1 = NEW_LABEL(line);
7493 ADD_LABEL(body_seq, l1);
7494
7495 const NODE *const coverage_node = RNODE_WHEN(node)->nd_body ? RNODE_WHEN(node)->nd_body : node;
7496 add_trace_branch_coverage(
7497 iseq,
7498 body_seq,
7499 nd_code_loc(coverage_node),
7500 nd_node_id(coverage_node),
7501 branch_id++,
7502 "when",
7503 branches);
7504
7505 CHECK(COMPILE_(body_seq, "when", RNODE_WHEN(node)->nd_body, popped));
7506 ADD_INSNL(body_seq, node, jump, endlabel);
7507
7508 vals = RNODE_WHEN(node)->nd_head;
7509 if (!vals) {
7510 EXPECT_NODE_NONULL("NODE_WHEN", node, NODE_LIST, COMPILE_NG);
7511 }
7512 switch (nd_type(vals)) {
7513 case NODE_LIST:
7514 while (vals) {
7515 LABEL *lnext;
7516 val = RNODE_LIST(vals)->nd_head;
7517 lnext = NEW_LABEL(nd_line(val));
7518 debug_compile("== when2\n", (void)0);
7519 CHECK(compile_branch_condition(iseq, ret, val, l1, lnext));
7520 ADD_LABEL(ret, lnext);
7521 vals = RNODE_LIST(vals)->nd_next;
7522 }
7523 break;
7524 case NODE_SPLAT:
7525 case NODE_ARGSCAT:
7526 case NODE_ARGSPUSH:
7527 ADD_INSN(ret, vals, putnil);
7528 CHECK(COMPILE(ret, "when2/cond splat", vals));
7529 ADD_INSN1(ret, vals, checkmatch, INT2FIX(VM_CHECKMATCH_TYPE_WHEN | VM_CHECKMATCH_ARRAY));
7530 ADD_INSNL(ret, vals, branchif, l1);
7531 break;
7532 default:
7533 UNKNOWN_NODE("NODE_WHEN", vals, COMPILE_NG);
7534 }
7535 node = RNODE_WHEN(node)->nd_next;
7536 }
7537 /* else */
7538 const NODE *const coverage_node = node ? node : orig_node;
7539 add_trace_branch_coverage(
7540 iseq,
7541 ret,
7542 nd_code_loc(coverage_node),
7543 nd_node_id(coverage_node),
7544 branch_id,
7545 "else",
7546 branches);
7547 CHECK(COMPILE_(ret, "else", node, popped));
7548 ADD_INSNL(ret, orig_node, jump, endlabel);
7549
7550 ADD_SEQ(ret, body_seq);
7551 ADD_LABEL(ret, endlabel);
7552 return COMPILE_OK;
7553}
7554
7555static int iseq_compile_pattern_match(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, LABEL *unmatched, bool in_single_pattern, bool in_alt_pattern, int base_index, bool use_deconstructed_cache);
7556
7557static int iseq_compile_pattern_constant(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, LABEL *match_failed, bool in_single_pattern, int base_index);
7558static int iseq_compile_array_deconstruct(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, LABEL *deconstruct, LABEL *deconstructed, LABEL *match_failed, LABEL *type_error, bool in_single_pattern, int base_index, bool use_deconstructed_cache);
7559static int iseq_compile_pattern_set_general_errmsg(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, VALUE errmsg, int base_index);
7560static int iseq_compile_pattern_set_length_errmsg(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, VALUE errmsg, VALUE pattern_length, int base_index);
7561static int iseq_compile_pattern_set_eqq_errmsg(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int base_index);
7562
7563#define CASE3_BI_OFFSET_DECONSTRUCTED_CACHE 0
7564#define CASE3_BI_OFFSET_ERROR_STRING 1
7565#define CASE3_BI_OFFSET_KEY_ERROR_P 2
7566#define CASE3_BI_OFFSET_KEY_ERROR_MATCHEE 3
7567#define CASE3_BI_OFFSET_KEY_ERROR_KEY 4
7568
7569static int
7570iseq_compile_pattern_each(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, LABEL *matched, LABEL *unmatched, bool in_single_pattern, bool in_alt_pattern, int base_index, bool use_deconstructed_cache)
7571{
7572 const int line = nd_line(node);
7573 const NODE *line_node = node;
7574
7575 switch (nd_type(node)) {
7576 case NODE_ARYPTN: {
7577 /*
7578 * if pattern.use_rest_num?
7579 * rest_num = 0
7580 * end
7581 * if pattern.has_constant_node?
7582 * unless pattern.constant === obj
7583 * goto match_failed
7584 * end
7585 * end
7586 * unless obj.respond_to?(:deconstruct)
7587 * goto match_failed
7588 * end
7589 * d = obj.deconstruct
7590 * unless Array === d
7591 * goto type_error
7592 * end
7593 * min_argc = pattern.pre_args_num + pattern.post_args_num
7594 * if pattern.has_rest_arg?
7595 * unless d.length >= min_argc
7596 * goto match_failed
7597 * end
7598 * else
7599 * unless d.length == min_argc
7600 * goto match_failed
7601 * end
7602 * end
7603 * pattern.pre_args_num.each do |i|
7604 * unless pattern.pre_args[i].match?(d[i])
7605 * goto match_failed
7606 * end
7607 * end
7608 * if pattern.use_rest_num?
7609 * rest_num = d.length - min_argc
7610 * if pattern.has_rest_arg? && pattern.has_rest_arg_id # not `*`, but `*rest`
7611 * unless pattern.rest_arg.match?(d[pattern.pre_args_num, rest_num])
7612 * goto match_failed
7613 * end
7614 * end
7615 * end
7616 * pattern.post_args_num.each do |i|
7617 * j = pattern.pre_args_num + i
7618 * j += rest_num
7619 * unless pattern.post_args[i].match?(d[j])
7620 * goto match_failed
7621 * end
7622 * end
7623 * goto matched
7624 * type_error:
7625 * FrozenCore.raise TypeError
7626 * match_failed:
7627 * goto unmatched
7628 */
7629 const NODE *args = RNODE_ARYPTN(node)->pre_args;
7630 const int pre_args_num = RNODE_ARYPTN(node)->pre_args ? rb_long2int(RNODE_LIST(RNODE_ARYPTN(node)->pre_args)->as.nd_alen) : 0;
7631 const int post_args_num = RNODE_ARYPTN(node)->post_args ? rb_long2int(RNODE_LIST(RNODE_ARYPTN(node)->post_args)->as.nd_alen) : 0;
7632
7633 const int min_argc = pre_args_num + post_args_num;
7634 const int use_rest_num = RNODE_ARYPTN(node)->rest_arg && (NODE_NAMED_REST_P(RNODE_ARYPTN(node)->rest_arg) ||
7635 (!NODE_NAMED_REST_P(RNODE_ARYPTN(node)->rest_arg) && post_args_num > 0));
7636
7637 LABEL *match_failed, *type_error, *deconstruct, *deconstructed;
7638 int i;
7639 match_failed = NEW_LABEL(line);
7640 type_error = NEW_LABEL(line);
7641 deconstruct = NEW_LABEL(line);
7642 deconstructed = NEW_LABEL(line);
7643
7644 if (use_rest_num) {
7645 ADD_INSN1(ret, line_node, putobject, INT2FIX(0)); /* allocate stack for rest_num */
7646 ADD_INSN(ret, line_node, swap);
7647 if (base_index) {
7648 base_index++;
7649 }
7650 }
7651
7652 CHECK(iseq_compile_pattern_constant(iseq, ret, node, match_failed, in_single_pattern, base_index));
7653
7654 CHECK(iseq_compile_array_deconstruct(iseq, ret, node, deconstruct, deconstructed, match_failed, type_error, in_single_pattern, base_index, use_deconstructed_cache));
7655
7656 ADD_INSN(ret, line_node, dup);
7657 ADD_SEND(ret, line_node, idLength, INT2FIX(0));
7658 ADD_INSN1(ret, line_node, putobject, INT2FIX(min_argc));
7659 ADD_SEND(ret, line_node, RNODE_ARYPTN(node)->rest_arg ? idGE : idEq, INT2FIX(1)); // (1)
7660 if (in_single_pattern) {
7661 CHECK(iseq_compile_pattern_set_length_errmsg(iseq, ret, node,
7662 RNODE_ARYPTN(node)->rest_arg ? rb_fstring_lit("%p length mismatch (given %p, expected %p+)") :
7663 rb_fstring_lit("%p length mismatch (given %p, expected %p)"),
7664 INT2FIX(min_argc), base_index + 1 /* (1) */));
7665 }
7666 ADD_INSNL(ret, line_node, branchunless, match_failed);
7667
7668 for (i = 0; i < pre_args_num; i++) {
7669 ADD_INSN(ret, line_node, dup);
7670 ADD_INSN1(ret, line_node, putobject, INT2FIX(i));
7671 ADD_SEND(ret, line_node, idAREF, INT2FIX(1)); // (2)
7672 CHECK(iseq_compile_pattern_match(iseq, ret, RNODE_LIST(args)->nd_head, match_failed, in_single_pattern, in_alt_pattern, base_index + 1 /* (2) */, false));
7673 args = RNODE_LIST(args)->nd_next;
7674 }
7675
7676 if (RNODE_ARYPTN(node)->rest_arg) {
7677 if (NODE_NAMED_REST_P(RNODE_ARYPTN(node)->rest_arg)) {
7678 ADD_INSN(ret, line_node, dup);
7679 ADD_INSN1(ret, line_node, putobject, INT2FIX(pre_args_num));
7680 ADD_INSN1(ret, line_node, topn, INT2FIX(1));
7681 ADD_SEND(ret, line_node, idLength, INT2FIX(0));
7682 ADD_INSN1(ret, line_node, putobject, INT2FIX(min_argc));
7683 ADD_SEND(ret, line_node, idMINUS, INT2FIX(1));
7684 ADD_INSN1(ret, line_node, setn, INT2FIX(4));
7685 ADD_SEND(ret, line_node, idAREF, INT2FIX(2)); // (3)
7686
7687 CHECK(iseq_compile_pattern_match(iseq, ret, RNODE_ARYPTN(node)->rest_arg, match_failed, in_single_pattern, in_alt_pattern, base_index + 1 /* (3) */, false));
7688 }
7689 else {
7690 if (post_args_num > 0) {
7691 ADD_INSN(ret, line_node, dup);
7692 ADD_SEND(ret, line_node, idLength, INT2FIX(0));
7693 ADD_INSN1(ret, line_node, putobject, INT2FIX(min_argc));
7694 ADD_SEND(ret, line_node, idMINUS, INT2FIX(1));
7695 ADD_INSN1(ret, line_node, setn, INT2FIX(2));
7696 ADD_INSN(ret, line_node, pop);
7697 }
7698 }
7699 }
7700
7701 args = RNODE_ARYPTN(node)->post_args;
7702 for (i = 0; i < post_args_num; i++) {
7703 ADD_INSN(ret, line_node, dup);
7704
7705 ADD_INSN1(ret, line_node, putobject, INT2FIX(pre_args_num + i));
7706 ADD_INSN1(ret, line_node, topn, INT2FIX(3));
7707 ADD_SEND(ret, line_node, idPLUS, INT2FIX(1));
7708
7709 ADD_SEND(ret, line_node, idAREF, INT2FIX(1)); // (4)
7710 CHECK(iseq_compile_pattern_match(iseq, ret, RNODE_LIST(args)->nd_head, match_failed, in_single_pattern, in_alt_pattern, base_index + 1 /* (4) */, false));
7711 args = RNODE_LIST(args)->nd_next;
7712 }
7713
7714 ADD_INSN(ret, line_node, pop);
7715 if (use_rest_num) {
7716 ADD_INSN(ret, line_node, pop);
7717 }
7718 ADD_INSNL(ret, line_node, jump, matched);
7719 ADD_INSN(ret, line_node, putnil);
7720 if (use_rest_num) {
7721 ADD_INSN(ret, line_node, putnil);
7722 }
7723
7724 ADD_LABEL(ret, type_error);
7725 ADD_INSN1(ret, line_node, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
7726 ADD_INSN1(ret, line_node, putobject, rb_eTypeError);
7727 ADD_INSN1(ret, line_node, putobject, rb_fstring_lit("deconstruct must return Array"));
7728 ADD_SEND(ret, line_node, id_core_raise, INT2FIX(2));
7729 ADD_INSN(ret, line_node, pop);
7730
7731 ADD_LABEL(ret, match_failed);
7732 ADD_INSN(ret, line_node, pop);
7733 if (use_rest_num) {
7734 ADD_INSN(ret, line_node, pop);
7735 }
7736 ADD_INSNL(ret, line_node, jump, unmatched);
7737
7738 break;
7739 }
7740 case NODE_FNDPTN: {
7741 /*
7742 * if pattern.has_constant_node?
7743 * unless pattern.constant === obj
7744 * goto match_failed
7745 * end
7746 * end
7747 * unless obj.respond_to?(:deconstruct)
7748 * goto match_failed
7749 * end
7750 * d = obj.deconstruct
7751 * unless Array === d
7752 * goto type_error
7753 * end
7754 * unless d.length >= pattern.args_num
7755 * goto match_failed
7756 * end
7757 *
7758 * begin
7759 * len = d.length
7760 * limit = d.length - pattern.args_num
7761 * i = 0
7762 * while i <= limit
7763 * if pattern.args_num.times.all? {|j| pattern.args[j].match?(d[i+j]) }
7764 * if pattern.has_pre_rest_arg_id
7765 * unless pattern.pre_rest_arg.match?(d[0, i])
7766 * goto find_failed
7767 * end
7768 * end
7769 * if pattern.has_post_rest_arg_id
7770 * unless pattern.post_rest_arg.match?(d[i+pattern.args_num, len])
7771 * goto find_failed
7772 * end
7773 * end
7774 * goto find_succeeded
7775 * end
7776 * i+=1
7777 * end
7778 * find_failed:
7779 * goto match_failed
7780 * find_succeeded:
7781 * end
7782 *
7783 * goto matched
7784 * type_error:
7785 * FrozenCore.raise TypeError
7786 * match_failed:
7787 * goto unmatched
7788 */
7789 const NODE *args = RNODE_FNDPTN(node)->args;
7790 const int args_num = RNODE_FNDPTN(node)->args ? rb_long2int(RNODE_LIST(RNODE_FNDPTN(node)->args)->as.nd_alen) : 0;
7791
7792 LABEL *match_failed, *type_error, *deconstruct, *deconstructed;
7793 match_failed = NEW_LABEL(line);
7794 type_error = NEW_LABEL(line);
7795 deconstruct = NEW_LABEL(line);
7796 deconstructed = NEW_LABEL(line);
7797
7798 CHECK(iseq_compile_pattern_constant(iseq, ret, node, match_failed, in_single_pattern, base_index));
7799
7800 CHECK(iseq_compile_array_deconstruct(iseq, ret, node, deconstruct, deconstructed, match_failed, type_error, in_single_pattern, base_index, use_deconstructed_cache));
7801
7802 ADD_INSN(ret, line_node, dup);
7803 ADD_SEND(ret, line_node, idLength, INT2FIX(0));
7804 ADD_INSN1(ret, line_node, putobject, INT2FIX(args_num));
7805 ADD_SEND(ret, line_node, idGE, INT2FIX(1)); // (1)
7806 if (in_single_pattern) {
7807 CHECK(iseq_compile_pattern_set_length_errmsg(iseq, ret, node, rb_fstring_lit("%p length mismatch (given %p, expected %p+)"), INT2FIX(args_num), base_index + 1 /* (1) */));
7808 }
7809 ADD_INSNL(ret, line_node, branchunless, match_failed);
7810
7811 {
7812 LABEL *while_begin = NEW_LABEL(nd_line(node));
7813 LABEL *next_loop = NEW_LABEL(nd_line(node));
7814 LABEL *find_succeeded = NEW_LABEL(line);
7815 LABEL *find_failed = NEW_LABEL(nd_line(node));
7816 int j;
7817
7818 ADD_INSN(ret, line_node, dup); /* allocate stack for len */
7819 ADD_SEND(ret, line_node, idLength, INT2FIX(0)); // (2)
7820
7821 ADD_INSN(ret, line_node, dup); /* allocate stack for limit */
7822 ADD_INSN1(ret, line_node, putobject, INT2FIX(args_num));
7823 ADD_SEND(ret, line_node, idMINUS, INT2FIX(1)); // (3)
7824
7825 ADD_INSN1(ret, line_node, putobject, INT2FIX(0)); /* allocate stack for i */ // (4)
7826
7827 ADD_LABEL(ret, while_begin);
7828
7829 ADD_INSN(ret, line_node, dup);
7830 ADD_INSN1(ret, line_node, topn, INT2FIX(2));
7831 ADD_SEND(ret, line_node, idLE, INT2FIX(1));
7832 ADD_INSNL(ret, line_node, branchunless, find_failed);
7833
7834 for (j = 0; j < args_num; j++) {
7835 ADD_INSN1(ret, line_node, topn, INT2FIX(3));
7836 ADD_INSN1(ret, line_node, topn, INT2FIX(1));
7837 if (j != 0) {
7838 ADD_INSN1(ret, line_node, putobject, INT2FIX(j));
7839 ADD_SEND(ret, line_node, idPLUS, INT2FIX(1));
7840 }
7841 ADD_SEND(ret, line_node, idAREF, INT2FIX(1)); // (5)
7842
7843 CHECK(iseq_compile_pattern_match(iseq, ret, RNODE_LIST(args)->nd_head, next_loop, in_single_pattern, in_alt_pattern, base_index + 4 /* (2), (3), (4), (5) */, false));
7844 args = RNODE_LIST(args)->nd_next;
7845 }
7846
7847 if (NODE_NAMED_REST_P(RNODE_FNDPTN(node)->pre_rest_arg)) {
7848 ADD_INSN1(ret, line_node, topn, INT2FIX(3));
7849 ADD_INSN1(ret, line_node, putobject, INT2FIX(0));
7850 ADD_INSN1(ret, line_node, topn, INT2FIX(2));
7851 ADD_SEND(ret, line_node, idAREF, INT2FIX(2)); // (6)
7852 CHECK(iseq_compile_pattern_match(iseq, ret, RNODE_FNDPTN(node)->pre_rest_arg, find_failed, in_single_pattern, in_alt_pattern, base_index + 4 /* (2), (3), (4), (6) */, false));
7853 }
7854 if (NODE_NAMED_REST_P(RNODE_FNDPTN(node)->post_rest_arg)) {
7855 ADD_INSN1(ret, line_node, topn, INT2FIX(3));
7856 ADD_INSN1(ret, line_node, topn, INT2FIX(1));
7857 ADD_INSN1(ret, line_node, putobject, INT2FIX(args_num));
7858 ADD_SEND(ret, line_node, idPLUS, INT2FIX(1));
7859 ADD_INSN1(ret, line_node, topn, INT2FIX(3));
7860 ADD_SEND(ret, line_node, idAREF, INT2FIX(2)); // (7)
7861 CHECK(iseq_compile_pattern_match(iseq, ret, RNODE_FNDPTN(node)->post_rest_arg, find_failed, in_single_pattern, in_alt_pattern, base_index + 4 /* (2), (3),(4), (7) */, false));
7862 }
7863 ADD_INSNL(ret, line_node, jump, find_succeeded);
7864
7865 ADD_LABEL(ret, next_loop);
7866 ADD_INSN1(ret, line_node, putobject, INT2FIX(1));
7867 ADD_SEND(ret, line_node, idPLUS, INT2FIX(1));
7868 ADD_INSNL(ret, line_node, jump, while_begin);
7869
7870 ADD_LABEL(ret, find_failed);
7871 ADD_INSN1(ret, line_node, adjuststack, INT2FIX(3));
7872 if (in_single_pattern) {
7873 ADD_INSN1(ret, line_node, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
7874 ADD_INSN1(ret, line_node, putobject, rb_fstring_lit("%p does not match to find pattern"));
7875 ADD_INSN1(ret, line_node, topn, INT2FIX(2));
7876 ADD_SEND(ret, line_node, id_core_sprintf, INT2FIX(2)); // (8)
7877 ADD_INSN1(ret, line_node, setn, INT2FIX(base_index + CASE3_BI_OFFSET_ERROR_STRING + 1 /* (8) */)); // (9)
7878
7879 ADD_INSN1(ret, line_node, putobject, Qfalse);
7880 ADD_INSN1(ret, line_node, setn, INT2FIX(base_index + CASE3_BI_OFFSET_KEY_ERROR_P + 2 /* (8), (9) */));
7881
7882 ADD_INSN(ret, line_node, pop);
7883 ADD_INSN(ret, line_node, pop);
7884 }
7885 ADD_INSNL(ret, line_node, jump, match_failed);
7886 ADD_INSN1(ret, line_node, dupn, INT2FIX(3));
7887
7888 ADD_LABEL(ret, find_succeeded);
7889 ADD_INSN1(ret, line_node, adjuststack, INT2FIX(3));
7890 }
7891
7892 ADD_INSN(ret, line_node, pop);
7893 ADD_INSNL(ret, line_node, jump, matched);
7894 ADD_INSN(ret, line_node, putnil);
7895
7896 ADD_LABEL(ret, type_error);
7897 ADD_INSN1(ret, line_node, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
7898 ADD_INSN1(ret, line_node, putobject, rb_eTypeError);
7899 ADD_INSN1(ret, line_node, putobject, rb_fstring_lit("deconstruct must return Array"));
7900 ADD_SEND(ret, line_node, id_core_raise, INT2FIX(2));
7901 ADD_INSN(ret, line_node, pop);
7902
7903 ADD_LABEL(ret, match_failed);
7904 ADD_INSN(ret, line_node, pop);
7905 ADD_INSNL(ret, line_node, jump, unmatched);
7906
7907 break;
7908 }
7909 case NODE_HSHPTN: {
7910 /*
7911 * keys = nil
7912 * if pattern.has_kw_args_node? && !pattern.has_kw_rest_arg_node?
7913 * keys = pattern.kw_args_node.keys
7914 * end
7915 * if pattern.has_constant_node?
7916 * unless pattern.constant === obj
7917 * goto match_failed
7918 * end
7919 * end
7920 * unless obj.respond_to?(:deconstruct_keys)
7921 * goto match_failed
7922 * end
7923 * d = obj.deconstruct_keys(keys)
7924 * unless Hash === d
7925 * goto type_error
7926 * end
7927 * if pattern.has_kw_rest_arg_node?
7928 * d = d.dup
7929 * end
7930 * if pattern.has_kw_args_node?
7931 * pattern.kw_args_node.each |k,|
7932 * unless d.key?(k)
7933 * goto match_failed
7934 * end
7935 * end
7936 * pattern.kw_args_node.each |k, pat|
7937 * if pattern.has_kw_rest_arg_node?
7938 * unless pat.match?(d.delete(k))
7939 * goto match_failed
7940 * end
7941 * else
7942 * unless pat.match?(d[k])
7943 * goto match_failed
7944 * end
7945 * end
7946 * end
7947 * else
7948 * unless d.empty?
7949 * goto match_failed
7950 * end
7951 * end
7952 * if pattern.has_kw_rest_arg_node?
7953 * if pattern.no_rest_keyword?
7954 * unless d.empty?
7955 * goto match_failed
7956 * end
7957 * else
7958 * unless pattern.kw_rest_arg_node.match?(d)
7959 * goto match_failed
7960 * end
7961 * end
7962 * end
7963 * goto matched
7964 * type_error:
7965 * FrozenCore.raise TypeError
7966 * match_failed:
7967 * goto unmatched
7968 */
7969 LABEL *match_failed, *type_error;
7970 VALUE keys = Qnil;
7971
7972 match_failed = NEW_LABEL(line);
7973 type_error = NEW_LABEL(line);
7974
7975 if (RNODE_HSHPTN(node)->nd_pkwargs && !RNODE_HSHPTN(node)->nd_pkwrestarg) {
7976 const NODE *kw_args = RNODE_HASH(RNODE_HSHPTN(node)->nd_pkwargs)->nd_head;
7977 keys = rb_ary_new_capa(kw_args ? RNODE_LIST(kw_args)->as.nd_alen/2 : 0);
7978 while (kw_args) {
7979 rb_ary_push(keys, get_symbol_value(iseq, RNODE_LIST(kw_args)->nd_head));
7980 kw_args = RNODE_LIST(RNODE_LIST(kw_args)->nd_next)->nd_next;
7981 }
7982 }
7983
7984 CHECK(iseq_compile_pattern_constant(iseq, ret, node, match_failed, in_single_pattern, base_index));
7985
7986 ADD_INSN(ret, line_node, dup);
7987 ADD_INSN1(ret, line_node, putobject, ID2SYM(rb_intern("deconstruct_keys")));
7988 ADD_SEND(ret, line_node, idRespond_to, INT2FIX(1)); // (1)
7989 if (in_single_pattern) {
7990 CHECK(iseq_compile_pattern_set_general_errmsg(iseq, ret, node, rb_fstring_lit("%p does not respond to #deconstruct_keys"), base_index + 1 /* (1) */));
7991 }
7992 ADD_INSNL(ret, line_node, branchunless, match_failed);
7993
7994 if (NIL_P(keys)) {
7995 ADD_INSN(ret, line_node, putnil);
7996 }
7997 else {
7999 ADD_INSN1(ret, line_node, duparray, keys);
8000 RB_OBJ_WRITTEN(iseq, Qundef, rb_obj_hide(keys));
8001 }
8002 ADD_SEND(ret, line_node, rb_intern("deconstruct_keys"), INT2FIX(1)); // (2)
8003
8004 ADD_INSN(ret, line_node, dup);
8005 ADD_INSN1(ret, line_node, checktype, INT2FIX(T_HASH));
8006 ADD_INSNL(ret, line_node, branchunless, type_error);
8007
8008 if (RNODE_HSHPTN(node)->nd_pkwrestarg) {
8009 ADD_SEND(ret, line_node, rb_intern("dup"), INT2FIX(0));
8010 }
8011
8012 if (RNODE_HSHPTN(node)->nd_pkwargs) {
8013 int i;
8014 int keys_num;
8015 const NODE *args;
8016 args = RNODE_HASH(RNODE_HSHPTN(node)->nd_pkwargs)->nd_head;
8017 if (args) {
8018 DECL_ANCHOR(match_values);
8019 INIT_ANCHOR(match_values);
8020 keys_num = rb_long2int(RNODE_LIST(args)->as.nd_alen) / 2;
8021 for (i = 0; i < keys_num; i++) {
8022 NODE *key_node = RNODE_LIST(args)->nd_head;
8023 NODE *value_node = RNODE_LIST(RNODE_LIST(args)->nd_next)->nd_head;
8024 VALUE key = get_symbol_value(iseq, key_node);
8025
8026 ADD_INSN(ret, line_node, dup);
8027 ADD_INSN1(ret, line_node, putobject, key);
8028 ADD_SEND(ret, line_node, rb_intern("key?"), INT2FIX(1)); // (3)
8029 if (in_single_pattern) {
8030 LABEL *match_succeeded;
8031 match_succeeded = NEW_LABEL(line);
8032
8033 ADD_INSN(ret, line_node, dup);
8034 ADD_INSNL(ret, line_node, branchif, match_succeeded);
8035
8036 VALUE str = rb_str_freeze(rb_sprintf("key not found: %+"PRIsVALUE, key));
8037 ADD_INSN1(ret, line_node, putobject, RB_OBJ_SET_SHAREABLE(str)); // (4)
8038 ADD_INSN1(ret, line_node, setn, INT2FIX(base_index + CASE3_BI_OFFSET_ERROR_STRING + 2 /* (3), (4) */));
8039 ADD_INSN1(ret, line_node, putobject, Qtrue); // (5)
8040 ADD_INSN1(ret, line_node, setn, INT2FIX(base_index + CASE3_BI_OFFSET_KEY_ERROR_P + 3 /* (3), (4), (5) */));
8041 ADD_INSN1(ret, line_node, topn, INT2FIX(3)); // (6)
8042 ADD_INSN1(ret, line_node, setn, INT2FIX(base_index + CASE3_BI_OFFSET_KEY_ERROR_MATCHEE + 4 /* (3), (4), (5), (6) */));
8043 ADD_INSN1(ret, line_node, putobject, key); // (7)
8044 ADD_INSN1(ret, line_node, setn, INT2FIX(base_index + CASE3_BI_OFFSET_KEY_ERROR_KEY + 5 /* (3), (4), (5), (6), (7) */));
8045
8046 ADD_INSN1(ret, line_node, adjuststack, INT2FIX(4));
8047
8048 ADD_LABEL(ret, match_succeeded);
8049 }
8050 ADD_INSNL(ret, line_node, branchunless, match_failed);
8051
8052 ADD_INSN(match_values, line_node, dup);
8053 ADD_INSN1(match_values, line_node, putobject, key);
8054 ADD_SEND(match_values, line_node, RNODE_HSHPTN(node)->nd_pkwrestarg ? rb_intern("delete") : idAREF, INT2FIX(1)); // (8)
8055 CHECK(iseq_compile_pattern_match(iseq, match_values, value_node, match_failed, in_single_pattern, in_alt_pattern, base_index + 1 /* (8) */, false));
8056 args = RNODE_LIST(RNODE_LIST(args)->nd_next)->nd_next;
8057 }
8058 ADD_SEQ(ret, match_values);
8059 }
8060 }
8061 else {
8062 ADD_INSN(ret, line_node, dup);
8063 ADD_SEND(ret, line_node, idEmptyP, INT2FIX(0)); // (9)
8064 if (in_single_pattern) {
8065 CHECK(iseq_compile_pattern_set_general_errmsg(iseq, ret, node, rb_fstring_lit("%p is not empty"), base_index + 1 /* (9) */));
8066 }
8067 ADD_INSNL(ret, line_node, branchunless, match_failed);
8068 }
8069
8070 if (RNODE_HSHPTN(node)->nd_pkwrestarg) {
8071 if (RNODE_HSHPTN(node)->nd_pkwrestarg == NODE_SPECIAL_NO_REST_KEYWORD) {
8072 ADD_INSN(ret, line_node, dup);
8073 ADD_SEND(ret, line_node, idEmptyP, INT2FIX(0)); // (10)
8074 if (in_single_pattern) {
8075 CHECK(iseq_compile_pattern_set_general_errmsg(iseq, ret, node, rb_fstring_lit("rest of %p is not empty"), base_index + 1 /* (10) */));
8076 }
8077 ADD_INSNL(ret, line_node, branchunless, match_failed);
8078 }
8079 else {
8080 ADD_INSN(ret, line_node, dup); // (11)
8081 CHECK(iseq_compile_pattern_match(iseq, ret, RNODE_HSHPTN(node)->nd_pkwrestarg, match_failed, in_single_pattern, in_alt_pattern, base_index + 1 /* (11) */, false));
8082 }
8083 }
8084
8085 ADD_INSN(ret, line_node, pop);
8086 ADD_INSNL(ret, line_node, jump, matched);
8087 ADD_INSN(ret, line_node, putnil);
8088
8089 ADD_LABEL(ret, type_error);
8090 ADD_INSN1(ret, line_node, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
8091 ADD_INSN1(ret, line_node, putobject, rb_eTypeError);
8092 ADD_INSN1(ret, line_node, putobject, rb_fstring_lit("deconstruct_keys must return Hash"));
8093 ADD_SEND(ret, line_node, id_core_raise, INT2FIX(2));
8094 ADD_INSN(ret, line_node, pop);
8095
8096 ADD_LABEL(ret, match_failed);
8097 ADD_INSN(ret, line_node, pop);
8098 ADD_INSNL(ret, line_node, jump, unmatched);
8099 break;
8100 }
8101 case NODE_SYM:
8102 case NODE_REGX:
8103 case NODE_LINE:
8104 case NODE_INTEGER:
8105 case NODE_FLOAT:
8106 case NODE_RATIONAL:
8107 case NODE_IMAGINARY:
8108 case NODE_FILE:
8109 case NODE_ENCODING:
8110 case NODE_STR:
8111 case NODE_XSTR:
8112 case NODE_DSTR:
8113 case NODE_DSYM:
8114 case NODE_DREGX:
8115 case NODE_LIST:
8116 case NODE_ZLIST:
8117 case NODE_LAMBDA:
8118 case NODE_DOT2:
8119 case NODE_DOT3:
8120 case NODE_CONST:
8121 case NODE_LVAR:
8122 case NODE_DVAR:
8123 case NODE_IVAR:
8124 case NODE_CVAR:
8125 case NODE_GVAR:
8126 case NODE_TRUE:
8127 case NODE_FALSE:
8128 case NODE_SELF:
8129 case NODE_NIL:
8130 case NODE_COLON2:
8131 case NODE_COLON3:
8132 case NODE_BEGIN:
8133 case NODE_BLOCK:
8134 case NODE_ONCE:
8135 CHECK(COMPILE(ret, "case in literal", node)); // (1)
8136 if (in_single_pattern) {
8137 ADD_INSN1(ret, line_node, dupn, INT2FIX(2));
8138 }
8139 ADD_INSN1(ret, line_node, checkmatch, INT2FIX(VM_CHECKMATCH_TYPE_CASE)); // (2)
8140 if (in_single_pattern) {
8141 CHECK(iseq_compile_pattern_set_eqq_errmsg(iseq, ret, node, base_index + 2 /* (1), (2) */));
8142 }
8143 ADD_INSNL(ret, line_node, branchif, matched);
8144 ADD_INSNL(ret, line_node, jump, unmatched);
8145 break;
8146 case NODE_LASGN: {
8147 struct rb_iseq_constant_body *const body = ISEQ_BODY(iseq);
8148 ID id = RNODE_LASGN(node)->nd_vid;
8149 int idx = ISEQ_BODY(body->local_iseq)->local_table_size - get_local_var_idx(iseq, id);
8150
8151 if (in_alt_pattern) {
8152 const char *name = rb_id2name(id);
8153 if (name && strlen(name) > 0 && name[0] != '_') {
8154 COMPILE_ERROR(ERROR_ARGS "illegal variable in alternative pattern (%"PRIsVALUE")",
8155 rb_id2str(id));
8156 return COMPILE_NG;
8157 }
8158 }
8159
8160 ADD_SETLOCAL(ret, line_node, idx, get_lvar_level(iseq));
8161 ADD_INSNL(ret, line_node, jump, matched);
8162 break;
8163 }
8164 case NODE_DASGN: {
8165 int idx, lv, ls;
8166 ID id = RNODE_DASGN(node)->nd_vid;
8167
8168 idx = get_dyna_var_idx(iseq, id, &lv, &ls);
8169
8170 if (in_alt_pattern) {
8171 const char *name = rb_id2name(id);
8172 if (name && strlen(name) > 0 && name[0] != '_') {
8173 COMPILE_ERROR(ERROR_ARGS "illegal variable in alternative pattern (%"PRIsVALUE")",
8174 rb_id2str(id));
8175 return COMPILE_NG;
8176 }
8177 }
8178
8179 if (idx < 0) {
8180 COMPILE_ERROR(ERROR_ARGS "NODE_DASGN: unknown id (%"PRIsVALUE")",
8181 rb_id2str(id));
8182 return COMPILE_NG;
8183 }
8184 ADD_SETLOCAL(ret, line_node, ls - idx, lv);
8185 ADD_INSNL(ret, line_node, jump, matched);
8186 break;
8187 }
8188 case NODE_IF:
8189 case NODE_UNLESS: {
8190 LABEL *match_failed;
8191 match_failed = unmatched;
8192 CHECK(iseq_compile_pattern_match(iseq, ret, RNODE_IF(node)->nd_body, unmatched, in_single_pattern, in_alt_pattern, base_index, use_deconstructed_cache));
8193 CHECK(COMPILE(ret, "case in if", RNODE_IF(node)->nd_cond));
8194 if (in_single_pattern) {
8195 LABEL *match_succeeded;
8196 match_succeeded = NEW_LABEL(line);
8197
8198 ADD_INSN(ret, line_node, dup);
8199 if (nd_type_p(node, NODE_IF)) {
8200 ADD_INSNL(ret, line_node, branchif, match_succeeded);
8201 }
8202 else {
8203 ADD_INSNL(ret, line_node, branchunless, match_succeeded);
8204 }
8205
8206 ADD_INSN1(ret, line_node, putobject, rb_fstring_lit("guard clause does not return true")); // (1)
8207 ADD_INSN1(ret, line_node, setn, INT2FIX(base_index + CASE3_BI_OFFSET_ERROR_STRING + 1 /* (1) */)); // (2)
8208 ADD_INSN1(ret, line_node, putobject, Qfalse);
8209 ADD_INSN1(ret, line_node, setn, INT2FIX(base_index + CASE3_BI_OFFSET_KEY_ERROR_P + 2 /* (1), (2) */));
8210
8211 ADD_INSN(ret, line_node, pop);
8212 ADD_INSN(ret, line_node, pop);
8213
8214 ADD_LABEL(ret, match_succeeded);
8215 }
8216 if (nd_type_p(node, NODE_IF)) {
8217 ADD_INSNL(ret, line_node, branchunless, match_failed);
8218 }
8219 else {
8220 ADD_INSNL(ret, line_node, branchif, match_failed);
8221 }
8222 ADD_INSNL(ret, line_node, jump, matched);
8223 break;
8224 }
8225 case NODE_HASH: {
8226 NODE *n;
8227 LABEL *match_failed;
8228 match_failed = NEW_LABEL(line);
8229
8230 n = RNODE_HASH(node)->nd_head;
8231 if (! (nd_type_p(n, NODE_LIST) && RNODE_LIST(n)->as.nd_alen == 2)) {
8232 COMPILE_ERROR(ERROR_ARGS "unexpected node");
8233 return COMPILE_NG;
8234 }
8235
8236 ADD_INSN(ret, line_node, dup); // (1)
8237 CHECK(iseq_compile_pattern_match(iseq, ret, RNODE_LIST(n)->nd_head, match_failed, in_single_pattern, in_alt_pattern, base_index + 1 /* (1) */, use_deconstructed_cache));
8238 CHECK(iseq_compile_pattern_each(iseq, ret, RNODE_LIST(RNODE_LIST(n)->nd_next)->nd_head, matched, match_failed, in_single_pattern, in_alt_pattern, base_index, false));
8239 ADD_INSN(ret, line_node, putnil);
8240
8241 ADD_LABEL(ret, match_failed);
8242 ADD_INSN(ret, line_node, pop);
8243 ADD_INSNL(ret, line_node, jump, unmatched);
8244 break;
8245 }
8246 case NODE_OR: {
8247 LABEL *match_succeeded, *fin;
8248 match_succeeded = NEW_LABEL(line);
8249 fin = NEW_LABEL(line);
8250
8251 ADD_INSN(ret, line_node, dup); // (1)
8252 CHECK(iseq_compile_pattern_each(iseq, ret, RNODE_OR(node)->nd_1st, match_succeeded, fin, in_single_pattern, true, base_index + 1 /* (1) */, use_deconstructed_cache));
8253 ADD_LABEL(ret, match_succeeded);
8254 ADD_INSN(ret, line_node, pop);
8255 ADD_INSNL(ret, line_node, jump, matched);
8256 ADD_INSN(ret, line_node, putnil);
8257 ADD_LABEL(ret, fin);
8258 CHECK(iseq_compile_pattern_each(iseq, ret, RNODE_OR(node)->nd_2nd, matched, unmatched, in_single_pattern, true, base_index, use_deconstructed_cache));
8259 break;
8260 }
8261 default:
8262 UNKNOWN_NODE("NODE_IN", node, COMPILE_NG);
8263 }
8264 return COMPILE_OK;
8265}
8266
8267static int
8268iseq_compile_pattern_match(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, LABEL *unmatched, bool in_single_pattern, bool in_alt_pattern, int base_index, bool use_deconstructed_cache)
8269{
8270 LABEL *fin = NEW_LABEL(nd_line(node));
8271 CHECK(iseq_compile_pattern_each(iseq, ret, node, fin, unmatched, in_single_pattern, in_alt_pattern, base_index, use_deconstructed_cache));
8272 ADD_LABEL(ret, fin);
8273 return COMPILE_OK;
8274}
8275
8276static int
8277iseq_compile_pattern_constant(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, LABEL *match_failed, bool in_single_pattern, int base_index)
8278{
8279 const NODE *line_node = node;
8280
8281 if (RNODE_ARYPTN(node)->nd_pconst) {
8282 ADD_INSN(ret, line_node, dup); // (1)
8283 CHECK(COMPILE(ret, "constant", RNODE_ARYPTN(node)->nd_pconst)); // (2)
8284 if (in_single_pattern) {
8285 ADD_INSN1(ret, line_node, dupn, INT2FIX(2));
8286 }
8287 ADD_INSN1(ret, line_node, checkmatch, INT2FIX(VM_CHECKMATCH_TYPE_CASE)); // (3)
8288 if (in_single_pattern) {
8289 CHECK(iseq_compile_pattern_set_eqq_errmsg(iseq, ret, node, base_index + 3 /* (1), (2), (3) */));
8290 }
8291 ADD_INSNL(ret, line_node, branchunless, match_failed);
8292 }
8293 return COMPILE_OK;
8294}
8295
8296
8297static int
8298iseq_compile_array_deconstruct(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, LABEL *deconstruct, LABEL *deconstructed, LABEL *match_failed, LABEL *type_error, bool in_single_pattern, int base_index, bool use_deconstructed_cache)
8299{
8300 const NODE *line_node = node;
8301
8302 // NOTE: this optimization allows us to re-use the #deconstruct value
8303 // (or its absence).
8304 if (use_deconstructed_cache) {
8305 // If value is nil then we haven't tried to deconstruct
8306 ADD_INSN1(ret, line_node, topn, INT2FIX(base_index + CASE3_BI_OFFSET_DECONSTRUCTED_CACHE));
8307 ADD_INSNL(ret, line_node, branchnil, deconstruct);
8308
8309 // If false then the value is not deconstructable
8310 ADD_INSN1(ret, line_node, topn, INT2FIX(base_index + CASE3_BI_OFFSET_DECONSTRUCTED_CACHE));
8311 ADD_INSNL(ret, line_node, branchunless, match_failed);
8312
8313 // Drop value, add deconstructed to the stack and jump
8314 ADD_INSN(ret, line_node, pop); // (1)
8315 ADD_INSN1(ret, line_node, topn, INT2FIX(base_index + CASE3_BI_OFFSET_DECONSTRUCTED_CACHE - 1 /* (1) */));
8316 ADD_INSNL(ret, line_node, jump, deconstructed);
8317 }
8318 else {
8319 ADD_INSNL(ret, line_node, jump, deconstruct);
8320 }
8321
8322 ADD_LABEL(ret, deconstruct);
8323 ADD_INSN(ret, line_node, dup);
8324 ADD_INSN1(ret, line_node, putobject, ID2SYM(rb_intern("deconstruct")));
8325 ADD_SEND(ret, line_node, idRespond_to, INT2FIX(1)); // (2)
8326
8327 // Cache the result of respond_to? (in case it's false is stays there, if true - it's overwritten after #deconstruct)
8328 if (use_deconstructed_cache) {
8329 ADD_INSN1(ret, line_node, setn, INT2FIX(base_index + CASE3_BI_OFFSET_DECONSTRUCTED_CACHE + 1 /* (2) */));
8330 }
8331
8332 if (in_single_pattern) {
8333 CHECK(iseq_compile_pattern_set_general_errmsg(iseq, ret, node, rb_fstring_lit("%p does not respond to #deconstruct"), base_index + 1 /* (2) */));
8334 }
8335
8336 ADD_INSNL(ret, line_node, branchunless, match_failed);
8337
8338 ADD_SEND(ret, line_node, rb_intern("deconstruct"), INT2FIX(0));
8339
8340 // Cache the result (if it's cacheable - currently, only top-level array patterns)
8341 if (use_deconstructed_cache) {
8342 ADD_INSN1(ret, line_node, setn, INT2FIX(base_index + CASE3_BI_OFFSET_DECONSTRUCTED_CACHE));
8343 }
8344
8345 ADD_INSN(ret, line_node, dup);
8346 ADD_INSN1(ret, line_node, checktype, INT2FIX(T_ARRAY));
8347 ADD_INSNL(ret, line_node, branchunless, type_error);
8348
8349 ADD_LABEL(ret, deconstructed);
8350
8351 return COMPILE_OK;
8352}
8353
8354static int
8355iseq_compile_pattern_set_general_errmsg(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, VALUE errmsg, int base_index)
8356{
8357 /*
8358 * if match_succeeded?
8359 * goto match_succeeded
8360 * end
8361 * error_string = FrozenCore.sprintf(errmsg, matchee)
8362 * key_error_p = false
8363 * match_succeeded:
8364 */
8365 const int line = nd_line(node);
8366 const NODE *line_node = node;
8367 LABEL *match_succeeded = NEW_LABEL(line);
8368
8369 ADD_INSN(ret, line_node, dup);
8370 ADD_INSNL(ret, line_node, branchif, match_succeeded);
8371
8372 ADD_INSN1(ret, line_node, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
8373 ADD_INSN1(ret, line_node, putobject, errmsg);
8374 ADD_INSN1(ret, line_node, topn, INT2FIX(3));
8375 ADD_SEND(ret, line_node, id_core_sprintf, INT2FIX(2)); // (1)
8376 ADD_INSN1(ret, line_node, setn, INT2FIX(base_index + CASE3_BI_OFFSET_ERROR_STRING + 1 /* (1) */)); // (2)
8377
8378 ADD_INSN1(ret, line_node, putobject, Qfalse);
8379 ADD_INSN1(ret, line_node, setn, INT2FIX(base_index + CASE3_BI_OFFSET_KEY_ERROR_P + 2 /* (1), (2) */));
8380
8381 ADD_INSN(ret, line_node, pop);
8382 ADD_INSN(ret, line_node, pop);
8383 ADD_LABEL(ret, match_succeeded);
8384
8385 return COMPILE_OK;
8386}
8387
8388static int
8389iseq_compile_pattern_set_length_errmsg(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, VALUE errmsg, VALUE pattern_length, int base_index)
8390{
8391 /*
8392 * if match_succeeded?
8393 * goto match_succeeded
8394 * end
8395 * error_string = FrozenCore.sprintf(errmsg, matchee, matchee.length, pat.length)
8396 * key_error_p = false
8397 * match_succeeded:
8398 */
8399 const int line = nd_line(node);
8400 const NODE *line_node = node;
8401 LABEL *match_succeeded = NEW_LABEL(line);
8402
8403 ADD_INSN(ret, line_node, dup);
8404 ADD_INSNL(ret, line_node, branchif, match_succeeded);
8405
8406 ADD_INSN1(ret, line_node, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
8407 ADD_INSN1(ret, line_node, putobject, errmsg);
8408 ADD_INSN1(ret, line_node, topn, INT2FIX(3));
8409 ADD_INSN(ret, line_node, dup);
8410 ADD_SEND(ret, line_node, idLength, INT2FIX(0));
8411 ADD_INSN1(ret, line_node, putobject, pattern_length);
8412 ADD_SEND(ret, line_node, id_core_sprintf, INT2FIX(4)); // (1)
8413 ADD_INSN1(ret, line_node, setn, INT2FIX(base_index + CASE3_BI_OFFSET_ERROR_STRING + 1 /* (1) */)); // (2)
8414
8415 ADD_INSN1(ret, line_node, putobject, Qfalse);
8416 ADD_INSN1(ret, line_node, setn, INT2FIX(base_index + CASE3_BI_OFFSET_KEY_ERROR_P + 2/* (1), (2) */));
8417
8418 ADD_INSN(ret, line_node, pop);
8419 ADD_INSN(ret, line_node, pop);
8420 ADD_LABEL(ret, match_succeeded);
8421
8422 return COMPILE_OK;
8423}
8424
8425static int
8426iseq_compile_pattern_set_eqq_errmsg(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int base_index)
8427{
8428 /*
8429 * if match_succeeded?
8430 * goto match_succeeded
8431 * end
8432 * error_string = FrozenCore.sprintf("%p === %p does not return true", pat, matchee)
8433 * key_error_p = false
8434 * match_succeeded:
8435 */
8436 const int line = nd_line(node);
8437 const NODE *line_node = node;
8438 LABEL *match_succeeded = NEW_LABEL(line);
8439
8440 ADD_INSN(ret, line_node, dup);
8441 ADD_INSNL(ret, line_node, branchif, match_succeeded);
8442
8443 ADD_INSN1(ret, line_node, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
8444 ADD_INSN1(ret, line_node, putobject, rb_fstring_lit("%p === %p does not return true"));
8445 ADD_INSN1(ret, line_node, topn, INT2FIX(3));
8446 ADD_INSN1(ret, line_node, topn, INT2FIX(5));
8447 ADD_SEND(ret, line_node, id_core_sprintf, INT2FIX(3)); // (1)
8448 ADD_INSN1(ret, line_node, setn, INT2FIX(base_index + CASE3_BI_OFFSET_ERROR_STRING + 1 /* (1) */)); // (2)
8449
8450 ADD_INSN1(ret, line_node, putobject, Qfalse);
8451 ADD_INSN1(ret, line_node, setn, INT2FIX(base_index + CASE3_BI_OFFSET_KEY_ERROR_P + 2 /* (1), (2) */));
8452
8453 ADD_INSN(ret, line_node, pop);
8454 ADD_INSN(ret, line_node, pop);
8455
8456 ADD_LABEL(ret, match_succeeded);
8457 ADD_INSN1(ret, line_node, setn, INT2FIX(2));
8458 ADD_INSN(ret, line_node, pop);
8459 ADD_INSN(ret, line_node, pop);
8460
8461 return COMPILE_OK;
8462}
8463
8464static int
8465compile_case3(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const orig_node, int popped)
8466{
8467 const NODE *pattern;
8468 const NODE *node = orig_node;
8469 LABEL *endlabel, *elselabel;
8470 DECL_ANCHOR(head);
8471 DECL_ANCHOR(body_seq);
8472 DECL_ANCHOR(cond_seq);
8473 int line;
8474 enum node_type type;
8475 const NODE *line_node;
8476 VALUE branches = 0;
8477 int branch_id = 0;
8478 bool single_pattern;
8479
8480 INIT_ANCHOR(head);
8481 INIT_ANCHOR(body_seq);
8482 INIT_ANCHOR(cond_seq);
8483
8484 branches = decl_branch_base(iseq, nd_node_id(node), nd_code_loc(node), "case");
8485
8486 node = RNODE_CASE3(node)->nd_body;
8487 EXPECT_NODE("NODE_CASE3", node, NODE_IN, COMPILE_NG);
8488 type = nd_type(node);
8489 line = nd_line(node);
8490 line_node = node;
8491 single_pattern = !RNODE_IN(node)->nd_next;
8492
8493 endlabel = NEW_LABEL(line);
8494 elselabel = NEW_LABEL(line);
8495
8496 if (single_pattern) {
8497 /* allocate stack for ... */
8498 ADD_INSN(head, line_node, putnil); /* key_error_key */
8499 ADD_INSN(head, line_node, putnil); /* key_error_matchee */
8500 ADD_INSN1(head, line_node, putobject, Qfalse); /* key_error_p */
8501 ADD_INSN(head, line_node, putnil); /* error_string */
8502 }
8503 ADD_INSN(head, line_node, putnil); /* allocate stack for cached #deconstruct value */
8504
8505 CHECK(COMPILE(head, "case base", RNODE_CASE3(orig_node)->nd_head));
8506
8507 ADD_SEQ(ret, head); /* case VAL */
8508
8509 while (type == NODE_IN) {
8510 LABEL *l1;
8511
8512 if (branch_id) {
8513 ADD_INSN(body_seq, line_node, putnil);
8514 }
8515 l1 = NEW_LABEL(line);
8516 ADD_LABEL(body_seq, l1);
8517 ADD_INSN1(body_seq, line_node, adjuststack, INT2FIX(single_pattern ? 6 : 2));
8518
8519 const NODE *const coverage_node = RNODE_IN(node)->nd_body ? RNODE_IN(node)->nd_body : node;
8520 add_trace_branch_coverage(
8521 iseq,
8522 body_seq,
8523 nd_code_loc(coverage_node),
8524 nd_node_id(coverage_node),
8525 branch_id++,
8526 "in",
8527 branches);
8528
8529 CHECK(COMPILE_(body_seq, "in body", RNODE_IN(node)->nd_body, popped));
8530 ADD_INSNL(body_seq, line_node, jump, endlabel);
8531
8532 pattern = RNODE_IN(node)->nd_head;
8533 if (pattern) {
8534 int pat_line = nd_line(pattern);
8535 LABEL *next_pat = NEW_LABEL(pat_line);
8536 ADD_INSN (cond_seq, pattern, dup); /* dup case VAL */
8537 // NOTE: set base_index (it's "under" the matchee value, so it's position is 2)
8538 CHECK(iseq_compile_pattern_each(iseq, cond_seq, pattern, l1, next_pat, single_pattern, false, 2, true));
8539 ADD_LABEL(cond_seq, next_pat);
8540 LABEL_UNREMOVABLE(next_pat);
8541 }
8542 else {
8543 COMPILE_ERROR(ERROR_ARGS "unexpected node");
8544 return COMPILE_NG;
8545 }
8546
8547 node = RNODE_IN(node)->nd_next;
8548 if (!node) {
8549 break;
8550 }
8551 type = nd_type(node);
8552 line = nd_line(node);
8553 line_node = node;
8554 }
8555 /* else */
8556 if (node) {
8557 ADD_LABEL(cond_seq, elselabel);
8558 ADD_INSN(cond_seq, line_node, pop);
8559 ADD_INSN(cond_seq, line_node, pop); /* discard cached #deconstruct value */
8560 add_trace_branch_coverage(iseq, cond_seq, nd_code_loc(node), nd_node_id(node), branch_id, "else", branches);
8561 CHECK(COMPILE_(cond_seq, "else", node, popped));
8562 ADD_INSNL(cond_seq, line_node, jump, endlabel);
8563 ADD_INSN(cond_seq, line_node, putnil);
8564 if (popped) {
8565 ADD_INSN(cond_seq, line_node, putnil);
8566 }
8567 }
8568 else {
8569 debugs("== else (implicit)\n");
8570 ADD_LABEL(cond_seq, elselabel);
8571 add_trace_branch_coverage(iseq, cond_seq, nd_code_loc(orig_node), nd_node_id(orig_node), branch_id, "else", branches);
8572 ADD_INSN1(cond_seq, orig_node, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
8573
8574 if (single_pattern) {
8575 /*
8576 * if key_error_p
8577 * FrozenCore.raise NoMatchingPatternKeyError.new(FrozenCore.sprintf("%p: %s", case_val, error_string), matchee: key_error_matchee, key: key_error_key)
8578 * else
8579 * FrozenCore.raise NoMatchingPatternError, FrozenCore.sprintf("%p: %s", case_val, error_string)
8580 * end
8581 */
8582 LABEL *key_error, *fin;
8583 struct rb_callinfo_kwarg *kw_arg;
8584
8585 key_error = NEW_LABEL(line);
8586 fin = NEW_LABEL(line);
8587
8588 kw_arg = rb_xmalloc_mul_add(2, sizeof(VALUE), sizeof(struct rb_callinfo_kwarg));
8589 kw_arg->references = 0;
8590 kw_arg->keyword_len = 2;
8591 kw_arg->keywords[0] = ID2SYM(rb_intern("matchee"));
8592 kw_arg->keywords[1] = ID2SYM(rb_intern("key"));
8593
8594 ADD_INSN1(cond_seq, orig_node, topn, INT2FIX(CASE3_BI_OFFSET_KEY_ERROR_P + 2));
8595 ADD_INSNL(cond_seq, orig_node, branchif, key_error);
8596 ADD_INSN1(cond_seq, orig_node, putobject, rb_eNoMatchingPatternError);
8597 ADD_INSN1(cond_seq, orig_node, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
8598 ADD_INSN1(cond_seq, orig_node, putobject, rb_fstring_lit("%p: %s"));
8599 ADD_INSN1(cond_seq, orig_node, topn, INT2FIX(4)); /* case VAL */
8600 ADD_INSN1(cond_seq, orig_node, topn, INT2FIX(CASE3_BI_OFFSET_ERROR_STRING + 6));
8601 ADD_SEND(cond_seq, orig_node, id_core_sprintf, INT2FIX(3));
8602 ADD_SEND(cond_seq, orig_node, id_core_raise, INT2FIX(2));
8603 ADD_INSNL(cond_seq, orig_node, jump, fin);
8604
8605 ADD_LABEL(cond_seq, key_error);
8606 ADD_INSN1(cond_seq, orig_node, putobject, rb_eNoMatchingPatternKeyError);
8607 ADD_INSN1(cond_seq, orig_node, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
8608 ADD_INSN1(cond_seq, orig_node, putobject, rb_fstring_lit("%p: %s"));
8609 ADD_INSN1(cond_seq, orig_node, topn, INT2FIX(4)); /* case VAL */
8610 ADD_INSN1(cond_seq, orig_node, topn, INT2FIX(CASE3_BI_OFFSET_ERROR_STRING + 6));
8611 ADD_SEND(cond_seq, orig_node, id_core_sprintf, INT2FIX(3));
8612 ADD_INSN1(cond_seq, orig_node, topn, INT2FIX(CASE3_BI_OFFSET_KEY_ERROR_MATCHEE + 4));
8613 ADD_INSN1(cond_seq, orig_node, topn, INT2FIX(CASE3_BI_OFFSET_KEY_ERROR_KEY + 5));
8614 ADD_SEND_R(cond_seq, orig_node, rb_intern("new"), INT2FIX(1), NULL, INT2FIX(VM_CALL_KWARG), kw_arg);
8615 ADD_SEND(cond_seq, orig_node, id_core_raise, INT2FIX(1));
8616
8617 ADD_LABEL(cond_seq, fin);
8618 }
8619 else {
8620 ADD_INSN1(cond_seq, orig_node, putobject, rb_eNoMatchingPatternError);
8621 ADD_INSN1(cond_seq, orig_node, topn, INT2FIX(2));
8622 ADD_SEND(cond_seq, orig_node, id_core_raise, INT2FIX(2));
8623 }
8624 ADD_INSN1(cond_seq, orig_node, adjuststack, INT2FIX(single_pattern ? 7 : 3));
8625 if (!popped) {
8626 ADD_INSN(cond_seq, orig_node, putnil);
8627 }
8628 ADD_INSNL(cond_seq, orig_node, jump, endlabel);
8629 ADD_INSN1(cond_seq, orig_node, dupn, INT2FIX(single_pattern ? 5 : 1));
8630 if (popped) {
8631 ADD_INSN(cond_seq, line_node, putnil);
8632 }
8633 }
8634
8635 ADD_SEQ(ret, cond_seq);
8636 ADD_SEQ(ret, body_seq);
8637 ADD_LABEL(ret, endlabel);
8638 return COMPILE_OK;
8639}
8640
8641#undef CASE3_BI_OFFSET_DECONSTRUCTED_CACHE
8642#undef CASE3_BI_OFFSET_ERROR_STRING
8643#undef CASE3_BI_OFFSET_KEY_ERROR_P
8644#undef CASE3_BI_OFFSET_KEY_ERROR_MATCHEE
8645#undef CASE3_BI_OFFSET_KEY_ERROR_KEY
8646
8647static int
8648compile_loop(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped, const enum node_type type)
8649{
8650 const int line = (int)nd_line(node);
8651 const NODE *line_node = node;
8652 int result = COMPILE_OK;
8653
8654 LABEL *prev_start_label = ISEQ_COMPILE_DATA(iseq)->start_label;
8655 LABEL *prev_end_label = ISEQ_COMPILE_DATA(iseq)->end_label;
8656 LABEL *prev_redo_label = ISEQ_COMPILE_DATA(iseq)->redo_label;
8657 int prev_loopval_popped = ISEQ_COMPILE_DATA(iseq)->loopval_popped;
8658 VALUE branches = Qfalse;
8659
8661
8662 LABEL *next_label = ISEQ_COMPILE_DATA(iseq)->start_label = NEW_LABEL(line); /* next */
8663 LABEL *redo_label = ISEQ_COMPILE_DATA(iseq)->redo_label = NEW_LABEL(line); /* redo */
8664 LABEL *break_label = ISEQ_COMPILE_DATA(iseq)->end_label = NEW_LABEL(line); /* break */
8665 LABEL *end_label = NEW_LABEL(line);
8666 LABEL *adjust_label = NEW_LABEL(line);
8667
8668 LABEL *next_catch_label = NEW_LABEL(line);
8669 LABEL *tmp_label = NULL;
8670
8671 ISEQ_COMPILE_DATA(iseq)->loopval_popped = 0;
8672 push_ensure_entry(iseq, &enl, NULL, NULL);
8673
8674 if (RNODE_WHILE(node)->nd_state == 1) {
8675 ADD_INSNL(ret, line_node, jump, next_label);
8676 }
8677 else {
8678 tmp_label = NEW_LABEL(line);
8679 ADD_INSNL(ret, line_node, jump, tmp_label);
8680 }
8681 ADD_LABEL(ret, adjust_label);
8682 ADD_INSN(ret, line_node, putnil);
8683 ADD_LABEL(ret, next_catch_label);
8684 ADD_INSN(ret, line_node, pop);
8685 ADD_INSNL(ret, line_node, jump, next_label);
8686 if (tmp_label) ADD_LABEL(ret, tmp_label);
8687
8688 ADD_LABEL(ret, redo_label);
8689 branches = decl_branch_base(iseq, nd_node_id(node), nd_code_loc(node), type == NODE_WHILE ? "while" : "until");
8690
8691 const NODE *const coverage_node = RNODE_WHILE(node)->nd_body ? RNODE_WHILE(node)->nd_body : node;
8692 add_trace_branch_coverage(
8693 iseq,
8694 ret,
8695 nd_code_loc(coverage_node),
8696 nd_node_id(coverage_node),
8697 0,
8698 "body",
8699 branches);
8700
8701 if (!COMPILE_POPPED(ret, "while body", RNODE_WHILE(node)->nd_body)) {
8702 result = COMPILE_NG;
8703 goto cleanup;
8704 }
8705 ADD_LABEL(ret, next_label); /* next */
8706
8707 if (type == NODE_WHILE) {
8708 if (!compile_branch_condition(iseq, ret, RNODE_WHILE(node)->nd_cond,
8709 redo_label, end_label)) {
8710 result = COMPILE_NG;
8711 goto cleanup;
8712 }
8713 }
8714 else {
8715 /* until */
8716 if (!compile_branch_condition(iseq, ret, RNODE_WHILE(node)->nd_cond,
8717 end_label, redo_label)) {
8718 result = COMPILE_NG;
8719 goto cleanup;
8720 }
8721 }
8722
8723 ADD_LABEL(ret, end_label);
8724 ADD_ADJUST_RESTORE(ret, adjust_label);
8725
8726 if (UNDEF_P(RNODE_WHILE(node)->nd_state)) {
8727 /* ADD_INSN(ret, line_node, putundef); */
8728 COMPILE_ERROR(ERROR_ARGS "unsupported: putundef");
8729 result = COMPILE_NG;
8730 goto cleanup;
8731 }
8732 else {
8733 ADD_INSN(ret, line_node, putnil);
8734 }
8735
8736 ADD_LABEL(ret, break_label); /* break */
8737
8738 if (popped) {
8739 ADD_INSN(ret, line_node, pop);
8740 }
8741
8742 ADD_CATCH_ENTRY(CATCH_TYPE_BREAK, redo_label, break_label, NULL,
8743 break_label);
8744 ADD_CATCH_ENTRY(CATCH_TYPE_NEXT, redo_label, break_label, NULL,
8745 next_catch_label);
8746 ADD_CATCH_ENTRY(CATCH_TYPE_REDO, redo_label, break_label, NULL,
8747 ISEQ_COMPILE_DATA(iseq)->redo_label);
8748
8749 cleanup:
8750 ISEQ_COMPILE_DATA(iseq)->start_label = prev_start_label;
8751 ISEQ_COMPILE_DATA(iseq)->end_label = prev_end_label;
8752 ISEQ_COMPILE_DATA(iseq)->redo_label = prev_redo_label;
8753 ISEQ_COMPILE_DATA(iseq)->loopval_popped = prev_loopval_popped;
8754 ISEQ_COMPILE_DATA(iseq)->ensure_node_stack = enl.prev;
8755 return result;
8756}
8757
8758static int
8759compile_iter(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped)
8760{
8761 const int line = nd_line(node);
8762 const NODE *line_node = node;
8763 const rb_iseq_t *prevblock = ISEQ_COMPILE_DATA(iseq)->current_block;
8764 LABEL *retry_label = NEW_LABEL(line);
8765 LABEL *retry_end_l = NEW_LABEL(line);
8766 const rb_iseq_t *child_iseq;
8767
8768 ADD_LABEL(ret, retry_label);
8769 if (nd_type_p(node, NODE_FOR)) {
8770 CHECK(COMPILE(ret, "iter caller (for)", RNODE_FOR(node)->nd_iter));
8771
8772 ISEQ_COMPILE_DATA(iseq)->current_block = child_iseq =
8773 NEW_CHILD_ISEQ(RNODE_FOR(node)->nd_body, make_name_for_block(iseq),
8774 ISEQ_TYPE_BLOCK, line);
8775 ADD_SEND_WITH_BLOCK(ret, line_node, idEach, INT2FIX(0), child_iseq);
8776 }
8777 else {
8778 ISEQ_COMPILE_DATA(iseq)->current_block = child_iseq =
8779 NEW_CHILD_ISEQ(RNODE_ITER(node)->nd_body, make_name_for_block(iseq),
8780 ISEQ_TYPE_BLOCK, line);
8781 CHECK(COMPILE(ret, "iter caller", RNODE_ITER(node)->nd_iter));
8782 }
8783
8784 {
8785 // We need to put the label "retry_end_l" immediately after the last "send" instruction.
8786 // This because vm_throw checks if the break cont is equal to the index of next insn of the "send".
8787 // (Otherwise, it is considered "break from proc-closure". See "TAG_BREAK" handling in "vm_throw_start".)
8788 //
8789 // Normally, "send" instruction is at the last.
8790 // However, qcall under branch coverage measurement adds some instructions after the "send".
8791 //
8792 // Note that "invokesuper", "invokesuperforward" appears instead of "send".
8793 INSN *iobj;
8794 LINK_ELEMENT *last_elem = LAST_ELEMENT(ret);
8795 iobj = IS_INSN(last_elem) ? (INSN*) last_elem : (INSN*) get_prev_insn((INSN*) last_elem);
8796 while (!IS_INSN_ID(iobj, send) && !IS_INSN_ID(iobj, invokesuper) && !IS_INSN_ID(iobj, sendforward) && !IS_INSN_ID(iobj, invokesuperforward)) {
8797 iobj = (INSN*) get_prev_insn(iobj);
8798 }
8799 ELEM_INSERT_NEXT(&iobj->link, (LINK_ELEMENT*) retry_end_l);
8800
8801 // LINK_ANCHOR has a pointer to the last element, but ELEM_INSERT_NEXT does not update it
8802 // even if we add an insn to the last of LINK_ANCHOR. So this updates it manually.
8803 if (&iobj->link == LAST_ELEMENT(ret)) {
8804 ret->last = (LINK_ELEMENT*) retry_end_l;
8805 }
8806 }
8807
8808 if (popped) {
8809 ADD_INSN(ret, line_node, pop);
8810 }
8811
8812 ISEQ_COMPILE_DATA(iseq)->current_block = prevblock;
8813
8814 ADD_CATCH_ENTRY(CATCH_TYPE_BREAK, retry_label, retry_end_l, child_iseq, retry_end_l);
8815 return COMPILE_OK;
8816}
8817
8818static int
8819compile_for_masgn(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped)
8820{
8821 /* massign to var in "for"
8822 * (args.length == 1 && Array.try_convert(args[0])) || args
8823 */
8824 const NODE *line_node = node;
8825 const NODE *var = RNODE_FOR_MASGN(node)->nd_var;
8826 LABEL *not_single = NEW_LABEL(nd_line(var));
8827 LABEL *not_ary = NEW_LABEL(nd_line(var));
8828 CHECK(COMPILE(ret, "for var", var));
8829 ADD_INSN(ret, line_node, dup);
8830 ADD_CALL(ret, line_node, idLength, INT2FIX(0));
8831 ADD_INSN1(ret, line_node, putobject, INT2FIX(1));
8832 ADD_CALL(ret, line_node, idEq, INT2FIX(1));
8833 ADD_INSNL(ret, line_node, branchunless, not_single);
8834 ADD_INSN(ret, line_node, dup);
8835 ADD_INSN1(ret, line_node, putobject, INT2FIX(0));
8836 ADD_CALL(ret, line_node, idAREF, INT2FIX(1));
8837 ADD_INSN1(ret, line_node, putobject, rb_cArray);
8838 ADD_INSN(ret, line_node, swap);
8839 ADD_CALL(ret, line_node, rb_intern("try_convert"), INT2FIX(1));
8840 ADD_INSN(ret, line_node, dup);
8841 ADD_INSNL(ret, line_node, branchunless, not_ary);
8842 ADD_INSN(ret, line_node, swap);
8843 ADD_LABEL(ret, not_ary);
8844 ADD_INSN(ret, line_node, pop);
8845 ADD_LABEL(ret, not_single);
8846 return COMPILE_OK;
8847}
8848
8849static int
8850compile_break(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped)
8851{
8852 const NODE *line_node = node;
8853 unsigned long throw_flag = 0;
8854
8855 if (ISEQ_COMPILE_DATA(iseq)->redo_label != 0 && can_add_ensure_iseq(iseq)) {
8856 /* while/until */
8857 LABEL *splabel = NEW_LABEL(0);
8858 ADD_LABEL(ret, splabel);
8859 ADD_ADJUST(ret, line_node, ISEQ_COMPILE_DATA(iseq)->redo_label);
8860 CHECK(COMPILE_(ret, "break val (while/until)", RNODE_BREAK(node)->nd_stts,
8861 ISEQ_COMPILE_DATA(iseq)->loopval_popped));
8862 add_ensure_iseq(ret, iseq, 0);
8863 ADD_INSNL(ret, line_node, jump, ISEQ_COMPILE_DATA(iseq)->end_label);
8864 ADD_ADJUST_RESTORE(ret, splabel);
8865
8866 if (!popped) {
8867 ADD_INSN(ret, line_node, putnil);
8868 }
8869 }
8870 else {
8871 const rb_iseq_t *ip = iseq;
8872
8873 while (ip) {
8874 if (!ISEQ_COMPILE_DATA(ip)) {
8875 ip = 0;
8876 break;
8877 }
8878
8879 if (ISEQ_COMPILE_DATA(ip)->redo_label != 0) {
8880 throw_flag = VM_THROW_NO_ESCAPE_FLAG;
8881 }
8882 else if (ISEQ_BODY(ip)->type == ISEQ_TYPE_BLOCK) {
8883 throw_flag = 0;
8884 }
8885 else if (ISEQ_BODY(ip)->type == ISEQ_TYPE_EVAL) {
8886 COMPILE_ERROR(ERROR_ARGS "Can't escape from eval with break");
8887 return COMPILE_NG;
8888 }
8889 else {
8890 ip = ISEQ_BODY(ip)->parent_iseq;
8891 continue;
8892 }
8893
8894 /* escape from block */
8895 CHECK(COMPILE(ret, "break val (block)", RNODE_BREAK(node)->nd_stts));
8896 ADD_INSN1(ret, line_node, throw, INT2FIX(throw_flag | TAG_BREAK));
8897 if (popped) {
8898 ADD_INSN(ret, line_node, pop);
8899 }
8900 return COMPILE_OK;
8901 }
8902 COMPILE_ERROR(ERROR_ARGS "Invalid break");
8903 return COMPILE_NG;
8904 }
8905 return COMPILE_OK;
8906}
8907
8908static int
8909compile_next(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped)
8910{
8911 const NODE *line_node = node;
8912 unsigned long throw_flag = 0;
8913
8914 if (ISEQ_COMPILE_DATA(iseq)->redo_label != 0 && can_add_ensure_iseq(iseq)) {
8915 LABEL *splabel = NEW_LABEL(0);
8916 debugs("next in while loop\n");
8917 ADD_LABEL(ret, splabel);
8918 CHECK(COMPILE(ret, "next val/valid syntax?", RNODE_NEXT(node)->nd_stts));
8919 add_ensure_iseq(ret, iseq, 0);
8920 ADD_ADJUST(ret, line_node, ISEQ_COMPILE_DATA(iseq)->redo_label);
8921 ADD_INSNL(ret, line_node, jump, ISEQ_COMPILE_DATA(iseq)->start_label);
8922 ADD_ADJUST_RESTORE(ret, splabel);
8923 if (!popped) {
8924 ADD_INSN(ret, line_node, putnil);
8925 }
8926 }
8927 else if (ISEQ_COMPILE_DATA(iseq)->end_label && can_add_ensure_iseq(iseq)) {
8928 LABEL *splabel = NEW_LABEL(0);
8929 debugs("next in block\n");
8930 ADD_LABEL(ret, splabel);
8931 ADD_ADJUST(ret, line_node, ISEQ_COMPILE_DATA(iseq)->start_label);
8932 CHECK(COMPILE(ret, "next val", RNODE_NEXT(node)->nd_stts));
8933 add_ensure_iseq(ret, iseq, 0);
8934 ADD_INSNL(ret, line_node, jump, ISEQ_COMPILE_DATA(iseq)->end_label);
8935 ADD_ADJUST_RESTORE(ret, splabel);
8936
8937 if (!popped) {
8938 ADD_INSN(ret, line_node, putnil);
8939 }
8940 }
8941 else {
8942 const rb_iseq_t *ip = iseq;
8943
8944 while (ip) {
8945 if (!ISEQ_COMPILE_DATA(ip)) {
8946 ip = 0;
8947 break;
8948 }
8949
8950 throw_flag = VM_THROW_NO_ESCAPE_FLAG;
8951 if (ISEQ_COMPILE_DATA(ip)->redo_label != 0) {
8952 /* while loop */
8953 break;
8954 }
8955 else if (ISEQ_BODY(ip)->type == ISEQ_TYPE_BLOCK) {
8956 break;
8957 }
8958 else if (ISEQ_BODY(ip)->type == ISEQ_TYPE_EVAL) {
8959 COMPILE_ERROR(ERROR_ARGS "Can't escape from eval with next");
8960 return COMPILE_NG;
8961 }
8962
8963 ip = ISEQ_BODY(ip)->parent_iseq;
8964 }
8965 if (ip != 0) {
8966 CHECK(COMPILE(ret, "next val", RNODE_NEXT(node)->nd_stts));
8967 ADD_INSN1(ret, line_node, throw, INT2FIX(throw_flag | TAG_NEXT));
8968
8969 if (popped) {
8970 ADD_INSN(ret, line_node, pop);
8971 }
8972 }
8973 else {
8974 COMPILE_ERROR(ERROR_ARGS "Invalid next");
8975 return COMPILE_NG;
8976 }
8977 }
8978 return COMPILE_OK;
8979}
8980
8981static int
8982compile_redo(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped)
8983{
8984 const NODE *line_node = node;
8985
8986 if (ISEQ_COMPILE_DATA(iseq)->redo_label && can_add_ensure_iseq(iseq)) {
8987 LABEL *splabel = NEW_LABEL(0);
8988 debugs("redo in while");
8989 ADD_LABEL(ret, splabel);
8990 ADD_ADJUST(ret, line_node, ISEQ_COMPILE_DATA(iseq)->redo_label);
8991 add_ensure_iseq(ret, iseq, 0);
8992 ADD_INSNL(ret, line_node, jump, ISEQ_COMPILE_DATA(iseq)->redo_label);
8993 ADD_ADJUST_RESTORE(ret, splabel);
8994 if (!popped) {
8995 ADD_INSN(ret, line_node, putnil);
8996 }
8997 }
8998 else if (ISEQ_BODY(iseq)->type != ISEQ_TYPE_EVAL && ISEQ_COMPILE_DATA(iseq)->start_label && can_add_ensure_iseq(iseq)) {
8999 LABEL *splabel = NEW_LABEL(0);
9000
9001 debugs("redo in block");
9002 ADD_LABEL(ret, splabel);
9003 add_ensure_iseq(ret, iseq, 0);
9004 ADD_ADJUST(ret, line_node, ISEQ_COMPILE_DATA(iseq)->start_label);
9005 ADD_INSNL(ret, line_node, jump, ISEQ_COMPILE_DATA(iseq)->start_label);
9006 ADD_ADJUST_RESTORE(ret, splabel);
9007
9008 if (!popped) {
9009 ADD_INSN(ret, line_node, putnil);
9010 }
9011 }
9012 else {
9013 const rb_iseq_t *ip = iseq;
9014
9015 while (ip) {
9016 if (!ISEQ_COMPILE_DATA(ip)) {
9017 ip = 0;
9018 break;
9019 }
9020
9021 if (ISEQ_COMPILE_DATA(ip)->redo_label != 0) {
9022 break;
9023 }
9024 else if (ISEQ_BODY(ip)->type == ISEQ_TYPE_BLOCK) {
9025 break;
9026 }
9027 else if (ISEQ_BODY(ip)->type == ISEQ_TYPE_EVAL) {
9028 COMPILE_ERROR(ERROR_ARGS "Can't escape from eval with redo");
9029 return COMPILE_NG;
9030 }
9031
9032 ip = ISEQ_BODY(ip)->parent_iseq;
9033 }
9034 if (ip != 0) {
9035 ADD_INSN(ret, line_node, putnil);
9036 ADD_INSN1(ret, line_node, throw, INT2FIX(VM_THROW_NO_ESCAPE_FLAG | TAG_REDO));
9037
9038 if (popped) {
9039 ADD_INSN(ret, line_node, pop);
9040 }
9041 }
9042 else {
9043 COMPILE_ERROR(ERROR_ARGS "Invalid redo");
9044 return COMPILE_NG;
9045 }
9046 }
9047 return COMPILE_OK;
9048}
9049
9050static int
9051compile_retry(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped)
9052{
9053 const NODE *line_node = node;
9054
9055 if (ISEQ_BODY(iseq)->type == ISEQ_TYPE_RESCUE) {
9056 ADD_INSN(ret, line_node, putnil);
9057 ADD_INSN1(ret, line_node, throw, INT2FIX(TAG_RETRY));
9058
9059 if (popped) {
9060 ADD_INSN(ret, line_node, pop);
9061 }
9062 }
9063 else {
9064 COMPILE_ERROR(ERROR_ARGS "Invalid retry");
9065 return COMPILE_NG;
9066 }
9067 return COMPILE_OK;
9068}
9069
9070static int
9071compile_rescue(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped)
9072{
9073 const int line = nd_line(node);
9074 const NODE *line_node = node;
9075 LABEL *lstart = NEW_LABEL(line);
9076 LABEL *lend = NEW_LABEL(line);
9077 LABEL *lcont = NEW_LABEL(line);
9078 const rb_iseq_t *rescue = NEW_CHILD_ISEQ(RNODE_RESCUE(node)->nd_resq,
9079 rb_str_concat(rb_str_new2("rescue in "),
9080 ISEQ_BODY(iseq)->location.label),
9081 ISEQ_TYPE_RESCUE, line);
9082
9083 lstart->rescued = LABEL_RESCUE_BEG;
9084 lend->rescued = LABEL_RESCUE_END;
9085 ADD_LABEL(ret, lstart);
9086
9087 bool prev_in_rescue = ISEQ_COMPILE_DATA(iseq)->in_rescue;
9088 ISEQ_COMPILE_DATA(iseq)->in_rescue = true;
9089 {
9090 CHECK(COMPILE(ret, "rescue head", RNODE_RESCUE(node)->nd_head));
9091 }
9092 ISEQ_COMPILE_DATA(iseq)->in_rescue = prev_in_rescue;
9093
9094 ADD_LABEL(ret, lend);
9095 if (RNODE_RESCUE(node)->nd_else) {
9096 ADD_INSN(ret, line_node, pop);
9097 CHECK(COMPILE(ret, "rescue else", RNODE_RESCUE(node)->nd_else));
9098 }
9099 ADD_INSN(ret, line_node, nop);
9100 ADD_LABEL(ret, lcont);
9101
9102 if (popped) {
9103 ADD_INSN(ret, line_node, pop);
9104 }
9105
9106 /* register catch entry */
9107 ADD_CATCH_ENTRY(CATCH_TYPE_RESCUE, lstart, lend, rescue, lcont);
9108 ADD_CATCH_ENTRY(CATCH_TYPE_RETRY, lend, lcont, NULL, lstart);
9109 return COMPILE_OK;
9110}
9111
9112static int
9113compile_resbody(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped)
9114{
9115 const int line = nd_line(node);
9116 const NODE *line_node = node;
9117 const NODE *resq = node;
9118 const NODE *narg;
9119 LABEL *label_miss, *label_hit;
9120
9121 while (resq) {
9122 label_miss = NEW_LABEL(line);
9123 label_hit = NEW_LABEL(line);
9124
9125 narg = RNODE_RESBODY(resq)->nd_args;
9126 if (narg) {
9127 switch (nd_type(narg)) {
9128 case NODE_LIST:
9129 while (narg) {
9130 ADD_GETLOCAL(ret, line_node, LVAR_ERRINFO, 0);
9131 CHECK(COMPILE(ret, "rescue arg", RNODE_LIST(narg)->nd_head));
9132 ADD_INSN1(ret, line_node, checkmatch, INT2FIX(VM_CHECKMATCH_TYPE_RESCUE));
9133 ADD_INSNL(ret, line_node, branchif, label_hit);
9134 narg = RNODE_LIST(narg)->nd_next;
9135 }
9136 break;
9137 case NODE_SPLAT:
9138 case NODE_ARGSCAT:
9139 case NODE_ARGSPUSH:
9140 ADD_GETLOCAL(ret, line_node, LVAR_ERRINFO, 0);
9141 CHECK(COMPILE(ret, "rescue/cond splat", narg));
9142 ADD_INSN1(ret, line_node, checkmatch, INT2FIX(VM_CHECKMATCH_TYPE_RESCUE | VM_CHECKMATCH_ARRAY));
9143 ADD_INSNL(ret, line_node, branchif, label_hit);
9144 break;
9145 default:
9146 UNKNOWN_NODE("NODE_RESBODY", narg, COMPILE_NG);
9147 }
9148 }
9149 else {
9150 ADD_GETLOCAL(ret, line_node, LVAR_ERRINFO, 0);
9151 ADD_INSN1(ret, line_node, putobject, rb_eStandardError);
9152 ADD_INSN1(ret, line_node, checkmatch, INT2FIX(VM_CHECKMATCH_TYPE_RESCUE));
9153 ADD_INSNL(ret, line_node, branchif, label_hit);
9154 }
9155 ADD_INSNL(ret, line_node, jump, label_miss);
9156 ADD_LABEL(ret, label_hit);
9157 ADD_TRACE(ret, RUBY_EVENT_RESCUE);
9158
9159 if (RNODE_RESBODY(resq)->nd_exc_var) {
9160 CHECK(COMPILE_POPPED(ret, "resbody exc_var", RNODE_RESBODY(resq)->nd_exc_var));
9161 }
9162
9163 if (nd_type(RNODE_RESBODY(resq)->nd_body) == NODE_BEGIN && RNODE_BEGIN(RNODE_RESBODY(resq)->nd_body)->nd_body == NULL && !RNODE_RESBODY(resq)->nd_exc_var) {
9164 // empty body
9165 ADD_SYNTHETIC_INSN(ret, nd_line(RNODE_RESBODY(resq)->nd_body), -1, putnil);
9166 }
9167 else {
9168 CHECK(COMPILE(ret, "resbody body", RNODE_RESBODY(resq)->nd_body));
9169 }
9170
9171 if (ISEQ_COMPILE_DATA(iseq)->option->tailcall_optimization) {
9172 ADD_INSN(ret, line_node, nop);
9173 }
9174 ADD_INSN(ret, line_node, leave);
9175 ADD_LABEL(ret, label_miss);
9176 resq = RNODE_RESBODY(resq)->nd_next;
9177 }
9178 return COMPILE_OK;
9179}
9180
9181static int
9182compile_ensure(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped)
9183{
9184 const int line = nd_line(RNODE_ENSURE(node)->nd_ensr);
9185 const NODE *line_node = node;
9186 DECL_ANCHOR(ensr);
9187 const rb_iseq_t *ensure = NEW_CHILD_ISEQ(RNODE_ENSURE(node)->nd_ensr,
9188 rb_str_concat(rb_str_new2 ("ensure in "), ISEQ_BODY(iseq)->location.label),
9189 ISEQ_TYPE_ENSURE, line);
9190 LABEL *lstart = NEW_LABEL(line);
9191 LABEL *lend = NEW_LABEL(line);
9192 LABEL *lcont = NEW_LABEL(line);
9193 LINK_ELEMENT *last;
9194 int last_leave = 0;
9195 struct ensure_range er;
9197 struct ensure_range *erange;
9198 int result = COMPILE_OK;
9199
9200 INIT_ANCHOR(ensr);
9201 CHECK(COMPILE_POPPED(ensr, "ensure ensr", RNODE_ENSURE(node)->nd_ensr));
9202 last = ensr->last;
9203 last_leave = last && IS_INSN(last) && IS_INSN_ID(last, leave);
9204
9205 er.begin = lstart;
9206 er.end = lend;
9207 er.next = 0;
9208 push_ensure_entry(iseq, &enl, &er, RNODE_ENSURE(node)->nd_ensr);
9209
9210 ADD_LABEL(ret, lstart);
9211 if (!COMPILE_(ret, "ensure head", RNODE_ENSURE(node)->nd_head, (popped | last_leave))) {
9212 result = COMPILE_NG;
9213 goto cleanup;
9214 }
9215 ADD_LABEL(ret, lend);
9216 ADD_SEQ(ret, ensr);
9217 if (!popped && last_leave) ADD_INSN(ret, line_node, putnil);
9218 ADD_LABEL(ret, lcont);
9219 if (last_leave) ADD_INSN(ret, line_node, pop);
9220
9221 erange = ISEQ_COMPILE_DATA(iseq)->ensure_node_stack->erange;
9222 if (lstart->link.next != &lend->link) {
9223 while (erange) {
9224 ADD_CATCH_ENTRY(CATCH_TYPE_ENSURE, erange->begin, erange->end,
9225 ensure, lcont);
9226 erange = erange->next;
9227 }
9228 }
9229
9230 cleanup:
9231 ISEQ_COMPILE_DATA(iseq)->ensure_node_stack = enl.prev;
9232 return result;
9233}
9234
9235static int
9236compile_return(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped)
9237{
9238 const NODE *line_node = node;
9239
9240 if (iseq) {
9241 enum rb_iseq_type type = ISEQ_BODY(iseq)->type;
9242 const rb_iseq_t *is = iseq;
9243 enum rb_iseq_type t = type;
9244 const NODE *retval = RNODE_RETURN(node)->nd_stts;
9245 LABEL *splabel = 0;
9246
9247 while (t == ISEQ_TYPE_RESCUE || t == ISEQ_TYPE_ENSURE) {
9248 if (!(is = ISEQ_BODY(is)->parent_iseq)) break;
9249 t = ISEQ_BODY(is)->type;
9250 }
9251 switch (t) {
9252 case ISEQ_TYPE_TOP:
9253 case ISEQ_TYPE_MAIN:
9254 if (retval) {
9255 rb_warn("argument of top-level return is ignored");
9256 }
9257 if (is == iseq) {
9258 /* plain top-level, leave directly */
9259 type = ISEQ_TYPE_METHOD;
9260 }
9261 break;
9262 default:
9263 break;
9264 }
9265
9266 bool direct_return = can_inline_return(iseq, type);
9267 if (direct_return) {
9268 splabel = NEW_LABEL(0);
9269 ADD_LABEL(ret, splabel);
9270 ADD_ADJUST(ret, line_node, 0);
9271 }
9272
9273 CHECK(COMPILE(ret, "return nd_stts (return val)", retval));
9274
9275 if (direct_return) {
9276 add_ensure_iseq(ret, iseq, 1);
9277 ADD_TRACE(ret, RUBY_EVENT_RETURN);
9278 ADD_INSN(ret, line_node, leave);
9279 ADD_ADJUST_RESTORE(ret, splabel);
9280
9281 if (!popped) {
9282 ADD_INSN(ret, line_node, putnil);
9283 }
9284 }
9285 else {
9286 ADD_INSN1(ret, line_node, throw, INT2FIX(TAG_RETURN));
9287 if (popped) {
9288 ADD_INSN(ret, line_node, pop);
9289 }
9290 }
9291 }
9292 return COMPILE_OK;
9293}
9294
9295static bool
9296drop_unreachable_return(LINK_ANCHOR *ret)
9297{
9298 LINK_ELEMENT *i = ret->last, *last;
9299 if (!i) return false;
9300 if (IS_TRACE(i)) i = i->prev;
9301 if (!IS_INSN(i) || !IS_INSN_ID(i, putnil)) return false;
9302 last = i = i->prev;
9303 if (IS_ADJUST(i)) i = i->prev;
9304 if (!IS_INSN(i)) return false;
9305 switch (INSN_OF(i)) {
9306 case BIN(leave):
9307 case BIN(jump):
9308 break;
9309 default:
9310 return false;
9311 }
9312 (ret->last = last->prev)->next = NULL;
9313 return true;
9314}
9315
9316static int
9317compile_evstr(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped)
9318{
9319 CHECK(COMPILE_(ret, "nd_body", node, popped));
9320
9321 if (!popped && !all_string_result_p(node)) {
9322 const NODE *line_node = node;
9323 const unsigned int flag = VM_CALL_FCALL;
9324
9325 // Note, this dup could be removed if we are willing to change anytostring. It pops
9326 // two VALUEs off the stack when it could work by replacing the top most VALUE.
9327 ADD_INSN(ret, line_node, dup);
9328 ADD_INSN1(ret, line_node, objtostring, new_callinfo(iseq, idTo_s, 0, flag, NULL, FALSE));
9329 ADD_INSN(ret, line_node, anytostring);
9330 }
9331 return COMPILE_OK;
9332}
9333
9334static void
9335compile_lvar(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *line_node, ID id)
9336{
9337 int idx = ISEQ_BODY(ISEQ_BODY(iseq)->local_iseq)->local_table_size - get_local_var_idx(iseq, id);
9338
9339 debugs("id: %s idx: %d\n", rb_id2name(id), idx);
9340 ADD_GETLOCAL(ret, line_node, idx, get_lvar_level(iseq));
9341}
9342
9343static LABEL *
9344qcall_branch_start(rb_iseq_t *iseq, LINK_ANCHOR *const recv, VALUE *branches, const NODE *node, const NODE *line_node)
9345{
9346 LABEL *else_label = NEW_LABEL(nd_line(line_node));
9347 VALUE br = 0;
9348
9349 br = decl_branch_base(iseq, nd_node_id(node), nd_code_loc(node), "&.");
9350 *branches = br;
9351 ADD_INSN(recv, line_node, dup);
9352 ADD_INSNL(recv, line_node, branchnil, else_label);
9353 add_trace_branch_coverage(iseq, recv, nd_code_loc(node), nd_node_id(node), 0, "then", br);
9354 return else_label;
9355}
9356
9357static void
9358qcall_branch_end(rb_iseq_t *iseq, LINK_ANCHOR *const ret, LABEL *else_label, VALUE branches, const NODE *node, const NODE *line_node)
9359{
9360 LABEL *end_label;
9361 if (!else_label) return;
9362 end_label = NEW_LABEL(nd_line(line_node));
9363 ADD_INSNL(ret, line_node, jump, end_label);
9364 ADD_LABEL(ret, else_label);
9365 add_trace_branch_coverage(iseq, ret, nd_code_loc(node), nd_node_id(node), 1, "else", branches);
9366 ADD_LABEL(ret, end_label);
9367}
9368
9369static int
9370compile_call_precheck_freeze(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, const NODE *line_node, int popped)
9371{
9372 /* optimization shortcut
9373 * "literal".freeze -> opt_str_freeze("literal")
9374 */
9375 if (get_nd_recv(node) &&
9376 nd_type_p(get_nd_recv(node), NODE_STR) &&
9377 (get_node_call_nd_mid(node) == idFreeze || get_node_call_nd_mid(node) == idUMinus) &&
9378 get_nd_args(node) == NULL &&
9379 ISEQ_COMPILE_DATA(iseq)->current_block == NULL &&
9380 ISEQ_COMPILE_DATA(iseq)->option->specialized_instruction) {
9381 VALUE str = get_string_value(get_nd_recv(node));
9382 if (get_node_call_nd_mid(node) == idUMinus) {
9383 ADD_INSN2(ret, line_node, opt_str_uminus, str,
9384 new_callinfo(iseq, idUMinus, 0, 0, NULL, FALSE));
9385 }
9386 else {
9387 ADD_INSN2(ret, line_node, opt_str_freeze, str,
9388 new_callinfo(iseq, idFreeze, 0, 0, NULL, FALSE));
9389 }
9390 RB_OBJ_WRITTEN(iseq, Qundef, str);
9391 if (popped) {
9392 ADD_INSN(ret, line_node, pop);
9393 }
9394 return TRUE;
9395 }
9396 return FALSE;
9397}
9398
9399static int
9400iseq_has_builtin_function_table(const rb_iseq_t *iseq)
9401{
9402 return ISEQ_COMPILE_DATA(iseq)->builtin_function_table != NULL;
9403}
9404
9405static const struct rb_builtin_function *
9406iseq_builtin_function_lookup(const rb_iseq_t *iseq, const char *name)
9407{
9408 int i;
9409 const struct rb_builtin_function *table = ISEQ_COMPILE_DATA(iseq)->builtin_function_table;
9410 for (i=0; table[i].index != -1; i++) {
9411 if (strcmp(table[i].name, name) == 0) {
9412 return &table[i];
9413 }
9414 }
9415 return NULL;
9416}
9417
9418static const char *
9419iseq_builtin_function_name(const enum node_type type, const NODE *recv, ID mid)
9420{
9421 const char *name = rb_id2name(mid);
9422 static const char prefix[] = "__builtin_";
9423 const size_t prefix_len = sizeof(prefix) - 1;
9424
9425 switch (type) {
9426 case NODE_CALL:
9427 if (recv) {
9428 switch (nd_type(recv)) {
9429 case NODE_VCALL:
9430 if (RNODE_VCALL(recv)->nd_mid == rb_intern("__builtin")) {
9431 return name;
9432 }
9433 break;
9434 case NODE_CONST:
9435 if (RNODE_CONST(recv)->nd_vid == rb_intern("Primitive")) {
9436 return name;
9437 }
9438 break;
9439 default: break;
9440 }
9441 }
9442 break;
9443 case NODE_VCALL:
9444 case NODE_FCALL:
9445 if (UNLIKELY(strncmp(prefix, name, prefix_len) == 0)) {
9446 return &name[prefix_len];
9447 }
9448 break;
9449 default: break;
9450 }
9451 return NULL;
9452}
9453
9454static int
9455delegate_call_p(const rb_iseq_t *iseq, unsigned int argc, const LINK_ANCHOR *args, unsigned int *pstart_index)
9456{
9457
9458 if (argc == 0) {
9459 *pstart_index = 0;
9460 return TRUE;
9461 }
9462 else if (argc <= ISEQ_BODY(iseq)->local_table_size) {
9463 unsigned int start=0;
9464
9465 // local_table: [p1, p2, p3, l1, l2, l3]
9466 // arguments: [p3, l1, l2] -> 2
9467 for (start = 0;
9468 argc + start <= ISEQ_BODY(iseq)->local_table_size;
9469 start++) {
9470 const LINK_ELEMENT *elem = FIRST_ELEMENT(args);
9471
9472 for (unsigned int i=start; i-start<argc; i++) {
9473 if (IS_INSN(elem) &&
9474 INSN_OF(elem) == BIN(getlocal)) {
9475 int local_index = FIX2INT(OPERAND_AT(elem, 0));
9476 int local_level = FIX2INT(OPERAND_AT(elem, 1));
9477
9478 if (local_level == 0) {
9479 unsigned int index = ISEQ_BODY(iseq)->local_table_size - (local_index - VM_ENV_DATA_SIZE + 1);
9480 if (0) { // for debug
9481 fprintf(stderr, "lvar:%s (%d), id:%s (%d) local_index:%d, local_size:%d\n",
9482 rb_id2name(ISEQ_BODY(iseq)->local_table[i]), i,
9483 rb_id2name(ISEQ_BODY(iseq)->local_table[index]), index,
9484 local_index, (int)ISEQ_BODY(iseq)->local_table_size);
9485 }
9486 if (i == index) {
9487 elem = elem->next;
9488 continue; /* for */
9489 }
9490 else {
9491 goto next;
9492 }
9493 }
9494 else {
9495 goto fail; // level != 0 is unsupported
9496 }
9497 }
9498 else {
9499 goto fail; // insn is not a getlocal
9500 }
9501 }
9502 goto success;
9503 next:;
9504 }
9505 fail:
9506 return FALSE;
9507 success:
9508 *pstart_index = start;
9509 return TRUE;
9510 }
9511 else {
9512 return FALSE;
9513 }
9514}
9515
9516static int
9517compile_builtin_attr_symbol(rb_iseq_t *iseq, VALUE symbol)
9518{
9519 VALUE string = rb_sym2str(symbol);
9520 if (rb_streql_lit(string, "leaf")) {
9521 ISEQ_BODY(iseq)->builtin_attrs |= BUILTIN_ATTR_LEAF;
9522 }
9523 else if (rb_streql_lit(string, "inline_block")) {
9524 ISEQ_BODY(iseq)->builtin_attrs |= BUILTIN_ATTR_INLINE_BLOCK;
9525 }
9526 else if (rb_streql_lit(string, "use_block")) {
9527 iseq_set_use_block(iseq);
9528 }
9529 else if (rb_streql_lit(string, "c_trace")) {
9530 // Let the iseq act like a C method in backtraces
9531 ISEQ_BODY(iseq)->builtin_attrs |= BUILTIN_ATTR_C_TRACE;
9532 }
9533 else if (rb_streql_lit(string, "without_interrupts")) {
9534 ISEQ_BODY(iseq)->builtin_attrs |= BUILTIN_ATTR_WITHOUT_INTERRUPTS;
9535 }
9536 else if (rb_streql_lit(string, "caller_user_box")) {
9537 ISEQ_BODY(iseq)->builtin_attrs |= BUILTIN_ATTR_CALLER_USER_BOX;
9538 }
9539 else if (rb_streql_lit(string, "always_inline")) {
9540 ISEQ_BODY(iseq)->builtin_attrs |= BUILTIN_ATTR_ALWAYS_INLINE;
9541 }
9542 else {
9543 return COMPILE_NG;
9544 }
9545 return COMPILE_OK;
9546}
9547
9548// Compile Primitive.attr! :leaf, ...
9549static int
9550compile_builtin_attr(rb_iseq_t *iseq, const NODE *node)
9551{
9552 VALUE symbol;
9553 if (!node) goto no_arg;
9554 while (node) {
9555 if (!nd_type_p(node, NODE_LIST)) goto bad_arg;
9556 const NODE *next = RNODE_LIST(node)->nd_next;
9557
9558 node = RNODE_LIST(node)->nd_head;
9559 if (!node) goto no_arg;
9560 switch (nd_type(node)) {
9561 case NODE_SYM:
9562 symbol = rb_node_sym_string_val(node);
9563 break;
9564 default:
9565 goto bad_arg;
9566 }
9567
9568 if (!SYMBOL_P(symbol)) goto non_symbol_arg;
9569 if (compile_builtin_attr_symbol(iseq, symbol) != COMPILE_OK) goto unknown_arg;
9570 node = next;
9571 }
9572 return COMPILE_OK;
9573 no_arg:
9574 COMPILE_ERROR(ERROR_ARGS "attr!: no argument");
9575 return COMPILE_NG;
9576 non_symbol_arg:
9577 COMPILE_ERROR(ERROR_ARGS "non symbol argument to attr!: %s", rb_builtin_class_name(symbol));
9578 return COMPILE_NG;
9579 unknown_arg:
9580 COMPILE_ERROR(ERROR_ARGS "unknown argument to attr!: %" PRIsVALUE, symbol);
9581 return COMPILE_NG;
9582 bad_arg:
9583 UNKNOWN_NODE("attr!", node, COMPILE_NG);
9584}
9585
9586static int
9587compile_builtin_arg(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *node, const NODE *line_node, int popped)
9588{
9589 VALUE name;
9590
9591 if (!node) goto no_arg;
9592 if (!nd_type_p(node, NODE_LIST)) goto bad_arg;
9593 if (RNODE_LIST(node)->nd_next) goto too_many_arg;
9594 node = RNODE_LIST(node)->nd_head;
9595 if (!node) goto no_arg;
9596 switch (nd_type(node)) {
9597 case NODE_SYM:
9598 name = rb_node_sym_string_val(node);
9599 break;
9600 default:
9601 goto bad_arg;
9602 }
9603 if (!SYMBOL_P(name)) goto non_symbol_arg;
9604 if (!popped) {
9605 compile_lvar(iseq, ret, line_node, SYM2ID(name));
9606 }
9607 return COMPILE_OK;
9608 no_arg:
9609 COMPILE_ERROR(ERROR_ARGS "arg!: no argument");
9610 return COMPILE_NG;
9611 too_many_arg:
9612 COMPILE_ERROR(ERROR_ARGS "arg!: too many argument");
9613 return COMPILE_NG;
9614 non_symbol_arg:
9615 COMPILE_ERROR(ERROR_ARGS "non symbol argument to arg!: %s",
9616 rb_builtin_class_name(name));
9617 return COMPILE_NG;
9618 bad_arg:
9619 UNKNOWN_NODE("arg!", node, COMPILE_NG);
9620}
9621
9622static NODE *
9623mandatory_node(const rb_iseq_t *iseq, const NODE *cond_node)
9624{
9625 const NODE *node = ISEQ_COMPILE_DATA(iseq)->root_node;
9626 if (nd_type(node) == NODE_IF && RNODE_IF(node)->nd_cond == cond_node) {
9627 return RNODE_IF(node)->nd_body;
9628 }
9629 else {
9630 rb_bug("mandatory_node: can't find mandatory node");
9631 }
9632}
9633
9634static int
9635compile_builtin_mandatory_only_method(rb_iseq_t *iseq, const NODE *node, const NODE *line_node)
9636{
9637 // arguments
9638 struct rb_args_info args = {
9639 .pre_args_num = ISEQ_BODY(iseq)->param.lead_num,
9640 };
9641 rb_node_args_t args_node;
9642 rb_node_init(RNODE(&args_node), NODE_ARGS);
9643 args_node.nd_ainfo = args;
9644
9645 // local table without non-mandatory parameters
9646 const int skip_local_size = ISEQ_BODY(iseq)->param.size - ISEQ_BODY(iseq)->param.lead_num;
9647 const int table_size = ISEQ_BODY(iseq)->local_table_size - skip_local_size;
9648
9649 VALUE idtmp = 0;
9650 rb_ast_id_table_t *tbl = ALLOCV(idtmp, sizeof(rb_ast_id_table_t) + table_size * sizeof(ID));
9651 tbl->size = table_size;
9652
9653 int i;
9654
9655 // lead parameters
9656 for (i=0; i<ISEQ_BODY(iseq)->param.lead_num; i++) {
9657 tbl->ids[i] = ISEQ_BODY(iseq)->local_table[i];
9658 }
9659 // local variables
9660 for (; i<table_size; i++) {
9661 tbl->ids[i] = ISEQ_BODY(iseq)->local_table[i + skip_local_size];
9662 }
9663
9664 rb_node_scope_t scope_node;
9665 rb_node_init(RNODE(&scope_node), NODE_SCOPE);
9666 scope_node.nd_tbl = tbl;
9667 scope_node.nd_body = mandatory_node(iseq, node);
9668 scope_node.nd_parent = NULL;
9669 scope_node.nd_args = &args_node;
9670
9671 VALUE ast_value = rb_ruby_ast_new(RNODE(&scope_node));
9672
9673 const rb_iseq_t *mandatory_only_iseq =
9674 rb_iseq_new_with_opt(ast_value, rb_iseq_base_label(iseq),
9675 rb_iseq_path(iseq), rb_iseq_realpath(iseq),
9676 nd_line(line_node), NULL, 0,
9677 ISEQ_TYPE_METHOD, ISEQ_COMPILE_DATA(iseq)->option,
9678 ISEQ_SCRIPT_LINES(iseq));
9679 rb_iseq_mandatory_only_iseq_set(iseq, mandatory_only_iseq);
9680
9681 ALLOCV_END(idtmp);
9682 return COMPILE_OK;
9683}
9684
9685static int
9686compile_builtin_function_call(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, const NODE *line_node, int popped,
9687 const rb_iseq_t *parent_block, LINK_ANCHOR *args, const char *builtin_func)
9688{
9689 NODE *args_node = get_nd_args(node);
9690
9691 if (parent_block != NULL) {
9692 COMPILE_ERROR(ERROR_ARGS_AT(line_node) "should not call builtins here.");
9693 return COMPILE_NG;
9694 }
9695 else {
9696# define BUILTIN_INLINE_PREFIX "_bi"
9697 char inline_func[sizeof(BUILTIN_INLINE_PREFIX) + DECIMAL_SIZE_OF(int)];
9698 bool cconst = false;
9699 retry:;
9700 const struct rb_builtin_function *bf = iseq_builtin_function_lookup(iseq, builtin_func);
9701
9702 if (bf == NULL) {
9703 if (strcmp("cstmt!", builtin_func) == 0 ||
9704 strcmp("cexpr!", builtin_func) == 0) {
9705 // ok
9706 }
9707 else if (strcmp("cconst!", builtin_func) == 0) {
9708 cconst = true;
9709 }
9710 else if (strcmp("cinit!", builtin_func) == 0) {
9711 // ignore
9712 return COMPILE_OK;
9713 }
9714 else if (strcmp("attr!", builtin_func) == 0) {
9715 return compile_builtin_attr(iseq, args_node);
9716 }
9717 else if (strcmp("arg!", builtin_func) == 0) {
9718 return compile_builtin_arg(iseq, ret, args_node, line_node, popped);
9719 }
9720 else if (strcmp("mandatory_only?", builtin_func) == 0) {
9721 if (popped) {
9722 rb_bug("mandatory_only? should be in if condition");
9723 }
9724 else if (!LIST_INSN_SIZE_ZERO(ret)) {
9725 rb_bug("mandatory_only? should be put on top");
9726 }
9727
9728 ADD_INSN1(ret, line_node, putobject, Qfalse);
9729 return compile_builtin_mandatory_only_method(iseq, node, line_node);
9730 }
9731 else if (strcmp("local_self!", builtin_func) == 0) {
9732 // Push the local named "self" (e.g. the `self:` keyword
9733 // parameter of Ractor.shareable_proc) onto the stack.
9734 ID id_self;
9735 CONST_ID(id_self, "self");
9736 compile_lvar(iseq, ret, line_node, id_self);
9737 return COMPILE_OK;
9738 }
9739 else if (1) {
9740 rb_bug("can't find builtin function:%s", builtin_func);
9741 }
9742 else {
9743 COMPILE_ERROR(ERROR_ARGS "can't find builtin function:%s", builtin_func);
9744 return COMPILE_NG;
9745 }
9746
9747 int inline_index = nd_line(node);
9748 snprintf(inline_func, sizeof(inline_func), BUILTIN_INLINE_PREFIX "%d", inline_index);
9749 builtin_func = inline_func;
9750 args_node = NULL;
9751 goto retry;
9752 }
9753
9754 if (cconst) {
9755 typedef VALUE(*builtin_func0)(void *, VALUE);
9756 VALUE const_val = (*(builtin_func0)(uintptr_t)bf->func_ptr)(NULL, Qnil);
9757 ADD_INSN1(ret, line_node, putobject, const_val);
9758 return COMPILE_OK;
9759 }
9760
9761 // fprintf(stderr, "func_name:%s -> %p\n", builtin_func, bf->func_ptr);
9762
9763 unsigned int flag = 0;
9764 struct rb_callinfo_kwarg *keywords = NULL;
9765 VALUE argc = setup_args(iseq, args, args_node, &flag, &keywords);
9766
9767 if (FIX2INT(argc) != bf->argc) {
9768 COMPILE_ERROR(ERROR_ARGS "argc is not match for builtin function:%s (expect %d but %d)",
9769 builtin_func, bf->argc, FIX2INT(argc));
9770 return COMPILE_NG;
9771 }
9772
9773 unsigned int start_index;
9774 if (delegate_call_p(iseq, FIX2INT(argc), args, &start_index)) {
9775 ADD_INSN2(ret, line_node, opt_invokebuiltin_delegate, bf, INT2FIX(start_index));
9776 }
9777 else {
9778 ADD_SEQ(ret, args);
9779 ADD_INSN1(ret, line_node, invokebuiltin, bf);
9780 }
9781
9782 if (popped) ADD_INSN(ret, line_node, pop);
9783 return COMPILE_OK;
9784 }
9785}
9786
9787static int
9788compile_call(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, const enum node_type type, const NODE *const line_node, int popped, bool assume_receiver)
9789{
9790 /* call: obj.method(...)
9791 * fcall: func(...)
9792 * vcall: func
9793 */
9794 DECL_ANCHOR(recv);
9795 DECL_ANCHOR(args);
9796 ID mid = get_node_call_nd_mid(node);
9797 VALUE argc;
9798 unsigned int flag = 0;
9799 struct rb_callinfo_kwarg *keywords = NULL;
9800 const rb_iseq_t *parent_block = ISEQ_COMPILE_DATA(iseq)->current_block;
9801 LABEL *else_label = NULL;
9802 VALUE branches = Qfalse;
9803
9804 ISEQ_COMPILE_DATA(iseq)->current_block = NULL;
9805
9806 INIT_ANCHOR(recv);
9807 INIT_ANCHOR(args);
9808
9809#if OPT_SUPPORT_JOKE
9810 if (nd_type_p(node, NODE_VCALL)) {
9811 ID id_bitblt;
9812 ID id_answer;
9813
9814 CONST_ID(id_bitblt, "bitblt");
9815 CONST_ID(id_answer, "the_answer_to_life_the_universe_and_everything");
9816
9817 if (mid == id_bitblt) {
9818 ADD_INSN(ret, line_node, bitblt);
9819 return COMPILE_OK;
9820 }
9821 else if (mid == id_answer) {
9822 ADD_INSN(ret, line_node, answer);
9823 return COMPILE_OK;
9824 }
9825 }
9826 /* only joke */
9827 {
9828 ID goto_id;
9829 ID label_id;
9830
9831 CONST_ID(goto_id, "__goto__");
9832 CONST_ID(label_id, "__label__");
9833
9834 if (nd_type_p(node, NODE_FCALL) &&
9835 (mid == goto_id || mid == label_id)) {
9836 LABEL *label;
9837 st_data_t data;
9838 st_table *labels_table = ISEQ_COMPILE_DATA(iseq)->labels_table;
9839 VALUE label_name;
9840
9841 if (!labels_table) {
9842 labels_table = st_init_numtable();
9843 ISEQ_COMPILE_DATA(iseq)->labels_table = labels_table;
9844 }
9845 {
9846 COMPILE_ERROR(ERROR_ARGS "invalid goto/label format");
9847 return COMPILE_NG;
9848 }
9849
9850 if (mid == goto_id) {
9851 ADD_INSNL(ret, line_node, jump, label);
9852 }
9853 else {
9854 ADD_LABEL(ret, label);
9855 }
9856 return COMPILE_OK;
9857 }
9858 }
9859#endif
9860
9861 const char *builtin_func;
9862 if (UNLIKELY(iseq_has_builtin_function_table(iseq)) &&
9863 (builtin_func = iseq_builtin_function_name(type, get_nd_recv(node), mid)) != NULL) {
9864 return compile_builtin_function_call(iseq, ret, node, line_node, popped, parent_block, args, builtin_func);
9865 }
9866
9867 /* receiver */
9868 if (!assume_receiver) {
9869 if (type == NODE_CALL || type == NODE_OPCALL || type == NODE_QCALL) {
9870 int idx, level;
9871
9872 if ((mid == idCall || mid == idAREF || mid == idYield || mid == idEqq) &&
9873 nd_type_p(get_nd_recv(node), NODE_LVAR) &&
9874 iseq_block_param_id_p(iseq, RNODE_LVAR(get_nd_recv(node))->nd_vid, &idx, &level)) {
9875 ADD_INSN2(recv, get_nd_recv(node), getblockparamproxy, INT2FIX(idx + VM_ENV_DATA_SIZE - 1), INT2FIX(level));
9876 }
9877 else if (private_recv_p(node)) {
9878 ADD_INSN(recv, node, putself);
9879 flag |= VM_CALL_FCALL;
9880 }
9881 else {
9882 CHECK(COMPILE(recv, "recv", get_nd_recv(node)));
9883 }
9884
9885 if (type == NODE_QCALL) {
9886 else_label = qcall_branch_start(iseq, recv, &branches, node, line_node);
9887 }
9888 }
9889 else if (type == NODE_FCALL || type == NODE_VCALL) {
9890 ADD_CALL_RECEIVER(recv, line_node);
9891 }
9892 }
9893
9894 /* args */
9895 if (type != NODE_VCALL) {
9896 argc = setup_args(iseq, args, get_nd_args(node), &flag, &keywords);
9897 CHECK(!NIL_P(argc));
9898 }
9899 else {
9900 argc = INT2FIX(0);
9901 }
9902
9903 ADD_SEQ(ret, recv);
9904
9905 bool inline_new = ISEQ_COMPILE_DATA(iseq)->option->specialized_instruction &&
9906 mid == rb_intern("new") &&
9907 parent_block == NULL &&
9908 !(flag & VM_CALL_ARGS_BLOCKARG);
9909
9910 if (inline_new) {
9911 ADD_INSN(ret, node, putnil);
9912 ADD_INSN(ret, node, swap);
9913 }
9914
9915 ADD_SEQ(ret, args);
9916
9917 debugp_param("call args argc", argc);
9918 debugp_param("call method", ID2SYM(mid));
9919
9920 switch ((int)type) {
9921 case NODE_VCALL:
9922 flag |= VM_CALL_VCALL;
9923 /* VCALL is funcall, so fall through */
9924 case NODE_FCALL:
9925 flag |= VM_CALL_FCALL;
9926 }
9927
9928 if ((flag & VM_CALL_ARGS_BLOCKARG) && (flag & VM_CALL_KW_SPLAT) && !(flag & VM_CALL_KW_SPLAT_MUT)) {
9929 ADD_INSN(ret, line_node, splatkw);
9930 }
9931
9932 LABEL *not_basic_new = NEW_LABEL(nd_line(node));
9933 LABEL *not_basic_new_finish = NEW_LABEL(nd_line(node));
9934
9935 if (inline_new) {
9936 // Jump unless the receiver uses the "basic" implementation of "new"
9937 VALUE ci;
9938 if (flag & VM_CALL_FORWARDING) {
9939 ci = (VALUE)new_callinfo(iseq, mid, NUM2INT(argc) + 1, flag, keywords, 0);
9940 }
9941 else {
9942 ci = (VALUE)new_callinfo(iseq, mid, NUM2INT(argc), flag, keywords, 0);
9943 }
9944 ADD_INSN2(ret, node, opt_new, ci, not_basic_new);
9945 LABEL_REF(not_basic_new);
9946
9947 // optimized path
9948 ADD_SEND_R(ret, line_node, rb_intern("initialize"), argc, parent_block, INT2FIX(flag | VM_CALL_FCALL | VM_CALL_IGNORE_REFINEMENTS), keywords);
9949 ADD_INSNL(ret, line_node, jump, not_basic_new_finish);
9950
9951 ADD_LABEL(ret, not_basic_new);
9952 // Fall back to normal send
9953 ADD_SEND_R(ret, line_node, mid, argc, parent_block, INT2FIX(flag), keywords);
9954 ADD_INSN(ret, line_node, swap);
9955
9956 ADD_LABEL(ret, not_basic_new_finish);
9957 ADD_INSN(ret, line_node, pop);
9958 }
9959 else {
9960 ADD_SEND_R(ret, line_node, mid, argc, parent_block, INT2FIX(flag), keywords);
9961 }
9962
9963 qcall_branch_end(iseq, ret, else_label, branches, node, line_node);
9964 if (popped) {
9965 ADD_INSN(ret, line_node, pop);
9966 }
9967 return COMPILE_OK;
9968}
9969
9970static int
9971compile_op_asgn1(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped)
9972{
9973 const int line = nd_line(node);
9974 VALUE argc;
9975 unsigned int flag = 0;
9976 int asgnflag = 0;
9977 ID id = RNODE_OP_ASGN1(node)->nd_mid;
9978
9979 /*
9980 * a[x] (op)= y
9981 *
9982 * nil # nil
9983 * eval a # nil a
9984 * eval x # nil a x
9985 * dupn 2 # nil a x a x
9986 * send :[] # nil a x a[x]
9987 * eval y # nil a x a[x] y
9988 * send op # nil a x ret
9989 * setn 3 # ret a x ret
9990 * send []= # ret ?
9991 * pop # ret
9992 */
9993
9994 /*
9995 * nd_recv[nd_args->nd_body] (nd_mid)= nd_args->nd_head;
9996 * NODE_OP_ASGN nd_recv
9997 * nd_args->nd_head
9998 * nd_args->nd_body
9999 * nd_mid
10000 */
10001
10002 if (!popped) {
10003 ADD_INSN(ret, node, putnil);
10004 }
10005 asgnflag = COMPILE_RECV(ret, "NODE_OP_ASGN1 recv", node, RNODE_OP_ASGN1(node)->nd_recv);
10006 CHECK(asgnflag != -1);
10007 switch (nd_type(RNODE_OP_ASGN1(node)->nd_index)) {
10008 case NODE_ZLIST:
10009 argc = INT2FIX(0);
10010 break;
10011 default:
10012 argc = setup_args(iseq, ret, RNODE_OP_ASGN1(node)->nd_index, &flag, NULL);
10013 CHECK(!NIL_P(argc));
10014 }
10015 int dup_argn = FIX2INT(argc) + 1;
10016 ADD_INSN1(ret, node, dupn, INT2FIX(dup_argn));
10017 flag |= asgnflag;
10018 ADD_SEND_R(ret, node, idAREF, argc, NULL, INT2FIX(flag & ~VM_CALL_ARGS_SPLAT_MUT), NULL);
10019
10020 if (id == idOROP || id == idANDOP) {
10021 /* a[x] ||= y or a[x] &&= y
10022
10023 unless/if a[x]
10024 a[x]= y
10025 else
10026 nil
10027 end
10028 */
10029 LABEL *label = NEW_LABEL(line);
10030 LABEL *lfin = NEW_LABEL(line);
10031
10032 ADD_INSN(ret, node, dup);
10033 if (id == idOROP) {
10034 ADD_INSNL(ret, node, branchif, label);
10035 }
10036 else { /* idANDOP */
10037 ADD_INSNL(ret, node, branchunless, label);
10038 }
10039 ADD_INSN(ret, node, pop);
10040
10041 CHECK(COMPILE(ret, "NODE_OP_ASGN1 nd_rvalue: ", RNODE_OP_ASGN1(node)->nd_rvalue));
10042 if (!popped) {
10043 ADD_INSN1(ret, node, setn, INT2FIX(dup_argn+1));
10044 }
10045 if (flag & VM_CALL_ARGS_SPLAT) {
10046 if (!(flag & VM_CALL_ARGS_SPLAT_MUT)) {
10047 ADD_INSN(ret, node, swap);
10048 ADD_INSN1(ret, node, splatarray, Qtrue);
10049 ADD_INSN(ret, node, swap);
10050 flag |= VM_CALL_ARGS_SPLAT_MUT;
10051 }
10052 ADD_INSN1(ret, node, pushtoarray, INT2FIX(1));
10053 ADD_SEND_R(ret, node, idASET, argc, NULL, INT2FIX(flag), NULL);
10054 }
10055 else {
10056 ADD_SEND_R(ret, node, idASET, FIXNUM_INC(argc, 1), NULL, INT2FIX(flag), NULL);
10057 }
10058 ADD_INSN(ret, node, pop);
10059 ADD_INSNL(ret, node, jump, lfin);
10060 ADD_LABEL(ret, label);
10061 if (!popped) {
10062 ADD_INSN1(ret, node, setn, INT2FIX(dup_argn+1));
10063 }
10064 ADD_INSN1(ret, node, adjuststack, INT2FIX(dup_argn+1));
10065 ADD_LABEL(ret, lfin);
10066 }
10067 else {
10068 CHECK(COMPILE(ret, "NODE_OP_ASGN1 nd_rvalue: ", RNODE_OP_ASGN1(node)->nd_rvalue));
10069 ADD_SEND(ret, node, id, INT2FIX(1));
10070 if (!popped) {
10071 ADD_INSN1(ret, node, setn, INT2FIX(dup_argn+1));
10072 }
10073 if (flag & VM_CALL_ARGS_SPLAT) {
10074 if (flag & VM_CALL_KW_SPLAT) {
10075 ADD_INSN1(ret, node, topn, INT2FIX(2));
10076 if (!(flag & VM_CALL_ARGS_SPLAT_MUT)) {
10077 ADD_INSN1(ret, node, splatarray, Qtrue);
10078 flag |= VM_CALL_ARGS_SPLAT_MUT;
10079 }
10080 ADD_INSN(ret, node, swap);
10081 ADD_INSN1(ret, node, pushtoarray, INT2FIX(1));
10082 ADD_INSN1(ret, node, setn, INT2FIX(2));
10083 ADD_INSN(ret, node, pop);
10084 }
10085 else {
10086 if (!(flag & VM_CALL_ARGS_SPLAT_MUT)) {
10087 ADD_INSN(ret, node, swap);
10088 ADD_INSN1(ret, node, splatarray, Qtrue);
10089 ADD_INSN(ret, node, swap);
10090 flag |= VM_CALL_ARGS_SPLAT_MUT;
10091 }
10092 ADD_INSN1(ret, node, pushtoarray, INT2FIX(1));
10093 }
10094 ADD_SEND_R(ret, node, idASET, argc, NULL, INT2FIX(flag), NULL);
10095 }
10096 else {
10097 ADD_SEND_R(ret, node, idASET, FIXNUM_INC(argc, 1), NULL, INT2FIX(flag), NULL);
10098 }
10099 ADD_INSN(ret, node, pop);
10100 }
10101 return COMPILE_OK;
10102}
10103
10104static int
10105compile_op_asgn2(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped)
10106{
10107 const int line = nd_line(node);
10108 ID atype = RNODE_OP_ASGN2(node)->nd_mid;
10109 ID vid = RNODE_OP_ASGN2(node)->nd_vid, aid = rb_id_attrset(vid);
10110 int asgnflag;
10111 LABEL *lfin = NEW_LABEL(line);
10112 LABEL *lcfin = NEW_LABEL(line);
10113 LABEL *lskip = 0;
10114 /*
10115 class C; attr_accessor :c; end
10116 r = C.new
10117 r.a &&= v # asgn2
10118
10119 eval r # r
10120 dup # r r
10121 eval r.a # r o
10122
10123 # or
10124 dup # r o o
10125 if lcfin # r o
10126 pop # r
10127 eval v # r v
10128 swap # v r
10129 topn 1 # v r v
10130 send a= # v ?
10131 jump lfin # v ?
10132
10133 lcfin: # r o
10134 swap # o r
10135
10136 lfin: # o ?
10137 pop # o
10138
10139 # or (popped)
10140 if lcfin # r
10141 eval v # r v
10142 send a= # ?
10143 jump lfin # ?
10144
10145 lcfin: # r
10146
10147 lfin: # ?
10148 pop #
10149
10150 # and
10151 dup # r o o
10152 unless lcfin
10153 pop # r
10154 eval v # r v
10155 swap # v r
10156 topn 1 # v r v
10157 send a= # v ?
10158 jump lfin # v ?
10159
10160 # others
10161 eval v # r o v
10162 send ?? # r w
10163 send a= # w
10164
10165 */
10166
10167 asgnflag = COMPILE_RECV(ret, "NODE_OP_ASGN2#recv", node, RNODE_OP_ASGN2(node)->nd_recv);
10168 CHECK(asgnflag != -1);
10169 if (RNODE_OP_ASGN2(node)->nd_aid) {
10170 lskip = NEW_LABEL(line);
10171 ADD_INSN(ret, node, dup);
10172 ADD_INSNL(ret, node, branchnil, lskip);
10173 }
10174 ADD_INSN(ret, node, dup);
10175 ADD_SEND_WITH_FLAG(ret, node, vid, INT2FIX(0), INT2FIX(asgnflag));
10176
10177 if (atype == idOROP || atype == idANDOP) {
10178 if (!popped) {
10179 ADD_INSN(ret, node, dup);
10180 }
10181 if (atype == idOROP) {
10182 ADD_INSNL(ret, node, branchif, lcfin);
10183 }
10184 else { /* idANDOP */
10185 ADD_INSNL(ret, node, branchunless, lcfin);
10186 }
10187 if (!popped) {
10188 ADD_INSN(ret, node, pop);
10189 }
10190 CHECK(COMPILE(ret, "NODE_OP_ASGN2 val", RNODE_OP_ASGN2(node)->nd_value));
10191 if (!popped) {
10192 ADD_INSN(ret, node, swap);
10193 ADD_INSN1(ret, node, topn, INT2FIX(1));
10194 }
10195 ADD_SEND_WITH_FLAG(ret, node, aid, INT2FIX(1), INT2FIX(asgnflag));
10196 ADD_INSNL(ret, node, jump, lfin);
10197
10198 ADD_LABEL(ret, lcfin);
10199 if (!popped) {
10200 ADD_INSN(ret, node, swap);
10201 }
10202
10203 ADD_LABEL(ret, lfin);
10204 }
10205 else {
10206 CHECK(COMPILE(ret, "NODE_OP_ASGN2 val", RNODE_OP_ASGN2(node)->nd_value));
10207 ADD_SEND(ret, node, atype, INT2FIX(1));
10208 if (!popped) {
10209 ADD_INSN(ret, node, swap);
10210 ADD_INSN1(ret, node, topn, INT2FIX(1));
10211 }
10212 ADD_SEND_WITH_FLAG(ret, node, aid, INT2FIX(1), INT2FIX(asgnflag));
10213 }
10214 if (lskip && popped) {
10215 ADD_LABEL(ret, lskip);
10216 }
10217 ADD_INSN(ret, node, pop);
10218 if (lskip && !popped) {
10219 ADD_LABEL(ret, lskip);
10220 }
10221 return COMPILE_OK;
10222}
10223
10224static int compile_shareable_constant_value(rb_iseq_t *iseq, LINK_ANCHOR *ret, enum rb_parser_shareability shareable, const NODE *lhs, const NODE *value);
10225
10226static int
10227compile_op_cdecl(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped)
10228{
10229 const int line = nd_line(node);
10230 LABEL *lfin = 0;
10231 LABEL *lassign = 0;
10232 ID mid;
10233
10234 switch (nd_type(RNODE_OP_CDECL(node)->nd_head)) {
10235 case NODE_COLON3:
10236 ADD_INSN1(ret, node, putobject, rb_cObject);
10237 break;
10238 case NODE_COLON2:
10239 CHECK(COMPILE(ret, "NODE_OP_CDECL/colon2#nd_head", RNODE_COLON2(RNODE_OP_CDECL(node)->nd_head)->nd_head));
10240 break;
10241 default:
10242 COMPILE_ERROR(ERROR_ARGS "%s: invalid node in NODE_OP_CDECL",
10243 ruby_node_name(nd_type(RNODE_OP_CDECL(node)->nd_head)));
10244 return COMPILE_NG;
10245 }
10246 mid = get_node_colon_nd_mid(RNODE_OP_CDECL(node)->nd_head);
10247 /* cref */
10248 if (RNODE_OP_CDECL(node)->nd_aid == idOROP) {
10249 lassign = NEW_LABEL(line);
10250 ADD_INSN(ret, node, dup); /* cref cref */
10251 ADD_INSN3(ret, node, defined, INT2FIX(DEFINED_CONST_FROM),
10252 ID2SYM(mid), Qtrue); /* cref bool */
10253 ADD_INSNL(ret, node, branchunless, lassign); /* cref */
10254 }
10255 ADD_INSN(ret, node, dup); /* cref cref */
10256 ADD_INSN1(ret, node, putobject, Qtrue);
10257 ADD_INSN1(ret, node, getconstant, ID2SYM(mid)); /* cref obj */
10258
10259 if (RNODE_OP_CDECL(node)->nd_aid == idOROP || RNODE_OP_CDECL(node)->nd_aid == idANDOP) {
10260 lfin = NEW_LABEL(line);
10261 if (!popped) ADD_INSN(ret, node, dup); /* cref [obj] obj */
10262 if (RNODE_OP_CDECL(node)->nd_aid == idOROP)
10263 ADD_INSNL(ret, node, branchif, lfin);
10264 else /* idANDOP */
10265 ADD_INSNL(ret, node, branchunless, lfin);
10266 /* cref [obj] */
10267 if (!popped) ADD_INSN(ret, node, pop); /* cref */
10268 if (lassign) ADD_LABEL(ret, lassign);
10269 CHECK(compile_shareable_constant_value(iseq, ret, RNODE_OP_CDECL(node)->shareability, RNODE_OP_CDECL(node)->nd_head, RNODE_OP_CDECL(node)->nd_value));
10270 /* cref value */
10271 if (popped)
10272 ADD_INSN1(ret, node, topn, INT2FIX(1)); /* cref value cref */
10273 else {
10274 ADD_INSN1(ret, node, dupn, INT2FIX(2)); /* cref value cref value */
10275 ADD_INSN(ret, node, swap); /* cref value value cref */
10276 }
10277 ADD_INSN1(ret, node, setconstant, ID2SYM(mid)); /* cref [value] */
10278 ADD_LABEL(ret, lfin); /* cref [value] */
10279 if (!popped) ADD_INSN(ret, node, swap); /* [value] cref */
10280 ADD_INSN(ret, node, pop); /* [value] */
10281 }
10282 else {
10283 CHECK(compile_shareable_constant_value(iseq, ret, RNODE_OP_CDECL(node)->shareability, RNODE_OP_CDECL(node)->nd_head, RNODE_OP_CDECL(node)->nd_value));
10284 /* cref obj value */
10285 ADD_CALL(ret, node, RNODE_OP_CDECL(node)->nd_aid, INT2FIX(1));
10286 /* cref value */
10287 ADD_INSN(ret, node, swap); /* value cref */
10288 if (!popped) {
10289 ADD_INSN1(ret, node, topn, INT2FIX(1)); /* value cref value */
10290 ADD_INSN(ret, node, swap); /* value value cref */
10291 }
10292 ADD_INSN1(ret, node, setconstant, ID2SYM(mid));
10293 }
10294 return COMPILE_OK;
10295}
10296
10297static int
10298compile_op_log(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped, const enum node_type type)
10299{
10300 const int line = nd_line(node);
10301 LABEL *lfin = NEW_LABEL(line);
10302 LABEL *lassign;
10303
10304 if (type == NODE_OP_ASGN_OR && !nd_type_p(RNODE_OP_ASGN_OR(node)->nd_head, NODE_IVAR)) {
10305 LABEL *lfinish[2];
10306 lfinish[0] = lfin;
10307 lfinish[1] = 0;
10308 defined_expr(iseq, ret, RNODE_OP_ASGN_OR(node)->nd_head, lfinish, Qfalse, false);
10309 lassign = lfinish[1];
10310 if (!lassign) {
10311 lassign = NEW_LABEL(line);
10312 }
10313 ADD_INSNL(ret, node, branchunless, lassign);
10314 }
10315 else {
10316 lassign = NEW_LABEL(line);
10317 }
10318
10319 CHECK(COMPILE(ret, "NODE_OP_ASGN_AND/OR#nd_head", RNODE_OP_ASGN_OR(node)->nd_head));
10320
10321 if (!popped) {
10322 ADD_INSN(ret, node, dup);
10323 }
10324
10325 if (type == NODE_OP_ASGN_AND) {
10326 ADD_INSNL(ret, node, branchunless, lfin);
10327 }
10328 else {
10329 ADD_INSNL(ret, node, branchif, lfin);
10330 }
10331
10332 if (!popped) {
10333 ADD_INSN(ret, node, pop);
10334 }
10335
10336 ADD_LABEL(ret, lassign);
10337 CHECK(COMPILE_(ret, "NODE_OP_ASGN_AND/OR#nd_value", RNODE_OP_ASGN_OR(node)->nd_value, popped));
10338 ADD_LABEL(ret, lfin);
10339 return COMPILE_OK;
10340}
10341
10342static int
10343compile_super(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped, const enum node_type type)
10344{
10345 struct rb_iseq_constant_body *const body = ISEQ_BODY(iseq);
10346 DECL_ANCHOR(args);
10347 int argc;
10348 unsigned int flag = 0;
10349 struct rb_callinfo_kwarg *keywords = NULL;
10350 const rb_iseq_t *parent_block = ISEQ_COMPILE_DATA(iseq)->current_block;
10351 int use_block = 1;
10352
10353 INIT_ANCHOR(args);
10354 ISEQ_COMPILE_DATA(iseq)->current_block = NULL;
10355
10356 if (type == NODE_SUPER) {
10357 VALUE vargc = setup_args(iseq, args, RNODE_SUPER(node)->nd_args, &flag, &keywords);
10358 CHECK(!NIL_P(vargc));
10359 argc = FIX2INT(vargc);
10360 if ((flag & VM_CALL_ARGS_BLOCKARG) && (flag & VM_CALL_KW_SPLAT) && !(flag & VM_CALL_KW_SPLAT_MUT)) {
10361 ADD_INSN(args, node, splatkw);
10362 }
10363
10364 if (flag & VM_CALL_ARGS_BLOCKARG) {
10365 use_block = 0;
10366 }
10367 }
10368 else {
10369 /* NODE_ZSUPER */
10370 int i;
10371 const rb_iseq_t *liseq = body->local_iseq;
10372 const struct rb_iseq_constant_body *const local_body = ISEQ_BODY(liseq);
10373 const struct rb_iseq_param_keyword *const local_kwd = local_body->param.keyword;
10374 int lvar_level = get_lvar_level(iseq);
10375
10376 argc = local_body->param.lead_num;
10377
10378 /* normal arguments */
10379 for (i = 0; i < local_body->param.lead_num; i++) {
10380 int idx = local_body->local_table_size - i;
10381 ADD_GETLOCAL(args, node, idx, lvar_level);
10382 }
10383
10384 /* forward ... */
10385 if (local_body->param.flags.forwardable) {
10386 flag |= VM_CALL_FORWARDING;
10387 int idx = local_body->local_table_size - get_local_var_idx(liseq, idDot3);
10388 ADD_GETLOCAL(args, node, idx, lvar_level);
10389 }
10390
10391 if (local_body->param.flags.has_opt) {
10392 /* optional arguments */
10393 int j;
10394 for (j = 0; j < local_body->param.opt_num; j++) {
10395 int idx = local_body->local_table_size - (i + j);
10396 ADD_GETLOCAL(args, node, idx, lvar_level);
10397 }
10398 i += j;
10399 argc = i;
10400 }
10401 if (local_body->param.flags.has_rest) {
10402 /* rest argument */
10403 int idx = local_body->local_table_size - rb_iseq_param_rest_start(local_body);
10404 ADD_GETLOCAL(args, node, idx, lvar_level);
10405 ADD_INSN1(args, node, splatarray, RBOOL(local_body->param.flags.has_post));
10406
10407 argc = rb_iseq_param_rest_start(local_body) + 1;
10408 flag |= VM_CALL_ARGS_SPLAT;
10409 }
10410 if (local_body->param.flags.has_post) {
10411 /* post arguments */
10412 int post_len = local_body->param.post_num;
10413 int post_start = rb_iseq_param_post_start(local_body);
10414
10415 if (local_body->param.flags.has_rest) {
10416 int j;
10417 for (j=0; j<post_len; j++) {
10418 int idx = local_body->local_table_size - (post_start + j);
10419 ADD_GETLOCAL(args, node, idx, lvar_level);
10420 }
10421 ADD_INSN1(args, node, pushtoarray, INT2FIX(j));
10422 flag |= VM_CALL_ARGS_SPLAT_MUT;
10423 /* argc is settled at above */
10424 }
10425 else {
10426 int j;
10427 for (j=0; j<post_len; j++) {
10428 int idx = local_body->local_table_size - (post_start + j);
10429 ADD_GETLOCAL(args, node, idx, lvar_level);
10430 }
10431 argc = post_len + post_start;
10432 }
10433 }
10434
10435 if (local_body->param.flags.has_kw) { /* TODO: support keywords */
10436 int local_size = local_body->local_table_size;
10437 argc++;
10438
10439 /* The keyword rest local may have been reassigned to any
10440 * object, so it is never merged into in place. hash_merge_ptr
10441 * converts it with to_hash (nil being empty) and copies it into
10442 * a hash allocated at its final size. */
10443 if (local_body->param.flags.has_kwrest) {
10444 int idx = local_body->local_table_size - local_kwd->rest_start;
10445 RUBY_ASSERT(local_kwd->num > 0);
10446 ADD_INSN1(args, node, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
10447 ADD_GETLOCAL(args, node, idx, lvar_level);
10448 }
10449 for (i = 0; i < local_kwd->num; ++i) {
10450 ID id = local_kwd->table[i];
10451 int idx = local_size - get_local_var_idx(liseq, id);
10452 ADD_INSN1(args, node, putobject, ID2SYM(id));
10453 ADD_GETLOCAL(args, node, idx, lvar_level);
10454 }
10455 if (local_body->param.flags.has_kwrest) {
10456 ADD_SEND(args, node, id_core_hash_merge_ptr, INT2FIX(i * 2 + 1));
10457 }
10458 else {
10459 ADD_INSN1(args, node, newhash, INT2FIX(i * 2));
10460 }
10461 flag |= VM_CALL_KW_SPLAT| VM_CALL_KW_SPLAT_MUT;
10462 }
10463 else if (local_body->param.flags.has_kwrest) {
10464 int idx = local_body->local_table_size - local_kwd->rest_start;
10465 ADD_GETLOCAL(args, node, idx, lvar_level);
10466 argc++;
10467 flag |= VM_CALL_KW_SPLAT;
10468 }
10469 }
10470
10471 if (use_block && parent_block == NULL) {
10472 iseq_set_use_block(ISEQ_BODY(iseq)->local_iseq);
10473 }
10474
10475 flag |= VM_CALL_SUPER | VM_CALL_FCALL;
10476 if (type == NODE_ZSUPER) flag |= VM_CALL_ZSUPER;
10477 ADD_INSN(ret, node, putself);
10478 ADD_SEQ(ret, args);
10479
10480 const struct rb_callinfo * ci = new_callinfo(iseq, 0, argc, flag, keywords, parent_block != NULL);
10481
10482 if (vm_ci_flag(ci) & VM_CALL_FORWARDING) {
10483 ADD_INSN2(ret, node, invokesuperforward, ci, parent_block);
10484 }
10485 else {
10486 ADD_INSN2(ret, node, invokesuper, ci, parent_block);
10487 }
10488
10489 if (popped) {
10490 ADD_INSN(ret, node, pop);
10491 }
10492 return COMPILE_OK;
10493}
10494
10495static int
10496compile_yield(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped)
10497{
10498 DECL_ANCHOR(args);
10499 VALUE argc;
10500 unsigned int flag = 0;
10501 struct rb_callinfo_kwarg *keywords = NULL;
10502
10503 INIT_ANCHOR(args);
10504
10505 switch (ISEQ_BODY(ISEQ_BODY(iseq)->local_iseq)->type) {
10506 case ISEQ_TYPE_TOP:
10507 case ISEQ_TYPE_MAIN:
10508 case ISEQ_TYPE_CLASS:
10509 COMPILE_ERROR(ERROR_ARGS "Invalid yield");
10510 return COMPILE_NG;
10511 default: /* valid */;
10512 }
10513
10514 if (RNODE_YIELD(node)->nd_head) {
10515 argc = setup_args(iseq, args, RNODE_YIELD(node)->nd_head, &flag, &keywords);
10516 CHECK(!NIL_P(argc));
10517 }
10518 else {
10519 argc = INT2FIX(0);
10520 }
10521
10522 ADD_SEQ(ret, args);
10523 ADD_INSN1(ret, node, invokeblock, new_callinfo(iseq, 0, FIX2INT(argc), flag, keywords, FALSE));
10524 iseq_set_use_block(ISEQ_BODY(iseq)->local_iseq);
10525
10526 if (popped) {
10527 ADD_INSN(ret, node, pop);
10528 }
10529
10530 int level = 0;
10531 const rb_iseq_t *tmp_iseq = iseq;
10532 for (; tmp_iseq != ISEQ_BODY(iseq)->local_iseq; level++ ) {
10533 tmp_iseq = ISEQ_BODY(tmp_iseq)->parent_iseq;
10534 }
10535 if (level > 0) access_outer_variables(iseq, level, rb_intern("yield"), true);
10536
10537 return COMPILE_OK;
10538}
10539
10540static int
10541compile_match(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped, const enum node_type type)
10542{
10543 DECL_ANCHOR(recv);
10544 DECL_ANCHOR(val);
10545
10546 INIT_ANCHOR(recv);
10547 INIT_ANCHOR(val);
10548 switch ((int)type) {
10549 case NODE_MATCH:
10550 {
10551 VALUE re = rb_node_regx_string_val(node);
10553 ADD_INSN1(recv, node, putobject, re);
10554 ADD_INSN2(val, node, getspecial, INT2FIX(0),
10555 INT2FIX(0));
10556 }
10557 break;
10558 case NODE_MATCH2:
10559 CHECK(COMPILE(recv, "receiver", RNODE_MATCH2(node)->nd_recv));
10560 CHECK(COMPILE(val, "value", RNODE_MATCH2(node)->nd_value));
10561 break;
10562 case NODE_MATCH3:
10563 CHECK(COMPILE(recv, "receiver", RNODE_MATCH3(node)->nd_value));
10564 CHECK(COMPILE(val, "value", RNODE_MATCH3(node)->nd_recv));
10565 break;
10566 }
10567
10568 ADD_SEQ(ret, recv);
10569 ADD_SEQ(ret, val);
10570 ADD_SEND(ret, node, idEqTilde, INT2FIX(1));
10571
10572 if (nd_type_p(node, NODE_MATCH2) && RNODE_MATCH2(node)->nd_args) {
10573 compile_named_capture_assign(iseq, ret, RNODE_MATCH2(node)->nd_args);
10574 }
10575
10576 if (popped) {
10577 ADD_INSN(ret, node, pop);
10578 }
10579 return COMPILE_OK;
10580}
10581
10582static int
10583compile_colon2(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped)
10584{
10585 if (rb_is_const_id(RNODE_COLON2(node)->nd_mid)) {
10586 /* constant */
10587 rb_const_path_t const_path;
10588 if (ISEQ_COMPILE_DATA(iseq)->option->inline_const_cache &&
10589 (const_path = compile_const_path(iseq, node))) {
10590 ISEQ_BODY(iseq)->ic_size++;
10591 ADD_INSN1(ret, node, opt_getconstant_path, (VALUE)const_path);
10592 }
10593 else {
10594 /* constant */
10595 DECL_ANCHOR(pref);
10596 DECL_ANCHOR(body);
10597
10598 INIT_ANCHOR(pref);
10599 INIT_ANCHOR(body);
10600 CHECK(compile_const_prefix(iseq, node, pref, body));
10601 if (LIST_INSN_SIZE_ZERO(pref)) {
10602 ADD_INSN(ret, node, putnil);
10603 ADD_SEQ(ret, body);
10604 }
10605 else {
10606 ADD_SEQ(ret, pref);
10607 ADD_SEQ(ret, body);
10608 }
10609 }
10610 }
10611 else {
10612 /* function call */
10613 ADD_CALL_RECEIVER(ret, node);
10614 CHECK(COMPILE(ret, "colon2#nd_head", RNODE_COLON2(node)->nd_head));
10615 ADD_CALL(ret, node, RNODE_COLON2(node)->nd_mid, INT2FIX(1));
10616 }
10617 if (popped) {
10618 ADD_INSN(ret, node, pop);
10619 }
10620 return COMPILE_OK;
10621}
10622
10623static int
10624compile_colon3(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped)
10625{
10626 debugi("colon3#nd_mid", RNODE_COLON3(node)->nd_mid);
10627
10628 /* add cache insn */
10629 if (ISEQ_COMPILE_DATA(iseq)->option->inline_const_cache) {
10630 ISEQ_BODY(iseq)->ic_size++;
10631 rb_const_path_t const_path = rb_const_path_from_ids(true, &RNODE_COLON3(node)->nd_mid, 1);
10632 ADD_INSN1(ret, node, opt_getconstant_path, (VALUE)const_path);
10633 }
10634 else {
10635 ADD_INSN1(ret, node, putobject, rb_cObject);
10636 ADD_INSN1(ret, node, putobject, Qtrue);
10637 ADD_INSN1(ret, node, getconstant, ID2SYM(RNODE_COLON3(node)->nd_mid));
10638 }
10639
10640 if (popped) {
10641 ADD_INSN(ret, node, pop);
10642 }
10643 return COMPILE_OK;
10644}
10645
10646static int
10647compile_dots(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped, const int excl)
10648{
10649 VALUE flag = INT2FIX(excl);
10650 const NODE *b = RNODE_DOT2(node)->nd_beg;
10651 const NODE *e = RNODE_DOT2(node)->nd_end;
10652
10653 if (optimizable_range_item_p(b) && optimizable_range_item_p(e)) {
10654 if (!popped) {
10655 VALUE bv = optimized_range_item(b);
10656 VALUE ev = optimized_range_item(e);
10657 VALUE val = rb_range_new(bv, ev, excl);
10659 ADD_INSN1(ret, node, putobject, val);
10660 RB_OBJ_WRITTEN(iseq, Qundef, val);
10661 }
10662 }
10663 else {
10664 CHECK(COMPILE_(ret, "min", b, popped));
10665 CHECK(COMPILE_(ret, "max", e, popped));
10666 if (!popped) {
10667 ADD_INSN1(ret, node, newrange, flag);
10668 }
10669 }
10670 return COMPILE_OK;
10671}
10672
10673static int
10674compile_errinfo(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped)
10675{
10676 if (!popped) {
10677 if (ISEQ_BODY(iseq)->type == ISEQ_TYPE_RESCUE) {
10678 ADD_GETLOCAL(ret, node, LVAR_ERRINFO, 0);
10679 }
10680 else {
10681 const rb_iseq_t *ip = iseq;
10682 int level = 0;
10683 while (ip) {
10684 if (ISEQ_BODY(ip)->type == ISEQ_TYPE_RESCUE) {
10685 break;
10686 }
10687 ip = ISEQ_BODY(ip)->parent_iseq;
10688 level++;
10689 }
10690 if (ip) {
10691 ADD_GETLOCAL(ret, node, LVAR_ERRINFO, level);
10692 }
10693 else {
10694 ADD_INSN(ret, node, putnil);
10695 }
10696 }
10697 }
10698 return COMPILE_OK;
10699}
10700
10701static int
10702compile_kw_arg(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped)
10703{
10704 struct rb_iseq_constant_body *const body = ISEQ_BODY(iseq);
10705 LABEL *end_label = NEW_LABEL(nd_line(node));
10706 const NODE *default_value = get_nd_value(RNODE_KW_ARG(node)->nd_body);
10707
10708 if (default_value == NODE_SPECIAL_REQUIRED_KEYWORD) {
10709 /* required argument. do nothing */
10710 COMPILE_ERROR(ERROR_ARGS "unreachable");
10711 return COMPILE_NG;
10712 }
10713 else if (nd_type_p(default_value, NODE_SYM) ||
10714 nd_type_p(default_value, NODE_REGX) ||
10715 nd_type_p(default_value, NODE_LINE) ||
10716 nd_type_p(default_value, NODE_INTEGER) ||
10717 nd_type_p(default_value, NODE_FLOAT) ||
10718 nd_type_p(default_value, NODE_RATIONAL) ||
10719 nd_type_p(default_value, NODE_IMAGINARY) ||
10720 nd_type_p(default_value, NODE_NIL) ||
10721 nd_type_p(default_value, NODE_TRUE) ||
10722 nd_type_p(default_value, NODE_FALSE)) {
10723 COMPILE_ERROR(ERROR_ARGS "unreachable");
10724 return COMPILE_NG;
10725 }
10726 else {
10727 /* if keywordcheck(_kw_bits, nth_keyword)
10728 * kw = default_value
10729 * end
10730 */
10731 int kw_bits_idx = body->local_table_size - body->param.keyword->bits_start;
10732 int keyword_idx = body->param.keyword->num - body->param.keyword->required_num;
10733 for (const rb_node_kw_arg_t *kwarg = RNODE_KW_ARG(node); kwarg; kwarg = kwarg->nd_next) {
10734 if (get_nd_value(kwarg->nd_body) != NODE_SPECIAL_REQUIRED_KEYWORD) {
10735 keyword_idx--;
10736 }
10737 }
10738
10739 ADD_INSN2(ret, node, checkkeyword, INT2FIX(kw_bits_idx + VM_ENV_DATA_SIZE - 1), INT2FIX(keyword_idx));
10740 ADD_INSNL(ret, node, branchif, end_label);
10741 CHECK(COMPILE_POPPED(ret, "keyword default argument", RNODE_KW_ARG(node)->nd_body));
10742 ADD_LABEL(ret, end_label);
10743 }
10744 return COMPILE_OK;
10745}
10746
10747static int
10748compile_attrasgn(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped)
10749{
10750 DECL_ANCHOR(recv);
10751 DECL_ANCHOR(args);
10752 unsigned int flag = 0;
10753 ID mid = RNODE_ATTRASGN(node)->nd_mid;
10754 VALUE argc;
10755 LABEL *else_label = NULL;
10756 VALUE branches = Qfalse;
10757
10758 INIT_ANCHOR(recv);
10759 INIT_ANCHOR(args);
10760 argc = setup_args(iseq, args, RNODE_ATTRASGN(node)->nd_args, &flag, NULL);
10761 CHECK(!NIL_P(argc));
10762
10763 int asgnflag = COMPILE_RECV(recv, "recv", node, RNODE_ATTRASGN(node)->nd_recv);
10764 CHECK(asgnflag != -1);
10765 flag |= (unsigned int)asgnflag;
10766
10767 debugp_param("argc", argc);
10768 debugp_param("nd_mid", ID2SYM(mid));
10769
10770 if (!rb_is_attrset_id(mid)) {
10771 /* safe nav attr */
10772 mid = rb_id_attrset(mid);
10773 else_label = qcall_branch_start(iseq, recv, &branches, node, node);
10774 }
10775 if (!popped) {
10776 ADD_INSN(ret, node, putnil);
10777 ADD_SEQ(ret, recv);
10778 ADD_SEQ(ret, args);
10779
10780 if (flag & VM_CALL_ARGS_SPLAT) {
10781 ADD_INSN(ret, node, dup);
10782 ADD_INSN1(ret, node, putobject, INT2FIX(-1));
10783 ADD_SEND_WITH_FLAG(ret, node, idAREF, INT2FIX(1), INT2FIX(asgnflag));
10784 ADD_INSN1(ret, node, setn, FIXNUM_INC(argc, 2));
10785 ADD_INSN (ret, node, pop);
10786 }
10787 else {
10788 ADD_INSN1(ret, node, setn, FIXNUM_INC(argc, 1));
10789 }
10790 }
10791 else {
10792 ADD_SEQ(ret, recv);
10793 ADD_SEQ(ret, args);
10794 }
10795 ADD_SEND_WITH_FLAG(ret, node, mid, argc, INT2FIX(flag));
10796 qcall_branch_end(iseq, ret, else_label, branches, node, node);
10797 ADD_INSN(ret, node, pop);
10798 return COMPILE_OK;
10799}
10800
10801static int
10802compile_make_shareable_node(rb_iseq_t *iseq, LINK_ANCHOR *ret, LINK_ANCHOR *sub, const NODE *value, bool copy)
10803{
10804 ADD_INSN1(ret, value, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
10805 ADD_SEQ(ret, sub);
10806
10807 if (copy) {
10808 /*
10809 * NEW_CALL(fcore, rb_intern("make_shareable_copy"),
10810 * NEW_LIST(value, loc), loc);
10811 */
10812 ADD_SEND_WITH_FLAG(ret, value, rb_intern("make_shareable_copy"), INT2FIX(1), INT2FIX(VM_CALL_ARGS_SIMPLE));
10813 }
10814 else {
10815 /*
10816 * NEW_CALL(fcore, rb_intern("make_shareable"),
10817 * NEW_LIST(value, loc), loc);
10818 */
10819 ADD_SEND_WITH_FLAG(ret, value, rb_intern("make_shareable"), INT2FIX(1), INT2FIX(VM_CALL_ARGS_SIMPLE));
10820 }
10821
10822 return COMPILE_OK;
10823}
10824
10825static VALUE
10826node_const_decl_val(const NODE *node)
10827{
10828 VALUE path;
10829 switch (nd_type(node)) {
10830 case NODE_CDECL:
10831 if (RNODE_CDECL(node)->nd_vid) {
10832 path = rb_id2str(RNODE_CDECL(node)->nd_vid);
10833 goto end;
10834 }
10835 else {
10836 node = RNODE_CDECL(node)->nd_else;
10837 }
10838 break;
10839 case NODE_COLON2:
10840 break;
10841 case NODE_COLON3:
10842 // ::Const
10843 path = rb_str_new_cstr("::");
10844 rb_str_append(path, rb_id2str(RNODE_COLON3(node)->nd_mid));
10845 goto end;
10846 default:
10847 rb_bug("unexpected node: %s", ruby_node_name(nd_type(node)));
10849 }
10850
10851 path = rb_ary_new();
10852 if (node) {
10853 for (; node && nd_type_p(node, NODE_COLON2); node = RNODE_COLON2(node)->nd_head) {
10854 rb_ary_push(path, rb_id2str(RNODE_COLON2(node)->nd_mid));
10855 }
10856 if (node && nd_type_p(node, NODE_CONST)) {
10857 // Const::Name
10858 rb_ary_push(path, rb_id2str(RNODE_CONST(node)->nd_vid));
10859 }
10860 else if (node && nd_type_p(node, NODE_COLON3)) {
10861 // ::Const::Name
10862 rb_ary_push(path, rb_id2str(RNODE_COLON3(node)->nd_mid));
10863 rb_ary_push(path, rb_str_new(0, 0));
10864 }
10865 else {
10866 // expression::Name
10867 rb_ary_push(path, rb_str_new_cstr("..."));
10868 }
10869 path = rb_ary_join(rb_ary_reverse(path), rb_str_new_cstr("::"));
10870 }
10871 end:
10872 path = rb_fstring(path);
10873 return path;
10874}
10875
10876static VALUE
10877const_decl_path(NODE *dest)
10878{
10879 VALUE path = Qnil;
10880 if (!nd_type_p(dest, NODE_CALL)) {
10881 path = node_const_decl_val(dest);
10882 }
10883 return path;
10884}
10885
10886static int
10887compile_ensure_shareable_node(rb_iseq_t *iseq, LINK_ANCHOR *ret, NODE *dest, const NODE *value)
10888{
10889 /*
10890 *. RubyVM::FrozenCore.ensure_shareable(value, const_decl_path(dest))
10891 */
10892 VALUE path = const_decl_path(dest);
10893 ADD_INSN1(ret, value, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
10894 CHECK(COMPILE(ret, "compile_ensure_shareable_node", value));
10895 ADD_INSN1(ret, value, putobject, path);
10896 RB_OBJ_WRITTEN(iseq, Qundef, path);
10897 ADD_SEND_WITH_FLAG(ret, value, rb_intern("ensure_shareable"), INT2FIX(2), INT2FIX(VM_CALL_ARGS_SIMPLE));
10898
10899 return COMPILE_OK;
10900}
10901
10902#ifndef SHAREABLE_BARE_EXPRESSION
10903#define SHAREABLE_BARE_EXPRESSION 1
10904#endif
10905
10906static int
10907compile_shareable_literal_constant(rb_iseq_t *iseq, LINK_ANCHOR *ret, enum rb_parser_shareability shareable, NODE *dest, const NODE *node, size_t level, VALUE *value_p, int *shareable_literal_p)
10908{
10909# define compile_shareable_literal_constant_next(node, anchor, value_p, shareable_literal_p) \
10910 compile_shareable_literal_constant(iseq, anchor, shareable, dest, node, level+1, value_p, shareable_literal_p)
10911 VALUE lit = Qnil;
10912 DECL_ANCHOR(anchor);
10913
10914 enum node_type type = node ? nd_type(node) : NODE_NIL;
10915 switch (type) {
10916 case NODE_TRUE:
10917 *value_p = Qtrue;
10918 goto compile;
10919 case NODE_FALSE:
10920 *value_p = Qfalse;
10921 goto compile;
10922 case NODE_NIL:
10923 *value_p = Qnil;
10924 goto compile;
10925 case NODE_SYM:
10926 *value_p = rb_node_sym_string_val(node);
10927 goto compile;
10928 case NODE_REGX:
10929 *value_p = rb_node_regx_string_val(node);
10930 goto compile;
10931 case NODE_LINE:
10932 *value_p = rb_node_line_lineno_val(node);
10933 goto compile;
10934 case NODE_INTEGER:
10935 *value_p = rb_node_integer_literal_val(node);
10936 goto compile;
10937 case NODE_FLOAT:
10938 *value_p = rb_node_float_literal_val(node);
10939 goto compile;
10940 case NODE_RATIONAL:
10941 *value_p = rb_node_rational_literal_val(node);
10942 goto compile;
10943 case NODE_IMAGINARY:
10944 *value_p = rb_node_imaginary_literal_val(node);
10945 goto compile;
10946 case NODE_ENCODING:
10947 *value_p = rb_node_encoding_val(node);
10948
10949 compile:
10950 CHECK(COMPILE(ret, "shareable_literal_constant", node));
10951 *shareable_literal_p = 1;
10952 return COMPILE_OK;
10953
10954 case NODE_DSTR:
10955 CHECK(COMPILE(ret, "shareable_literal_constant", node));
10956 if (shareable == rb_parser_shareable_literal) {
10957 /*
10958 * NEW_CALL(node, idUMinus, 0, loc);
10959 *
10960 * -"#{var}"
10961 */
10962 ADD_SEND_WITH_FLAG(ret, node, idUMinus, INT2FIX(0), INT2FIX(VM_CALL_ARGS_SIMPLE));
10963 }
10964 *value_p = Qundef;
10965 *shareable_literal_p = 1;
10966 return COMPILE_OK;
10967
10968 case NODE_STR:{
10969 VALUE lit = rb_node_str_string_val(node);
10970 ADD_INSN1(ret, node, putobject, lit);
10971 RB_OBJ_WRITTEN(iseq, Qundef, lit);
10972 *value_p = lit;
10973 *shareable_literal_p = 1;
10974
10975 return COMPILE_OK;
10976 }
10977
10978 case NODE_FILE:
10979 compile_file_path(iseq, ret, node, ISEQ_FROZEN_STRING_LITERAL_ENABLED);
10980 *value_p = Qundef;
10981 *shareable_literal_p = 1;
10982 return COMPILE_OK;
10983
10984 case NODE_ZLIST:{
10985 VALUE lit = rb_ary_new();
10986 OBJ_FREEZE(lit);
10987 ADD_INSN1(ret, node, putobject, lit);
10988 RB_OBJ_WRITTEN(iseq, Qundef, lit);
10989 *value_p = lit;
10990 *shareable_literal_p = 1;
10991
10992 return COMPILE_OK;
10993 }
10994
10995 case NODE_LIST:{
10996 INIT_ANCHOR(anchor);
10997 lit = rb_ary_new();
10998 for (NODE *n = (NODE *)node; n; n = RNODE_LIST(n)->nd_next) {
10999 VALUE val = Qundef;
11000 int shareable_literal_p2;
11001 NODE *elt = RNODE_LIST(n)->nd_head;
11002 if (elt) {
11003 CHECK(compile_shareable_literal_constant_next(elt, anchor, &val, &shareable_literal_p2));
11004 if (shareable_literal_p2) {
11005 /* noop */
11006 }
11007 else if (RTEST(lit)) {
11008 rb_ary_clear(lit);
11009 lit = Qfalse;
11010 }
11011 }
11012 if (RTEST(lit)) {
11013 if (!UNDEF_P(val)) {
11014 rb_ary_push(lit, val);
11015 }
11016 else {
11017 rb_ary_clear(lit);
11018 lit = Qnil; /* make shareable at runtime */
11019 }
11020 }
11021 }
11022 break;
11023 }
11024 case NODE_HASH:{
11025 if (!RNODE_HASH(node)->nd_brace) goto compile_shareable;
11026 for (NODE *n = RNODE_HASH(node)->nd_head; n; n = RNODE_LIST(RNODE_LIST(n)->nd_next)->nd_next) {
11027 if (!RNODE_LIST(n)->nd_head) {
11028 // If the hash node have a keyword splat, fall back to the default case.
11029 goto compile_shareable;
11030 }
11031 }
11032
11033 INIT_ANCHOR(anchor);
11034 lit = rb_hash_new();
11035 for (NODE *n = RNODE_HASH(node)->nd_head; n; n = RNODE_LIST(RNODE_LIST(n)->nd_next)->nd_next) {
11036 VALUE key_val = 0;
11037 VALUE value_val = 0;
11038 int shareable_literal_p2;
11039 NODE *key = RNODE_LIST(n)->nd_head;
11040 NODE *val = RNODE_LIST(RNODE_LIST(n)->nd_next)->nd_head;
11041 CHECK(compile_shareable_literal_constant_next(key, anchor, &key_val, &shareable_literal_p2));
11042 if (shareable_literal_p2) {
11043 /* noop */
11044 }
11045 else if (RTEST(lit)) {
11046 rb_hash_clear(lit);
11047 lit = Qfalse;
11048 }
11049 CHECK(compile_shareable_literal_constant_next(val, anchor, &value_val, &shareable_literal_p2));
11050 if (shareable_literal_p2) {
11051 /* noop */
11052 }
11053 else if (RTEST(lit)) {
11054 rb_hash_clear(lit);
11055 lit = Qfalse;
11056 }
11057 if (RTEST(lit)) {
11058 if (!UNDEF_P(key_val) && !UNDEF_P(value_val)) {
11059 rb_hash_aset(lit, key_val, value_val);
11060 }
11061 else {
11062 rb_hash_clear(lit);
11063 lit = Qnil; /* make shareable at runtime */
11064 }
11065 }
11066 }
11067 break;
11068 }
11069
11070 default:
11071
11072 compile_shareable:
11073 if (shareable == rb_parser_shareable_literal &&
11074 (SHAREABLE_BARE_EXPRESSION || level > 0)) {
11075 CHECK(compile_ensure_shareable_node(iseq, ret, dest, node));
11076 *value_p = Qundef;
11077 *shareable_literal_p = 1;
11078 return COMPILE_OK;
11079 }
11080 CHECK(COMPILE(ret, "shareable_literal_constant", node));
11081 *value_p = Qundef;
11082 *shareable_literal_p = 0;
11083 return COMPILE_OK;
11084 }
11085
11086 /* Array or Hash that does not have keyword splat */
11087 if (!lit) {
11088 if (nd_type(node) == NODE_LIST) {
11089 ADD_INSN1(anchor, node, newarray, INT2FIX(RNODE_LIST(node)->as.nd_alen));
11090 }
11091 else if (nd_type(node) == NODE_HASH) {
11092 long len = RNODE_LIST(RNODE_HASH(node)->nd_head)->as.nd_alen;
11095 ADD_INSN1(anchor, node, newhash, LONG2FIX(len));
11096 }
11097 *value_p = Qundef;
11098 *shareable_literal_p = 0;
11099 ADD_SEQ(ret, anchor);
11100 return COMPILE_OK;
11101 }
11102 if (NIL_P(lit)) {
11103 // if shareable_literal, all elements should have been ensured
11104 // as shareable
11105 if (nd_type(node) == NODE_LIST) {
11106 ADD_INSN1(anchor, node, newarray, INT2FIX(RNODE_LIST(node)->as.nd_alen));
11107 }
11108 else if (nd_type(node) == NODE_HASH) {
11109 long len = RNODE_LIST(RNODE_HASH(node)->nd_head)->as.nd_alen;
11112 ADD_INSN1(anchor, node, newhash, LONG2FIX(len));
11113 }
11114 CHECK(compile_make_shareable_node(iseq, ret, anchor, node, false));
11115 *value_p = Qundef;
11116 *shareable_literal_p = 1;
11117 }
11118 else {
11120 ADD_INSN1(ret, node, putobject, val);
11121 RB_OBJ_WRITTEN(iseq, Qundef, val);
11122 *value_p = val;
11123 *shareable_literal_p = 1;
11124 }
11125
11126 return COMPILE_OK;
11127}
11128
11129static int
11130compile_shareable_constant_value(rb_iseq_t *iseq, LINK_ANCHOR *ret, enum rb_parser_shareability shareable, const NODE *lhs, const NODE *value)
11131{
11132 int literal_p = 0;
11133 VALUE val;
11134 DECL_ANCHOR(anchor);
11135 INIT_ANCHOR(anchor);
11136
11137 switch (shareable) {
11138 case rb_parser_shareable_none:
11139 CHECK(COMPILE(ret, "compile_shareable_constant_value", value));
11140 return COMPILE_OK;
11141
11142 case rb_parser_shareable_literal:
11143 CHECK(compile_shareable_literal_constant(iseq, anchor, shareable, (NODE *)lhs, value, 0, &val, &literal_p));
11144 ADD_SEQ(ret, anchor);
11145 return COMPILE_OK;
11146
11147 case rb_parser_shareable_copy:
11148 case rb_parser_shareable_everything:
11149 CHECK(compile_shareable_literal_constant(iseq, anchor, shareable, (NODE *)lhs, value, 0, &val, &literal_p));
11150 if (!literal_p) {
11151 CHECK(compile_make_shareable_node(iseq, ret, anchor, value, shareable == rb_parser_shareable_copy));
11152 }
11153 else {
11154 ADD_SEQ(ret, anchor);
11155 }
11156 return COMPILE_OK;
11157 default:
11158 rb_bug("unexpected rb_parser_shareability: %d", shareable);
11159 }
11160}
11161
11162static int iseq_compile_each0(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped);
11170static int
11171iseq_compile_each(rb_iseq_t *iseq, LINK_ANCHOR *ret, const NODE *node, int popped)
11172{
11173 if (node == 0) {
11174 if (!popped) {
11175 int lineno = ISEQ_COMPILE_DATA(iseq)->last_line;
11176 if (lineno == 0) lineno = FIX2INT(rb_iseq_first_lineno(iseq));
11177 debugs("node: NODE_NIL(implicit)\n");
11178 ADD_SYNTHETIC_INSN(ret, lineno, -1, putnil);
11179 }
11180 return COMPILE_OK;
11181 }
11182 return iseq_compile_each0(iseq, ret, node, popped);
11183}
11184
11185static int
11186iseq_compile_each0(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped)
11187{
11188 const int line = (int)nd_line(node);
11189 const enum node_type type = nd_type(node);
11190 struct rb_iseq_constant_body *const body = ISEQ_BODY(iseq);
11191
11192 if (ISEQ_COMPILE_DATA(iseq)->last_line == line) {
11193 /* ignore */
11194 }
11195 else {
11196 if (nd_fl_newline(node)) {
11197 int event = RUBY_EVENT_LINE;
11198 ISEQ_COMPILE_DATA(iseq)->last_line = line;
11199 if (line > 0 && ISEQ_COVERAGE(iseq) && ISEQ_LINE_COVERAGE(iseq)) {
11200 event |= RUBY_EVENT_COVERAGE_LINE;
11201 }
11202 ADD_TRACE(ret, event);
11203 }
11204 }
11205
11206 debug_node_start(node);
11207#undef BEFORE_RETURN
11208#define BEFORE_RETURN debug_node_end()
11209
11210 switch (type) {
11211 case NODE_BLOCK:
11212 CHECK(compile_block(iseq, ret, node, popped));
11213 break;
11214 case NODE_IF:
11215 case NODE_UNLESS:
11216 CHECK(compile_if(iseq, ret, node, popped, type));
11217 break;
11218 case NODE_CASE:
11219 CHECK(compile_case(iseq, ret, node, popped));
11220 break;
11221 case NODE_CASE2:
11222 CHECK(compile_case2(iseq, ret, node, popped));
11223 break;
11224 case NODE_CASE3:
11225 CHECK(compile_case3(iseq, ret, node, popped));
11226 break;
11227 case NODE_WHILE:
11228 case NODE_UNTIL:
11229 CHECK(compile_loop(iseq, ret, node, popped, type));
11230 break;
11231 case NODE_FOR:
11232 case NODE_ITER:
11233 CHECK(compile_iter(iseq, ret, node, popped));
11234 break;
11235 case NODE_FOR_MASGN:
11236 CHECK(compile_for_masgn(iseq, ret, node, popped));
11237 break;
11238 case NODE_BREAK:
11239 CHECK(compile_break(iseq, ret, node, popped));
11240 break;
11241 case NODE_NEXT:
11242 CHECK(compile_next(iseq, ret, node, popped));
11243 break;
11244 case NODE_REDO:
11245 CHECK(compile_redo(iseq, ret, node, popped));
11246 break;
11247 case NODE_RETRY:
11248 CHECK(compile_retry(iseq, ret, node, popped));
11249 break;
11250 case NODE_BEGIN:{
11251 CHECK(COMPILE_(ret, "NODE_BEGIN", RNODE_BEGIN(node)->nd_body, popped));
11252 break;
11253 }
11254 case NODE_RESCUE:
11255 CHECK(compile_rescue(iseq, ret, node, popped));
11256 break;
11257 case NODE_RESBODY:
11258 CHECK(compile_resbody(iseq, ret, node, popped));
11259 break;
11260 case NODE_ENSURE:
11261 CHECK(compile_ensure(iseq, ret, node, popped));
11262 break;
11263
11264 case NODE_AND:
11265 case NODE_OR:{
11266 LABEL *end_label = NEW_LABEL(line);
11267 const NODE *cond = node;
11268 /* Compile a chain of the same operator (`a && b && ...`) against one
11269 * shared end label, so every branch targets it directly. Compiling
11270 * nd_2nd recursively would instead give each operator its own label,
11271 * and the peephole optimizer would rewrite that chain in quadratic
11272 * time. */
11273 while (1) {
11274 CHECK(COMPILE(ret, "nd_1st", RNODE_OR(cond)->nd_1st));
11275 if (!popped) {
11276 ADD_INSN(ret, cond, dup);
11277 }
11278 if (type == NODE_AND) {
11279 ADD_INSNL(ret, cond, branchunless, end_label);
11280 }
11281 else {
11282 ADD_INSNL(ret, cond, branchif, end_label);
11283 }
11284 if (!popped) {
11285 ADD_INSN(ret, cond, pop);
11286 }
11287 const NODE *rest = RNODE_OR(cond)->nd_2nd;
11288 if (nd_type_p(rest, type)) {
11289 cond = rest;
11290 continue;
11291 }
11292 CHECK(COMPILE_(ret, "nd_2nd", rest, popped));
11293 break;
11294 }
11295 ADD_LABEL(ret, end_label);
11296 break;
11297 }
11298
11299 case NODE_MASGN:{
11300 compile_massign(iseq, ret, node, popped);
11301 break;
11302 }
11303
11304 case NODE_LASGN:{
11305 ID id = RNODE_LASGN(node)->nd_vid;
11306 int idx = ISEQ_BODY(body->local_iseq)->local_table_size - get_local_var_idx(iseq, id);
11307
11308 debugs("lvar: %s idx: %d\n", rb_id2name(id), idx);
11309 CHECK(COMPILE(ret, "rvalue", RNODE_LASGN(node)->nd_value));
11310
11311 if (!popped) {
11312 ADD_INSN(ret, node, dup);
11313 }
11314 ADD_SETLOCAL(ret, node, idx, get_lvar_level(iseq));
11315 break;
11316 }
11317 case NODE_DASGN: {
11318 int idx, lv, ls;
11319 ID id = RNODE_DASGN(node)->nd_vid;
11320 CHECK(COMPILE(ret, "dvalue", RNODE_DASGN(node)->nd_value));
11321 debugi("dassn id", rb_id2str(id) ? id : '*');
11322
11323 if (!popped) {
11324 ADD_INSN(ret, node, dup);
11325 }
11326
11327 idx = get_dyna_var_idx(iseq, id, &lv, &ls);
11328
11329 if (idx < 0) {
11330 COMPILE_ERROR(ERROR_ARGS "NODE_DASGN: unknown id (%"PRIsVALUE")",
11331 rb_id2str(id));
11332 goto ng;
11333 }
11334 ADD_SETLOCAL(ret, node, ls - idx, lv);
11335 break;
11336 }
11337 case NODE_GASGN:{
11338 CHECK(COMPILE(ret, "lvalue", RNODE_GASGN(node)->nd_value));
11339
11340 if (!popped) {
11341 ADD_INSN(ret, node, dup);
11342 }
11343 ADD_INSN1(ret, node, setglobal, ID2SYM(RNODE_GASGN(node)->nd_vid));
11344 break;
11345 }
11346 case NODE_IASGN:{
11347 CHECK(COMPILE(ret, "lvalue", RNODE_IASGN(node)->nd_value));
11348 if (!popped) {
11349 ADD_INSN(ret, node, dup);
11350 }
11351 ADD_INSN2(ret, node, setinstancevariable,
11352 ID2SYM(RNODE_IASGN(node)->nd_vid),
11353 get_ivar_ic_value(iseq,RNODE_IASGN(node)->nd_vid));
11354 break;
11355 }
11356 case NODE_CDECL:{
11357 if (RNODE_CDECL(node)->nd_vid) {
11358 CHECK(compile_shareable_constant_value(iseq, ret, RNODE_CDECL(node)->shareability, node, RNODE_CDECL(node)->nd_value));
11359
11360 if (!popped) {
11361 ADD_INSN(ret, node, dup);
11362 }
11363
11364 ADD_INSN1(ret, node, putspecialobject,
11365 INT2FIX(VM_SPECIAL_OBJECT_CONST_BASE));
11366 ADD_INSN1(ret, node, setconstant, ID2SYM(RNODE_CDECL(node)->nd_vid));
11367 }
11368 else {
11369 compile_cpath(ret, iseq, RNODE_CDECL(node)->nd_else);
11370 CHECK(compile_shareable_constant_value(iseq, ret, RNODE_CDECL(node)->shareability, node, RNODE_CDECL(node)->nd_value));
11371 ADD_INSN(ret, node, swap);
11372
11373 if (!popped) {
11374 ADD_INSN1(ret, node, topn, INT2FIX(1));
11375 ADD_INSN(ret, node, swap);
11376 }
11377
11378 ADD_INSN1(ret, node, setconstant, ID2SYM(get_node_colon_nd_mid(RNODE_CDECL(node)->nd_else)));
11379 }
11380 break;
11381 }
11382 case NODE_CVASGN:{
11383 CHECK(COMPILE(ret, "cvasgn val", RNODE_CVASGN(node)->nd_value));
11384 if (!popped) {
11385 ADD_INSN(ret, node, dup);
11386 }
11387 ADD_INSN2(ret, node, setclassvariable,
11388 ID2SYM(RNODE_CVASGN(node)->nd_vid),
11389 get_cvar_ic_value(iseq, RNODE_CVASGN(node)->nd_vid));
11390 break;
11391 }
11392 case NODE_OP_ASGN1:
11393 CHECK(compile_op_asgn1(iseq, ret, node, popped));
11394 break;
11395 case NODE_OP_ASGN2:
11396 CHECK(compile_op_asgn2(iseq, ret, node, popped));
11397 break;
11398 case NODE_OP_CDECL:
11399 CHECK(compile_op_cdecl(iseq, ret, node, popped));
11400 break;
11401 case NODE_OP_ASGN_AND:
11402 case NODE_OP_ASGN_OR:
11403 CHECK(compile_op_log(iseq, ret, node, popped, type));
11404 break;
11405 case NODE_CALL: /* obj.foo */
11406 case NODE_OPCALL: /* foo[] */
11407 if (compile_call_precheck_freeze(iseq, ret, node, node, popped) == TRUE) {
11408 break;
11409 }
11410 case NODE_QCALL: /* obj&.foo */
11411 case NODE_FCALL: /* foo() */
11412 case NODE_VCALL: /* foo (variable or call) */
11413 if (compile_call(iseq, ret, node, type, node, popped, false) == COMPILE_NG) {
11414 goto ng;
11415 }
11416 break;
11417 case NODE_SUPER:
11418 case NODE_ZSUPER:
11419 CHECK(compile_super(iseq, ret, node, popped, type));
11420 break;
11421 case NODE_LIST:{
11422 CHECK(compile_array(iseq, ret, node, popped, TRUE) >= 0);
11423 break;
11424 }
11425 case NODE_ZLIST:{
11426 if (!popped) {
11427 ADD_INSN1(ret, node, newarray, INT2FIX(0));
11428 }
11429 break;
11430 }
11431 case NODE_HASH:
11432 CHECK(compile_hash(iseq, ret, node, FALSE, popped) >= 0);
11433 break;
11434 case NODE_RETURN:
11435 CHECK(compile_return(iseq, ret, node, popped));
11436 break;
11437 case NODE_YIELD:
11438 CHECK(compile_yield(iseq, ret, node, popped));
11439 break;
11440 case NODE_LVAR:{
11441 if (!popped) {
11442 compile_lvar(iseq, ret, node, RNODE_LVAR(node)->nd_vid);
11443 }
11444 break;
11445 }
11446 case NODE_DVAR:{
11447 int lv, idx, ls;
11448 debugi("nd_vid", RNODE_DVAR(node)->nd_vid);
11449 if (!popped) {
11450 idx = get_dyna_var_idx(iseq, RNODE_DVAR(node)->nd_vid, &lv, &ls);
11451 if (idx < 0) {
11452 COMPILE_ERROR(ERROR_ARGS "unknown dvar (%"PRIsVALUE")",
11453 rb_id2str(RNODE_DVAR(node)->nd_vid));
11454 goto ng;
11455 }
11456 ADD_GETLOCAL(ret, node, ls - idx, lv);
11457 }
11458 break;
11459 }
11460 case NODE_GVAR:{
11461 ADD_INSN1(ret, node, getglobal, ID2SYM(RNODE_GVAR(node)->nd_vid));
11462 if (popped) {
11463 ADD_INSN(ret, node, pop);
11464 }
11465 break;
11466 }
11467 case NODE_IVAR:{
11468 debugi("nd_vid", RNODE_IVAR(node)->nd_vid);
11469 if (!popped) {
11470 ADD_INSN2(ret, node, getinstancevariable,
11471 ID2SYM(RNODE_IVAR(node)->nd_vid),
11472 get_ivar_ic_value(iseq, RNODE_IVAR(node)->nd_vid));
11473 }
11474 break;
11475 }
11476 case NODE_CONST:{
11477 debugi("nd_vid", RNODE_CONST(node)->nd_vid);
11478
11479 if (ISEQ_COMPILE_DATA(iseq)->option->inline_const_cache) {
11480 body->ic_size++;
11481 rb_const_path_t const_path = rb_const_path_from_ids(false, &RNODE_CONST(node)->nd_vid, 1);
11482 ADD_INSN1(ret, node, opt_getconstant_path, (VALUE)const_path);
11483 }
11484 else {
11485 ADD_INSN(ret, node, putnil);
11486 ADD_INSN1(ret, node, putobject, Qtrue);
11487 ADD_INSN1(ret, node, getconstant, ID2SYM(RNODE_CONST(node)->nd_vid));
11488 }
11489
11490 if (popped) {
11491 ADD_INSN(ret, node, pop);
11492 }
11493 break;
11494 }
11495 case NODE_CVAR:{
11496 if (!popped) {
11497 ADD_INSN2(ret, node, getclassvariable,
11498 ID2SYM(RNODE_CVAR(node)->nd_vid),
11499 get_cvar_ic_value(iseq, RNODE_CVAR(node)->nd_vid));
11500 }
11501 break;
11502 }
11503 case NODE_NTH_REF:{
11504 if (!popped) {
11505 if (!RNODE_NTH_REF(node)->nd_nth) {
11506 ADD_INSN(ret, node, putnil);
11507 break;
11508 }
11509 ADD_INSN2(ret, node, getspecial, INT2FIX(1) /* '~' */,
11510 INT2FIX(RNODE_NTH_REF(node)->nd_nth << 1));
11511 }
11512 break;
11513 }
11514 case NODE_BACK_REF:{
11515 if (!popped) {
11516 ADD_INSN2(ret, node, getspecial, INT2FIX(1) /* '~' */,
11517 INT2FIX(0x01 | (RNODE_BACK_REF(node)->nd_nth << 1)));
11518 }
11519 break;
11520 }
11521 case NODE_MATCH:
11522 case NODE_MATCH2:
11523 case NODE_MATCH3:
11524 CHECK(compile_match(iseq, ret, node, popped, type));
11525 break;
11526 case NODE_SYM:{
11527 if (!popped) {
11528 ADD_INSN1(ret, node, putobject, rb_node_sym_string_val(node));
11529 }
11530 break;
11531 }
11532 case NODE_LINE:{
11533 if (!popped) {
11534 ADD_INSN1(ret, node, putobject, rb_node_line_lineno_val(node));
11535 }
11536 break;
11537 }
11538 case NODE_ENCODING:{
11539 if (!popped) {
11540 ADD_INSN1(ret, node, putobject, rb_node_encoding_val(node));
11541 }
11542 break;
11543 }
11544 case NODE_INTEGER:{
11545 VALUE lit = rb_node_integer_literal_val(node);
11546 if (!SPECIAL_CONST_P(lit)) RB_OBJ_SET_SHAREABLE(lit);
11547 debugp_param("integer", lit);
11548 if (!popped) {
11549 ADD_INSN1(ret, node, putobject, lit);
11550 RB_OBJ_WRITTEN(iseq, Qundef, lit);
11551 }
11552 break;
11553 }
11554 case NODE_FLOAT:{
11555 VALUE lit = rb_node_float_literal_val(node);
11556 if (!SPECIAL_CONST_P(lit)) RB_OBJ_SET_SHAREABLE(lit);
11557 debugp_param("float", lit);
11558 if (!popped) {
11559 ADD_INSN1(ret, node, putobject, lit);
11560 RB_OBJ_WRITTEN(iseq, Qundef, lit);
11561 }
11562 break;
11563 }
11564 case NODE_RATIONAL:{
11565 VALUE lit = rb_node_rational_literal_val(node);
11567 debugp_param("rational", lit);
11568 if (!popped) {
11569 ADD_INSN1(ret, node, putobject, lit);
11570 RB_OBJ_WRITTEN(iseq, Qundef, lit);
11571 }
11572 break;
11573 }
11574 case NODE_IMAGINARY:{
11575 VALUE lit = rb_node_imaginary_literal_val(node);
11577 debugp_param("imaginary", lit);
11578 if (!popped) {
11579 ADD_INSN1(ret, node, putobject, lit);
11580 RB_OBJ_WRITTEN(iseq, Qundef, lit);
11581 }
11582 break;
11583 }
11584 case NODE_FILE:
11585 if (!popped) {
11586 compile_file_path(iseq, ret, node, ISEQ_COMPILE_DATA(iseq)->option->frozen_string_literal);
11587 }
11588 break;
11589 case NODE_STR:{
11590 debugp_param("nd_lit", get_string_value(node));
11591 if (!popped) {
11592 VALUE lit = get_string_value(node);
11593 const rb_compile_option_t *option = ISEQ_COMPILE_DATA(iseq)->option;
11594 if ((option->debug_frozen_string_literal || RTEST(ruby_debug)) &&
11595 option->frozen_string_literal != ISEQ_FROZEN_STRING_LITERAL_DISABLED) {
11596 lit = rb_str_with_debug_created_info(lit, rb_iseq_path(iseq), line);
11598 }
11599 switch (option->frozen_string_literal) {
11600 case ISEQ_FROZEN_STRING_LITERAL_UNSET:
11601 ADD_INSN1(ret, node, dupchilledstring, lit);
11602 break;
11603 case ISEQ_FROZEN_STRING_LITERAL_DISABLED:
11604 ADD_INSN1(ret, node, dupstring, lit);
11605 break;
11606 case ISEQ_FROZEN_STRING_LITERAL_ENABLED:
11607 ADD_INSN1(ret, node, putobject, lit);
11608 break;
11609 default:
11610 rb_bug("invalid frozen_string_literal");
11611 }
11612 RB_OBJ_WRITTEN(iseq, Qundef, lit);
11613 }
11614 break;
11615 }
11616 case NODE_DSTR:{
11617 compile_dstr(iseq, ret, node);
11618
11619 if (popped) {
11620 ADD_INSN(ret, node, pop);
11621 }
11622 break;
11623 }
11624 case NODE_XSTR:{
11625 ADD_CALL_RECEIVER(ret, node);
11626 VALUE str = rb_node_str_string_val(node);
11627 ADD_INSN1(ret, node, putobject, str);
11628 RB_OBJ_WRITTEN(iseq, Qundef, str);
11629 ADD_CALL(ret, node, idBackquote, INT2FIX(1));
11630
11631 if (popped) {
11632 ADD_INSN(ret, node, pop);
11633 }
11634 break;
11635 }
11636 case NODE_DXSTR:{
11637 ADD_CALL_RECEIVER(ret, node);
11638 compile_dstr(iseq, ret, node);
11639 ADD_CALL(ret, node, idBackquote, INT2FIX(1));
11640
11641 if (popped) {
11642 ADD_INSN(ret, node, pop);
11643 }
11644 break;
11645 }
11646 case NODE_EVSTR:
11647 CHECK(compile_evstr(iseq, ret, RNODE_EVSTR(node)->nd_body, popped));
11648 break;
11649 case NODE_REGX:{
11650 if (!popped) {
11651 VALUE lit = rb_node_regx_string_val(node);
11653 ADD_INSN1(ret, node, putobject, lit);
11654 RB_OBJ_WRITTEN(iseq, Qundef, lit);
11655 }
11656 break;
11657 }
11658 case NODE_DREGX:
11659 compile_dregx(iseq, ret, node, popped);
11660 break;
11661 case NODE_ONCE:{
11662 const rb_iseq_t *block_iseq;
11663 block_iseq = NEW_CHILD_ISEQ(RNODE_ONCE(node)->nd_body, make_name_for_block(iseq), ISEQ_TYPE_PLAIN, line);
11664
11665 VALUE once_storage = rb_imemo_once_storage_new();
11666 ADD_INSN2(ret, node, once, block_iseq, once_storage);
11667 RB_OBJ_WRITTEN(iseq, Qundef, (VALUE)block_iseq);
11668 RB_OBJ_WRITTEN(iseq, Qundef, once_storage);
11669
11670 if (popped) {
11671 ADD_INSN(ret, node, pop);
11672 }
11673 break;
11674 }
11675 case NODE_ARGSCAT:{
11676 if (popped) {
11677 CHECK(COMPILE(ret, "argscat head", RNODE_ARGSCAT(node)->nd_head));
11678 ADD_INSN1(ret, node, splatarray, Qfalse);
11679 ADD_INSN(ret, node, pop);
11680 CHECK(COMPILE(ret, "argscat body", RNODE_ARGSCAT(node)->nd_body));
11681 ADD_INSN1(ret, node, splatarray, Qfalse);
11682 ADD_INSN(ret, node, pop);
11683 }
11684 else {
11685 CHECK(COMPILE(ret, "argscat head", RNODE_ARGSCAT(node)->nd_head));
11686 const NODE *body_node = RNODE_ARGSCAT(node)->nd_body;
11687 if (nd_type_p(body_node, NODE_LIST)) {
11688 CHECK(compile_array(iseq, ret, body_node, popped, FALSE) >= 0);
11689 }
11690 else {
11691 CHECK(COMPILE(ret, "argscat body", body_node));
11692 ADD_INSN(ret, node, concattoarray);
11693 }
11694 }
11695 break;
11696 }
11697 case NODE_ARGSPUSH:{
11698 if (popped) {
11699 CHECK(COMPILE(ret, "argspush head", RNODE_ARGSPUSH(node)->nd_head));
11700 ADD_INSN1(ret, node, splatarray, Qfalse);
11701 ADD_INSN(ret, node, pop);
11702 CHECK(COMPILE_(ret, "argspush body", RNODE_ARGSPUSH(node)->nd_body, popped));
11703 }
11704 else {
11705 CHECK(COMPILE(ret, "argspush head", RNODE_ARGSPUSH(node)->nd_head));
11706 const NODE *body_node = RNODE_ARGSPUSH(node)->nd_body;
11707 if (keyword_node_p(body_node)) {
11708 CHECK(COMPILE_(ret, "array element", body_node, FALSE));
11709 ADD_INSN(ret, node, pushtoarraykwsplat);
11710 }
11711 else if (static_literal_node_p(body_node, iseq, false)) {
11712 ADD_INSN1(ret, body_node, putobject, static_literal_value(body_node, iseq));
11713 ADD_INSN1(ret, node, pushtoarray, INT2FIX(1));
11714 }
11715 else {
11716 CHECK(COMPILE_(ret, "array element", body_node, FALSE));
11717 ADD_INSN1(ret, node, pushtoarray, INT2FIX(1));
11718 }
11719 }
11720 break;
11721 }
11722 case NODE_SPLAT:{
11723 CHECK(COMPILE(ret, "splat", RNODE_SPLAT(node)->nd_head));
11724 ADD_INSN1(ret, node, splatarray, Qtrue);
11725
11726 if (popped) {
11727 ADD_INSN(ret, node, pop);
11728 }
11729 break;
11730 }
11731 case NODE_DEFN:{
11732 ID mid = RNODE_DEFN(node)->nd_mid;
11733 const rb_iseq_t *method_iseq = NEW_ISEQ(RNODE_DEFN(node)->nd_defn,
11734 rb_id2str(mid),
11735 ISEQ_TYPE_METHOD, line);
11736
11737 debugp_param("defn/iseq", rb_iseqw_new(method_iseq));
11738 ADD_INSN2(ret, node, definemethod, ID2SYM(mid), method_iseq);
11739 RB_OBJ_WRITTEN(iseq, Qundef, (VALUE)method_iseq);
11740
11741 if (!popped) {
11742 ADD_INSN1(ret, node, putobject, ID2SYM(mid));
11743 }
11744
11745 break;
11746 }
11747 case NODE_DEFS:{
11748 ID mid = RNODE_DEFS(node)->nd_mid;
11749 const rb_iseq_t * singleton_method_iseq = NEW_ISEQ(RNODE_DEFS(node)->nd_defn,
11750 rb_id2str(mid),
11751 ISEQ_TYPE_METHOD, line);
11752
11753 debugp_param("defs/iseq", rb_iseqw_new(singleton_method_iseq));
11754 CHECK(COMPILE(ret, "defs: recv", RNODE_DEFS(node)->nd_recv));
11755 ADD_INSN2(ret, node, definesmethod, ID2SYM(mid), singleton_method_iseq);
11756 RB_OBJ_WRITTEN(iseq, Qundef, (VALUE)singleton_method_iseq);
11757
11758 if (!popped) {
11759 ADD_INSN1(ret, node, putobject, ID2SYM(mid));
11760 }
11761 break;
11762 }
11763 case NODE_ALIAS:{
11764 ADD_INSN1(ret, node, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
11765 ADD_INSN1(ret, node, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_CBASE));
11766 CHECK(COMPILE(ret, "alias arg1", RNODE_ALIAS(node)->nd_1st));
11767 CHECK(COMPILE(ret, "alias arg2", RNODE_ALIAS(node)->nd_2nd));
11768 ADD_SEND(ret, node, id_core_set_method_alias, INT2FIX(3));
11769
11770 if (popped) {
11771 ADD_INSN(ret, node, pop);
11772 }
11773 break;
11774 }
11775 case NODE_VALIAS:{
11776 ADD_INSN1(ret, node, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
11777 ADD_INSN1(ret, node, putobject, ID2SYM(RNODE_VALIAS(node)->nd_alias));
11778 ADD_INSN1(ret, node, putobject, ID2SYM(RNODE_VALIAS(node)->nd_orig));
11779 ADD_SEND(ret, node, id_core_set_variable_alias, INT2FIX(2));
11780
11781 if (popped) {
11782 ADD_INSN(ret, node, pop);
11783 }
11784 break;
11785 }
11786 case NODE_UNDEF:{
11787 const rb_parser_ary_t *ary = RNODE_UNDEF(node)->nd_undefs;
11788
11789 for (long i = 0; i < ary->len; i++) {
11790 ADD_INSN1(ret, node, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
11791 ADD_INSN1(ret, node, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_CBASE));
11792 CHECK(COMPILE(ret, "undef arg", ary->data[i]));
11793 ADD_SEND(ret, node, id_core_undef_method, INT2FIX(2));
11794
11795 if (i < ary->len - 1) {
11796 ADD_INSN(ret, node, pop);
11797 }
11798 }
11799
11800 if (popped) {
11801 ADD_INSN(ret, node, pop);
11802 }
11803 break;
11804 }
11805 case NODE_CLASS:{
11806 const rb_iseq_t *class_iseq = NEW_CHILD_ISEQ(RNODE_CLASS(node)->nd_body,
11807 rb_str_freeze(rb_sprintf("<class:%"PRIsVALUE">", rb_id2str(get_node_colon_nd_mid(RNODE_CLASS(node)->nd_cpath)))),
11808 ISEQ_TYPE_CLASS, line);
11809 const int flags = VM_DEFINECLASS_TYPE_CLASS |
11810 (RNODE_CLASS(node)->nd_super ? VM_DEFINECLASS_FLAG_HAS_SUPERCLASS : 0) |
11811 compile_cpath(ret, iseq, RNODE_CLASS(node)->nd_cpath);
11812
11813 CHECK(COMPILE(ret, "super", RNODE_CLASS(node)->nd_super));
11814 ADD_INSN3(ret, node, defineclass, ID2SYM(get_node_colon_nd_mid(RNODE_CLASS(node)->nd_cpath)), class_iseq, INT2FIX(flags));
11815 RB_OBJ_WRITTEN(iseq, Qundef, (VALUE)class_iseq);
11816
11817 if (popped) {
11818 ADD_INSN(ret, node, pop);
11819 }
11820 break;
11821 }
11822 case NODE_MODULE:{
11823 const rb_iseq_t *module_iseq = NEW_CHILD_ISEQ(RNODE_MODULE(node)->nd_body,
11824 rb_str_freeze(rb_sprintf("<module:%"PRIsVALUE">", rb_id2str(get_node_colon_nd_mid(RNODE_MODULE(node)->nd_cpath)))),
11825 ISEQ_TYPE_CLASS, line);
11826 const int flags = VM_DEFINECLASS_TYPE_MODULE |
11827 compile_cpath(ret, iseq, RNODE_MODULE(node)->nd_cpath);
11828
11829 ADD_INSN (ret, node, putnil); /* dummy */
11830 ADD_INSN3(ret, node, defineclass, ID2SYM(get_node_colon_nd_mid(RNODE_MODULE(node)->nd_cpath)), module_iseq, INT2FIX(flags));
11831 RB_OBJ_WRITTEN(iseq, Qundef, (VALUE)module_iseq);
11832
11833 if (popped) {
11834 ADD_INSN(ret, node, pop);
11835 }
11836 break;
11837 }
11838 case NODE_SCLASS:{
11839 ID singletonclass;
11840 const rb_iseq_t *singleton_class = NEW_ISEQ(RNODE_SCLASS(node)->nd_body, rb_fstring_lit("singleton class"),
11841 ISEQ_TYPE_CLASS, line);
11842
11843 CHECK(COMPILE(ret, "sclass#recv", RNODE_SCLASS(node)->nd_recv));
11844 ADD_INSN (ret, node, putnil);
11845 CONST_ID(singletonclass, "singletonclass");
11846
11847 /* `class << self` in a class body and `class << Foo` (constant
11848 receiver) are stable. All other forms are potentially dynamic. */
11849 int sclass_flags = VM_DEFINECLASS_TYPE_SINGLETON_CLASS;
11850 const NODE *recv = RNODE_SCLASS(node)->nd_recv;
11851 if (!(nd_type_p(recv, NODE_SELF) &&
11852 ISEQ_BODY(iseq)->type == ISEQ_TYPE_CLASS) &&
11853 !cpath_const_p(recv)) {
11854 sclass_flags |= VM_DEFINECLASS_FLAG_DYNAMIC_CREF;
11855 }
11856
11857 ADD_INSN3(ret, node, defineclass,
11858 ID2SYM(singletonclass), singleton_class,
11859 INT2FIX(sclass_flags));
11860 RB_OBJ_WRITTEN(iseq, Qundef, (VALUE)singleton_class);
11861
11862 if (popped) {
11863 ADD_INSN(ret, node, pop);
11864 }
11865 break;
11866 }
11867 case NODE_COLON2:
11868 CHECK(compile_colon2(iseq, ret, node, popped));
11869 break;
11870 case NODE_COLON3:
11871 CHECK(compile_colon3(iseq, ret, node, popped));
11872 break;
11873 case NODE_DOT2:
11874 CHECK(compile_dots(iseq, ret, node, popped, FALSE));
11875 break;
11876 case NODE_DOT3:
11877 CHECK(compile_dots(iseq, ret, node, popped, TRUE));
11878 break;
11879 case NODE_FLIP2:
11880 case NODE_FLIP3:{
11881 LABEL *lend = NEW_LABEL(line);
11882 LABEL *ltrue = NEW_LABEL(line);
11883 LABEL *lfalse = NEW_LABEL(line);
11884 CHECK(compile_flip_flop(iseq, ret, node, type == NODE_FLIP2,
11885 ltrue, lfalse));
11886 ADD_LABEL(ret, ltrue);
11887 ADD_INSN1(ret, node, putobject, Qtrue);
11888 ADD_INSNL(ret, node, jump, lend);
11889 ADD_LABEL(ret, lfalse);
11890 ADD_INSN1(ret, node, putobject, Qfalse);
11891 ADD_LABEL(ret, lend);
11892 break;
11893 }
11894 case NODE_SELF:{
11895 if (!popped) {
11896 ADD_INSN(ret, node, putself);
11897 }
11898 break;
11899 }
11900 case NODE_NIL:{
11901 if (!popped) {
11902 ADD_INSN(ret, node, putnil);
11903 }
11904 break;
11905 }
11906 case NODE_TRUE:{
11907 if (!popped) {
11908 ADD_INSN1(ret, node, putobject, Qtrue);
11909 }
11910 break;
11911 }
11912 case NODE_FALSE:{
11913 if (!popped) {
11914 ADD_INSN1(ret, node, putobject, Qfalse);
11915 }
11916 break;
11917 }
11918 case NODE_ERRINFO:
11919 CHECK(compile_errinfo(iseq, ret, node, popped));
11920 break;
11921 case NODE_DEFINED:
11922 if (!popped) {
11923 CHECK(compile_defined_expr(iseq, ret, node, Qtrue, false));
11924 }
11925 break;
11926 case NODE_POSTEXE:{
11927 /* compiled to:
11928 * ONCE{ rb_mRubyVMFrozenCore::core#set_postexe{ ... } }
11929 */
11931 rb_iseq_new_with_callback_new_callback(build_postexe_iseq, RNODE_POSTEXE(node)->nd_body);
11932 const rb_iseq_t *once_iseq =
11933 NEW_CHILD_ISEQ_WITH_CALLBACK(ifunc, rb_fstring(make_name_for_block(iseq)), ISEQ_TYPE_BLOCK, line);
11934
11935 VALUE once_storage = rb_imemo_once_storage_new();
11936 ADD_INSN2(ret, node, once, once_iseq, once_storage);
11937 RB_OBJ_WRITTEN(iseq, Qundef, (VALUE)once_iseq);
11938 RB_OBJ_WRITTEN(iseq, Qundef, once_storage);
11939
11940 if (popped) {
11941 ADD_INSN(ret, node, pop);
11942 }
11943 break;
11944 }
11945 case NODE_KW_ARG:
11946 CHECK(compile_kw_arg(iseq, ret, node, popped));
11947 break;
11948 case NODE_DSYM:{
11949 compile_dstr(iseq, ret, node);
11950 if (!popped) {
11951 ADD_INSN(ret, node, intern);
11952 }
11953 else {
11954 ADD_INSN(ret, node, pop);
11955 }
11956 break;
11957 }
11958 case NODE_ATTRASGN:
11959 CHECK(compile_attrasgn(iseq, ret, node, popped));
11960 break;
11961 case NODE_LAMBDA:{
11962 /* compile same as lambda{...} */
11963 const rb_iseq_t *block = NEW_CHILD_ISEQ(RNODE_LAMBDA(node)->nd_body, make_name_for_block(iseq), ISEQ_TYPE_BLOCK, line);
11964 VALUE argc = INT2FIX(0);
11965
11966 ADD_INSN1(ret, node, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
11967 ADD_CALL_WITH_BLOCK(ret, node, idLambda, argc, block);
11968 RB_OBJ_WRITTEN(iseq, Qundef, (VALUE)block);
11969
11970 if (popped) {
11971 ADD_INSN(ret, node, pop);
11972 }
11973 break;
11974 }
11975 default:
11976 UNKNOWN_NODE("iseq_compile_each", node, COMPILE_NG);
11977 ng:
11978 debug_node_end();
11979 return COMPILE_NG;
11980 }
11981
11982 debug_node_end();
11983 return COMPILE_OK;
11984}
11985
11986/***************************/
11987/* instruction information */
11988/***************************/
11989
11990static int
11991insn_data_length(INSN *iobj)
11992{
11993 return insn_len(iobj->insn_id);
11994}
11995
11996static int
11997calc_sp_depth(int depth, INSN *insn)
11998{
11999 return comptime_insn_stack_increase(depth, insn->insn_id, insn->operands);
12000}
12001
12002static VALUE
12003opobj_inspect(VALUE obj)
12004{
12005 if (!SPECIAL_CONST_P(obj) && !RBASIC_CLASS(obj)) {
12006 switch (BUILTIN_TYPE(obj)) {
12007 case T_STRING:
12008 obj = rb_str_resurrect(obj);
12009 break;
12010 case T_ARRAY:
12011 obj = rb_ary_resurrect(obj);
12012 break;
12013 default:
12014 break;
12015 }
12016 }
12017 return rb_inspect(obj);
12018}
12019
12020
12021
12022static VALUE
12023insn_data_to_s_detail(INSN *iobj)
12024{
12025 VALUE str = rb_sprintf("%-20s ", insn_name(iobj->insn_id));
12026
12027 if (iobj->operands) {
12028 const char *types = insn_op_types(iobj->insn_id);
12029 int j;
12030
12031 for (j = 0; types[j]; j++) {
12032 char type = types[j];
12033
12034 switch (type) {
12035 case TS_OFFSET: /* label(destination position) */
12036 {
12037 LABEL *lobj = (LABEL *)OPERAND_AT(iobj, j);
12038 rb_str_catf(str, LABEL_FORMAT, lobj->label_no);
12039 break;
12040 }
12041 break;
12042 case TS_ISEQ: /* iseq */
12043 {
12044 rb_iseq_t *iseq = (rb_iseq_t *)OPERAND_AT(iobj, j);
12045 VALUE val = Qnil;
12046 if (0 && iseq) { /* TODO: invalidate now */
12047 val = (VALUE)iseq;
12048 }
12049 rb_str_concat(str, opobj_inspect(val));
12050 }
12051 break;
12052 case TS_LINDEX:
12053 case TS_NUM: /* ulong */
12054 case TS_VALUE: /* VALUE */
12055 {
12056 VALUE v = OPERAND_AT(iobj, j);
12057 if (!CLASS_OF(v))
12058 rb_str_cat2(str, "<hidden>");
12059 else {
12060 rb_str_concat(str, opobj_inspect(v));
12061 }
12062 break;
12063 }
12064 case TS_ID: /* ID */
12065 rb_str_concat(str, opobj_inspect(OPERAND_AT(iobj, j)));
12066 break;
12067 case TS_IC: /* inline cache */
12068 rb_str_concat(str, opobj_inspect(rb_const_path_to_array((rb_const_path_t)OPERAND_AT(iobj, j))));
12069 break;
12070 case TS_IVC: /* inline ivar cache */
12071 rb_str_catf(str, "<ivc:%d>", FIX2INT(OPERAND_AT(iobj, j)));
12072 break;
12073 case TS_ICVARC: /* inline cvar cache */
12074 rb_str_catf(str, "<icvarc:%d>", FIX2INT(OPERAND_AT(iobj, j)));
12075 break;
12076 case TS_CALLDATA: /* we store these as call infos at compile time */
12077 {
12078 const struct rb_callinfo *ci = (struct rb_callinfo *)OPERAND_AT(iobj, j);
12079 rb_str_cat2(str, "<calldata:");
12080 if (vm_ci_mid(ci)) rb_str_append(str, rb_id2str(vm_ci_mid(ci)));
12081 rb_str_catf(str, ", %d>", vm_ci_argc(ci));
12082 break;
12083 }
12084 case TS_CDHASH: /* case/when condition cache */
12085 rb_str_cat2(str, "<ch>");
12086 break;
12087 case TS_FUNCPTR:
12088 {
12089 void *func = (void *)OPERAND_AT(iobj, j);
12090#ifdef HAVE_DLADDR
12091 Dl_info info;
12092 if (dladdr(func, &info) && info.dli_sname) {
12093 rb_str_cat2(str, info.dli_sname);
12094 break;
12095 }
12096#endif
12097 rb_str_catf(str, "<%p>", func);
12098 }
12099 break;
12100 case TS_BUILTIN:
12101 rb_str_cat2(str, "<TS_BUILTIN>");
12102 break;
12103 default:{
12104 rb_raise(rb_eSyntaxError, "unknown operand type: %c", type);
12105 }
12106 }
12107 if (types[j + 1]) {
12108 rb_str_cat2(str, ", ");
12109 }
12110 }
12111 }
12112 return str;
12113}
12114
12115static void
12116dump_disasm_list(const LINK_ELEMENT *link)
12117{
12118 dump_disasm_list_with_cursor(link, NULL, NULL);
12119}
12120
12121static void
12122dump_disasm_list_with_cursor(const LINK_ELEMENT *link, const LINK_ELEMENT *curr, const LABEL *dest)
12123{
12124 int pos = 0;
12125 INSN *iobj;
12126 LABEL *lobj;
12127 VALUE str;
12128
12129 printf("-- raw disasm--------\n");
12130
12131 while (link) {
12132 if (curr) printf(curr == link ? "*" : " ");
12133 switch (link->type) {
12134 case ISEQ_ELEMENT_INSN:
12135 {
12136 iobj = (INSN *)link;
12137 str = insn_data_to_s_detail(iobj);
12138 printf(" %04d %-65s(%4u)\n", pos, StringValueCStr(str), iobj->insn_info.line_no);
12139 pos += insn_data_length(iobj);
12140 break;
12141 }
12142 case ISEQ_ELEMENT_LABEL:
12143 {
12144 lobj = (LABEL *)link;
12145 printf(LABEL_FORMAT" [sp: %d, unremovable: %d, refcnt: %d]%s\n", lobj->label_no, lobj->sp, lobj->unremovable, lobj->refcnt,
12146 dest == lobj ? " <---" : "");
12147 break;
12148 }
12149 case ISEQ_ELEMENT_TRACE:
12150 {
12151 TRACE *trace = (TRACE *)link;
12152 printf(" trace: %0x\n", trace->event);
12153 break;
12154 }
12155 case ISEQ_ELEMENT_ADJUST:
12156 {
12157 ADJUST *adjust = (ADJUST *)link;
12158 printf(" adjust: [label: %d]\n", adjust->label ? adjust->label->label_no : -1);
12159 break;
12160 }
12161 default:
12162 /* ignore */
12163 rb_raise(rb_eSyntaxError, "dump_disasm_list error: %d\n", (int)link->type);
12164 }
12165 link = link->next;
12166 }
12167 printf("---------------------\n");
12168 fflush(stdout);
12169}
12170
12171int
12172rb_insn_len(VALUE insn)
12173{
12174 return insn_len(insn);
12175}
12176
12177const char *
12178rb_insns_name(int i)
12179{
12180 return insn_name(i);
12181}
12182
12183VALUE
12184rb_insns_name_array(void)
12185{
12186 VALUE ary = rb_ary_new_capa(VM_INSTRUCTION_SIZE);
12187 int i;
12188 for (i = 0; i < VM_INSTRUCTION_SIZE; i++) {
12189 rb_ary_push(ary, rb_fstring_cstr(insn_name(i)));
12190 }
12191 return rb_ary_freeze(ary);
12192}
12193
12194static LABEL *
12195register_label(rb_iseq_t *iseq, struct st_table *labels_table, VALUE obj)
12196{
12197 LABEL *label = 0;
12198 st_data_t tmp;
12199 obj = rb_to_symbol_type(obj);
12200
12201 if (st_lookup(labels_table, obj, &tmp) == 0) {
12202 label = NEW_LABEL(0);
12203 st_insert(labels_table, obj, (st_data_t)label);
12204 }
12205 else {
12206 label = (LABEL *)tmp;
12207 }
12208 LABEL_REF(label);
12209 return label;
12210}
12211
12212static VALUE
12213get_exception_sym2type(VALUE sym)
12214{
12215 static VALUE symRescue, symEnsure, symRetry;
12216 static VALUE symBreak, symRedo, symNext;
12217
12218 if (symRescue == 0) {
12219 symRescue = ID2SYM(rb_intern_const("rescue"));
12220 symEnsure = ID2SYM(rb_intern_const("ensure"));
12221 symRetry = ID2SYM(rb_intern_const("retry"));
12222 symBreak = ID2SYM(rb_intern_const("break"));
12223 symRedo = ID2SYM(rb_intern_const("redo"));
12224 symNext = ID2SYM(rb_intern_const("next"));
12225 }
12226
12227 if (sym == symRescue) return CATCH_TYPE_RESCUE;
12228 if (sym == symEnsure) return CATCH_TYPE_ENSURE;
12229 if (sym == symRetry) return CATCH_TYPE_RETRY;
12230 if (sym == symBreak) return CATCH_TYPE_BREAK;
12231 if (sym == symRedo) return CATCH_TYPE_REDO;
12232 if (sym == symNext) return CATCH_TYPE_NEXT;
12233 rb_raise(rb_eSyntaxError, "invalid exception symbol: %+"PRIsVALUE, sym);
12234 return 0;
12235}
12236
12237static int
12238iseq_build_from_ary_exception(rb_iseq_t *iseq, struct st_table *labels_table,
12239 VALUE exception)
12240{
12241 int i;
12242
12243 for (i=0; i<RARRAY_LEN(exception); i++) {
12244 const rb_iseq_t *eiseq;
12245 VALUE v, type;
12246 LABEL *lstart, *lend, *lcont;
12247 unsigned int sp;
12248
12249 v = rb_to_array_type(RARRAY_AREF(exception, i));
12250 if (RARRAY_LEN(v) != 6) {
12251 rb_raise(rb_eSyntaxError, "wrong exception entry");
12252 }
12253 type = get_exception_sym2type(RARRAY_AREF(v, 0));
12254 if (NIL_P(RARRAY_AREF(v, 1))) {
12255 eiseq = NULL;
12256 }
12257 else {
12258 eiseq = rb_iseqw_to_iseq(rb_iseq_load(RARRAY_AREF(v, 1), (VALUE)iseq, Qnil));
12259 }
12260
12261 lstart = register_label(iseq, labels_table, RARRAY_AREF(v, 2));
12262 lend = register_label(iseq, labels_table, RARRAY_AREF(v, 3));
12263 lcont = register_label(iseq, labels_table, RARRAY_AREF(v, 4));
12264 sp = NUM2UINT(RARRAY_AREF(v, 5));
12265
12266 /* TODO: Dirty Hack! Fix me */
12267 if (type == CATCH_TYPE_RESCUE ||
12268 type == CATCH_TYPE_BREAK ||
12269 type == CATCH_TYPE_NEXT) {
12270 ++sp;
12271 }
12272
12273 lcont->sp = sp;
12274
12275 ADD_CATCH_ENTRY(type, lstart, lend, eiseq, lcont);
12276
12277 RB_GC_GUARD(v);
12278 }
12279 return COMPILE_OK;
12280}
12281
12282static struct st_table *
12283insn_make_insn_table(void)
12284{
12285 struct st_table *table;
12286 int i;
12287 table = st_init_numtable_with_size(VM_INSTRUCTION_SIZE);
12288
12289 for (i=0; i<VM_INSTRUCTION_SIZE; i++) {
12290 st_insert(table, ID2SYM(rb_intern_const(insn_name(i))), i);
12291 }
12292
12293 return table;
12294}
12295
12296static const rb_iseq_t *
12297iseq_build_load_iseq(const rb_iseq_t *iseq, VALUE op)
12298{
12299 VALUE iseqw;
12300 const rb_iseq_t *loaded_iseq;
12301
12302 if (RB_TYPE_P(op, T_ARRAY)) {
12303 iseqw = rb_iseq_load(op, (VALUE)iseq, Qnil);
12304 }
12305 else if (CLASS_OF(op) == rb_cISeq) {
12306 iseqw = op;
12307 }
12308 else {
12309 rb_raise(rb_eSyntaxError, "ISEQ is required");
12310 }
12311
12312 loaded_iseq = rb_iseqw_to_iseq(iseqw);
12313 return loaded_iseq;
12314}
12315
12316static VALUE
12317iseq_build_callinfo_from_hash(rb_iseq_t *iseq, VALUE op)
12318{
12319 ID mid = 0;
12320 int orig_argc = 0;
12321 unsigned int flag = 0;
12322 struct rb_callinfo_kwarg *kw_arg = 0;
12323
12324 if (!NIL_P(op)) {
12325 VALUE vmid = rb_hash_aref(op, ID2SYM(rb_intern_const("mid")));
12326 VALUE vflag = rb_hash_aref(op, ID2SYM(rb_intern_const("flag")));
12327 VALUE vorig_argc = rb_hash_aref(op, ID2SYM(rb_intern_const("orig_argc")));
12328 VALUE vkw_arg = rb_hash_aref(op, ID2SYM(rb_intern_const("kw_arg")));
12329
12330 if (!NIL_P(vmid)) mid = SYM2ID(vmid);
12331 if (!NIL_P(vflag)) flag = NUM2UINT(vflag);
12332 if (!NIL_P(vorig_argc)) orig_argc = FIX2INT(vorig_argc);
12333
12334 if (!NIL_P(vkw_arg)) {
12335 int i;
12336 int len = RARRAY_LENINT(vkw_arg);
12337 size_t n = rb_callinfo_kwarg_bytes(len);
12338
12339 kw_arg = xmalloc(n);
12340 kw_arg->references = 0;
12341 kw_arg->keyword_len = len;
12342 for (i = 0; i < len; i++) {
12343 VALUE kw = RARRAY_AREF(vkw_arg, i);
12344 SYM2ID(kw); /* make immortal */
12345 kw_arg->keywords[i] = kw;
12346 }
12347 }
12348 }
12349
12350 const struct rb_callinfo *ci = new_callinfo(iseq, mid, orig_argc, flag, kw_arg, (flag & VM_CALL_ARGS_SIMPLE) == 0);
12351 RB_OBJ_WRITTEN(iseq, Qundef, ci);
12352 return (VALUE)ci;
12353}
12354
12355static rb_event_flag_t
12356event_name_to_flag(VALUE sym)
12357{
12358#define CHECK_EVENT(ev) if (sym == ID2SYM(rb_intern_const(#ev))) return ev;
12359 CHECK_EVENT(RUBY_EVENT_LINE);
12360 CHECK_EVENT(RUBY_EVENT_CLASS);
12361 CHECK_EVENT(RUBY_EVENT_END);
12362 CHECK_EVENT(RUBY_EVENT_CALL);
12363 CHECK_EVENT(RUBY_EVENT_RETURN);
12364 CHECK_EVENT(RUBY_EVENT_B_CALL);
12365 CHECK_EVENT(RUBY_EVENT_B_RETURN);
12366 CHECK_EVENT(RUBY_EVENT_RESCUE);
12367#undef CHECK_EVENT
12368 return RUBY_EVENT_NONE;
12369}
12370
12371static int
12372iseq_build_from_ary_body(rb_iseq_t *iseq, LINK_ANCHOR *const anchor,
12373 VALUE body, VALUE node_ids, VALUE labels_wrapper)
12374{
12375 /* TODO: body should be frozen */
12376 rb_len_t i, len = RARRAY_LEN(body);
12377 struct st_table *labels_table = RTYPEDDATA_DATA(labels_wrapper);
12378 int j;
12379 int line_no = 0, node_id = -1, insn_idx = 0;
12380 int ret = COMPILE_OK;
12381
12382 /*
12383 * index -> LABEL *label
12384 */
12385 static struct st_table *insn_table;
12386
12387 if (insn_table == 0) {
12388 insn_table = insn_make_insn_table();
12389 }
12390
12391 for (i=0; i<len; i++) {
12392 VALUE obj = RARRAY_AREF(body, i);
12393
12394 if (SYMBOL_P(obj)) {
12395 rb_event_flag_t event;
12396 if ((event = event_name_to_flag(obj)) != RUBY_EVENT_NONE) {
12397 ADD_TRACE(anchor, event);
12398 }
12399 else {
12400 LABEL *label = register_label(iseq, labels_table, obj);
12401 ADD_LABEL(anchor, label);
12402 }
12403 }
12404 else if (FIXNUM_P(obj)) {
12405 line_no = NUM2INT(obj);
12406 }
12407 else if (RB_TYPE_P(obj, T_ARRAY)) {
12408 VALUE *argv = 0;
12409 int argc = RARRAY_LENINT(obj) - 1;
12410 st_data_t insn_id;
12411 VALUE insn;
12412
12413 if (node_ids) {
12414 node_id = NUM2INT(rb_ary_entry(node_ids, insn_idx++));
12415 }
12416
12417 insn = (argc < 0) ? Qnil : RARRAY_AREF(obj, 0);
12418 if (st_lookup(insn_table, (st_data_t)insn, &insn_id) == 0) {
12419 /* TODO: exception */
12420 COMPILE_ERROR(iseq, line_no,
12421 "unknown instruction: %+"PRIsVALUE, insn);
12422 ret = COMPILE_NG;
12423 break;
12424 }
12425
12426 if (argc != insn_len((VALUE)insn_id)-1) {
12427 COMPILE_ERROR(iseq, line_no,
12428 "operand size mismatch");
12429 ret = COMPILE_NG;
12430 break;
12431 }
12432
12433 if (argc > 0) {
12434 argv = compile_data_calloc2_type(iseq, VALUE, argc);
12435
12436 // add element before operand setup to make GC root
12437 ADD_ELEM(anchor,
12438 (LINK_ELEMENT*)new_insn_core(iseq, line_no, node_id,
12439 (enum ruby_vminsn_type)insn_id, argc, argv));
12440
12441 for (j=0; j<argc; j++) {
12442 VALUE op = rb_ary_entry(obj, j+1);
12443 switch (insn_op_type((VALUE)insn_id, j)) {
12444 case TS_OFFSET: {
12445 LABEL *label = register_label(iseq, labels_table, op);
12446 argv[j] = (VALUE)label;
12447 break;
12448 }
12449 case TS_LINDEX:
12450 case TS_NUM:
12451 (void)NUM2INT(op);
12452 argv[j] = op;
12453 break;
12454 case TS_VALUE:
12455 if (insn_id == BIN(once)) op = rb_imemo_once_storage_new();
12456 argv[j] = op;
12457 RB_OBJ_WRITTEN(iseq, Qundef, op);
12458 break;
12459 case TS_ISEQ:
12460 {
12461 if (op != Qnil) {
12462 VALUE v = (VALUE)iseq_build_load_iseq(iseq, op);
12463 argv[j] = v;
12464 RB_OBJ_WRITTEN(iseq, Qundef, v);
12465 }
12466 else {
12467 argv[j] = 0;
12468 }
12469 }
12470 break;
12471 case TS_IC:
12472 {
12473 VALUE segments = rb_ary_new();
12474 op = rb_to_array_type(op);
12475
12476 for (int i = 0; i < RARRAY_LEN(op); i++) {
12477 VALUE sym = RARRAY_AREF(op, i);
12478 sym = rb_to_symbol_type(sym);
12479 rb_ary_push(segments, sym);
12480 }
12481
12482 rb_const_path_t const_path = rb_const_path_from_array(segments);
12483 argv[j] = (VALUE)const_path;
12484 RB_GC_GUARD(op);
12485 RB_GC_GUARD(segments);
12486 ISEQ_BODY(iseq)->ic_size++;
12487 }
12488 break;
12489 case TS_IVC: /* inline ivar cache */
12490 argv[j] = op;
12491 if (NUM2UINT(op) >= ISEQ_BODY(iseq)->ivc_size) {
12492 ISEQ_BODY(iseq)->ivc_size = NUM2INT(op) + 1;
12493 }
12494 break;
12495 case TS_ICVARC: /* inline cvar cache */
12496 argv[j] = op;
12497 if (NUM2UINT(op) >= ISEQ_BODY(iseq)->icvarc_size) {
12498 ISEQ_BODY(iseq)->icvarc_size = NUM2INT(op) + 1;
12499 }
12500 break;
12501 case TS_CALLDATA:
12502 argv[j] = iseq_build_callinfo_from_hash(iseq, op);
12503 break;
12504 case TS_ID:
12505 argv[j] = rb_to_symbol_type(op);
12506 break;
12507 case TS_CDHASH:
12508 {
12509 int i;
12510 VALUE map = cdhash_new(RARRAY_LEN(op) / 2);
12511
12512 op = rb_to_array_type(op);
12513 for (i=0; i<RARRAY_LEN(op); i+=2) {
12514 VALUE key = RARRAY_AREF(op, i);
12515 VALUE sym = RARRAY_AREF(op, i+1);
12516 LABEL *label =
12517 register_label(iseq, labels_table, sym);
12518 cdhash_aset(map, key, (VALUE)label);
12519 }
12520 RB_GC_GUARD(op);
12521 RB_OBJ_SET_SHAREABLE(map); // allow mutation while compiling
12522 argv[j] = map;
12523 RB_OBJ_WRITTEN(iseq, Qundef, map);
12524 }
12525 break;
12526 case TS_FUNCPTR:
12527 {
12528#if SIZEOF_VALUE <= SIZEOF_LONG
12529 long funcptr = NUM2LONG(op);
12530#else
12531 LONG_LONG funcptr = NUM2LL(op);
12532#endif
12533 argv[j] = (VALUE)funcptr;
12534 }
12535 break;
12536 default:
12537 rb_raise(rb_eSyntaxError, "unknown operand: %c", insn_op_type((VALUE)insn_id, j));
12538 }
12539 }
12540 }
12541 else {
12542 ADD_ELEM(anchor,
12543 (LINK_ELEMENT*)new_insn_core(iseq, line_no, node_id,
12544 (enum ruby_vminsn_type)insn_id, argc, NULL));
12545 }
12546 }
12547 else {
12548 rb_raise(rb_eTypeError, "unexpected object for instruction");
12549 }
12550 }
12551 RTYPEDDATA_DATA(labels_wrapper) = 0;
12552 RB_GC_GUARD(labels_wrapper);
12553 validate_labels(iseq, labels_table);
12554 if (!ret) return ret;
12555 return iseq_setup(iseq, anchor);
12556}
12557
12558#define CHECK_ARRAY(v) rb_to_array_type(v)
12559#define CHECK_SYMBOL(v) rb_to_symbol_type(v)
12560
12561static int
12562int_param(int *dst, VALUE param, VALUE sym)
12563{
12564 VALUE val = rb_hash_aref(param, sym);
12565 if (FIXNUM_P(val)) {
12566 *dst = FIX2INT(val);
12567 return TRUE;
12568 }
12569 else if (!NIL_P(val)) {
12570 rb_raise(rb_eTypeError, "invalid %+"PRIsVALUE" Fixnum: %+"PRIsVALUE,
12571 sym, val);
12572 }
12573 return FALSE;
12574}
12575
12576static const struct rb_iseq_param_keyword *
12577iseq_build_kw(rb_iseq_t *iseq, VALUE params, VALUE keywords)
12578{
12579 int i, j;
12580 int len = RARRAY_LENINT(keywords);
12581 int default_len;
12582 VALUE key, sym, default_val;
12583 VALUE *dvs;
12584 ID *ids;
12585 struct rb_iseq_param_keyword *keyword = ZALLOC(struct rb_iseq_param_keyword);
12586
12587 ISEQ_BODY(iseq)->param.flags.has_kw = TRUE;
12588
12589 keyword->num = len;
12590#define SYM(s) ID2SYM(rb_intern_const(#s))
12591 (void)int_param(&keyword->bits_start, params, SYM(kwbits));
12592 i = keyword->bits_start - keyword->num;
12593 ids = (ID *)&ISEQ_BODY(iseq)->local_table[i];
12594#undef SYM
12595
12596 /* required args */
12597 for (i = 0; i < len; i++) {
12598 VALUE val = RARRAY_AREF(keywords, i);
12599
12600 if (!SYMBOL_P(val)) {
12601 goto default_values;
12602 }
12603 ids[i] = SYM2ID(val);
12604 keyword->required_num++;
12605 }
12606
12607 default_values: /* note: we intentionally preserve `i' from previous loop */
12608 default_len = len - i;
12609 if (default_len == 0) {
12610 keyword->table = ids;
12611 return keyword;
12612 }
12613 else if (default_len < 0) {
12615 }
12616
12617 dvs = ALLOC_N(VALUE, (unsigned int)default_len);
12618
12619 for (j = 0; i < len; i++, j++) {
12620 key = RARRAY_AREF(keywords, i);
12621 CHECK_ARRAY(key);
12622
12623 switch (RARRAY_LEN(key)) {
12624 case 1:
12625 sym = RARRAY_AREF(key, 0);
12626 default_val = Qundef;
12627 break;
12628 case 2:
12629 sym = RARRAY_AREF(key, 0);
12630 default_val = RARRAY_AREF(key, 1);
12631 break;
12632 default:
12633 rb_raise(rb_eTypeError, "keyword default has unsupported len %+"PRIsVALUE, key);
12634 }
12635 ids[i] = SYM2ID(sym);
12636 RB_OBJ_WRITE(iseq, &dvs[j], default_val);
12637 }
12638
12639 keyword->table = ids;
12640 keyword->default_values = dvs;
12641
12642 return keyword;
12643}
12644
12645static void
12646iseq_insn_each_object_mark_and_move(VALUE * obj, VALUE _)
12647{
12648 rb_gc_mark_and_move(obj);
12649}
12650
12651void
12652rb_iseq_mark_and_move_insn_storage(struct iseq_compile_data_storage *storage)
12653{
12654 INSN *iobj = 0;
12655 size_t size = sizeof(INSN);
12656 size_t align = ALIGNMENT_SIZE_OF(INSN);
12657 unsigned int pos = 0;
12658
12659 while (storage) {
12660 size_t padding = calc_padding((void *)&storage->buff[pos], align);
12661 size_t offset = pos + size + padding;
12662 if (offset > storage->size || offset > storage->pos) {
12663 pos = 0;
12664 storage = storage->next;
12665 }
12666 else {
12667 pos += (int)padding;
12668
12669 iobj = (INSN *)&storage->buff[pos];
12670
12671 if (iobj->operands) {
12672 iseq_insn_each_markable_object(iobj, iseq_insn_each_object_mark_and_move, (VALUE)0);
12673 }
12674 pos += (int)size;
12675 }
12676 }
12677}
12678
12679static const rb_data_type_t labels_wrapper_type = {
12680 .wrap_struct_name = "compiler/labels_wrapper",
12681 .function = {
12682 .dmark = (RUBY_DATA_FUNC)rb_mark_set,
12683 .dfree = (RUBY_DATA_FUNC)st_free_table,
12684 },
12685 .flags = RUBY_TYPED_THREAD_SAFE_FREE | RUBY_TYPED_WB_PROTECTED,
12686};
12687
12688void
12689rb_iseq_build_from_ary(rb_iseq_t *iseq, VALUE misc, VALUE locals, VALUE params,
12690 VALUE exception, VALUE body)
12691{
12692#define SYM(s) ID2SYM(rb_intern_const(#s))
12693 int i, len;
12694 unsigned int arg_size, local_size, stack_max;
12695 ID *tbl;
12696 struct st_table *labels_table = st_init_numtable();
12697 VALUE labels_wrapper = TypedData_Wrap_Struct(0, &labels_wrapper_type, labels_table);
12698 VALUE arg_opt_labels = rb_hash_aref(params, SYM(opt));
12699 VALUE keywords = rb_hash_aref(params, SYM(keyword));
12700 VALUE sym_arg_rest = ID2SYM(rb_intern_const("#arg_rest"));
12701 DECL_ANCHOR(anchor);
12702 INIT_ANCHOR(anchor);
12703
12704 len = RARRAY_LENINT(locals);
12705 ISEQ_BODY(iseq)->local_table_size = len;
12706 ISEQ_BODY(iseq)->local_table = tbl = len > 0 ? (ID *)ALLOC_N(ID, ISEQ_BODY(iseq)->local_table_size) : NULL;
12707
12708 for (i = 0; i < len; i++) {
12709 VALUE lv = RARRAY_AREF(locals, i);
12710
12711 if (sym_arg_rest == lv) {
12712 tbl[i] = 0;
12713 }
12714 else {
12715 tbl[i] = FIXNUM_P(lv) ? (ID)FIX2LONG(lv) : SYM2ID(CHECK_SYMBOL(lv));
12716 }
12717 }
12718
12719#define INT_PARAM(F) int_param(&ISEQ_BODY(iseq)->param.F, params, SYM(F))
12720 if (INT_PARAM(lead_num)) {
12721 ISEQ_BODY(iseq)->param.flags.has_lead = TRUE;
12722 }
12723 if (INT_PARAM(post_num)) ISEQ_BODY(iseq)->param.flags.has_post = TRUE;
12724 if (INT_PARAM(block_start)) ISEQ_BODY(iseq)->param.flags.has_block = TRUE;
12725#undef INT_PARAM
12726 if (Qtrue == rb_hash_aref(params, SYM(rest))) ISEQ_BODY(iseq)->param.flags.has_rest = TRUE;
12727 {
12728#define INT_PARAM(F) F = (int_param(&x, misc, SYM(F)) ? (unsigned int)x : 0)
12729 int x;
12730 INT_PARAM(arg_size);
12731 INT_PARAM(local_size);
12732 INT_PARAM(stack_max);
12733#undef INT_PARAM
12734 }
12735
12736 VALUE source_hash = rb_hash_aref(misc, ID2SYM(rb_intern("source_hash")));
12737 if (!NIL_P(source_hash)) {
12738 ISEQ_BODY(iseq)->source_hash = NUM2ULL(source_hash);
12739 }
12740
12741 VALUE node_ids = Qfalse;
12742 node_ids = rb_hash_aref(misc, ID2SYM(rb_intern("node_ids")));
12743 if (!RB_TYPE_P(node_ids, T_ARRAY)) {
12744 rb_raise(rb_eTypeError, "node_ids is not an array");
12745 }
12746
12747 if (RB_TYPE_P(arg_opt_labels, T_ARRAY)) {
12748 len = RARRAY_LENINT(arg_opt_labels);
12749 ISEQ_BODY(iseq)->param.flags.has_opt = !!(len - 1 >= 0);
12750
12751 if (ISEQ_BODY(iseq)->param.flags.has_opt) {
12752 VALUE *opt_table = ALLOC_N(VALUE, len);
12753
12754 for (i = 0; i < len; i++) {
12755 VALUE ent = RARRAY_AREF(arg_opt_labels, i);
12756 LABEL *label = register_label(iseq, labels_table, ent);
12757 opt_table[i] = (VALUE)label;
12758 }
12759
12760 ISEQ_BODY(iseq)->param.opt_num = len - 1;
12761 ISEQ_BODY(iseq)->param.opt_table = opt_table;
12762 }
12763 }
12764 else if (!NIL_P(arg_opt_labels)) {
12765 rb_raise(rb_eTypeError, ":opt param is not an array: %+"PRIsVALUE,
12766 arg_opt_labels);
12767 }
12768
12769 if (RB_TYPE_P(keywords, T_ARRAY)) {
12770 ISEQ_BODY(iseq)->param.keyword = iseq_build_kw(iseq, params, keywords);
12771 }
12772 else if (!NIL_P(keywords)) {
12773 rb_raise(rb_eTypeError, ":keywords param is not an array: %+"PRIsVALUE,
12774 keywords);
12775 }
12776
12777 if (Qtrue == rb_hash_aref(params, SYM(ambiguous_param0))) {
12778 ISEQ_BODY(iseq)->param.flags.ambiguous_param0 = TRUE;
12779 }
12780
12781 if (Qtrue == rb_hash_aref(params, SYM(use_block))) {
12782 ISEQ_BODY(iseq)->param.flags.use_block = TRUE;
12783 }
12784
12785 if (int_param(&i, params, SYM(kwrest))) {
12786 struct rb_iseq_param_keyword *keyword = (struct rb_iseq_param_keyword *)ISEQ_BODY(iseq)->param.keyword;
12787 if (keyword == NULL) {
12788 ISEQ_BODY(iseq)->param.keyword = keyword = ZALLOC(struct rb_iseq_param_keyword);
12789 }
12790 keyword->rest_start = i;
12791 ISEQ_BODY(iseq)->param.flags.has_kwrest = TRUE;
12792 }
12793#undef SYM
12794 iseq_calc_param_size(iseq);
12795
12796 /* exception */
12797 iseq_build_from_ary_exception(iseq, labels_table, exception);
12798
12799 /* body */
12800 iseq_build_from_ary_body(iseq, anchor, body, node_ids, labels_wrapper);
12801
12802 ISEQ_BODY(iseq)->param.size = arg_size;
12803 ISEQ_BODY(iseq)->local_table_size = local_size;
12804 ISEQ_BODY(iseq)->stack_max = stack_max;
12805}
12806
12807/* for parser */
12808
12809int
12810rb_dvar_defined(ID id, const rb_iseq_t *iseq)
12811{
12812 if (iseq) {
12813 const struct rb_iseq_constant_body *body = ISEQ_BODY(iseq);
12814 while (body->type == ISEQ_TYPE_BLOCK ||
12815 body->type == ISEQ_TYPE_RESCUE ||
12816 body->type == ISEQ_TYPE_ENSURE ||
12817 body->type == ISEQ_TYPE_EVAL ||
12818 body->type == ISEQ_TYPE_MAIN
12819 ) {
12820 unsigned int i;
12821
12822 for (i = 0; i < body->local_table_size; i++) {
12823 if (body->local_table[i] == id) {
12824 return 1;
12825 }
12826 }
12827 iseq = body->parent_iseq;
12828 body = ISEQ_BODY(iseq);
12829 }
12830 }
12831 return 0;
12832}
12833
12834int
12835rb_local_defined(ID id, const rb_iseq_t *iseq)
12836{
12837 if (iseq) {
12838 unsigned int i;
12839 const struct rb_iseq_constant_body *const body = ISEQ_BODY(ISEQ_BODY(iseq)->local_iseq);
12840
12841 for (i=0; i<body->local_table_size; i++) {
12842 if (body->local_table[i] == id) {
12843 return 1;
12844 }
12845 }
12846 }
12847 return 0;
12848}
12849
12850/* ISeq binary format */
12851
12852#ifndef IBF_ISEQ_DEBUG
12853#define IBF_ISEQ_DEBUG 0
12854#endif
12855
12856#ifndef IBF_ISEQ_ENABLE_LOCAL_BUFFER
12857#define IBF_ISEQ_ENABLE_LOCAL_BUFFER 0
12858#endif
12859
12860typedef uint32_t ibf_offset_t;
12861#define IBF_OFFSET(ptr) ((ibf_offset_t)(VALUE)(ptr))
12862
12863#define IBF_MAJOR_VERSION ISEQ_MAJOR_VERSION
12864#ifdef RUBY_DEVEL
12865#define IBF_DEVEL_VERSION 15
12866#define IBF_MINOR_VERSION (ISEQ_MINOR_VERSION * 10000 + IBF_DEVEL_VERSION)
12867#else
12868#define IBF_MINOR_VERSION ISEQ_MINOR_VERSION
12869#endif
12870
12871static const char IBF_ENDIAN_MARK =
12872#ifdef WORDS_BIGENDIAN
12873 'b'
12874#else
12875 'l'
12876#endif
12877 ;
12878
12880 char magic[4]; /* YARB */
12881 uint32_t major_version;
12882 uint32_t minor_version;
12883 uint32_t size;
12884 uint32_t extra_size;
12885
12886 uint32_t iseq_list_size;
12887 uint32_t global_object_list_size;
12888 ibf_offset_t iseq_list_offset;
12889 ibf_offset_t global_object_list_offset;
12890 uint8_t endian;
12891 uint8_t wordsize; /* assume no 2048-bit CPU */
12892};
12893
12895 VALUE str;
12896 st_table *obj_table; /* obj -> obj number */
12897};
12898
12899struct ibf_dump {
12900 st_table *iseq_table; /* iseq -> iseq number */
12901 struct ibf_dump_buffer global_buffer;
12902 struct ibf_dump_buffer *current_buffer;
12903};
12904
12906 const char *buff;
12907 ibf_offset_t size;
12908
12909 VALUE obj_list; /* [obj0, ...] */
12910 unsigned int obj_list_size;
12911 ibf_offset_t obj_list_offset;
12912};
12913
12914struct ibf_load {
12915 const struct ibf_header *header;
12916 VALUE iseq_list; /* [iseq0, ...] */
12917 struct ibf_load_buffer global_buffer;
12918 VALUE loader_obj;
12919 rb_iseq_t *iseq;
12920 VALUE str;
12921 VALUE path_override;
12922 VALUE realpath_override;
12923 struct ibf_load_buffer *current_buffer;
12924};
12925
12927 long size;
12928 VALUE buffer[1];
12929};
12930
12931static void
12932pinned_list_mark(void *ptr)
12933{
12934 long i;
12935 struct pinned_list *list = (struct pinned_list *)ptr;
12936 for (i = 0; i < list->size; i++) {
12937 if (list->buffer[i]) {
12938 rb_gc_mark(list->buffer[i]);
12939 }
12940 }
12941}
12942
12943static const rb_data_type_t pinned_list_type = {
12944 "pinned_list",
12945 {
12946 pinned_list_mark,
12948 NULL, // No external memory to report,
12949 },
12950 0, 0, RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_THREAD_SAFE_FREE | RUBY_TYPED_EMBEDDABLE
12951};
12952
12953static VALUE
12954pinned_list_fetch(VALUE list, long offset)
12955{
12956 struct pinned_list * ptr;
12957
12958 TypedData_Get_Struct(list, struct pinned_list, &pinned_list_type, ptr);
12959
12960 if (offset < 0 || offset >= ptr->size) {
12961 rb_raise(rb_eIndexError, "object index out of range: %ld", offset);
12962 }
12963
12964 return ptr->buffer[offset];
12965}
12966
12967static void
12968pinned_list_store(VALUE list, long offset, VALUE object)
12969{
12970 struct pinned_list * ptr;
12971
12972 TypedData_Get_Struct(list, struct pinned_list, &pinned_list_type, ptr);
12973
12974 if (offset < 0 || offset >= ptr->size) {
12975 rb_raise(rb_eIndexError, "object index out of range: %ld", offset);
12976 }
12977
12978 RB_OBJ_WRITE(list, &ptr->buffer[offset], object);
12979}
12980
12981static VALUE
12982pinned_list_new(long size)
12983{
12984 size_t memsize = offsetof(struct pinned_list, buffer) + size * sizeof(VALUE);
12985 VALUE obj_list = rb_data_typed_object_zalloc(0, memsize, &pinned_list_type);
12986 struct pinned_list * ptr = RTYPEDDATA_GET_DATA(obj_list);
12987 ptr->size = size;
12988 return obj_list;
12989}
12990
12991static ibf_offset_t
12992ibf_dump_pos(struct ibf_dump *dump)
12993{
12994 rb_len_t pos = RSTRING_LEN(dump->current_buffer->str);
12995#if SIZEOF_RB_LEN_T > SIZEOF_INT
12996 if (pos >= UINT_MAX) {
12997 rb_raise(rb_eRuntimeError, "dump size exceeds");
12998 }
12999#endif
13000 return (unsigned int)pos;
13001}
13002
13003static void
13004ibf_dump_align(struct ibf_dump *dump, size_t align)
13005{
13006 ibf_offset_t pos = ibf_dump_pos(dump);
13007 if (pos % align) {
13008 static const char padding[sizeof(VALUE)];
13009 size_t size = align - ((size_t)pos % align);
13010#if SIZEOF_RB_LEN_T > SIZEOF_INT
13011 if (pos + size >= UINT_MAX) {
13012 rb_raise(rb_eRuntimeError, "dump size exceeds");
13013 }
13014#endif
13015 for (; size > sizeof(padding); size -= sizeof(padding)) {
13016 rb_str_cat(dump->current_buffer->str, padding, sizeof(padding));
13017 }
13018 rb_str_cat(dump->current_buffer->str, padding, size);
13019 }
13020}
13021
13022static ibf_offset_t
13023ibf_dump_write(struct ibf_dump *dump, const void *buff, size_t size)
13024{
13025 ibf_offset_t pos = ibf_dump_pos(dump);
13026#if SIZEOF_RB_LEN_T > SIZEOF_INT
13027 /* ensure the resulting dump does not exceed UINT_MAX */
13028 if (size >= UINT_MAX || pos + size >= UINT_MAX) {
13029 rb_raise(rb_eRuntimeError, "dump size exceeds");
13030 }
13031#endif
13032 rb_str_cat(dump->current_buffer->str, (const char *)buff, size);
13033 return pos;
13034}
13035
13036static ibf_offset_t
13037ibf_dump_write_byte(struct ibf_dump *dump, unsigned char byte)
13038{
13039 return ibf_dump_write(dump, &byte, sizeof(unsigned char));
13040}
13041
13042static void
13043ibf_dump_overwrite(struct ibf_dump *dump, void *buff, unsigned int size, rb_len_t offset)
13044{
13045 VALUE str = dump->current_buffer->str;
13046 char *ptr = RSTRING_PTR(str);
13047 if ((rb_ulen_t)(size + offset) > (rb_ulen_t)RSTRING_LEN(str))
13048 rb_bug("ibf_dump_overwrite: overflow");
13049 memcpy(ptr + offset, buff, size);
13050}
13051
13052static const void *
13053ibf_load_ptr(const struct ibf_load *load, ibf_offset_t *offset, int size)
13054{
13055 ibf_offset_t beg = *offset;
13056 *offset += size;
13057 return load->current_buffer->buff + beg;
13058}
13059
13060static void *
13061ibf_load_alloc(const struct ibf_load *load, ibf_offset_t offset, size_t x, size_t y)
13062{
13063 void *buff = ruby_xmalloc2(x, y);
13064 size_t size = x * y;
13065 memcpy(buff, load->current_buffer->buff + offset, size);
13066 return buff;
13067}
13068
13069#define IBF_W_ALIGN(type) (RUBY_ALIGNOF(type) > 1 ? ibf_dump_align(dump, RUBY_ALIGNOF(type)) : (void)0)
13070
13071#define IBF_W(b, type, n) (IBF_W_ALIGN(type), (type *)(VALUE)IBF_WP(b, type, n))
13072#define IBF_WV(variable) ibf_dump_write(dump, &(variable), sizeof(variable))
13073#define IBF_WP(b, type, n) ibf_dump_write(dump, (b), sizeof(type) * (n))
13074#define IBF_R(val, type, n) (type *)ibf_load_alloc(load, IBF_OFFSET(val), sizeof(type), (n))
13075#define IBF_ZERO(variable) memset(&(variable), 0, sizeof(variable))
13076
13077static int
13078ibf_table_lookup(struct st_table *table, st_data_t key)
13079{
13080 st_data_t val;
13081
13082 if (st_lookup(table, key, &val)) {
13083 return (int)val;
13084 }
13085 else {
13086 return -1;
13087 }
13088}
13089
13090static int
13091ibf_table_find_or_insert(struct st_table *table, st_data_t key)
13092{
13093 int index = ibf_table_lookup(table, key);
13094
13095 if (index < 0) { /* not found */
13096 index = (int)table->num_entries;
13097 st_insert(table, key, (st_data_t)index);
13098 }
13099
13100 return index;
13101}
13102
13103/* dump/load generic */
13104
13105static void ibf_dump_object_list(struct ibf_dump *dump, ibf_offset_t *obj_list_offset, unsigned int *obj_list_size);
13106
13107static VALUE ibf_load_object(const struct ibf_load *load, VALUE object_index);
13108static rb_iseq_t *ibf_load_iseq(const struct ibf_load *load, const rb_iseq_t *index_iseq);
13109
13110static st_table *
13111ibf_dump_object_table_new(void)
13112{
13113 st_table *obj_table = st_init_numtable(); /* need free */
13114 st_insert(obj_table, (st_data_t)Qnil, (st_data_t)0); /* 0th is nil */
13115
13116 return obj_table;
13117}
13118
13119static VALUE
13120ibf_dump_object(struct ibf_dump *dump, VALUE obj)
13121{
13122 return ibf_table_find_or_insert(dump->current_buffer->obj_table, (st_data_t)obj);
13123}
13124
13125static VALUE
13126ibf_dump_id(struct ibf_dump *dump, ID id)
13127{
13128 if (id == 0 || rb_id2name(id) == NULL) {
13129 return 0;
13130 }
13131 return ibf_dump_object(dump, rb_id2sym(id));
13132}
13133
13134static ID
13135ibf_load_id(const struct ibf_load *load, const ID id_index)
13136{
13137 if (id_index == 0) {
13138 return 0;
13139 }
13140 VALUE sym = ibf_load_object(load, id_index);
13141 if (rb_integer_type_p(sym)) {
13142 /* Load hidden local variables as indexes */
13143 return NUM2ULONG(sym);
13144 }
13145 return rb_sym2id(sym);
13146}
13147
13148/* dump/load: code */
13149
13150static ibf_offset_t ibf_dump_iseq_each(struct ibf_dump *dump, const rb_iseq_t *iseq);
13151
13152static int
13153ibf_dump_iseq(struct ibf_dump *dump, const rb_iseq_t *iseq)
13154{
13155 if (iseq == NULL) {
13156 return -1;
13157 }
13158 else {
13159 return ibf_table_find_or_insert(dump->iseq_table, (st_data_t)iseq);
13160 }
13161}
13162
13163static unsigned char
13164ibf_load_byte(const struct ibf_load *load, ibf_offset_t *offset)
13165{
13166 if (*offset >= load->current_buffer->size) { rb_raise(rb_eRuntimeError, "invalid bytecode"); }
13167 return (unsigned char)load->current_buffer->buff[(*offset)++];
13168}
13169
13170/*
13171 * Small uint serialization
13172 * 0x00000000_00000000 - 0x00000000_0000007f: 1byte | XXXX XXX1 |
13173 * 0x00000000_00000080 - 0x00000000_00003fff: 2byte | XXXX XX10 | XXXX XXXX |
13174 * 0x00000000_00004000 - 0x00000000_001fffff: 3byte | XXXX X100 | XXXX XXXX | XXXX XXXX |
13175 * 0x00000000_00020000 - 0x00000000_0fffffff: 4byte | XXXX 1000 | XXXX XXXX | XXXX XXXX | XXXX XXXX |
13176 * ...
13177 * 0x00010000_00000000 - 0x00ffffff_ffffffff: 8byte | 1000 0000 | XXXX XXXX | XXXX XXXX | XXXX XXXX | XXXX XXXX | XXXX XXXX | XXXX XXXX | XXXX XXXX |
13178 * 0x01000000_00000000 - 0xffffffff_ffffffff: 9byte | 0000 0000 | XXXX XXXX | XXXX XXXX | XXXX XXXX | XXXX XXXX | XXXX XXXX | XXXX XXXX | XXXX XXXX | XXXX XXXX |
13179 */
13180static void
13181ibf_dump_write_small_value(struct ibf_dump *dump, VALUE x)
13182{
13183 if (sizeof(VALUE) > 8 || CHAR_BIT != 8) {
13184 ibf_dump_write(dump, &x, sizeof(VALUE));
13185 return;
13186 }
13187
13188 enum { max_byte_length = sizeof(VALUE) + 1 };
13189
13190 unsigned char bytes[max_byte_length];
13191 ibf_offset_t n;
13192
13193 for (n = 0; n < sizeof(VALUE) && (x >> (7 - n)); n++, x >>= 8) {
13194 bytes[max_byte_length - 1 - n] = (unsigned char)x;
13195 }
13196
13197 x <<= 1;
13198 x |= 1;
13199 x <<= n;
13200 bytes[max_byte_length - 1 - n] = (unsigned char)x;
13201 n++;
13202
13203 ibf_dump_write(dump, bytes + max_byte_length - n, n);
13204}
13205
13206static VALUE
13207ibf_load_small_value(const struct ibf_load *load, ibf_offset_t *offset)
13208{
13209 if (sizeof(VALUE) > 8 || CHAR_BIT != 8) {
13210 union { char s[sizeof(VALUE)]; VALUE v; } x;
13211
13212 memcpy(x.s, load->current_buffer->buff + *offset, sizeof(VALUE));
13213 *offset += sizeof(VALUE);
13214
13215 return x.v;
13216 }
13217
13218 enum { max_byte_length = sizeof(VALUE) + 1 };
13219
13220 const unsigned char *buffer = (const unsigned char *)load->current_buffer->buff;
13221 const unsigned char c = buffer[*offset];
13222
13223 ibf_offset_t n =
13224 c & 1 ? 1 :
13225 c == 0 ? 9 : ntz_int32(c) + 1;
13226 VALUE x = (VALUE)c >> n;
13227
13228 if (*offset + n > load->current_buffer->size) {
13229 rb_raise(rb_eRuntimeError, "invalid byte sequence");
13230 }
13231
13232 ibf_offset_t i;
13233 for (i = 1; i < n; i++) {
13234 x <<= 8;
13235 x |= (VALUE)buffer[*offset + i];
13236 }
13237
13238 *offset += n;
13239 return x;
13240}
13241
13242static void
13243ibf_dump_builtin(struct ibf_dump *dump, const struct rb_builtin_function *bf)
13244{
13245 // short: index
13246 // short: name.length
13247 // bytes: name
13248 // // omit argc (only verify with name)
13249 ibf_dump_write_small_value(dump, (VALUE)bf->index);
13250
13251 size_t len = strlen(bf->name);
13252 ibf_dump_write_small_value(dump, (VALUE)len);
13253 ibf_dump_write(dump, bf->name, len);
13254}
13255
13256static const struct rb_builtin_function *
13257ibf_load_builtin(const struct ibf_load *load, ibf_offset_t *offset)
13258{
13259 int i = (int)ibf_load_small_value(load, offset);
13260 int len = (int)ibf_load_small_value(load, offset);
13261 const char *name = (char *)ibf_load_ptr(load, offset, len);
13262
13263 if (0) {
13264 fprintf(stderr, "%.*s!!\n", len, name);
13265 }
13266
13267 const struct rb_builtin_function *table = GET_VM()->builtin_function_table;
13268 if (table == NULL) rb_raise(rb_eArgError, "builtin function table is not provided");
13269 if (strncmp(table[i].name, name, len) != 0) {
13270 rb_raise(rb_eArgError, "builtin function index (%d) mismatch (expect %.*s but %s)",
13271 i, len, name, table[i].name);
13272 }
13273 // fprintf(stderr, "load-builtin: name:%s(%d)\n", table[i].name, table[i].argc);
13274
13275 return &table[i];
13276}
13277
13278static ibf_offset_t
13279ibf_dump_code(struct ibf_dump *dump, const rb_iseq_t *iseq)
13280{
13281 const struct rb_iseq_constant_body *const body = ISEQ_BODY(iseq);
13282 const int iseq_size = body->iseq_size;
13283 int code_index;
13284 const VALUE *orig_code = rb_iseq_original_iseq(iseq);
13285
13286 ibf_offset_t offset = ibf_dump_pos(dump);
13287
13288 for (code_index=0; code_index<iseq_size;) {
13289 const VALUE insn = orig_code[code_index++];
13290 const char *types = insn_op_types(insn);
13291 int op_index;
13292
13293 /* opcode */
13294 if (insn >= 0x100) { rb_raise(rb_eRuntimeError, "invalid instruction"); }
13295 ibf_dump_write_small_value(dump, insn);
13296
13297 /* operands */
13298 for (op_index=0; types[op_index]; op_index++, code_index++) {
13299 VALUE op = orig_code[code_index];
13300 VALUE wv;
13301
13302 switch (types[op_index]) {
13303 case TS_CDHASH:
13304 case TS_VALUE:
13305 wv = ibf_dump_object(dump, op);
13306 break;
13307 case TS_ISEQ:
13308 wv = (VALUE)ibf_dump_iseq(dump, (const rb_iseq_t *)op);
13309 break;
13310 case TS_IC:
13311 case TS_IVC:
13312 case TS_ICVARC:
13313 {
13315 wv = is - ISEQ_IS_ENTRY_START(body, types[op_index]);
13316 }
13317 break;
13318 case TS_CALLDATA:
13319 {
13320 goto skip_wv;
13321 }
13322 case TS_ID:
13323 wv = ibf_dump_id(dump, (ID)op);
13324 break;
13325 case TS_FUNCPTR:
13326 rb_raise(rb_eRuntimeError, "TS_FUNCPTR is not supported");
13327 goto skip_wv;
13328 case TS_BUILTIN:
13329 ibf_dump_builtin(dump, (const struct rb_builtin_function *)op);
13330 goto skip_wv;
13331 default:
13332 wv = op;
13333 break;
13334 }
13335 ibf_dump_write_small_value(dump, wv);
13336 skip_wv:;
13337 }
13338 RUBY_ASSERT(insn_len(insn) == op_index+1);
13339 }
13340
13341 return offset;
13342}
13343
13344static rb_const_path_t
13345ibf_load_const_path(const struct ibf_load *load, ibf_offset_t *reading_pos)
13346{
13347 size_t header = (size_t)ibf_load_small_value(load, reading_pos);
13348 bool absolute = header & 1;
13349 size_t size = header >> 1;
13350 if (size == 0) {
13351 rb_raise(rb_eRuntimeError, "broken binary format");
13352 }
13353
13354 VALUE buf_v = 0;
13355 ID *ids = ALLOCV_N(ID, buf_v, size);
13356 for (size_t i = 0; i < size; i++) {
13357 ids[i] = ibf_load_id(load, (ID)ibf_load_small_value(load, reading_pos));
13358 if (!is_notop_id(ids[i]) || !is_const_id(ids[i])) {
13359 rb_raise(rb_eRuntimeError, "broken binary format");
13360 }
13361 }
13362
13363 rb_const_path_t const_path = rb_const_path_from_ids(absolute, ids, size);
13364 ALLOCV_END(buf_v);
13365 return const_path;
13366}
13367
13368static VALUE *
13369ibf_load_code(const struct ibf_load *load, rb_iseq_t *iseq, ibf_offset_t bytecode_offset, ibf_offset_t bytecode_size, unsigned int iseq_size)
13370{
13371 VALUE iseqv = (VALUE)iseq;
13372 unsigned int code_index;
13373 ibf_offset_t reading_pos = bytecode_offset;
13374 VALUE *code = ZALLOC_N(VALUE, iseq_size);
13375
13376 struct rb_iseq_constant_body *load_body = ISEQ_BODY(iseq);
13377 struct rb_call_data *cd_entries = load_body->call_data;
13378
13379 load_body->iseq_encoded = code;
13380 load_body->iseq_size = iseq_size;
13381
13382 iseq_bits_t * mark_offset_bits;
13383 if (ISEQ_MBITS_BUFLEN(iseq_size) == 1) {
13384 load_body->mark_bits.single = 0;
13385 mark_offset_bits = &load_body->mark_bits.single;
13386 }
13387 else {
13388 load_body->mark_bits.list = ZALLOC_N(iseq_bits_t, ISEQ_MBITS_BUFLEN(iseq_size));
13389 mark_offset_bits = load_body->mark_bits.list;
13390 }
13391 bool needs_bitmap = false;
13392
13393 for (code_index=0; code_index<iseq_size;) {
13394 /* opcode */
13395 const VALUE insn = code[code_index] = ibf_load_small_value(load, &reading_pos);
13396 const char *types = insn_op_types(insn);
13397 int op_index;
13398
13399 code_index++;
13400
13401 /* operands */
13402 for (op_index=0; types[op_index]; op_index++, code_index++) {
13403 const char operand_type = types[op_index];
13404 switch (operand_type) {
13405 case TS_VALUE:
13406 {
13407 VALUE op = ibf_load_small_value(load, &reading_pos);
13408 VALUE v = ibf_load_object(load, op);
13409 code[code_index] = v;
13410 if (!SPECIAL_CONST_P(v)) {
13411 RB_OBJ_WRITTEN(iseqv, Qundef, v);
13412 ISEQ_MBITS_SET(mark_offset_bits, code_index);
13413 needs_bitmap = true;
13414 }
13415 break;
13416 }
13417 case TS_CDHASH:
13418 {
13419 VALUE op = ibf_load_small_value(load, &reading_pos);
13420 VALUE v = ibf_load_object(load, op);
13421
13422 // Overwrite the existing hash in the object list. This
13423 // is to keep the object alive during load time.
13424 // [Bug #17984] [ruby-core:104259]
13425 pinned_list_store(load->current_buffer->obj_list, (long)op, v);
13426
13427 code[code_index] = v;
13428 ISEQ_MBITS_SET(mark_offset_bits, code_index);
13429 RB_OBJ_WRITTEN(iseqv, Qundef, v);
13430 needs_bitmap = true;
13431 break;
13432 }
13433 case TS_ISEQ:
13434 {
13435 VALUE op = (VALUE)ibf_load_small_value(load, &reading_pos);
13436 VALUE v = (VALUE)ibf_load_iseq(load, (const rb_iseq_t *)op);
13437 code[code_index] = v;
13438 if (!SPECIAL_CONST_P(v)) {
13439 RB_OBJ_WRITTEN(iseqv, Qundef, v);
13440 ISEQ_MBITS_SET(mark_offset_bits, code_index);
13441 needs_bitmap = true;
13442 }
13443 break;
13444 }
13445 case TS_IC:
13446 case TS_ICVARC:
13447 case TS_IVC:
13448 {
13449 unsigned int op = (unsigned int)ibf_load_small_value(load, &reading_pos);
13450
13451 union iseq_inline_storage_entry *ic = ISEQ_IS_ENTRY_START(load_body, operand_type) + op;
13452 code[code_index] = (VALUE)ic;
13453
13454 if (operand_type == TS_IVC) {
13455 IVC cache = (IVC)ic;
13456
13457 if (insn == BIN(setinstancevariable)) {
13458 ID iv_name = (ID)code[code_index - 1];
13459 cache->iv_set_name = iv_name;
13460 cache->value = IVAR_CACHE_INIT;
13461 }
13462 else {
13463 cache->iv_set_name = 0;
13464 cache->value = rb_getivar_cache_pack(ROOT_SHAPE_ID, ATTR_INDEX_NOT_SET);
13465 }
13466 }
13467
13468 }
13469 break;
13470 case TS_CALLDATA:
13471 {
13472 code[code_index] = (VALUE)cd_entries++;
13473 }
13474 break;
13475 case TS_ID:
13476 {
13477 VALUE op = ibf_load_small_value(load, &reading_pos);
13478 code[code_index] = ibf_load_id(load, (ID)(VALUE)op);
13479 }
13480 break;
13481 case TS_FUNCPTR:
13482 rb_raise(rb_eRuntimeError, "TS_FUNCPTR is not supported");
13483 break;
13484 case TS_BUILTIN:
13485 code[code_index] = (VALUE)ibf_load_builtin(load, &reading_pos);
13486 break;
13487 default:
13488 code[code_index] = ibf_load_small_value(load, &reading_pos);
13489 continue;
13490 }
13491 }
13492 if (insn_len(insn) != op_index+1) {
13493 rb_raise(rb_eRuntimeError, "operand size mismatch");
13494 }
13495 }
13496
13497 if (!needs_bitmap) {
13498 SIZED_FREE_N(load_body->mark_bits.list, ISEQ_MBITS_BUFLEN(iseq_size));
13499 load_body->mark_bits.list = NULL;
13500 }
13501
13502 RUBY_ASSERT(code_index == iseq_size);
13503 RUBY_ASSERT(reading_pos == bytecode_offset + bytecode_size);
13504 return code;
13505}
13506
13507static ibf_offset_t
13508ibf_dump_param_opt_table(struct ibf_dump *dump, const rb_iseq_t *iseq)
13509{
13510 int opt_num = ISEQ_BODY(iseq)->param.opt_num;
13511
13512 if (opt_num > 0) {
13513 IBF_W_ALIGN(VALUE);
13514 return ibf_dump_write(dump, ISEQ_BODY(iseq)->param.opt_table, sizeof(VALUE) * (opt_num + 1));
13515 }
13516 else {
13517 return ibf_dump_pos(dump);
13518 }
13519}
13520
13521static VALUE *
13522ibf_load_param_opt_table(const struct ibf_load *load, ibf_offset_t opt_table_offset, int opt_num)
13523{
13524 if (opt_num > 0) {
13525 VALUE *table = ALLOC_N(VALUE, opt_num+1);
13526 MEMCPY(table, load->current_buffer->buff + opt_table_offset, VALUE, opt_num+1);
13527 return table;
13528 }
13529 else {
13530 return NULL;
13531 }
13532}
13533
13534static ibf_offset_t
13535ibf_dump_param_keyword(struct ibf_dump *dump, const rb_iseq_t *iseq)
13536{
13537 const struct rb_iseq_param_keyword *kw = ISEQ_BODY(iseq)->param.keyword;
13538
13539 if (kw) {
13540 struct rb_iseq_param_keyword dump_kw = *kw;
13541 int dv_num = kw->num - kw->required_num;
13542 ID *ids = kw->num > 0 ? ALLOCA_N(ID, kw->num) : NULL;
13543 VALUE *dvs = dv_num > 0 ? ALLOCA_N(VALUE, dv_num) : NULL;
13544 int i;
13545
13546 for (i=0; i<kw->num; i++) ids[i] = (ID)ibf_dump_id(dump, kw->table[i]);
13547 for (i=0; i<dv_num; i++) dvs[i] = (VALUE)ibf_dump_object(dump, kw->default_values[i]);
13548
13549 dump_kw.table = IBF_W(ids, ID, kw->num);
13550 dump_kw.default_values = IBF_W(dvs, VALUE, dv_num);
13551 IBF_W_ALIGN(struct rb_iseq_param_keyword);
13552 return ibf_dump_write(dump, &dump_kw, sizeof(struct rb_iseq_param_keyword) * 1);
13553 }
13554 else {
13555 return 0;
13556 }
13557}
13558
13559static const struct rb_iseq_param_keyword *
13560ibf_load_param_keyword(const struct ibf_load *load, ibf_offset_t param_keyword_offset)
13561{
13562 if (param_keyword_offset) {
13563 struct rb_iseq_param_keyword *kw = IBF_R(param_keyword_offset, struct rb_iseq_param_keyword, 1);
13564 int dv_num = kw->num - kw->required_num;
13565 VALUE *dvs = dv_num ? IBF_R(kw->default_values, VALUE, dv_num) : NULL;
13566
13567 int i;
13568 for (i=0; i<dv_num; i++) {
13569 dvs[i] = ibf_load_object(load, dvs[i]);
13570 }
13571
13572 // Will be set once the local table is loaded.
13573 kw->table = NULL;
13574
13575 kw->default_values = dvs;
13576 return kw;
13577 }
13578 else {
13579 return NULL;
13580 }
13581}
13582
13583static ibf_offset_t
13584ibf_dump_insns_info_body(struct ibf_dump *dump, const rb_iseq_t *iseq)
13585{
13586 ibf_offset_t offset = ibf_dump_pos(dump);
13587 const struct rb_iseq_constant_body *body = ISEQ_BODY(iseq);
13588 const struct iseq_insn_info *info = body->insns_info;
13589 const struct iseq_insn_info_entry *entries = info->entries;
13590
13591 ibf_dump_write_small_value(dump, info->node_ids_size);
13592 unsigned int i;
13593 for (i = 0; i < info->size; i++) {
13594 ibf_dump_write_small_value(dump, entries[i].line_no);
13595 ibf_dump_write_small_value(dump, entries[i].events);
13596 }
13597 ibf_dump_write(dump, rb_iseq_insn_info_node_ids(info), info->node_ids_size);
13598
13599 return offset;
13600}
13601
13602static ibf_offset_t
13603ibf_dump_insns_info_positions(struct ibf_dump *dump, const unsigned int *positions, unsigned int size)
13604{
13605 ibf_offset_t offset = ibf_dump_pos(dump);
13606
13607 unsigned int last = 0;
13608 unsigned int i;
13609 for (i = 0; i < size; i++) {
13610 ibf_dump_write_small_value(dump, positions[i] - last);
13611 last = positions[i];
13612 }
13613
13614 return offset;
13615}
13616
13617static const struct iseq_insn_info *
13618ibf_load_insns_info(const struct ibf_load *load, ibf_offset_t body_offset, ibf_offset_t positions_offset,
13619 unsigned int size, unsigned int iseq_size)
13620{
13621 VALUE entries_buf, positions_buf;
13622 struct iseq_insn_info_entry *entries = ALLOCV_N(struct iseq_insn_info_entry, entries_buf, size);
13623 unsigned int *positions = ALLOCV_N(unsigned int, positions_buf, size);
13624
13625 ibf_offset_t reading_pos = body_offset;
13626 const unsigned int node_ids_size = (unsigned int)ibf_load_small_value(load, &reading_pos);
13627 for (unsigned int i = 0; i < size; i++) {
13628 entries[i].line_no = (int)ibf_load_small_value(load, &reading_pos);
13629 entries[i].events = (rb_event_flag_t)ibf_load_small_value(load, &reading_pos);
13630 }
13631 if (node_ids_size == 0 || node_ids_size > load->current_buffer->size - reading_pos) {
13632 rb_raise(rb_eRuntimeError, "invalid byte sequence");
13633 }
13634 const uint8_t *node_ids = (const uint8_t *)load->current_buffer->buff + reading_pos;
13635
13636 reading_pos = positions_offset;
13637 unsigned int last = 0;
13638 for (unsigned int i = 0; i < size; i++) {
13639 positions[i] = last + (unsigned int)ibf_load_small_value(load, &reading_pos);
13640 last = positions[i];
13641 }
13642
13643 const struct iseq_insn_info *info = rb_iseq_insn_info_new(iseq_size, entries, positions, size, node_ids, node_ids_size);
13644
13645 ALLOCV_END(entries_buf);
13646 ALLOCV_END(positions_buf);
13647 return info;
13648}
13649
13650static ibf_offset_t
13651ibf_dump_local_table(struct ibf_dump *dump, const rb_iseq_t *iseq)
13652{
13653 const struct rb_iseq_constant_body *const body = ISEQ_BODY(iseq);
13654 const int size = body->local_table_size;
13655 ID *table = ALLOCA_N(ID, size);
13656 int i;
13657
13658 for (i=0; i<size; i++) {
13659 VALUE v = ibf_dump_id(dump, body->local_table[i]);
13660 if (v == 0) {
13661 /* Dump hidden local variables as indexes, so load_from_binary will work with them */
13662 v = ibf_dump_object(dump, ULONG2NUM(body->local_table[i]));
13663 }
13664 table[i] = v;
13665 }
13666
13667 IBF_W_ALIGN(ID);
13668 return ibf_dump_write(dump, table, sizeof(ID) * size);
13669}
13670
13671static const ID *
13672ibf_load_local_table(const struct ibf_load *load, ibf_offset_t local_table_offset, int size)
13673{
13674 if (size > 0) {
13675 ID *table = IBF_R(local_table_offset, ID, size);
13676 int i;
13677
13678 for (i=0; i<size; i++) {
13679 table[i] = ibf_load_id(load, table[i]);
13680 }
13681
13682 if (size == 1 && table[0] == idERROR_INFO) {
13683 ruby_xfree_sized(table, sizeof(ID) * size);
13684 return rb_iseq_shared_exc_local_tbl;
13685 }
13686 else {
13687 return table;
13688 }
13689 }
13690 else {
13691 return NULL;
13692 }
13693}
13694
13695static ibf_offset_t
13696ibf_dump_lvar_states(struct ibf_dump *dump, const rb_iseq_t *iseq)
13697{
13698 const struct rb_iseq_constant_body *const body = ISEQ_BODY(iseq);
13699 const int size = ISEQ_LVAR_STATES_BUFLEN(body->local_table_size);
13700 IBF_W_ALIGN(uint8_t);
13701 if (iseq_has_lvar_states_p(body)) {
13702 return ibf_dump_write(dump, iseq_lvar_states(body), sizeof(uint8_t) * size);
13703 }
13704 else {
13705 return ibf_dump_write(dump, NULL, 0);
13706 }
13707}
13708
13709static void
13710ibf_load_lvar_states(const struct ibf_load *load, struct rb_iseq_constant_body *load_body, ibf_offset_t lvar_states_offset, int size, const ID *local_table)
13711{
13712 if (local_table == rb_iseq_shared_exc_local_tbl ||
13713 size <= 0) {
13714 load_body->lvar_states.list = NULL;
13715 }
13716 else if (ISEQ_LVAR_STATES_EMBED_P((unsigned int)size)) {
13717 ibf_offset_t pos = lvar_states_offset;
13718 const int len = sizeof(uint8_t) * ISEQ_LVAR_STATES_BUFLEN(size);
13719 memcpy(load_body->lvar_states.single, ibf_load_ptr(load, &pos, len), len);
13720 }
13721 else {
13722 load_body->lvar_states.list = IBF_R(lvar_states_offset, uint8_t, ISEQ_LVAR_STATES_BUFLEN(size));
13723 }
13724}
13725
13726static ibf_offset_t
13727ibf_dump_catch_table(struct ibf_dump *dump, const rb_iseq_t *iseq)
13728{
13729 const struct iseq_catch_table *table = ISEQ_BODY(iseq)->catch_table;
13730
13731 if (table) {
13732 int *iseq_indices = ALLOCA_N(int, table->size);
13733 unsigned int i;
13734
13735 for (i=0; i<table->size; i++) {
13736 iseq_indices[i] = ibf_dump_iseq(dump, table->entries[i].iseq);
13737 }
13738
13739 const ibf_offset_t offset = ibf_dump_pos(dump);
13740
13741 for (i=0; i<table->size; i++) {
13742 ibf_dump_write_small_value(dump, iseq_indices[i]);
13743 ibf_dump_write_small_value(dump, table->entries[i].type);
13744 ibf_dump_write_small_value(dump, table->entries[i].start);
13745 ibf_dump_write_small_value(dump, table->entries[i].end);
13746 ibf_dump_write_small_value(dump, table->entries[i].cont);
13747 ibf_dump_write_small_value(dump, table->entries[i].sp);
13748 }
13749 return offset;
13750 }
13751 else {
13752 return ibf_dump_pos(dump);
13753 }
13754}
13755
13756static void
13757ibf_load_catch_table(const struct ibf_load *load, ibf_offset_t catch_table_offset, unsigned int size, const rb_iseq_t *parent_iseq)
13758{
13759 if (size) {
13760 struct iseq_catch_table *table = ruby_xcalloc(1, iseq_catch_table_bytes(size));
13761 table->size = size;
13762 ISEQ_BODY(parent_iseq)->catch_table = table;
13763
13764 ibf_offset_t reading_pos = catch_table_offset;
13765
13766 unsigned int i;
13767 for (i=0; i<table->size; i++) {
13768 int iseq_index = (int)ibf_load_small_value(load, &reading_pos);
13769 table->entries[i].type = (enum rb_catch_type)ibf_load_small_value(load, &reading_pos);
13770 table->entries[i].start = (unsigned int)ibf_load_small_value(load, &reading_pos);
13771 table->entries[i].end = (unsigned int)ibf_load_small_value(load, &reading_pos);
13772 table->entries[i].cont = (unsigned int)ibf_load_small_value(load, &reading_pos);
13773 table->entries[i].sp = (unsigned int)ibf_load_small_value(load, &reading_pos);
13774
13775 rb_iseq_t *catch_iseq = (rb_iseq_t *)ibf_load_iseq(load, (const rb_iseq_t *)(VALUE)iseq_index);
13776 RB_OBJ_WRITE(parent_iseq, UNALIGNED_MEMBER_PTR(&table->entries[i], iseq), catch_iseq);
13777 }
13778 }
13779 else {
13780 ISEQ_BODY(parent_iseq)->catch_table = NULL;
13781 }
13782}
13783
13784static ibf_offset_t
13785ibf_dump_ci_entries(struct ibf_dump *dump, const rb_iseq_t *iseq)
13786{
13787 const struct rb_iseq_constant_body *const body = ISEQ_BODY(iseq);
13788 const unsigned int ci_size = body->ci_size;
13789 const struct rb_call_data *cds = body->call_data;
13790
13791 ibf_offset_t offset = ibf_dump_pos(dump);
13792
13793 unsigned int i;
13794
13795 for (i = 0; i < ci_size; i++) {
13796 const struct rb_callinfo *ci = cds[i].ci;
13797 if (ci != NULL) {
13798 ibf_dump_write_small_value(dump, ibf_dump_id(dump, vm_ci_mid(ci)));
13799 ibf_dump_write_small_value(dump, vm_ci_flag(ci));
13800 ibf_dump_write_small_value(dump, vm_ci_argc(ci));
13801
13802 const struct rb_callinfo_kwarg *kwarg = vm_ci_kwarg(ci);
13803 if (kwarg) {
13804 int len = kwarg->keyword_len;
13805 ibf_dump_write_small_value(dump, len);
13806 for (int j=0; j<len; j++) {
13807 VALUE keyword = ibf_dump_object(dump, kwarg->keywords[j]);
13808 ibf_dump_write_small_value(dump, keyword);
13809 }
13810 }
13811 else {
13812 ibf_dump_write_small_value(dump, 0);
13813 }
13814 }
13815 else {
13816 // TODO: truncate NULL ci from call_data.
13817 ibf_dump_write_small_value(dump, (VALUE)-1);
13818 }
13819 }
13820
13821 return offset;
13822}
13823
13825 ID id;
13826 VALUE name;
13827 VALUE val;
13828};
13829
13831 size_t num;
13832 struct outer_variable_pair pairs[1];
13833};
13834
13835static enum rb_id_table_iterator_result
13836store_outer_variable(ID id, VALUE val, void *dump)
13837{
13838 struct outer_variable_list *ovlist = dump;
13839 struct outer_variable_pair *pair = &ovlist->pairs[ovlist->num++];
13840 pair->id = id;
13841 pair->name = rb_id2str(id);
13842 pair->val = val;
13843 return ID_TABLE_CONTINUE;
13844}
13845
13846static int
13847outer_variable_cmp(const void *a, const void *b, void *arg)
13848{
13849 const struct outer_variable_pair *ap = (const struct outer_variable_pair *)a;
13850 const struct outer_variable_pair *bp = (const struct outer_variable_pair *)b;
13851
13852 if (!ap->name) {
13853 return -1;
13854 }
13855 else if (!bp->name) {
13856 return 1;
13857 }
13858
13859 return rb_str_cmp(ap->name, bp->name);
13860}
13861
13862static ibf_offset_t
13863ibf_dump_outer_variables(struct ibf_dump *dump, const rb_iseq_t *iseq)
13864{
13865 struct rb_id_table * ovs = ISEQ_BODY(iseq)->outer_variables;
13866
13867 ibf_offset_t offset = ibf_dump_pos(dump);
13868
13869 size_t size = ovs ? rb_id_table_size(ovs) : 0;
13870 ibf_dump_write_small_value(dump, (VALUE)size);
13871 if (size > 0) {
13872 VALUE buff;
13873 size_t buffsize =
13874 rb_size_mul_add_or_raise(sizeof(struct outer_variable_pair), size,
13875 offsetof(struct outer_variable_list, pairs),
13876 rb_eArgError);
13877 struct outer_variable_list *ovlist = RB_ALLOCV(buff, buffsize);
13878 ovlist->num = 0;
13879 rb_id_table_foreach(ovs, store_outer_variable, ovlist);
13880 ruby_qsort(ovlist->pairs, size, sizeof(struct outer_variable_pair), outer_variable_cmp, NULL);
13881 for (size_t i = 0; i < size; ++i) {
13882 ID id = ovlist->pairs[i].id;
13883 ID val = ovlist->pairs[i].val;
13884 ibf_dump_write_small_value(dump, ibf_dump_id(dump, id));
13885 ibf_dump_write_small_value(dump, val);
13886 }
13887 ALLOCV_END(buff);
13888 }
13889
13890 return offset;
13891}
13892
13893static ibf_offset_t
13894ibf_dump_ic_entries(struct ibf_dump *dump, const rb_iseq_t *iseq)
13895{
13896 const struct rb_iseq_constant_body *const body = ISEQ_BODY(iseq);
13897 ibf_offset_t offset = ibf_dump_pos(dump);
13898
13899 for (unsigned int i = 0; i < body->ic_size; i++) {
13900 const struct iseq_inline_constant_cache *ic = &ISEQ_IS_IC_ENTRY(body, i);
13901 const rb_const_path_t const_path = ic->const_path;
13902 size_t size = const_path_size(const_path);
13903 ibf_dump_write_small_value(dump, (size << 1) | (const_path_absolute_p(const_path) ? 1 : 0));
13904 for (size_t j = 0; j < size; j++) {
13905 ibf_dump_write_small_value(dump, ibf_dump_id(dump, const_path_aref(const_path, j)));
13906 }
13907 }
13908
13909 return offset;
13910}
13911
13912static void
13913ibf_load_ic_entries(const struct ibf_load *load, ibf_offset_t ic_entries_offset, struct rb_iseq_constant_body *load_body)
13914{
13915 ibf_offset_t reading_pos = ic_entries_offset;
13916
13917 for (unsigned int i = 0; i < load_body->ic_size; i++) {
13918 IC ic = &ISEQ_IS_IC_ENTRY(load_body, i);
13919 ic->const_path = ibf_load_const_path(load, &reading_pos);
13920 }
13921}
13922
13923/* note that we dump out rb_call_info but load back rb_call_data */
13924static void
13925ibf_load_ci_entries(const struct ibf_load *load,
13926 ibf_offset_t ci_entries_offset,
13927 unsigned int ci_size,
13928 struct rb_call_data **cd_ptr)
13929{
13930 if (!ci_size) {
13931 *cd_ptr = NULL;
13932 return;
13933 }
13934
13935 ibf_offset_t reading_pos = ci_entries_offset;
13936
13937 unsigned int i;
13938
13939 struct rb_call_data *cds = ZALLOC_N(struct rb_call_data, ci_size);
13940 *cd_ptr = cds;
13941
13942 for (i = 0; i < ci_size; i++) {
13943 VALUE mid_index = ibf_load_small_value(load, &reading_pos);
13944 if (mid_index != (VALUE)-1) {
13945 ID mid = ibf_load_id(load, mid_index);
13946 unsigned int flag = (unsigned int)ibf_load_small_value(load, &reading_pos);
13947 unsigned int argc = (unsigned int)ibf_load_small_value(load, &reading_pos);
13948
13949 struct rb_callinfo_kwarg *kwarg = NULL;
13950 int kwlen = (int)ibf_load_small_value(load, &reading_pos);
13951 if (kwlen > 0) {
13952 kwarg = rb_xmalloc_mul_add(kwlen, sizeof(VALUE), sizeof(struct rb_callinfo_kwarg));
13953 kwarg->references = 0;
13954 kwarg->keyword_len = kwlen;
13955 for (int j=0; j<kwlen; j++) {
13956 VALUE keyword = ibf_load_small_value(load, &reading_pos);
13957 kwarg->keywords[j] = ibf_load_object(load, keyword);
13958 }
13959 }
13960
13961 cds[i].ci = vm_ci_new(mid, flag, argc, kwarg);
13962 RB_OBJ_WRITTEN(load->iseq, Qundef, cds[i].ci);
13963 cds[i].cc = vm_cc_empty();
13964 }
13965 else {
13966 // NULL ci
13967 cds[i].ci = NULL;
13968 cds[i].cc = NULL;
13969 }
13970 }
13971}
13972
13973static struct rb_id_table *
13974ibf_load_outer_variables(const struct ibf_load * load, ibf_offset_t outer_variables_offset)
13975{
13976 ibf_offset_t reading_pos = outer_variables_offset;
13977
13978 struct rb_id_table *tbl = NULL;
13979
13980 size_t table_size = (size_t)ibf_load_small_value(load, &reading_pos);
13981
13982 if (table_size > 0) {
13983 tbl = rb_id_table_create(table_size);
13984 }
13985
13986 for (size_t i = 0; i < table_size; i++) {
13987 ID key = ibf_load_id(load, (ID)ibf_load_small_value(load, &reading_pos));
13988 VALUE value = ibf_load_small_value(load, &reading_pos);
13989 if (!key) key = rb_make_temporary_id(i);
13990 rb_id_table_insert(tbl, key, value);
13991 }
13992
13993 return tbl;
13994}
13995
13996static ibf_offset_t
13997ibf_dump_iseq_each(struct ibf_dump *dump, const rb_iseq_t *iseq)
13998{
13999 RUBY_ASSERT(dump->current_buffer == &dump->global_buffer);
14000
14001 unsigned int *positions;
14002
14003 const struct rb_iseq_constant_body *body = ISEQ_BODY(iseq);
14004
14005 const VALUE location_pathobj_index = ibf_dump_object(dump, body->location.pathobj); /* TODO: freeze */
14006 const VALUE location_label_index = ibf_dump_object(dump, body->location.label);
14007
14008#if IBF_ISEQ_ENABLE_LOCAL_BUFFER
14009 ibf_offset_t iseq_start = ibf_dump_pos(dump);
14010
14011 struct ibf_dump_buffer *saved_buffer = dump->current_buffer;
14012 struct ibf_dump_buffer buffer;
14013 buffer.str = rb_str_new(0, 0);
14014 buffer.obj_table = ibf_dump_object_table_new();
14015 dump->current_buffer = &buffer;
14016#endif
14017
14018 const ibf_offset_t bytecode_offset = ibf_dump_code(dump, iseq);
14019 const ibf_offset_t bytecode_size = ibf_dump_pos(dump) - bytecode_offset;
14020 const ibf_offset_t param_opt_table_offset = ibf_dump_param_opt_table(dump, iseq);
14021 const ibf_offset_t param_keyword_offset = ibf_dump_param_keyword(dump, iseq);
14022 const ibf_offset_t insns_info_body_offset = ibf_dump_insns_info_body(dump, iseq);
14023
14024 positions = rb_iseq_insns_info_decode_positions(ISEQ_BODY(iseq));
14025 const ibf_offset_t insns_info_positions_offset = ibf_dump_insns_info_positions(dump, positions, body->insns_info->size);
14026 SIZED_FREE_N(positions, body->insns_info->size);
14027
14028 const ibf_offset_t local_table_offset = ibf_dump_local_table(dump, iseq);
14029 const ibf_offset_t lvar_states_offset = ibf_dump_lvar_states(dump, iseq);
14030 const unsigned int catch_table_size = body->catch_table ? body->catch_table->size : 0;
14031 const ibf_offset_t catch_table_offset = ibf_dump_catch_table(dump, iseq);
14032 /* a NULL parent (persisted root) and references outside a Proc#refined subtree dump come out absent (-1) */
14033 const int parent_iseq_index = ibf_table_lookup(dump->iseq_table, (st_data_t)ISEQ_BODY(iseq)->parent_iseq);
14034 const int local_iseq_index = ibf_table_lookup(dump->iseq_table, (st_data_t)ISEQ_BODY(iseq)->local_iseq);
14035 const int mandatory_only_iseq_index = ibf_dump_iseq(dump, ISEQ_MANDATORY_ONLY_ISEQ(iseq));
14036 const ibf_offset_t ci_entries_offset = ibf_dump_ci_entries(dump, iseq);
14037 const ibf_offset_t outer_variables_offset = ibf_dump_outer_variables(dump, iseq);
14038 const ibf_offset_t ic_entries_offset = ibf_dump_ic_entries(dump, iseq);
14039
14040#if IBF_ISEQ_ENABLE_LOCAL_BUFFER
14041 ibf_offset_t local_obj_list_offset;
14042 unsigned int local_obj_list_size;
14043
14044 ibf_dump_object_list(dump, &local_obj_list_offset, &local_obj_list_size);
14045#endif
14046
14047 ibf_offset_t body_offset = ibf_dump_pos(dump);
14048
14049 /* dump the constant body */
14050 unsigned int param_flags =
14051 (body->param.flags.has_lead << 0) |
14052 (body->param.flags.has_opt << 1) |
14053 (body->param.flags.has_rest << 2) |
14054 (body->param.flags.has_post << 3) |
14055 (body->param.flags.has_kw << 4) |
14056 (body->param.flags.has_kwrest << 5) |
14057 (body->param.flags.has_block << 6) |
14058 (body->param.flags.ambiguous_param0 << 7) |
14059 (body->param.flags.accepts_no_kwarg << 8) |
14060 (body->param.flags.ruby2_keywords << 9) |
14061 (body->param.flags.anon_rest << 10) |
14062 (body->param.flags.anon_kwrest << 11) |
14063 (body->param.flags.use_block << 12) |
14064 (body->param.flags.forwardable << 13) |
14065 (body->param.flags.accepts_no_block << 14);
14066
14067#if IBF_ISEQ_ENABLE_LOCAL_BUFFER
14068# define IBF_BODY_OFFSET(x) (x)
14069#else
14070# define IBF_BODY_OFFSET(x) (body_offset - (x))
14071#endif
14072
14073 ibf_dump_write_small_value(dump, body->type);
14074 ibf_dump_write_small_value(dump, body->iseq_size);
14075 ibf_dump_write_small_value(dump, IBF_BODY_OFFSET(bytecode_offset));
14076 ibf_dump_write_small_value(dump, bytecode_size);
14077 ibf_dump_write_small_value(dump, param_flags);
14078 ibf_dump_write_small_value(dump, body->param.size);
14079 ibf_dump_write_small_value(dump, body->param.lead_num);
14080 ibf_dump_write_small_value(dump, body->param.opt_num);
14081 ibf_dump_write_small_value(dump, body->param.post_num);
14082 ibf_dump_write_small_value(dump, body->param.block_start);
14083 ibf_dump_write_small_value(dump, IBF_BODY_OFFSET(param_opt_table_offset));
14084 ibf_dump_write_small_value(dump, param_keyword_offset);
14085 ibf_dump_write_small_value(dump, location_pathobj_index);
14086 ibf_dump_write_small_value(dump, body->no_realpath);
14087 ibf_dump_write_small_value(dump, location_label_index);
14088 ibf_dump_write_small_value(dump, body->location.first_lineno);
14089 ibf_dump_write_small_value(dump, body->location.node_id);
14090 /* Dump the source hash (0 if unavailable) in two 32-bit halves, because
14091 * VALUE may be 32 bits wide. */
14092 ibf_dump_write_small_value(dump, (VALUE)(uint32_t)(body->source_hash >> 32));
14093 ibf_dump_write_small_value(dump, (VALUE)(uint32_t)body->source_hash);
14094 ibf_dump_write_small_value(dump, body->location.code_location.beg_pos.lineno);
14095 ibf_dump_write_small_value(dump, body->location.code_location.beg_pos.column);
14096 ibf_dump_write_small_value(dump, body->location.code_location.end_pos.lineno);
14097 ibf_dump_write_small_value(dump, body->location.code_location.end_pos.column);
14098 ibf_dump_write_small_value(dump, IBF_BODY_OFFSET(insns_info_body_offset));
14099 ibf_dump_write_small_value(dump, IBF_BODY_OFFSET(insns_info_positions_offset));
14100 ibf_dump_write_small_value(dump, body->insns_info->size);
14101 ibf_dump_write_small_value(dump, IBF_BODY_OFFSET(local_table_offset));
14102 ibf_dump_write_small_value(dump, IBF_BODY_OFFSET(lvar_states_offset));
14103 ibf_dump_write_small_value(dump, catch_table_size);
14104 ibf_dump_write_small_value(dump, IBF_BODY_OFFSET(catch_table_offset));
14105 ibf_dump_write_small_value(dump, parent_iseq_index);
14106 ibf_dump_write_small_value(dump, local_iseq_index);
14107 ibf_dump_write_small_value(dump, mandatory_only_iseq_index);
14108 ibf_dump_write_small_value(dump, IBF_BODY_OFFSET(ci_entries_offset));
14109 ibf_dump_write_small_value(dump, IBF_BODY_OFFSET(outer_variables_offset));
14110 ibf_dump_write_small_value(dump, ISEQ_FLIP_CNT(iseq));
14111 ibf_dump_write_small_value(dump, body->local_table_size);
14112 ibf_dump_write_small_value(dump, body->ivc_size);
14113 ibf_dump_write_small_value(dump, body->icvarc_size);
14114 ibf_dump_write_small_value(dump, body->ic_size);
14115 if (body->ic_size) {
14116 ibf_dump_write_small_value(dump, IBF_BODY_OFFSET(ic_entries_offset));
14117 }
14118 ibf_dump_write_small_value(dump, body->ci_size);
14119 ibf_dump_write_small_value(dump, body->stack_max);
14120 ibf_dump_write_small_value(dump, body->builtin_attrs);
14121 ibf_dump_write_small_value(dump, body->prism ? 1 : 0);
14122
14123#undef IBF_BODY_OFFSET
14124
14125#if IBF_ISEQ_ENABLE_LOCAL_BUFFER
14126 ibf_offset_t iseq_length_bytes = ibf_dump_pos(dump);
14127
14128 dump->current_buffer = saved_buffer;
14129 ibf_dump_write(dump, RSTRING_PTR(buffer.str), iseq_length_bytes);
14130
14131 ibf_offset_t offset = ibf_dump_pos(dump);
14132 ibf_dump_write_small_value(dump, iseq_start);
14133 ibf_dump_write_small_value(dump, iseq_length_bytes);
14134 ibf_dump_write_small_value(dump, body_offset);
14135
14136 ibf_dump_write_small_value(dump, local_obj_list_offset);
14137 ibf_dump_write_small_value(dump, local_obj_list_size);
14138
14139 st_free_table(buffer.obj_table); // TODO: this leaks in case of exception
14140
14141 return offset;
14142#else
14143 return body_offset;
14144#endif
14145}
14146
14147static VALUE
14148ibf_load_location_str(const struct ibf_load *load, VALUE str_index)
14149{
14150 VALUE str = ibf_load_object(load, str_index);
14151 if (str != Qnil) {
14152 str = rb_fstring(str);
14153 }
14154 return str;
14155}
14156
14157static void
14158ibf_load_iseq_each(struct ibf_load *load, rb_iseq_t *iseq, ibf_offset_t offset)
14159{
14160 struct rb_iseq_constant_body *load_body = ISEQ_BODY(iseq) = rb_iseq_constant_body_alloc();
14161
14162 ibf_offset_t reading_pos = offset;
14163
14164#if IBF_ISEQ_ENABLE_LOCAL_BUFFER
14165 struct ibf_load_buffer *saved_buffer = load->current_buffer;
14166 load->current_buffer = &load->global_buffer;
14167
14168 const ibf_offset_t iseq_start = (ibf_offset_t)ibf_load_small_value(load, &reading_pos);
14169 const ibf_offset_t iseq_length_bytes = (ibf_offset_t)ibf_load_small_value(load, &reading_pos);
14170 const ibf_offset_t body_offset = (ibf_offset_t)ibf_load_small_value(load, &reading_pos);
14171
14172 struct ibf_load_buffer buffer;
14173 buffer.buff = load->global_buffer.buff + iseq_start;
14174 buffer.size = iseq_length_bytes;
14175 buffer.obj_list_offset = (ibf_offset_t)ibf_load_small_value(load, &reading_pos);
14176 buffer.obj_list_size = (ibf_offset_t)ibf_load_small_value(load, &reading_pos);
14177 buffer.obj_list = pinned_list_new(buffer.obj_list_size);
14178
14179 load->current_buffer = &buffer;
14180 reading_pos = body_offset;
14181#endif
14182
14183#if IBF_ISEQ_ENABLE_LOCAL_BUFFER
14184# define IBF_BODY_OFFSET(x) (x)
14185#else
14186# define IBF_BODY_OFFSET(x) (offset - (x))
14187#endif
14188
14189 const unsigned int type = (unsigned int)ibf_load_small_value(load, &reading_pos);
14190 const unsigned int iseq_size = (unsigned int)ibf_load_small_value(load, &reading_pos);
14191 const ibf_offset_t bytecode_offset = (ibf_offset_t)IBF_BODY_OFFSET(ibf_load_small_value(load, &reading_pos));
14192 const ibf_offset_t bytecode_size = (ibf_offset_t)ibf_load_small_value(load, &reading_pos);
14193 const unsigned int param_flags = (unsigned int)ibf_load_small_value(load, &reading_pos);
14194 const unsigned int param_size = (unsigned int)ibf_load_small_value(load, &reading_pos);
14195 const int param_lead_num = (int)ibf_load_small_value(load, &reading_pos);
14196 const int param_opt_num = (int)ibf_load_small_value(load, &reading_pos);
14197 const int param_post_num = (int)ibf_load_small_value(load, &reading_pos);
14198 const int param_block_start = (int)ibf_load_small_value(load, &reading_pos);
14199 const ibf_offset_t param_opt_table_offset = (ibf_offset_t)IBF_BODY_OFFSET(ibf_load_small_value(load, &reading_pos));
14200 const ibf_offset_t param_keyword_offset = (ibf_offset_t)ibf_load_small_value(load, &reading_pos);
14201 const VALUE location_pathobj_index = ibf_load_small_value(load, &reading_pos);
14202 const bool no_realpath = (bool)ibf_load_small_value(load, &reading_pos);
14203 const VALUE location_label_index = ibf_load_small_value(load, &reading_pos);
14204 const int location_first_lineno = (int)ibf_load_small_value(load, &reading_pos);
14205 const int location_node_id = (int)ibf_load_small_value(load, &reading_pos);
14206 const uint64_t source_hash_hi = (uint64_t)ibf_load_small_value(load, &reading_pos);
14207 const uint64_t source_hash_lo = (uint64_t)ibf_load_small_value(load, &reading_pos);
14208 const uint64_t source_hash = (source_hash_hi << 32) | (uint32_t)source_hash_lo;
14209 const int location_code_location_beg_pos_lineno = (int)ibf_load_small_value(load, &reading_pos);
14210 const int location_code_location_beg_pos_column = (int)ibf_load_small_value(load, &reading_pos);
14211 const int location_code_location_end_pos_lineno = (int)ibf_load_small_value(load, &reading_pos);
14212 const int location_code_location_end_pos_column = (int)ibf_load_small_value(load, &reading_pos);
14213 const ibf_offset_t insns_info_body_offset = (ibf_offset_t)IBF_BODY_OFFSET(ibf_load_small_value(load, &reading_pos));
14214 const ibf_offset_t insns_info_positions_offset = (ibf_offset_t)IBF_BODY_OFFSET(ibf_load_small_value(load, &reading_pos));
14215 const unsigned int insns_info_size = (unsigned int)ibf_load_small_value(load, &reading_pos);
14216 const ibf_offset_t local_table_offset = (ibf_offset_t)IBF_BODY_OFFSET(ibf_load_small_value(load, &reading_pos));
14217 const ibf_offset_t lvar_states_offset = (ibf_offset_t)IBF_BODY_OFFSET(ibf_load_small_value(load, &reading_pos));
14218 const unsigned int catch_table_size = (unsigned int)ibf_load_small_value(load, &reading_pos);
14219 const ibf_offset_t catch_table_offset = (ibf_offset_t)IBF_BODY_OFFSET(ibf_load_small_value(load, &reading_pos));
14220 const int parent_iseq_index = (int)ibf_load_small_value(load, &reading_pos);
14221 const int local_iseq_index = (int)ibf_load_small_value(load, &reading_pos);
14222 const int mandatory_only_iseq_index = (int)ibf_load_small_value(load, &reading_pos);
14223 const ibf_offset_t ci_entries_offset = (ibf_offset_t)IBF_BODY_OFFSET(ibf_load_small_value(load, &reading_pos));
14224 const ibf_offset_t outer_variables_offset = (ibf_offset_t)IBF_BODY_OFFSET(ibf_load_small_value(load, &reading_pos));
14225 const rb_snum_t variable_flip_count = (rb_snum_t)ibf_load_small_value(load, &reading_pos);
14226 const unsigned int local_table_size = (unsigned int)ibf_load_small_value(load, &reading_pos);
14227
14228 const unsigned int ivc_size = (unsigned int)ibf_load_small_value(load, &reading_pos);
14229 const unsigned int icvarc_size = (unsigned int)ibf_load_small_value(load, &reading_pos);
14230 const unsigned int ic_size = (unsigned int)ibf_load_small_value(load, &reading_pos);
14231 const ibf_offset_t ic_entries_offset = ic_size ? (ibf_offset_t)IBF_BODY_OFFSET(ibf_load_small_value(load, &reading_pos)) : 0;
14232
14233 const unsigned int ci_size = (unsigned int)ibf_load_small_value(load, &reading_pos);
14234 const unsigned int stack_max = (unsigned int)ibf_load_small_value(load, &reading_pos);
14235 const unsigned int builtin_attrs = (unsigned int)ibf_load_small_value(load, &reading_pos);
14236 const bool prism = (bool)ibf_load_small_value(load, &reading_pos);
14237
14238 // setup fname and dummy frame
14239 VALUE path = ibf_load_object(load, location_pathobj_index);
14240 {
14241 VALUE realpath = Qnil;
14242
14243 if (RB_TYPE_P(path, T_STRING)) {
14244 path = rb_fstring(path);
14245 realpath = no_realpath ? Qnil : path;
14246 }
14247 else if (RB_TYPE_P(path, T_ARRAY)) {
14248 VALUE pathobj = path;
14249 if (RARRAY_LEN(pathobj) != 2) {
14250 rb_raise(rb_eRuntimeError, "path object size mismatch");
14251 }
14252 path = rb_fstring(RARRAY_AREF(pathobj, 0));
14253 realpath = RARRAY_AREF(pathobj, 1);
14254 if (!NIL_P(realpath)) {
14255 if (!RB_TYPE_P(realpath, T_STRING)) {
14256 rb_raise(rb_eArgError, "unexpected realpath %"PRIxVALUE
14257 "(%x), path=%+"PRIsVALUE,
14258 realpath, TYPE(realpath), path);
14259 }
14260 realpath = rb_fstring(realpath);
14261 }
14262 }
14263 else {
14264 rb_raise(rb_eRuntimeError, "unexpected path object");
14265 }
14266 if (RTEST(load->path_override)) {
14267 path = load->path_override;
14268 realpath = load->realpath_override;
14269 }
14270 rb_iseq_pathobj_set(iseq, path, realpath);
14271 }
14272
14273 // push dummy frame
14274 rb_execution_context_t *ec = GET_EC();
14275 VALUE dummy_frame = rb_vm_push_frame_fname(ec, path);
14276
14277#undef IBF_BODY_OFFSET
14278
14279 load_body->type = type;
14280 load_body->stack_max = stack_max;
14281 load_body->param.flags.has_lead = (param_flags >> 0) & 1;
14282 load_body->param.flags.has_opt = (param_flags >> 1) & 1;
14283 load_body->param.flags.has_rest = (param_flags >> 2) & 1;
14284 load_body->param.flags.has_post = (param_flags >> 3) & 1;
14285 load_body->param.flags.has_kw = FALSE;
14286 load_body->param.flags.has_kwrest = (param_flags >> 5) & 1;
14287 load_body->param.flags.has_block = (param_flags >> 6) & 1;
14288 load_body->param.flags.ambiguous_param0 = (param_flags >> 7) & 1;
14289 load_body->param.flags.accepts_no_kwarg = (param_flags >> 8) & 1;
14290 load_body->param.flags.ruby2_keywords = (param_flags >> 9) & 1;
14291 load_body->param.flags.anon_rest = (param_flags >> 10) & 1;
14292 load_body->param.flags.anon_kwrest = (param_flags >> 11) & 1;
14293 load_body->param.flags.use_block = (param_flags >> 12) & 1;
14294 load_body->param.flags.forwardable = (param_flags >> 13) & 1;
14295 load_body->param.flags.accepts_no_block = (param_flags >> 14) & 1;
14296 load_body->param.size = param_size;
14297 load_body->param.lead_num = param_lead_num;
14298 load_body->param.opt_num = param_opt_num;
14299 load_body->param.post_num = param_post_num;
14300 load_body->param.block_start = param_block_start;
14301 load_body->local_table_size = local_table_size;
14302 load_body->ci_size = ci_size;
14303
14304 // variable is NULL from ZALLOC; only allocate if flip_count is non-zero.
14305 ISEQ_ORIGINAL_ISEQ_CLEAR(iseq);
14306 if (variable_flip_count) {
14307 struct rb_iseq_variable *v = rb_iseq_variable_ensure(iseq);
14308 v->flip_count = variable_flip_count;
14309 }
14310
14311 load_body->location.first_lineno = location_first_lineno;
14312 load_body->location.node_id = location_node_id;
14313 load_body->source_hash = source_hash;
14314 load_body->location.code_location.beg_pos.lineno = location_code_location_beg_pos_lineno;
14315 load_body->location.code_location.beg_pos.column = location_code_location_beg_pos_column;
14316 load_body->location.code_location.end_pos.lineno = location_code_location_end_pos_lineno;
14317 load_body->location.code_location.end_pos.column = location_code_location_end_pos_column;
14318 load_body->builtin_attrs = builtin_attrs;
14319 load_body->prism = prism;
14320
14321 load_body->ivc_size = ivc_size;
14322 load_body->icvarc_size = icvarc_size;
14323 load_body->ic_size = ic_size;
14324
14325 if (ISEQ_IS_SIZE(load_body)) {
14326 load_body->is_entries = ZALLOC_N(union iseq_inline_storage_entry, ISEQ_IS_SIZE(load_body));
14327 }
14328 else {
14329 load_body->is_entries = NULL;
14330 }
14331 ibf_load_ci_entries(load, ci_entries_offset, ci_size, &load_body->call_data);
14332 load_body->outer_variables = ibf_load_outer_variables(load, outer_variables_offset);
14333 ibf_load_ic_entries(load, ic_entries_offset, load_body);
14334 load_body->param.opt_table = ibf_load_param_opt_table(load, param_opt_table_offset, param_opt_num);
14335 load_body->param.keyword = ibf_load_param_keyword(load, param_keyword_offset);
14336 load_body->param.flags.has_kw = (param_flags >> 4) & 1;
14337 load_body->local_table = ibf_load_local_table(load, local_table_offset, local_table_size);
14338 ibf_load_lvar_states(load, load_body, lvar_states_offset, local_table_size, load_body->local_table);
14339 ibf_load_catch_table(load, catch_table_offset, catch_table_size, iseq);
14340
14341 const rb_iseq_t *parent_iseq = ibf_load_iseq(load, (const rb_iseq_t *)(VALUE)parent_iseq_index);
14342 const rb_iseq_t *local_iseq = ibf_load_iseq(load, (const rb_iseq_t *)(VALUE)local_iseq_index);
14343 const rb_iseq_t *mandatory_only_iseq = ibf_load_iseq(load, (const rb_iseq_t *)(VALUE)mandatory_only_iseq_index);
14344
14345 RB_OBJ_WRITE(iseq, &load_body->parent_iseq, parent_iseq);
14346 RB_OBJ_WRITE(iseq, &load_body->local_iseq, local_iseq);
14347 rb_iseq_mandatory_only_iseq_set(iseq, mandatory_only_iseq);
14348
14349 // This must be done after the local table is loaded.
14350 if (load_body->param.keyword != NULL) {
14351 RUBY_ASSERT(load_body->local_table);
14352 struct rb_iseq_param_keyword *keyword = (struct rb_iseq_param_keyword *) load_body->param.keyword;
14353 keyword->table = &load_body->local_table[keyword->bits_start - keyword->num];
14354 }
14355
14356 ibf_load_code(load, iseq, bytecode_offset, bytecode_size, iseq_size);
14357 load_body->insns_info = ibf_load_insns_info(load, insns_info_body_offset, insns_info_positions_offset,
14358 insns_info_size, load_body->iseq_size);
14359
14360 rb_iseq_translate_threaded_code(iseq);
14361
14362#if IBF_ISEQ_ENABLE_LOCAL_BUFFER
14363 load->current_buffer = &load->global_buffer;
14364#endif
14365
14366 RB_OBJ_WRITE(iseq, &load_body->location.label, ibf_load_location_str(load, location_label_index));
14367
14368#if IBF_ISEQ_ENABLE_LOCAL_BUFFER
14369 load->current_buffer = saved_buffer;
14370#endif
14371 verify_call_cache(iseq);
14372
14373 RB_GC_GUARD(dummy_frame);
14374 rb_vm_pop_frame_no_int(ec);
14375}
14376
14378{
14379 struct ibf_dump *dump;
14380 VALUE offset_list;
14381};
14382
14383static int
14384ibf_dump_iseq_list_i(st_data_t key, st_data_t val, st_data_t ptr)
14385{
14386 const rb_iseq_t *iseq = (const rb_iseq_t *)key;
14387 struct ibf_dump_iseq_list_arg *args = (struct ibf_dump_iseq_list_arg *)ptr;
14388
14389 ibf_offset_t offset = ibf_dump_iseq_each(args->dump, iseq);
14390 rb_ary_push(args->offset_list, UINT2NUM(offset));
14391
14392 return ST_CONTINUE;
14393}
14394
14395static void
14396ibf_dump_iseq_list(struct ibf_dump *dump, struct ibf_header *header)
14397{
14398 VALUE offset_list = rb_ary_hidden_new(dump->iseq_table->num_entries);
14399
14400 struct ibf_dump_iseq_list_arg args;
14401 args.dump = dump;
14402 args.offset_list = offset_list;
14403
14404 st_foreach(dump->iseq_table, ibf_dump_iseq_list_i, (st_data_t)&args);
14405
14406 st_index_t i;
14407 st_index_t size = dump->iseq_table->num_entries;
14408 ibf_offset_t *offsets = ALLOCA_N(ibf_offset_t, size);
14409
14410 for (i = 0; i < size; i++) {
14411 offsets[i] = NUM2UINT(RARRAY_AREF(offset_list, i));
14412 }
14413
14414 ibf_dump_align(dump, sizeof(ibf_offset_t));
14415 header->iseq_list_offset = ibf_dump_write(dump, offsets, sizeof(ibf_offset_t) * size);
14416 header->iseq_list_size = (unsigned int)size;
14417}
14418
14419/*
14420 * Binary format
14421 * - ibf_object_header
14422 * - ibf_object_xxx (xxx is type)
14423 */
14424
14426 unsigned int type: 5;
14427 unsigned int special_const: 1;
14428 unsigned int frozen: 1;
14429 unsigned int internal: 1;
14430};
14431
14432enum ibf_object_class_index {
14433 IBF_OBJECT_CLASS_OBJECT,
14434 IBF_OBJECT_CLASS_ARRAY,
14435 IBF_OBJECT_CLASS_STANDARD_ERROR,
14436 IBF_OBJECT_CLASS_NO_MATCHING_PATTERN_ERROR,
14437 IBF_OBJECT_CLASS_TYPE_ERROR,
14438 IBF_OBJECT_CLASS_NO_MATCHING_PATTERN_KEY_ERROR,
14439};
14440
14442 long srcstr;
14443 char option;
14444};
14445
14447 long len;
14448 long keyval[FLEX_ARY_LEN];
14449};
14450
14452 long class_index;
14453 long len;
14454 long beg;
14455 long end;
14456 int excl;
14457};
14458
14460 ssize_t slen;
14461 BDIGIT digits[FLEX_ARY_LEN];
14462};
14463
14464enum ibf_object_data_type {
14465 IBF_OBJECT_DATA_ENCODING,
14466};
14467
14469 long a, b;
14470};
14471
14473 long str;
14474};
14475
14476#define IBF_ALIGNED_OFFSET(align, offset) /* offset > 0 */ \
14477 ((((offset) - 1) / (align) + 1) * (align))
14478/* No cast, since it's UB to create an unaligned pointer.
14479 * Leave as void* for use with memcpy in those cases.
14480 * We align the offset, but the buffer pointer is only VALUE aligned,
14481 * so the returned pointer may be unaligned for `type` .*/
14482#define IBF_OBJBODY(type, offset) \
14483 ibf_load_check_offset(load, IBF_ALIGNED_OFFSET(RUBY_ALIGNOF(type), offset))
14484
14485static const void *
14486ibf_load_check_offset(const struct ibf_load *load, size_t offset)
14487{
14488 if (offset >= load->current_buffer->size) {
14489 rb_raise(rb_eIndexError, "object offset out of range: %"PRIdSIZE, offset);
14490 }
14491 return load->current_buffer->buff + offset;
14492}
14493
14494NORETURN(static void ibf_dump_object_unsupported(struct ibf_dump *dump, VALUE obj));
14495
14496static void
14497ibf_dump_object_unsupported(struct ibf_dump *dump, VALUE obj)
14498{
14499 char buff[0x100];
14500 rb_raw_obj_info(buff, sizeof(buff), obj);
14501 rb_raise(rb_eNotImpError, "ibf_dump_object_unsupported: %s", buff);
14502}
14503
14504NORETURN(static VALUE ibf_load_object_unsupported(const struct ibf_load *load, const struct ibf_object_header *header, ibf_offset_t offset));
14505
14506static VALUE
14507ibf_load_object_unsupported(const struct ibf_load *load, const struct ibf_object_header *header, ibf_offset_t offset)
14508{
14509 rb_raise(rb_eArgError, "unsupported");
14511}
14512
14513static void
14514ibf_dump_object_class(struct ibf_dump *dump, VALUE obj)
14515{
14516 enum ibf_object_class_index cindex;
14517 if (obj == rb_cObject) {
14518 cindex = IBF_OBJECT_CLASS_OBJECT;
14519 }
14520 else if (obj == rb_cArray) {
14521 cindex = IBF_OBJECT_CLASS_ARRAY;
14522 }
14523 else if (obj == rb_eStandardError) {
14524 cindex = IBF_OBJECT_CLASS_STANDARD_ERROR;
14525 }
14526 else if (obj == rb_eNoMatchingPatternError) {
14527 cindex = IBF_OBJECT_CLASS_NO_MATCHING_PATTERN_ERROR;
14528 }
14529 else if (obj == rb_eTypeError) {
14530 cindex = IBF_OBJECT_CLASS_TYPE_ERROR;
14531 }
14532 else if (obj == rb_eNoMatchingPatternKeyError) {
14533 cindex = IBF_OBJECT_CLASS_NO_MATCHING_PATTERN_KEY_ERROR;
14534 }
14535 else {
14536 rb_obj_info_dump(obj);
14537 rb_p(obj);
14538 rb_bug("unsupported class");
14539 }
14540 ibf_dump_write_small_value(dump, (VALUE)cindex);
14541}
14542
14543static VALUE
14544ibf_load_object_class(const struct ibf_load *load, const struct ibf_object_header *header, ibf_offset_t offset)
14545{
14546 enum ibf_object_class_index cindex = (enum ibf_object_class_index)ibf_load_small_value(load, &offset);
14547
14548 switch (cindex) {
14549 case IBF_OBJECT_CLASS_OBJECT:
14550 return rb_cObject;
14551 case IBF_OBJECT_CLASS_ARRAY:
14552 return rb_cArray;
14553 case IBF_OBJECT_CLASS_STANDARD_ERROR:
14554 return rb_eStandardError;
14555 case IBF_OBJECT_CLASS_NO_MATCHING_PATTERN_ERROR:
14557 case IBF_OBJECT_CLASS_TYPE_ERROR:
14558 return rb_eTypeError;
14559 case IBF_OBJECT_CLASS_NO_MATCHING_PATTERN_KEY_ERROR:
14561 }
14562
14563 rb_raise(rb_eArgError, "ibf_load_object_class: unknown class (%d)", (int)cindex);
14564}
14565
14566
14567static void
14568ibf_dump_object_float(struct ibf_dump *dump, VALUE obj)
14569{
14570 double dbl = RFLOAT_VALUE(obj);
14571 (void)IBF_W(&dbl, double, 1);
14572}
14573
14574static VALUE
14575ibf_load_object_float(const struct ibf_load *load, const struct ibf_object_header *header, ibf_offset_t offset)
14576{
14577 double d;
14578 /* Avoid unaligned VFP load on ARMv7; IBF payload may be unaligned (C99 6.3.2.3 p7). */
14579 memcpy(&d, IBF_OBJBODY(double, offset), sizeof(d));
14580 VALUE f = DBL2NUM(d);
14581 if (!FLONUM_P(f)) RB_OBJ_SET_SHAREABLE(f);
14582 return f;
14583}
14584
14585static void
14586ibf_dump_object_string(struct ibf_dump *dump, VALUE obj)
14587{
14588 long encindex = (long)rb_enc_get_index(obj);
14589 rb_len_t len = RSTRING_LEN(obj);
14590 const char *ptr = RSTRING_PTR(obj);
14591
14592 if (encindex > RUBY_ENCINDEX_BUILTIN_MAX) {
14593 rb_encoding *enc = rb_enc_from_index((int)encindex);
14594 const char *enc_name = rb_enc_name(enc);
14595 encindex = RUBY_ENCINDEX_BUILTIN_MAX + ibf_dump_object(dump, rb_str_new2(enc_name));
14596 }
14597
14598 ibf_dump_write_small_value(dump, encindex);
14599 ibf_dump_write_small_value(dump, len);
14600 IBF_WP(ptr, char, len);
14601}
14602
14603static VALUE
14604ibf_load_object_string(const struct ibf_load *load, const struct ibf_object_header *header, ibf_offset_t offset)
14605{
14606 ibf_offset_t reading_pos = offset;
14607
14608 int encindex = (int)ibf_load_small_value(load, &reading_pos);
14609 const rb_len_t len = (rb_len_t)ibf_load_small_value(load, &reading_pos);
14610 const char *ptr = load->current_buffer->buff + reading_pos;
14611
14612 if (encindex > RUBY_ENCINDEX_BUILTIN_MAX) {
14613 VALUE enc_name_str = ibf_load_object(load, encindex - RUBY_ENCINDEX_BUILTIN_MAX);
14614 encindex = rb_enc_find_index(RSTRING_PTR(enc_name_str));
14615 }
14616
14617 VALUE str;
14618 if (header->frozen && !header->internal) {
14619 str = rb_enc_literal_str(ptr, len, rb_enc_from_index(encindex));
14620 }
14621 else {
14622 str = rb_enc_str_new(ptr, len, rb_enc_from_index(encindex));
14623
14624 if (header->internal) rb_obj_hide(str);
14625 if (header->frozen) str = rb_fstring(str);
14626 }
14627 return str;
14628}
14629
14630static void
14631ibf_dump_object_regexp(struct ibf_dump *dump, VALUE obj)
14632{
14633 VALUE srcstr = RREGEXP_SRC(obj);
14634 struct ibf_object_regexp regexp;
14635 regexp.option = (char)rb_reg_options(obj);
14636 regexp.srcstr = (long)ibf_dump_object(dump, srcstr);
14637
14638 ibf_dump_write_byte(dump, (unsigned char)regexp.option);
14639 ibf_dump_write_small_value(dump, regexp.srcstr);
14640}
14641
14642static VALUE
14643ibf_load_object_regexp(const struct ibf_load *load, const struct ibf_object_header *header, ibf_offset_t offset)
14644{
14645 struct ibf_object_regexp regexp;
14646 regexp.option = ibf_load_byte(load, &offset);
14647 regexp.srcstr = ibf_load_small_value(load, &offset);
14648
14649 VALUE srcstr = ibf_load_object(load, regexp.srcstr);
14650 VALUE reg = rb_reg_compile(srcstr, (int)regexp.option, NULL, 0);
14651
14652 if (header->internal) rb_obj_hide(reg);
14653 if (header->frozen) RB_OBJ_SET_SHAREABLE(rb_obj_freeze(reg));
14654
14655 return reg;
14656}
14657
14658static void
14659ibf_dump_object_array(struct ibf_dump *dump, VALUE obj)
14660{
14661 rb_len_t i, len = RARRAY_LEN(obj);
14662 ibf_dump_write_small_value(dump, len);
14663 for (i=0; i<len; i++) {
14664 long index = (long)ibf_dump_object(dump, RARRAY_AREF(obj, i));
14665 ibf_dump_write_small_value(dump, index);
14666 }
14667}
14668
14669static VALUE
14670ibf_load_object_array(const struct ibf_load *load, const struct ibf_object_header *header, ibf_offset_t offset)
14671{
14672 ibf_offset_t reading_pos = offset;
14673
14674 const rb_len_t len = (rb_len_t)ibf_load_small_value(load, &reading_pos);
14675
14676 VALUE ary = header->internal ? rb_ary_hidden_new(len) : rb_ary_new_capa(len);
14677 int i;
14678
14679 for (i=0; i<len; i++) {
14680 const VALUE index = ibf_load_small_value(load, &reading_pos);
14681 rb_ary_push(ary, ibf_load_object(load, index));
14682 }
14683
14684 if (header->frozen) {
14685 rb_ary_freeze(ary);
14686 rb_ractor_make_shareable(ary); // TODO: check elements
14687 }
14688
14689 return ary;
14690}
14691
14692static int
14693ibf_dump_object_hash_i(st_data_t key, st_data_t val, st_data_t ptr)
14694{
14695 struct ibf_dump *dump = (struct ibf_dump *)ptr;
14696
14697 VALUE key_index = ibf_dump_object(dump, (VALUE)key);
14698 VALUE val_index = ibf_dump_object(dump, (VALUE)val);
14699
14700 ibf_dump_write_small_value(dump, key_index);
14701 ibf_dump_write_small_value(dump, val_index);
14702 return ST_CONTINUE;
14703}
14704
14705static void
14706ibf_dump_object_hash(struct ibf_dump *dump, VALUE obj)
14707{
14708 long len = RHASH_SIZE(obj);
14709 ibf_dump_write_small_value(dump, (VALUE)len);
14710
14711 if (len > 0) rb_hash_foreach(obj, ibf_dump_object_hash_i, (VALUE)dump);
14712}
14713
14714static VALUE
14715ibf_load_object_hash(const struct ibf_load *load, const struct ibf_object_header *header, ibf_offset_t offset)
14716{
14717 long len = (long)ibf_load_small_value(load, &offset);
14718 VALUE obj = header->frozen ? rb_hash_alloc_fixed_size(rb_cHash, len) : rb_hash_new_capa(len);
14719 int i;
14720
14721 for (i = 0; i < len; i++) {
14722 VALUE key_index = ibf_load_small_value(load, &offset);
14723 VALUE val_index = ibf_load_small_value(load, &offset);
14724
14725 VALUE key = ibf_load_object(load, key_index);
14726 VALUE val = ibf_load_object(load, val_index);
14727 rb_hash_aset(obj, key, val);
14728 }
14729
14730 if (header->internal) rb_obj_hide(obj);
14731 if (header->frozen) {
14732 RB_OBJ_SET_FROZEN_SHAREABLE(obj);
14733 }
14734
14735 return obj;
14736}
14737
14738static int
14739ibf_dump_cdhash_i(st_data_t key, st_data_t val, st_data_t ptr)
14740{
14741 struct ibf_dump *dump = (struct ibf_dump *)ptr;
14742
14743 VALUE key_index = ibf_dump_object(dump, (VALUE)key);
14744
14745 ibf_dump_write_small_value(dump, key_index);
14746 ibf_dump_write_small_value(dump, val);
14747 return ST_CONTINUE;
14748}
14749
14750static void
14751ibf_dump_object_imemo(struct ibf_dump *dump, VALUE obj)
14752{
14753 ibf_dump_write_small_value(dump, (VALUE)imemo_type(obj));
14754 switch (imemo_type(obj)) {
14755 case imemo_once_storage:
14756 break;
14757 case imemo_cdhash: {
14758 st_table *tbl = rb_imemo_cdhash_tbl(obj);
14759
14760 long len = tbl->num_entries;
14761 ibf_dump_write_small_value(dump, (VALUE)len);
14762 if (len > 0) st_foreach(tbl, ibf_dump_cdhash_i, (VALUE)dump);
14763 break;
14764 }
14765 default:
14766 ibf_dump_object_unsupported(dump, obj);
14767 break;
14768 }
14769}
14770
14771static VALUE
14772ibf_load_object_imemo(const struct ibf_load *load, const struct ibf_object_header *header, ibf_offset_t offset)
14773{
14774 enum imemo_type type = (enum imemo_type)ibf_load_small_value(load, &offset);
14775 switch (type) {
14776 case imemo_once_storage:
14777 return rb_imemo_once_storage_new();
14778 case imemo_cdhash: {
14779 long len = (long)ibf_load_small_value(load, &offset);
14780 VALUE obj = cdhash_new(len);
14781
14782 for (long i = 0; i < len; i++) {
14783 VALUE key_index = ibf_load_small_value(load, &offset);
14784 VALUE val = ibf_load_small_value(load, &offset);
14785
14786 VALUE key = ibf_load_object(load, key_index);
14787 cdhash_aset(obj, key, val);
14788 }
14789
14790 return obj;
14791 }
14792 default:
14793 return ibf_load_object_unsupported(load, header, offset);
14794 }
14795}
14796
14797static void
14798ibf_dump_object_struct(struct ibf_dump *dump, VALUE obj)
14799{
14800 if (rb_obj_is_kind_of(obj, rb_cRange)) {
14801 struct ibf_object_struct_range range;
14802 VALUE beg, end;
14803 IBF_ZERO(range);
14804 range.len = 3;
14805 range.class_index = 0;
14806
14807 rb_range_values(obj, &beg, &end, &range.excl);
14808 range.beg = (long)ibf_dump_object(dump, beg);
14809 range.end = (long)ibf_dump_object(dump, end);
14810
14811 IBF_W_ALIGN(struct ibf_object_struct_range);
14812 IBF_WV(range);
14813 }
14814 else {
14815 rb_raise(rb_eNotImpError, "ibf_dump_object_struct: unsupported class %"PRIsVALUE,
14816 rb_class_name(CLASS_OF(obj)));
14817 }
14818}
14819
14820static VALUE
14821ibf_load_object_struct(const struct ibf_load *load, const struct ibf_object_header *header, ibf_offset_t offset)
14822{
14823 const struct ibf_object_struct_range *range = IBF_OBJBODY(struct ibf_object_struct_range, offset);
14824 VALUE beg = ibf_load_object(load, range->beg);
14825 VALUE end = ibf_load_object(load, range->end);
14826 VALUE obj = rb_range_new(beg, end, range->excl);
14827 if (header->internal) rb_obj_hide(obj);
14828 if (header->frozen) RB_OBJ_SET_FROZEN_SHAREABLE(obj);
14829 return obj;
14830}
14831
14832static void
14833ibf_dump_object_bignum(struct ibf_dump *dump, VALUE obj)
14834{
14835 ssize_t len = BIGNUM_LEN(obj);
14836 ssize_t slen = BIGNUM_SIGN(obj) > 0 ? len : len * -1;
14837 BDIGIT *d = BIGNUM_DIGITS(obj);
14838
14839 (void)IBF_W(&slen, ssize_t, 1);
14840 IBF_WP(d, BDIGIT, len);
14841}
14842
14843static VALUE
14844ibf_load_object_bignum(const struct ibf_load *load, const struct ibf_object_header *header, ibf_offset_t offset)
14845{
14846 const struct ibf_object_bignum *bignum = IBF_OBJBODY(struct ibf_object_bignum, offset);
14847 int sign = bignum->slen > 0;
14848 ssize_t len = sign > 0 ? bignum->slen : -1 * bignum->slen;
14849 const int big_unpack_flags = /* c.f. rb_big_unpack() */
14852 VALUE obj = rb_integer_unpack(bignum->digits, len, sizeof(BDIGIT), 0,
14853 big_unpack_flags |
14854 (sign == 0 ? INTEGER_PACK_NEGATIVE : 0));
14855 if (header->internal) rb_obj_hide(obj);
14856 if (header->frozen) RB_OBJ_SET_FROZEN_SHAREABLE(obj);
14857 return obj;
14858}
14859
14860static void
14861ibf_dump_object_data(struct ibf_dump *dump, VALUE obj)
14862{
14863 if (rb_data_is_encoding(obj)) {
14864 rb_encoding *enc = rb_to_encoding(obj);
14865 const char *name = rb_enc_name(enc);
14866 long len = strlen(name) + 1;
14867 long data[2];
14868 data[0] = IBF_OBJECT_DATA_ENCODING;
14869 data[1] = len;
14870 (void)IBF_W(data, long, 2);
14871 IBF_WP(name, char, len);
14872 }
14873 else {
14874 ibf_dump_object_unsupported(dump, obj);
14875 }
14876}
14877
14878static VALUE
14879ibf_load_object_data(const struct ibf_load *load, const struct ibf_object_header *header, ibf_offset_t offset)
14880{
14881 const long *body = IBF_OBJBODY(long, offset);
14882 const enum ibf_object_data_type type = (enum ibf_object_data_type)body[0];
14883 /* const long len = body[1]; */
14884 const char *data = (const char *)&body[2];
14885
14886 switch (type) {
14887 case IBF_OBJECT_DATA_ENCODING:
14888 {
14889 VALUE encobj = rb_enc_from_encoding(rb_enc_find(data));
14890 return encobj;
14891 }
14892 }
14893
14894 return ibf_load_object_unsupported(load, header, offset);
14895}
14896
14897static void
14898ibf_dump_object_complex_rational(struct ibf_dump *dump, VALUE obj)
14899{
14900 long data[2];
14901 data[0] = (long)ibf_dump_object(dump, RCOMPLEX(obj)->real);
14902 data[1] = (long)ibf_dump_object(dump, RCOMPLEX(obj)->imag);
14903
14904 (void)IBF_W(data, long, 2);
14905}
14906
14907static VALUE
14908ibf_load_object_complex_rational(const struct ibf_load *load, const struct ibf_object_header *header, ibf_offset_t offset)
14909{
14910 const struct ibf_object_complex_rational *nums = IBF_OBJBODY(struct ibf_object_complex_rational, offset);
14911 VALUE a = ibf_load_object(load, nums->a);
14912 VALUE b = ibf_load_object(load, nums->b);
14913 VALUE obj = header->type == T_COMPLEX ?
14914 rb_complex_new(a, b) : rb_rational_new(a, b);
14915
14916 if (header->internal) rb_obj_hide(obj);
14917 if (header->frozen) rb_ractor_make_shareable(rb_obj_freeze(obj));
14918 return obj;
14919}
14920
14921static void
14922ibf_dump_object_symbol(struct ibf_dump *dump, VALUE obj)
14923{
14924 ibf_dump_object_string(dump, rb_sym2str(obj));
14925}
14926
14927static VALUE
14928ibf_load_object_symbol(const struct ibf_load *load, const struct ibf_object_header *header, ibf_offset_t offset)
14929{
14930 ibf_offset_t reading_pos = offset;
14931
14932 int encindex = (int)ibf_load_small_value(load, &reading_pos);
14933 const rb_len_t len = (rb_len_t)ibf_load_small_value(load, &reading_pos);
14934 const char *ptr = load->current_buffer->buff + reading_pos;
14935
14936 if (encindex > RUBY_ENCINDEX_BUILTIN_MAX) {
14937 VALUE enc_name_str = ibf_load_object(load, encindex - RUBY_ENCINDEX_BUILTIN_MAX);
14938 encindex = rb_enc_find_index(RSTRING_PTR(enc_name_str));
14939 }
14940
14941 ID id = rb_intern3(ptr, len, rb_enc_from_index(encindex));
14942 return ID2SYM(id);
14943}
14944
14945typedef void (*ibf_dump_object_function)(struct ibf_dump *dump, VALUE obj);
14946static const ibf_dump_object_function dump_object_functions[RUBY_T_MASK+1] = {
14947 ibf_dump_object_unsupported, /* T_NONE */
14948 ibf_dump_object_unsupported, /* T_OBJECT */
14949 ibf_dump_object_class, /* T_CLASS */
14950 ibf_dump_object_unsupported, /* T_MODULE */
14951 ibf_dump_object_float, /* T_FLOAT */
14952 ibf_dump_object_string, /* T_STRING */
14953 ibf_dump_object_regexp, /* T_REGEXP */
14954 ibf_dump_object_array, /* T_ARRAY */
14955 ibf_dump_object_hash, /* T_HASH */
14956 ibf_dump_object_struct, /* T_STRUCT */
14957 ibf_dump_object_bignum, /* T_BIGNUM */
14958 ibf_dump_object_unsupported, /* T_FILE */
14959 ibf_dump_object_data, /* T_DATA */
14960 ibf_dump_object_unsupported, /* T_MATCH */
14961 ibf_dump_object_complex_rational, /* T_COMPLEX */
14962 ibf_dump_object_complex_rational, /* T_RATIONAL */
14963 ibf_dump_object_unsupported, /* 0x10 */
14964 ibf_dump_object_unsupported, /* 0x11 T_NIL */
14965 ibf_dump_object_unsupported, /* 0x12 T_TRUE */
14966 ibf_dump_object_unsupported, /* 0x13 T_FALSE */
14967 ibf_dump_object_symbol, /* 0x14 T_SYMBOL */
14968 ibf_dump_object_unsupported, /* T_FIXNUM */
14969 ibf_dump_object_unsupported, /* T_UNDEF */
14970 ibf_dump_object_unsupported, /* 0x17 */
14971 ibf_dump_object_unsupported, /* 0x18 */
14972 ibf_dump_object_unsupported, /* 0x19 */
14973 ibf_dump_object_imemo, /* T_IMEMO 0x1a */
14974 ibf_dump_object_unsupported, /* T_NODE 0x1b */
14975 ibf_dump_object_unsupported, /* T_ICLASS 0x1c */
14976 ibf_dump_object_unsupported, /* T_ZOMBIE 0x1d */
14977 ibf_dump_object_unsupported, /* 0x1e */
14978 ibf_dump_object_unsupported, /* 0x1f */
14979};
14980
14981static void
14982ibf_dump_object_object_header(struct ibf_dump *dump, const struct ibf_object_header header)
14983{
14984 unsigned char byte =
14985 (header.type << 0) |
14986 (header.special_const << 5) |
14987 (header.frozen << 6) |
14988 (header.internal << 7);
14989
14990 IBF_WV(byte);
14991}
14992
14993static struct ibf_object_header
14994ibf_load_object_object_header(const struct ibf_load *load, ibf_offset_t *offset)
14995{
14996 unsigned char byte = ibf_load_byte(load, offset);
14997
14998 struct ibf_object_header header;
14999 header.type = (byte >> 0) & 0x1f;
15000 header.special_const = (byte >> 5) & 0x01;
15001 header.frozen = (byte >> 6) & 0x01;
15002 header.internal = (byte >> 7) & 0x01;
15003
15004 return header;
15005}
15006
15007static ibf_offset_t
15008ibf_dump_object_object(struct ibf_dump *dump, VALUE obj)
15009{
15010 struct ibf_object_header obj_header;
15011 ibf_offset_t current_offset;
15012 IBF_ZERO(obj_header);
15013 obj_header.type = TYPE(obj);
15014
15015 IBF_W_ALIGN(ibf_offset_t);
15016 current_offset = ibf_dump_pos(dump);
15017
15018 if (SPECIAL_CONST_P(obj) &&
15019 ! (SYMBOL_P(obj) ||
15020 RB_FLOAT_TYPE_P(obj))) {
15021 obj_header.special_const = TRUE;
15022 obj_header.frozen = TRUE;
15023 obj_header.internal = TRUE;
15024 ibf_dump_object_object_header(dump, obj_header);
15025 ibf_dump_write_small_value(dump, obj);
15026 }
15027 else {
15028 obj_header.internal = SPECIAL_CONST_P(obj) ? FALSE : (RBASIC_CLASS(obj) == 0) ? TRUE : FALSE;
15029 obj_header.special_const = FALSE;
15030 obj_header.frozen = OBJ_FROZEN(obj) ? TRUE : FALSE;
15031 ibf_dump_object_object_header(dump, obj_header);
15032 (*dump_object_functions[obj_header.type])(dump, obj);
15033 }
15034
15035 return current_offset;
15036}
15037
15038typedef VALUE (*ibf_load_object_function)(const struct ibf_load *load, const struct ibf_object_header *header, ibf_offset_t offset);
15039static const ibf_load_object_function load_object_functions[RUBY_T_MASK+1] = {
15040 ibf_load_object_unsupported, /* T_NONE */
15041 ibf_load_object_unsupported, /* T_OBJECT */
15042 ibf_load_object_class, /* T_CLASS */
15043 ibf_load_object_unsupported, /* T_MODULE */
15044 ibf_load_object_float, /* T_FLOAT */
15045 ibf_load_object_string, /* T_STRING */
15046 ibf_load_object_regexp, /* T_REGEXP */
15047 ibf_load_object_array, /* T_ARRAY */
15048 ibf_load_object_hash, /* T_HASH */
15049 ibf_load_object_struct, /* T_STRUCT */
15050 ibf_load_object_bignum, /* T_BIGNUM */
15051 ibf_load_object_unsupported, /* T_FILE */
15052 ibf_load_object_data, /* T_DATA */
15053 ibf_load_object_unsupported, /* T_MATCH */
15054 ibf_load_object_complex_rational, /* T_COMPLEX */
15055 ibf_load_object_complex_rational, /* T_RATIONAL */
15056 ibf_load_object_unsupported, /* 0x10 */
15057 ibf_load_object_unsupported, /* T_NIL */
15058 ibf_load_object_unsupported, /* T_TRUE */
15059 ibf_load_object_unsupported, /* T_FALSE */
15060 ibf_load_object_symbol,
15061 ibf_load_object_unsupported, /* T_FIXNUM */
15062 ibf_load_object_unsupported, /* T_UNDEF */
15063 ibf_load_object_unsupported, /* 0x17 */
15064 ibf_load_object_unsupported, /* 0x18 */
15065 ibf_load_object_unsupported, /* 0x19 */
15066 ibf_load_object_imemo, /* T_IMEMO 0x1a */
15067 ibf_load_object_unsupported, /* T_NODE 0x1b */
15068 ibf_load_object_unsupported, /* T_ICLASS 0x1c */
15069 ibf_load_object_unsupported, /* T_ZOMBIE 0x1d */
15070 ibf_load_object_unsupported, /* 0x1e */
15071 ibf_load_object_unsupported, /* 0x1f */
15072};
15073
15074static VALUE
15075ibf_load_object(const struct ibf_load *load, VALUE object_index)
15076{
15077 if (object_index == 0) {
15078 return Qnil;
15079 }
15080 else {
15081 VALUE obj = pinned_list_fetch(load->current_buffer->obj_list, (long)object_index);
15082 if (!obj) {
15083 ibf_offset_t *offsets = (ibf_offset_t *)(load->current_buffer->obj_list_offset + load->current_buffer->buff);
15084 ibf_offset_t offset = offsets[object_index];
15085 const struct ibf_object_header header = ibf_load_object_object_header(load, &offset);
15086
15087#if IBF_ISEQ_DEBUG
15088 fprintf(stderr, "ibf_load_object: list=%#x offsets=%p offset=%#x\n",
15089 load->current_buffer->obj_list_offset, (void *)offsets, offset);
15090 fprintf(stderr, "ibf_load_object: type=%#x special=%d frozen=%d internal=%d\n",
15091 header.type, header.special_const, header.frozen, header.internal);
15092#endif
15093 if (offset >= load->current_buffer->size) {
15094 rb_raise(rb_eIndexError, "object offset out of range: %u", offset);
15095 }
15096
15097 if (header.special_const) {
15098 ibf_offset_t reading_pos = offset;
15099
15100 obj = ibf_load_small_value(load, &reading_pos);
15101 }
15102 else {
15103 obj = (*load_object_functions[header.type])(load, &header, offset);
15104 }
15105
15106 pinned_list_store(load->current_buffer->obj_list, (long)object_index, obj);
15107 }
15108#if IBF_ISEQ_DEBUG
15109 fprintf(stderr, "ibf_load_object: index=%#"PRIxVALUE" obj=%#"PRIxVALUE"\n",
15110 object_index, obj);
15111#endif
15112 return obj;
15113 }
15114}
15115
15117{
15118 struct ibf_dump *dump;
15119 VALUE offset_list;
15120};
15121
15122static int
15123ibf_dump_object_list_i(st_data_t key, st_data_t val, st_data_t ptr)
15124{
15125 VALUE obj = (VALUE)key;
15126 struct ibf_dump_object_list_arg *args = (struct ibf_dump_object_list_arg *)ptr;
15127
15128 ibf_offset_t offset = ibf_dump_object_object(args->dump, obj);
15129 rb_ary_push(args->offset_list, UINT2NUM(offset));
15130
15131 return ST_CONTINUE;
15132}
15133
15134static void
15135ibf_dump_object_list(struct ibf_dump *dump, ibf_offset_t *obj_list_offset, unsigned int *obj_list_size)
15136{
15137 st_table *obj_table = dump->current_buffer->obj_table;
15138 VALUE offset_list = rb_ary_hidden_new(obj_table->num_entries);
15139
15140 struct ibf_dump_object_list_arg args;
15141 args.dump = dump;
15142 args.offset_list = offset_list;
15143
15144 st_foreach(obj_table, ibf_dump_object_list_i, (st_data_t)&args);
15145
15146 IBF_W_ALIGN(ibf_offset_t);
15147 *obj_list_offset = ibf_dump_pos(dump);
15148
15149 st_index_t size = obj_table->num_entries;
15150 st_index_t i;
15151
15152 for (i=0; i<size; i++) {
15153 ibf_offset_t offset = NUM2UINT(RARRAY_AREF(offset_list, i));
15154 IBF_WV(offset);
15155 }
15156
15157 *obj_list_size = (unsigned int)size;
15158}
15159
15160static void
15161ibf_dump_mark(void *ptr)
15162{
15163 struct ibf_dump *dump = (struct ibf_dump *)ptr;
15164 rb_gc_mark(dump->global_buffer.str);
15165
15166 rb_mark_set(dump->global_buffer.obj_table);
15167 rb_mark_set(dump->iseq_table);
15168}
15169
15170static void
15171ibf_dump_free(void *ptr)
15172{
15173 struct ibf_dump *dump = (struct ibf_dump *)ptr;
15174 if (dump->global_buffer.obj_table) {
15175 st_free_table(dump->global_buffer.obj_table);
15176 dump->global_buffer.obj_table = 0;
15177 }
15178 if (dump->iseq_table) {
15179 st_free_table(dump->iseq_table);
15180 dump->iseq_table = 0;
15181 }
15182}
15183
15184static size_t
15185ibf_dump_memsize(const void *ptr)
15186{
15187 struct ibf_dump *dump = (struct ibf_dump *)ptr;
15188 size_t size = 0;
15189 if (dump->iseq_table) size += st_memsize(dump->iseq_table);
15190 if (dump->global_buffer.obj_table) size += st_memsize(dump->global_buffer.obj_table);
15191 return size;
15192}
15193
15194static const rb_data_type_t ibf_dump_type = {
15195 "ibf_dump",
15196 {ibf_dump_mark, ibf_dump_free, ibf_dump_memsize,},
15197 0, 0, RUBY_TYPED_THREAD_SAFE_FREE | RUBY_TYPED_EMBEDDABLE
15198};
15199
15200static void
15201ibf_dump_setup(struct ibf_dump *dump, VALUE dumper_obj)
15202{
15203 dump->global_buffer.obj_table = NULL; // GC may run before a value is assigned
15204 dump->iseq_table = NULL;
15205
15206 RB_OBJ_WRITE(dumper_obj, &dump->global_buffer.str, rb_str_new(0, 0));
15207 dump->global_buffer.obj_table = ibf_dump_object_table_new();
15208 dump->iseq_table = st_init_numtable(); /* need free */
15209
15210 dump->current_buffer = &dump->global_buffer;
15211}
15212
15213static VALUE
15214iseq_ibf_dump_0(struct ibf_dump *dump, const rb_iseq_t *iseq, VALUE opt)
15215{
15216 struct ibf_header header = {{0}};
15217
15218 ibf_dump_write(dump, &header, sizeof(header));
15219 ibf_dump_iseq(dump, iseq);
15220
15221 header.magic[0] = 'Y'; /* YARB */
15222 header.magic[1] = 'A';
15223 header.magic[2] = 'R';
15224 header.magic[3] = 'B';
15225 header.major_version = IBF_MAJOR_VERSION;
15226 header.minor_version = IBF_MINOR_VERSION;
15227 header.endian = IBF_ENDIAN_MARK;
15228 header.wordsize = (uint8_t)SIZEOF_VALUE;
15229 ibf_dump_iseq_list(dump, &header);
15230 ibf_dump_object_list(dump, &header.global_object_list_offset, &header.global_object_list_size);
15231 header.size = ibf_dump_pos(dump);
15232
15233 if (RTEST(opt)) {
15234 VALUE opt_str = opt;
15235 const char *ptr = StringValuePtr(opt_str);
15236 header.extra_size = RSTRING_LENINT(opt_str);
15237 ibf_dump_write(dump, ptr, header.extra_size);
15238 }
15239 else {
15240 header.extra_size = 0;
15241 }
15242
15243 ibf_dump_overwrite(dump, &header, sizeof(header), 0);
15244
15245 return dump->global_buffer.str;
15246}
15247
15248VALUE
15249rb_iseq_ibf_dump(const rb_iseq_t *iseq, VALUE opt)
15250{
15251 struct ibf_dump *dump;
15252 VALUE dump_obj;
15253 VALUE str;
15254
15255 if (ISEQ_BODY(iseq)->parent_iseq != NULL ||
15256 ISEQ_BODY(iseq)->local_iseq != iseq) {
15257 rb_raise(rb_eRuntimeError, "should be top of iseq");
15258 }
15259 if (RTEST(ISEQ_COVERAGE(iseq))) {
15260 rb_raise(rb_eRuntimeError, "should not compile with coverage");
15261 }
15262
15263 dump_obj = TypedData_Make_Struct(0, struct ibf_dump, &ibf_dump_type, dump);
15264 ibf_dump_setup(dump, dump_obj);
15265
15266 str = iseq_ibf_dump_0(dump, iseq, opt);
15267 RB_GC_GUARD(dump_obj);
15268 return str;
15269}
15270
15271static const ibf_offset_t *
15272ibf_iseq_list(const struct ibf_load *load)
15273{
15274 return (const ibf_offset_t *)(load->global_buffer.buff + load->header->iseq_list_offset);
15275}
15276
15277void
15278rb_ibf_load_iseq_complete(rb_iseq_t *iseq)
15279{
15280 struct ibf_load *load = RTYPEDDATA_DATA(iseq->aux.loader.obj);
15281 rb_iseq_t *prev_src_iseq = load->iseq;
15282 ibf_offset_t offset = ibf_iseq_list(load)[iseq->aux.loader.index];
15283 load->iseq = iseq;
15284#if IBF_ISEQ_DEBUG
15285 fprintf(stderr, "rb_ibf_load_iseq_complete: index=%#x offset=%#x size=%#x\n",
15286 iseq->aux.loader.index, offset,
15287 load->header->size);
15288#endif
15289 ibf_load_iseq_each(load, iseq, offset);
15290 ISEQ_COMPILE_DATA_CLEAR(iseq);
15291 FL_UNSET((VALUE)iseq, ISEQ_NOT_LOADED_YET);
15292 rb_iseq_init_trace(iseq);
15293 load->iseq = prev_src_iseq;
15294}
15295
15296#if USE_LAZY_LOAD
15297const rb_iseq_t *
15298rb_iseq_complete(const rb_iseq_t *iseq)
15299{
15300 rb_ibf_load_iseq_complete((rb_iseq_t *)iseq);
15301 return iseq;
15302}
15303#endif
15304
15305static rb_iseq_t *
15306ibf_load_iseq(const struct ibf_load *load, const rb_iseq_t *index_iseq)
15307{
15308 int iseq_index = (int)(VALUE)index_iseq;
15309
15310#if IBF_ISEQ_DEBUG
15311 fprintf(stderr, "ibf_load_iseq: index_iseq=%p iseq_list=%p\n",
15312 (void *)index_iseq, (void *)load->iseq_list);
15313#endif
15314 if (iseq_index == -1) {
15315 return NULL;
15316 }
15317 else {
15318 VALUE iseqv = pinned_list_fetch(load->iseq_list, iseq_index);
15319
15320#if IBF_ISEQ_DEBUG
15321 fprintf(stderr, "ibf_load_iseq: iseqv=%p\n", (void *)iseqv);
15322#endif
15323 if (iseqv) {
15324 return (rb_iseq_t *)iseqv;
15325 }
15326 else {
15327 rb_iseq_t *iseq = iseq_imemo_alloc();
15328#if IBF_ISEQ_DEBUG
15329 fprintf(stderr, "ibf_load_iseq: new iseq=%p\n", (void *)iseq);
15330#endif
15331 FL_SET((VALUE)iseq, ISEQ_NOT_LOADED_YET);
15332 RB_OBJ_WRITE((VALUE)iseq, &iseq->aux.loader.obj, load->loader_obj);
15333 iseq->aux.loader.index = iseq_index;
15334#if IBF_ISEQ_DEBUG
15335 fprintf(stderr, "ibf_load_iseq: iseq=%p loader_obj=%p index=%d\n",
15336 (void *)iseq, (void *)load->loader_obj, iseq_index);
15337#endif
15338 pinned_list_store(load->iseq_list, iseq_index, (VALUE)iseq);
15339
15340 if (!USE_LAZY_LOAD || GET_VM()->builtin_function_table) {
15341#if IBF_ISEQ_DEBUG
15342 fprintf(stderr, "ibf_load_iseq: loading iseq=%p\n", (void *)iseq);
15343#endif
15344 rb_ibf_load_iseq_complete(iseq);
15345 }
15346
15347#if IBF_ISEQ_DEBUG
15348 fprintf(stderr, "ibf_load_iseq: iseq=%p loaded %p\n",
15349 (void *)iseq, (void *)load->iseq);
15350#endif
15351 return iseq;
15352 }
15353 }
15354}
15355
15356static void
15357ibf_load_setup_bytes(struct ibf_load *load, VALUE loader_obj, const char *bytes, size_t size)
15358{
15359 struct ibf_header *header = (struct ibf_header *)bytes;
15360 load->loader_obj = loader_obj;
15361 load->global_buffer.buff = bytes;
15362 load->header = header;
15363 load->global_buffer.size = header->size;
15364 load->global_buffer.obj_list_offset = header->global_object_list_offset;
15365 load->global_buffer.obj_list_size = header->global_object_list_size;
15366 RB_OBJ_WRITE(loader_obj, &load->iseq_list, pinned_list_new(header->iseq_list_size));
15367 RB_OBJ_WRITE(loader_obj, &load->global_buffer.obj_list, pinned_list_new(load->global_buffer.obj_list_size));
15368 load->iseq = NULL;
15369
15370 load->current_buffer = &load->global_buffer;
15371
15372 if (size < header->size) {
15373 rb_raise(rb_eRuntimeError, "broken binary format");
15374 }
15375 if (strncmp(header->magic, "YARB", 4) != 0) {
15376 rb_raise(rb_eRuntimeError, "unknown binary format");
15377 }
15378 if (header->major_version != IBF_MAJOR_VERSION ||
15379 header->minor_version != IBF_MINOR_VERSION) {
15380 rb_raise(rb_eRuntimeError, "unmatched version file (%u.%u for %u.%u)",
15381 header->major_version, header->minor_version, IBF_MAJOR_VERSION, IBF_MINOR_VERSION);
15382 }
15383 if (header->endian != IBF_ENDIAN_MARK) {
15384 rb_raise(rb_eRuntimeError, "unmatched endian: %c", header->endian);
15385 }
15386 if (header->wordsize != SIZEOF_VALUE) {
15387 rb_raise(rb_eRuntimeError, "unmatched word size: %d", header->wordsize);
15388 }
15389 if (header->iseq_list_offset % RUBY_ALIGNOF(ibf_offset_t)) {
15390 rb_raise(rb_eArgError, "unaligned iseq list offset: %u",
15391 header->iseq_list_offset);
15392 }
15393 if (load->global_buffer.obj_list_offset % RUBY_ALIGNOF(ibf_offset_t)) {
15394 rb_raise(rb_eArgError, "unaligned object list offset: %u",
15395 load->global_buffer.obj_list_offset);
15396 }
15397}
15398
15399static void
15400ibf_load_setup(struct ibf_load *load, VALUE loader_obj, VALUE str)
15401{
15402 StringValue(str);
15403
15404 if (RSTRING_LENINT(str) < (int)sizeof(struct ibf_header)) {
15405 rb_raise(rb_eRuntimeError, "broken binary format");
15406 }
15407
15408 if (USE_LAZY_LOAD) {
15409 str = rb_str_new(RSTRING_PTR(str), RSTRING_LEN(str));
15410 }
15411
15412 ibf_load_setup_bytes(load, loader_obj, RSTRING_PTR(str), RSTRING_LEN(str));
15413 RB_OBJ_WRITE(loader_obj, &load->str, str);
15414}
15415
15416static void
15417ibf_loader_mark(void *ptr)
15418{
15419 struct ibf_load *load = (struct ibf_load *)ptr;
15420 rb_gc_mark(load->str);
15421 rb_gc_mark(load->path_override);
15422 rb_gc_mark(load->realpath_override);
15423 rb_gc_mark(load->iseq_list);
15424 rb_gc_mark(load->global_buffer.obj_list);
15425}
15426
15427static void
15428ibf_loader_free(void *ptr)
15429{
15430 struct ibf_load *load = (struct ibf_load *)ptr;
15431 SIZED_FREE(load);
15432}
15433
15434static size_t
15435ibf_loader_memsize(const void *ptr)
15436{
15437 return sizeof(struct ibf_load);
15438}
15439
15440static const rb_data_type_t ibf_load_type = {
15441 "ibf_loader",
15442 {ibf_loader_mark, ibf_loader_free, ibf_loader_memsize,},
15443 0, 0, RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_THREAD_SAFE_FREE
15444};
15445
15446static void
15447ibf_load_set_path(struct ibf_load *load, VALUE path, VALUE realpath)
15448{
15449 if (NIL_P(path)) return;
15450 if (NIL_P(realpath)) realpath = path;
15451 RB_OBJ_WRITE(load->loader_obj, &load->path_override, rb_fstring(path));
15452 RB_OBJ_WRITE(load->loader_obj, &load->realpath_override, rb_fstring(realpath));
15453}
15454
15455const rb_iseq_t *
15456rb_iseq_ibf_load(VALUE str, VALUE fname, VALUE path)
15457{
15458 struct ibf_load *load;
15459 rb_iseq_t *iseq;
15460 VALUE loader_obj = TypedData_Make_Struct(0, struct ibf_load, &ibf_load_type, load);
15461
15462 ibf_load_setup(load, loader_obj, str);
15463 ibf_load_set_path(load, fname, path);
15464 iseq = ibf_load_iseq(load, 0);
15465
15466 RB_GC_GUARD(loader_obj);
15467 return iseq;
15468}
15469
15470const rb_iseq_t *
15471rb_iseq_ibf_load_bytes(const char *bytes, size_t size, VALUE fname, VALUE path)
15472{
15473 struct ibf_load *load;
15474 rb_iseq_t *iseq;
15475 VALUE loader_obj = TypedData_Make_Struct(0, struct ibf_load, &ibf_load_type, load);
15476
15477 ibf_load_setup_bytes(load, loader_obj, bytes, size);
15478 ibf_load_set_path(load, fname, path);
15479 iseq = ibf_load_iseq(load, 0);
15480
15481 RB_GC_GUARD(loader_obj);
15482 return iseq;
15483}
15484
15485/* collect the iseq table into an array indexed by iseq-list index */
15486static int
15487ibf_dump_iseq_table_collect_i(st_data_t key, st_data_t val, st_data_t arg)
15488{
15489 const rb_iseq_t **srcs = (const rb_iseq_t **)arg;
15490 srcs[(int)val] = (const rb_iseq_t *)key;
15491 return ST_CONTINUE;
15492}
15493
15494/* pc2branchindex (branch coverage) is per-iseq, so pair each copy with its
15495 * source by list index */
15496static void
15497iseq_subtree_copy_pc2branchindex(const struct ibf_dump *dump, const struct ibf_load *load)
15498{
15499 unsigned int iseq_count = (unsigned int)dump->iseq_table->num_entries;
15500 VALUE srcs_buf;
15501 const rb_iseq_t **srcs = ALLOCV_N(const rb_iseq_t *, srcs_buf, iseq_count);
15502 st_foreach(dump->iseq_table, ibf_dump_iseq_table_collect_i, (st_data_t)srcs);
15503
15504 for (unsigned int i = 0; i < iseq_count; i++) {
15505 rb_iseq_t *copy = ibf_load_iseq(load, (const rb_iseq_t *)(VALUE)i);
15506 VALUE pc2branchindex = ISEQ_PC2BRANCHINDEX(srcs[i]);
15507 if (pc2branchindex != Qnil) {
15508 ISEQ_PC2BRANCHINDEX_SET(copy, pc2branchindex);
15509 }
15510 }
15511
15512 ALLOCV_END(srcs_buf);
15513}
15514
15515/* Deep-copy an iseq subtree with independent inline caches for Proc#refined */
15516const rb_iseq_t *
15517rb_iseq_dup_with_independent_caches(const rb_iseq_t *src_root)
15518{
15519 struct ibf_dump *dump;
15520 VALUE dump_obj;
15521 VALUE str;
15522
15523 /* --- dump the subtree --- */
15524 dump_obj = TypedData_Make_Struct(0, struct ibf_dump, &ibf_dump_type, dump);
15525 ibf_dump_setup(dump, dump_obj);
15526
15527 str = iseq_ibf_dump_0(dump, src_root, Qnil);
15528
15529 /* --- load it back --- */
15530 struct ibf_load *load;
15531 VALUE loader_obj = TypedData_Make_Struct(0, struct ibf_load, &ibf_load_type, load);
15532 ibf_load_setup(load, loader_obj, str);
15533
15534 /* What the loader could not reconstruct is the same for every iseq in
15535 * the subtree: the only absent parent is the top's, every absent
15536 * local_iseq is the source's local root (runtime walks compare it
15537 * against the original frames, so a copy must not stand in), and
15538 * pathobj/script_lines/coverage are per-file values. */
15539 const struct rb_iseq_constant_body *sb = ISEQ_BODY(src_root);
15540 unsigned int iseq_count = (unsigned int)dump->iseq_table->num_entries;
15541 const rb_iseq_t *result = NULL;
15542 for (unsigned int i = 0; i < iseq_count; i++) {
15543 rb_iseq_t *copy = ibf_load_iseq(load, (const rb_iseq_t *)(VALUE)i);
15544 /* force completion even under USE_LAZY_LOAD */
15545 if (FL_TEST((VALUE)copy, ISEQ_NOT_LOADED_YET)) {
15546 rb_ibf_load_iseq_complete(copy);
15547 }
15548
15549 FL_SET((VALUE)copy, ISEQ_REFINED_COPY);
15550
15551 struct rb_iseq_constant_body *cb = ISEQ_BODY(copy);
15552 if (!cb->local_iseq) RB_OBJ_WRITE(copy, &cb->local_iseq, sb->local_iseq);
15553 RB_OBJ_WRITE(copy, &cb->location.pathobj, sb->location.pathobj);
15554 cb->no_realpath = sb->no_realpath;
15555 VALUE sl = ISEQ_SCRIPT_LINES(src_root);
15556 VALUE cov = ISEQ_COVERAGE(src_root);
15557 if (!NIL_P(sl) || !NIL_P(cov)) {
15558 struct rb_iseq_variable *v = rb_iseq_variable_ensure(copy);
15559 RB_OBJ_WRITE(copy, &v->script_lines, sl);
15560 RB_OBJ_WRITE(copy, &v->coverage, cov);
15561 }
15562
15563 if (i == 0) {
15564 RB_OBJ_WRITE(copy, &cb->parent_iseq, sb->parent_iseq);
15565 result = copy;
15566 }
15567
15568 /* Shared across Ractors through the Proc#refined memo; the duplicated
15569 * subtree is self-contained, so mark each copy shareable. */
15571 }
15572
15573 if (ISEQ_PC2BRANCHINDEX(src_root) != Qnil) {
15574 iseq_subtree_copy_pc2branchindex(dump, load);
15575 }
15576
15577 RB_GC_GUARD(dump_obj);
15578 RB_GC_GUARD(loader_obj);
15579 return result;
15580}
15581
15582VALUE
15583rb_iseq_ibf_load_extra_data(VALUE str)
15584{
15585 struct ibf_load *load;
15586 VALUE loader_obj = TypedData_Make_Struct(0, struct ibf_load, &ibf_load_type, load);
15587 VALUE extra_str;
15588
15589 ibf_load_setup(load, loader_obj, str);
15590 extra_str = rb_str_new(load->global_buffer.buff + load->header->size, load->header->extra_size);
15591 RB_GC_GUARD(loader_obj);
15592 return extra_str;
15593}
15594
15595#include "prism_compile.c"
#define RUBY_ATOMIC_PTR_LOAD(var)
Identical to RUBY_ATOMIC_LOAD, except it expects its arguments are void*.
Definition atomic.h:348
#define LONG_LONG
Definition long_long.h:38
#define RUBY_ALIGNOF
Wraps (or simulates) alignof.
Definition stdalign.h:28
#define RUBY_EVENT_END
Encountered an end of a class clause.
Definition event.h:40
#define RUBY_EVENT_C_CALL
A method, written in C, is called.
Definition event.h:43
#define RUBY_EVENT_B_RETURN
Encountered a next statement.
Definition event.h:56
#define RUBY_EVENT_CLASS
Encountered a new class.
Definition event.h:39
#define RUBY_EVENT_NONE
No events.
Definition event.h:37
#define RUBY_EVENT_LINE
Encountered a new line.
Definition event.h:38
#define RUBY_EVENT_RETURN
Encountered a return statement.
Definition event.h:42
#define RUBY_EVENT_C_RETURN
Return from a method, written in C.
Definition event.h:44
#define RUBY_EVENT_B_CALL
Encountered an yield statement.
Definition event.h:55
uint32_t rb_event_flag_t
Represents event(s).
Definition event.h:108
#define RUBY_EVENT_CALL
A method, written in Ruby, is called.
Definition event.h:41
#define RUBY_EVENT_RESCUE
Encountered a rescue statement.
Definition event.h:61
#define RBIMPL_ATTR_FORMAT(x, y, z)
Wraps (or simulates) __attribute__((format)).
Definition format.h:33
#define rb_str_new2
Old name of rb_str_new_cstr.
Definition string.h:1700
#define T_COMPLEX
Old name of RUBY_T_COMPLEX.
Definition value_type.h:59
#define TYPE(_)
Old name of rb_type.
Definition value_type.h:108
#define NUM2ULONG
Old name of RB_NUM2ULONG.
Definition long.h:52
#define NUM2LL
Old name of RB_NUM2LL.
Definition long_long.h:34
#define ALLOCV
Old name of RB_ALLOCV.
Definition memory.h:407
#define RFLOAT_VALUE
Old name of rb_float_value.
Definition double.h:28
#define T_STRING
Old name of RUBY_T_STRING.
Definition value_type.h:78
#define Qundef
Old name of RUBY_Qundef.
#define INT2FIX
Old name of RB_INT2FIX.
Definition long.h:48
#define OBJ_FROZEN
Old name of RB_OBJ_FROZEN.
Definition fl_type.h:133
#define rb_str_cat2
Old name of rb_str_cat_cstr.
Definition string.h:1708
#define T_NIL
Old name of RUBY_T_NIL.
Definition value_type.h:72
#define UNREACHABLE
Old name of RBIMPL_UNREACHABLE.
Definition assume.h:28
#define T_FLOAT
Old name of RUBY_T_FLOAT.
Definition value_type.h:64
#define ID2SYM
Old name of RB_ID2SYM.
Definition symbol.h:44
#define T_BIGNUM
Old name of RUBY_T_BIGNUM.
Definition value_type.h:57
#define SPECIAL_CONST_P
Old name of RB_SPECIAL_CONST_P.
#define OBJ_FREEZE
Old name of RB_OBJ_FREEZE.
Definition fl_type.h:131
#define ULONG2NUM
Old name of RB_ULONG2NUM.
Definition long.h:60
#define UNREACHABLE_RETURN
Old name of RBIMPL_UNREACHABLE_RETURN.
Definition assume.h:29
#define SYM2ID
Old name of RB_SYM2ID.
Definition symbol.h:45
#define FIX2UINT
Old name of RB_FIX2UINT.
Definition int.h:42
#define ZALLOC
Old name of RB_ZALLOC.
Definition memory.h:405
#define CLASS_OF
Old name of rb_class_of.
Definition globals.h:205
#define FIXABLE
Old name of RB_FIXABLE.
Definition fixnum.h:25
#define xmalloc
Old name of ruby_xmalloc.
Definition xmalloc.h:53
#define LONG2FIX
Old name of RB_INT2FIX.
Definition long.h:49
#define FIX2INT
Old name of RB_FIX2INT.
Definition int.h:41
#define NUM2UINT
Old name of RB_NUM2UINT.
Definition int.h:45
#define ZALLOC_N
Old name of RB_ZALLOC_N.
Definition memory.h:404
#define ASSUME
Old name of RBIMPL_ASSUME.
Definition assume.h:27
#define T_RATIONAL
Old name of RUBY_T_RATIONAL.
Definition value_type.h:76
#define T_HASH
Old name of RUBY_T_HASH.
Definition value_type.h:65
#define ALLOC_N
Old name of RB_ALLOC_N.
Definition memory.h:402
#define FL_SET
Old name of RB_FL_SET.
Definition fl_type.h:125
#define FLONUM_P
Old name of RB_FLONUM_P.
#define Qtrue
Old name of RUBY_Qtrue.
#define NUM2INT
Old name of RB_NUM2INT.
Definition int.h:44
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define FIX2LONG
Old name of RB_FIX2LONG.
Definition long.h:46
#define T_ARRAY
Old name of RUBY_T_ARRAY.
Definition value_type.h:56
#define NIL_P
Old name of RB_NIL_P.
#define ALLOCV_N
Old name of RB_ALLOCV_N.
Definition memory.h:408
#define NUM2ULL
Old name of RB_NUM2ULL.
Definition long_long.h:35
#define T_SYMBOL
Old name of RUBY_T_SYMBOL.
Definition value_type.h:80
#define DBL2NUM
Old name of rb_float_new.
Definition double.h:29
#define BUILTIN_TYPE
Old name of RB_BUILTIN_TYPE.
Definition value_type.h:85
#define FL_TEST
Old name of RB_FL_TEST.
Definition fl_type.h:127
#define NUM2LONG
Old name of RB_NUM2LONG.
Definition long.h:51
#define FL_UNSET
Old name of RB_FL_UNSET.
Definition fl_type.h:129
#define UINT2NUM
Old name of RB_UINT2NUM.
Definition int.h:46
#define FIXNUM_P
Old name of RB_FIXNUM_P.
#define CONST_ID
Old name of RUBY_CONST_ID.
Definition symbol.h:47
#define ALLOCV_END
Old name of RB_ALLOCV_END.
Definition memory.h:409
#define SYMBOL_P
Old name of RB_SYMBOL_P.
Definition value_type.h:88
#define T_REGEXP
Old name of RUBY_T_REGEXP.
Definition value_type.h:77
#define ruby_debug
This variable controls whether the interpreter is in debug mode.
Definition error.h:487
VALUE rb_eNotImpError
NotImplementedError exception.
Definition error.c:1467
VALUE rb_eStandardError
StandardError exception.
Definition error.c:1454
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1457
VALUE rb_eNoMatchingPatternError
NoMatchingPatternError exception.
Definition error.c:1470
void rb_exc_fatal(VALUE mesg)
Raises a fatal error in the current thread.
Definition eval.c:692
VALUE rb_eRuntimeError
RuntimeError exception.
Definition error.c:1455
void rb_warn(const char *fmt,...)
Identical to rb_warning(), except it reports unless $VERBOSE is nil.
Definition error.c:464
VALUE rb_eNoMatchingPatternKeyError
NoMatchingPatternKeyError exception.
Definition error.c:1471
VALUE rb_eIndexError
IndexError exception.
Definition error.c:1459
VALUE rb_errinfo(void)
This is the same as $! in Ruby.
Definition eval.c:2133
VALUE rb_eSyntaxError
SyntaxError exception.
Definition error.c:1474
@ RB_WARN_CATEGORY_STRICT_UNUSED_BLOCK
Warning is for checking unused block strictly.
Definition error.h:57
VALUE rb_obj_reveal(VALUE obj, VALUE klass)
Make a hidden object visible again.
Definition object.c:103
VALUE rb_cArray
Array class.
VALUE rb_cObject
Object class.
Definition object.c:60
VALUE rb_obj_hide(VALUE obj)
Make the object invisible from Ruby code.
Definition object.c:94
VALUE rb_cHash
Hash class.
Definition hash.c:123
VALUE rb_inspect(VALUE obj)
Generates a human-readable textual representation of the given object.
Definition object.c:665
VALUE rb_cRange
Range class.
Definition range.c:35
VALUE rb_obj_is_kind_of(VALUE obj, VALUE klass)
Queries if the given object is an instance (of possibly descendants) of the given class.
Definition object.c:902
VALUE rb_obj_freeze(VALUE obj)
Same as RB_OBJ_FREEZE(), but returns the given object.
Definition object.c:1305
#define RB_OBJ_WRITTEN(old, oldv, young)
Identical to RB_OBJ_WRITE(), except it doesn't write any values, but only a WB declaration.
Definition gc.h:504
#define RB_OBJ_WRITE(old, slot, young)
Declaration of a "back" pointer.
Definition gc.h:492
#define RBIMPL_ASSERT_OR_ASSUME(...)
This is either RUBY_ASSERT or RBIMPL_ASSUME, depending on RUBY_DEBUG.
Definition assert.h:311
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
Definition assert.h:219
#define RB_POSFIXABLE(_)
Checks if the passed value is in range of fixnum, assuming it is a positive number.
Definition fixnum.h:43
#define RBIMPL_ATTR_NORETURN()
Wraps (or simulates) [[noreturn]].
Definition noreturn.h:38
void rb_memerror(void)
Triggers out-of-memory error.
Definition gc.c:6683
VALUE rb_ary_reverse(VALUE ary)
Destructively reverses the passed array in-place.
VALUE rb_ary_resurrect(VALUE ary)
I guess there is no use case of this function in extension libraries, but this is a routine identical...
VALUE rb_ary_entry(VALUE ary, rb_len_t off)
Queries an element of an array.
VALUE rb_ary_new_capa(rb_len_t capa)
Identical to rb_ary_new(), except it additionally specifies how many rooms of objects it should alloc...
void rb_ary_store(VALUE ary, rb_len_t key, VALUE val)
Destructively stores the passed value to the passed array's passed index.
VALUE rb_ary_new(void)
Allocates a new, empty array.
VALUE rb_ary_clear(VALUE ary)
Destructively removes everything form an array.
VALUE rb_ary_hidden_new(rb_len_t capa)
Allocates a hidden (no class) empty array.
VALUE rb_ary_push(VALUE ary, VALUE elem)
Special case of rb_ary_cat() that it adds only one element.
VALUE rb_ary_freeze(VALUE obj)
Freeze an array, preventing further modifications.
VALUE rb_ary_cat(VALUE ary, const VALUE *train, rb_len_t len)
Destructively appends multiple elements at the end of the array.
VALUE rb_ary_join(VALUE ary, VALUE sep)
Recursively stringises the elements of the passed array, flattens that result, then joins the sequenc...
#define INTEGER_PACK_NATIVE_BYTE_ORDER
Means either INTEGER_PACK_MSBYTE_FIRST or INTEGER_PACK_LSBYTE_FIRST, depending on the host processor'...
Definition bignum.h:550
#define INTEGER_PACK_NEGATIVE
Interprets the input as a signed negative number (unpack only).
Definition bignum.h:568
#define INTEGER_PACK_LSWORD_FIRST
Stores/interprets the least significant word as the first word.
Definition bignum.h:532
VALUE rb_hash_new(void)
Creates a new, empty hash object.
Definition hash.c:1656
int rb_is_const_id(ID id)
Classifies the given ID, then sees if it is a constant.
Definition symbol.c:1249
int rb_is_attrset_id(ID id)
Classifies the given ID, then sees if it is an attribute writer.
Definition symbol.c:1273
int rb_range_values(VALUE range, VALUE *begp, VALUE *endp, int *exclp)
Deconstructs a range into its components.
Definition range.c:1857
VALUE rb_range_new(VALUE beg, VALUE end, int excl)
Creates a new Range.
Definition range.c:77
VALUE rb_rational_new(VALUE num, VALUE den)
Constructs a Rational, with reduction.
Definition rational.c:2006
int rb_reg_options(VALUE re)
Queries the options of the passed regular expression.
Definition re.c:5338
VALUE rb_str_append(VALUE dst, VALUE src)
Identical to rb_str_buf_append(), except it converts the right hand side before concatenating.
Definition string.c:3995
VALUE rb_str_tmp_new(rb_len_t len)
Allocates a "temporary" string.
Definition string.c:1816
int rb_str_hash_cmp(VALUE str1, VALUE str2)
Compares two strings.
Definition string.c:4378
#define rb_str_new(str, len)
Allocates an instance of rb_cString.
Definition string.h:1523
st_index_t rb_str_hash(VALUE str)
Calculates a hash value of a string.
Definition string.c:4364
VALUE rb_str_cat(VALUE dst, const char *src, rb_len_t srclen)
Destructively appends the passed contents to the string.
Definition string.c:3761
VALUE rb_str_resurrect(VALUE str)
Like rb_str_dup(), but always create an instance of rb_cString regardless of the given object's class...
Definition string.c:2075
VALUE rb_str_buf_append(VALUE dst, VALUE src)
Identical to rb_str_cat_cstr(), except it takes Ruby's string instead of C's.
Definition string.c:3959
int rb_str_cmp(VALUE lhs, VALUE rhs)
Compares two strings, as in strcmp(3).
Definition string.c:4450
VALUE rb_str_concat(VALUE dst, VALUE src)
Identical to rb_str_append(), except it also accepts an integer as a codepoint.
Definition string.c:4244
VALUE rb_str_freeze(VALUE str)
This is the implementation of String#freeze.
Definition string.c:3430
#define rb_str_new_cstr(str)
Identical to rb_str_new, except it assumes the passed pointer is a pointer to a C string.
Definition string.h:1539
VALUE rb_class_name(VALUE obj)
Queries the name of the given object's class.
Definition variable.c:517
static ID rb_intern_const(const char *str)
This is a "tiny optimisation" over rb_intern().
Definition symbol.h:285
VALUE rb_id2sym(ID id)
Allocates an instance of rb_cSymbol that has the given id.
Definition symbol.c:1142
VALUE rb_sym2str(VALUE symbol)
Obtain a frozen string representation of a symbol (not including the leading colon).
Definition symbol.c:1162
ID rb_sym2id(VALUE obj)
Converts an instance of rb_cSymbol into an ID.
Definition symbol.c:1104
int len
Length of the buffer.
Definition io.h:8
#define RB_OBJ_SET_SHAREABLE(obj)
Wrapper of rb_obj_set_shareable().
Definition ractor.h:290
#define RB_OBJ_SHAREABLE_P(obj)
Queries if the passed object has previously classified as shareable or not.
Definition ractor.h:255
static VALUE RB_OBJ_SET_FROZEN_SHAREABLE(VALUE obj)
Freezes and marks the object as shareable.
Definition ractor.h:301
VALUE rb_ractor_make_shareable(VALUE obj)
Destructively transforms the passed object so that multiple Ractors can share it.
Definition ractor.c:2074
#define DECIMAL_SIZE_OF(expr)
An approximation of decimal representation size.
Definition util.h:48
void ruby_qsort(void *, const size_t, const size_t, int(*)(const void *, const void *, void *), void *)
Reentrant implementation of quick sort.
#define rb_long2int
Just another name of rb_long2int_inline.
Definition long.h:62
#define MEMCPY(p1, p2, type, n)
Handy macro to call memcpy.
Definition memory.h:375
#define ALLOCA_N(type, n)
Definition memory.h:295
#define MEMZERO(p, type, n)
Handy macro to erase a region of memory.
Definition memory.h:363
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
Definition memory.h:170
#define RB_ALLOCV(v, n)
Identical to RB_ALLOCV_N(), except that it allocates a number of bytes and returns a void* .
Definition memory.h:307
VALUE type(ANYARGS)
ANYARGS-ed function type.
int st_foreach(st_table *q, int_type *w, st_data_t e)
Iteration over the given table.
void rb_hash_foreach(VALUE q, int_type *w, VALUE e)
Iteration over the given hash.
#define RARRAY_LEN
Just another name of rb_array_len.
Definition rarray.h:51
static int RARRAY_LENINT(VALUE ary)
Identical to rb_array_len(), except it differs for the return type.
Definition rarray.h:256
#define RARRAY_AREF(a, i)
References an object in an array.
Definition rarray.h:398
static void RARRAY_ASET(VALUE ary, rb_len_t i, VALUE v)
Assigns an object in an array.
Definition rarray.h:362
#define RARRAY_CONST_PTR
Just another name of rb_array_const_ptr.
Definition rarray.h:52
static VALUE RBASIC_CLASS(VALUE obj)
Queries the class of an object.
Definition rbasic.h:166
#define RUBY_DEFAULT_FREE
This is a value you can set to RData::dfree.
Definition rdata.h:56
void(* RUBY_DATA_FUNC)(void *)
This is the type of callbacks registered to RData.
Definition rdata.h:69
#define RHASH_SIZE(h)
Queries the size of the hash.
Definition rhash.h:57
static VALUE RREGEXP_SRC(VALUE rexp)
Convenient getter function.
Definition rregexp.h:93
#define StringValue(v)
Ensures that the parameter object is a String.
Definition rstring.h:66
#define StringValuePtr(v)
Identical to StringValue, except it returns a char*.
Definition rstring.h:76
static int RSTRING_LENINT(VALUE str)
Identical to RSTRING_LEN(), except it differs for the return type.
Definition rstring.h:438
#define StringValueCStr(v)
Identical to StringValuePtr, except it additionally checks for the contents for viability as a C stri...
Definition rstring.h:89
#define RTYPEDDATA_DATA(v)
Convenient getter macro.
Definition rtypeddata.h:106
#define TypedData_Get_Struct(obj, type, data_type, sval)
Obtains a C struct from inside of a wrapper Ruby object.
Definition rtypeddata.h:773
#define TypedData_Wrap_Struct(klass, data_type, sval)
Converts sval, a pointer to your struct, into a Ruby object.
Definition rtypeddata.h:557
struct rb_data_type_struct rb_data_type_t
This is the struct that holds necessary info for a struct.
Definition rtypeddata.h:239
#define TypedData_Make_Struct(klass, type, data_type, sval)
Identical to TypedData_Wrap_Struct, except it allocates a new data region internally instead of takin...
Definition rtypeddata.h:604
void rb_p(VALUE obj)
Inspects an object.
Definition io.c:9336
static bool RB_SPECIAL_CONST_P(VALUE obj)
Checks if the given object is of enum ruby_special_consts.
#define RTEST
This is an old name of RB_TEST.
#define _(args)
This was a transition path from K&R to ANSI.
Definition stdarg.h:35
Definition proc.c:31
Internal header for Complex.
Definition complex.h:13
Internal header for Rational.
Definition rational.h:16
Definition iseq.h:368
Definition vm_core.h:413
Definition st.h:79
Definition vm_core.h:277
long rb_len_t
A signed integer type for lengths and indices of objects such as String and Array.
Definition value.h:142
unsigned long rb_ulen_t
An unsigned integer type that has the same width with rb_len_t.
Definition value.h:145
uintptr_t ID
Type that represents a Ruby identifier such as a variable name.
Definition value.h:52
#define SIZEOF_VALUE
Identical to sizeof(VALUE), except it is a macro that can also be used inside of preprocessor directi...
Definition value.h:69
uintptr_t VALUE
Type that represents a Ruby object.
Definition value.h:40
static bool RB_FLOAT_TYPE_P(VALUE obj)
Queries if the object is an instance of rb_cFloat.
Definition value_type.h:264
static bool rb_integer_type_p(VALUE obj)
Queries if the object is an instance of rb_cInteger.
Definition value_type.h:204
static bool RB_TYPE_P(VALUE obj, enum ruby_value_type t)
Queries if the given object is of given type.
Definition value_type.h:376
@ RUBY_T_MASK
Bitmask of ruby_value_type.
Definition value_type.h:145