Debian Codegraph @

terps/tads/tads3/tct3.h

raw symbols SCIP
1 /* $Header: d:/cvsroot/tads/tads3/TCT3.H,v 1.5 1999/07/11 00:46:55 MJRoberts Exp $ */
2
3 /*
4 * Copyright (c) 1999, 2002 Michael J. Roberts. All Rights Reserved.
5 *
6 * Please see the accompanying license file, LICENSE.TXT, for information
7 * on using and copying this software.
8 */
9 /*
10 Name
11 tct3.h - TADS 3 compiler - T3 Virtual Machine Code Generator
12 Function
13
14 Notes
15
16 Modified
17 04/30/99 MJRoberts - Creation
18 */
19
20 #ifndef TCT3_H
21 #define TCT3_H
22
23 #include "t3std.h"
24 #include "tcprs.h"
25 #include "vmop.h"
26 #include "vmtype.h"
27 #include "tct3ty.h"
28
29 /* ------------------------------------------------------------------------ */
30 /*
31 * include the T3-specific CVmRuntimeSymbols class definition
32 */
33 #include "vmrunsym.h"
34
35
36 /* ------------------------------------------------------------------------ */
37 /*
38 * include the T3-specific final parse node classes
39 */
40 #include "tct3drv.h"
41
42
43 /* ------------------------------------------------------------------------ */
44 /*
45 * Define some internal compiler datatypes - any type
46 * VM_FIRST_INVALID_TYPE or higher is not used by the VM and can thus be
47 * used for our own internal types.
48 */
49 const vm_datatype_t VM_VOCAB_LIST = VM_MAKE_INTERNAL_TYPE(0);
50
51
52 /* ------------------------------------------------------------------------ */
53 /*
54 * Data structure sizes. These are the sizes of various data structures
55 * that we write to the image file; these values are global to the
56 * entire image file, and are constants of the current file format.
57 */
58
59 /* method header size */
60 #define TCT3_METHOD_HDR_SIZE 10
61
62 /* exception table entry size */
63 #define TCT3_EXC_ENTRY_SIZE 10
64
65 /* debugger line record entry size */
66 #define TCT3_LINE_ENTRY_SIZE 10
67
68 /* debug table header size */
69 #define TCT3_DBG_HDR_SIZE 0
70
71 /* debugger local symbol record size */
72 #define TCT3_DBG_LCLSYM_HDR_SIZE 6
73
74 /* debugger frame record header size */
75 #define TCT3_DBG_FRAME_SIZE 8
76
77 /* debugger record format version */
78 #define TCT3_DBG_FMT_VSN 2
79
80 /* ------------------------------------------------------------------------ */
81 /*
82 * Object file header flags.
83 */
84 #define TCT3_OBJHDR_DEBUG 0x0001
85
86
87 /* ------------------------------------------------------------------------ */
88 /*
89 * Object Stream prefix flags. Each object we write to the object
90 * stream starts with a prefix byte that we use to store some extra flag
91 * information about the object.
92 */
93
94 /* object has been replaced - do not write to image file */
95 #define TCT3_OBJ_REPLACED 0x0001
96
97 /* object has been modified */
98 #define TCT3_OBJ_MODIFIED 0x0002
99
100 /* object is transient */
101 #define TCT3_OBJ_TRANSIENT 0x0004
102
103
104 /* ------------------------------------------------------------------------ */
105 /*
106 * T3 metaclass object stream header sizes
107 */
108
109 /*
110 * internal header size - this is an extra header the compiler adds for
111 * each object in an object stream
112 *
113 * UINT2 compiler_flags
114 */
115 const size_t TCT3_OBJ_INTERNHDR_SIZE = 2;
116
117 /* offset of the internal header from the start of the object data */
118 const size_t TCT3_OBJ_INTERNHDR_OFS = 0;
119
120 /* offset of internal header flags */
121 const size_t TCT3_OBJ_INTERNHDR_FLAGS_OFS = TCT3_OBJ_INTERNHDR_OFS;
122
123 /*
124 * T3 generic metaclass header - this is the header on every metaclass
125 * in a T3 image file 'OBJS' block.
126 *
127 * UINT4 object_id
128 *. UINT2 metaclass_specific_byte_count
129 */
130 const size_t TCT3_META_HEADER_SIZE = 6;
131
132 /*
133 * large metaclass header size - this is the same as the standard
134 * header, but uses a 32-bit size field rather than the 16-bit size
135 * field
136 */
137 const size_t TCT3_LARGE_META_HEADER_SIZE = 8;
138
139 /* offset of generic metaclass header from the start of an object's data */
140 const size_t TCT3_META_HEADER_OFS =
141 TCT3_OBJ_INTERNHDR_OFS + TCT3_OBJ_INTERNHDR_SIZE;
142
143 /* ------------------------------------------------------------------------ */
144 /*
145 * tads-object metaclass object stream header sizes
146 */
147
148 /*
149 * tads-object header - each object with metaclass tads-object defines
150 * this header
151 *
152 *. UINT2 superclass_count
153 *. UINT2 property_count
154 *. UINT2 object_flags
155 */
156 const size_t TCT3_TADSOBJ_HEADER_SIZE = 6;
157
158 /* offset of the tads-object header from the start of an object's data */
159 const size_t TCT3_TADSOBJ_HEADER_OFS =
160 TCT3_META_HEADER_OFS + TCT3_META_HEADER_SIZE;
161
162 /*
163 * offset to the superclass table, which immediately follows the
164 * tads-object header
165 */
166 const size_t TCT3_TADSOBJ_SC_OFS =
167 TCT3_TADSOBJ_HEADER_OFS + TCT3_TADSOBJ_HEADER_SIZE;
168
169 /*
170 * size of a property table entry
171 *
172 *. UINT2 property_ID
173 *. DATAHOLDER value
174 */
175 const size_t TCT3_TADSOBJ_PROP_SIZE = 2 + VMB_DATAHOLDER;
176
177 /*
178 * T3 object flags
179 */
180
181 /* class flag - object is a class, not an instance */
182 #define TCT3_OBJFLG_CLASS 0x0001
183
184
185 /* ------------------------------------------------------------------------ */
186 /*
187 * Metaclass List Entry. This list keeps track of the metaclasses that
188 * the image file is dependent upon, and the dynamic link mapping
189 * between metaclass ID in the image file and the universally unique
190 * metaclass name.
191 */
192 struct tc_meta_entry
193 {
194 /* next entry in the list */
195 tc_meta_entry *nxt;
196
197 /*
198 * metaclass symbol object, if present - we get the property list
199 * from the metaclass symbol
200 */
201 class CTcSymMetaclass *sym;
202
203 /* external (universally unique) metaclass name */
204 char nm[1];
205 };
206
207 /*
208 * Fixed System Metaclasses. The compiler must generate code for these
209 * metaclasses directly, so it pre-loads the metaclass dependency table
210 * with these metaclasses at initialization. Because these entries are
211 * always loaded into the table in the same order, they have fixed table
212 * indices that we can define as constants here.
213 */
214
215 /* TADS Object Metaclass */
216 const int TCT3_METAID_TADSOBJ = 0;
217
218 /* list metaclass */
219 const int TCT3_METAID_LIST = 1;
220
221 /* dictionary metaclass */
222 const int TCT3_METAID_DICT = 2;
223
224 /* grammar production metaclass */
225 const int TCT3_METAID_GRAMPROD = 3;
226
227 /* vector metaclass */
228 const int TCT3_METAID_VECTOR = 4;
229
230 /* anonymous function pointer */
231 const int TCT3_METAID_ANONFN = 5;
232
233 /* intrinsic class modifiers */
234 const int TCT3_METAID_ICMOD = 6;
235
236 /* lookup table */
237 const int TCT3_METAID_LOOKUP_TABLE = 7;
238
239 /*
240 * IMPORTANT!!! When adding new entries to this list of pre-defined
241 * metaclasses, you must:
242 *
243 * - update the 'last' constant below
244 *
245 * - add the new entry to CTcGenTarg::load_image_file_meta_table()
246 */
247
248 /* last metaclass ID - adjust when new entries are added */
249 const int TCT3_METAID_LAST = 7;
250
251 /* ------------------------------------------------------------------------ */
252 /*
253 * Function set dependency list entry
254 */
255 struct tc_fnset_entry
256 {
257 /* next entry in the list */
258 tc_fnset_entry *nxt;
259
260 /* external (universally unique) function set name */
261 char nm[1];
262 };
263
264 /* ------------------------------------------------------------------------ */
265 /*
266 * Exception Table builder. This object keeps track of the entries in
267 * an exception table under construction, so that the exception table
268 * for a function can be written to the code stream after all of the
269 * code in the function has been generated.
270 */
271 class CTcT3ExcTable
272 {
273 public:
274 CTcT3ExcTable();
275
276 ~CTcT3ExcTable()
277 {
278 /* if we've allocated a table, delete it */
279 if (table_ != 0)
280 t3free(table_);
281 }
282
283 /*
284 * Set the current function or method's start offset. The code
285 * generator for the function body should set this to the code
286 * stream offset of the start of the method header; this allows us
287 * to calculate the offsets of protected code and 'catch' blocks.
288 *
289 * Important: this is the code stream offset (G_cs->get_ofs()), not
290 * the final code pool address. We need only relative offsets, so
291 * the code stream offset suffices (and is available much earlier in
292 * the code generation process).
293 */
294 void set_method_ofs(ulong ofs) { method_ofs_ = ofs; }
295
296 /*
297 * Add a 'catch' entry. The offsets are all code stream offsets
298 * (G_cs->get_ofs() values).
299 */
300 void add_catch(ulong protected_start_ofs, ulong protected_end_ofs,
301 ulong exc_obj_id, ulong catch_block_ofs);
302
303 /*
304 * write our exception table to the code stream - writes to the G_cs
305 * global code stream object
306 */
307 void write_to_code_stream();
308
309 /* get the number of entries */
310 size_t get_entry_count() const { return exc_used_; }
311
312 /* clear the exception table - remove all entries */
313 void clear_table() { exc_used_ = 0; }
314
315 protected:
316 /* the starting offset of this method header */
317 ulong method_ofs_;
318
319 /* exception table */
320 struct CTcT3ExcEntry *table_;
321
322 /* number of entries used/allocated in our table */
323 size_t exc_used_;
324 size_t exc_alloced_;
325 };
326
327 /*
328 * Exception table entry
329 */
330 struct CTcT3ExcEntry
331 {
332 /* start/end offset (from start of method header) of protected code */
333 ulong start_ofs;
334 ulong end_ofs;
335
336 /* object ID of exception class caught */
337 ulong exc_obj_id;
338
339 /* 'catch' block starting offset (from start of method header) */
340 ulong catch_ofs;
341 };
342
343 /* ------------------------------------------------------------------------ */
344 /*
345 * Data Stream Page Layout Manager. This works with a CTcDataStream
346 * object (such as the constant pool or the code pool) to divide the
347 * stream into pages for the image file.
348 */
349 class CTcStreamLayout
350 {
351 public:
352 CTcStreamLayout()
353 {
354 /* we don't know anything about our layout yet */
355 page_size_ = 0;
356 page_cnt_ = 0;
357 }
358
359 /*
360 * Calculate my layout, given the maximum object size. This can be
361 * called once the entire stream has been generated, hence the size
362 * of the largest indivisible item in the stream is known. This
363 * will apply all fixups throughout the stream.
364 *
365 * If this is the first stream for this layout, is_first is true.
366 * If we're adding more pages, is_first is false, and max_len is
367 * ignored (so the caller must ensure that the max_len provided on
368 * laying out the first stream for this page set is adequate for all
369 * streams added to this layout).
370 */
371 void calc_layout(class CTcDataStream *ds, ulong max_len, int is_first);
372
373 /*
374 * Write the stream(s) to an image file. We'll write the pool
375 * definition block and the pool pages. This cannot be called until
376 * after calc_layout() has been called for all streams, because we
377 * must apply all fixups throughout the entire image before we can
378 * write out anything.
379 */
380 void write_to_image(class CTcDataStream **ds_array, size_t ds_cnt,
381 class CVmImageWriter *image_writer, int pool_id,
382 uchar xor_mask);
383
384 /* page size */
385 ulong page_size_;
386
387 /* number of pages used */
388 size_t page_cnt_;
389 };
390
391
392 /* ------------------------------------------------------------------------ */
393 /*
394 * Debug line list page. We keep a linked list of these pages, and
395 * allocate new entries out of the last page. We keep going until the
396 * last page is filled up, then allocate a new page.
397 */
398 const size_t TCT3_DEBUG_LINE_PAGE_SIZE = 1024;
399 const size_t TCT3_DEBUG_LINE_REC_SIZE = 5;
400 struct tct3_debug_line_page
401 {
402 /* next page in list */
403 tct3_debug_line_page *nxt;
404
405 /*
406 * Entries on this page (each entry is a debug line record offset in
407 * the code stream). Each entry consists of one byte for the code
408 * stream identifier (TCGEN_xxx_STREAM) and four bytes for a
409 * portable UINT4 with the offset in the stream.
410 */
411 uchar line_ofs[TCT3_DEBUG_LINE_PAGE_SIZE * TCT3_DEBUG_LINE_REC_SIZE];
412 };
413
414
415 /* ------------------------------------------------------------------------ */
416 /*
417 * T3-specific code generator helper class. This class provides a set
418 * of static functions that are useful for T3 code generation.
419 */
420 class CTcGenTarg
421 {
422 public:
423 /* initialize the code generator */
424 CTcGenTarg();
425
426 /* destroy the code generator object */
427 ~CTcGenTarg();
428
429 /*
430 * Set the run-time metaclass dependency table index for a given
431 * metaclass, identified by 'name' (a string of length 'len'). 'idx'
432 * is the run-time metaclass dependency index.
433 *
434 * When we're operating as part of an interactive debugger, the image
435 * loader must call this for each entry in the metaclass dependency
436 * table loaded from the image file. This allows us to fix up our
437 * internal notion of the metaclass indices so that we generate code
438 * compatible with the actual loaded image file.
439 *
440 * The protocol is as follows: call start_image_file_meta_table(), then
441 * call load_image_file_meta_table() on each entry in the table, then
442 * call end_image_file_meta_table().
443 */
444 void start_image_file_meta_table();
445 void load_image_file_meta_table(const char *nm, size_t len, int idx);
446 void end_image_file_meta_table();
447
448 /*
449 * Allocate a new global property ID.
450 */
451 tctarg_prop_id_t new_prop_id() { return next_prop_++; }
452
453 /*
454 * Allocate a new global object ID.
455 */
456 tctarg_obj_id_t new_obj_id() { return next_obj_++; }
457
458 /*
459 * add a metaclass to the dependency table - returns the index of
460 * the metaclass in the table
461 */
462 int add_meta(const char *meta_extern_name, size_t len,
463 class CTcSymMetaclass *sym);
464 int add_meta(const char *nm, class CTcSymMetaclass *sym)
465 { return add_meta(nm, strlen(nm), sym); }
466 int add_meta(const char *nm)
467 { return add_meta(nm, strlen(nm), 0); }
468
469 /*
470 * Find a metaclass entry, adding it if it's not already there. If
471 * the metaclass is already defined, and it has an associated
472 * symbol, we will not change the associated symbol - this will let
473 * the caller detect that the metaclass has been previously defined
474 * for a different symbol, which is usually an error.
475 */
476 int find_or_add_meta(const char *nm, size_t len,
477 class CTcSymMetaclass *sym);
478
479 /*
480 * Get the property ID for the given method table index in the given
481 * metaclass. The metaclass ID is given as the internal metaclass ID
482 * (without the "/version" suffix), not as the external class name.
483 * Returns a parse node for the property, or null if it's not found.
484 */
485 CTcPrsNode *get_metaclass_prop(const char *name, ushort idx) const;
486
487 /* get a metaclass symbol by the metaclass's global identifier */
488 class CTcSymMetaclass *find_meta_sym(const char *nm, size_t len);
489
490 /*
491 * Find the metaclass table entry for a given global identifier. If
492 * update_vsn is true, we'll update the entry stored in the table to
493 * the given version number if the given name's version number is
494 * higher than the one in the table. If we find an entry, we'll
495 * fill in *entry_idx with the entry's index.
496 */
497 tc_meta_entry *find_meta_entry(const char *nm, size_t len,
498 int update_vsn, int *entry_idx);
499
500 /* get/set the symbol for a given metaclass */
501 class CTcSymMetaclass *get_meta_sym(int meta_idx);
502 void set_meta_sym(int meta_idx, class CTcSymMetaclass *sym);
503
504 /* get the number of metaclasses */
505 int get_meta_cnt() const { return meta_cnt_; }
506
507 /* get the external (universally unique) name for the given metaclass */
508 const char *get_meta_name(int idx) const;
509
510 /*
511 * Get the dependency table index for the given pre-defined metaclass,
512 * specified by the TCT3_METAID_xxx value.
513 */
514 int get_predef_meta_idx(int id) const { return predef_meta_idx_[id]; }
515
516 /*
517 * Add a function set to the dependency table - returns the index of
518 * the function set in the table
519 */
520 ushort add_fnset(const char *fnset_extern_name, size_t len);
521 ushort add_fnset(const char *fnset_extern_name)
522 { return add_fnset(fnset_extern_name, strlen(fnset_extern_name)); }
523
524 /* get the name of a function set given its index */
525 const char *get_fnset_name(int idx) const;
526
527 /* get the number of defined function sets */
528 int get_fnset_cnt() const { return fnset_cnt_; }
529
530 /*
531 * Notify the code generator that parsing is finished. This should
532 * be called after parsing and before code generation begins.
533 */
534 void parsing_done();
535
536 /*
537 * Note a string value's length. This should be invoked during the
538 * parsing phase for each constant string value. We'll keep track
539 * of the largest constant data in the file, so that after parsing
540 * is finished, we'll know the minimum size we need for each
541 * constant pool page. This doesn't actually allocate any space in
542 * the constant pool; this merely keeps track of the longest string
543 * we'll eventually need to store.
544 */
545 void note_str(size_t len);
546
547 /*
548 * Note number of elements in a constant list value. This is the
549 * list equivalent of note_str().
550 */
551 void note_list(size_t element_count);
552
553 /*
554 * Note the length of a code block's byte code. This should be
555 * invoked during code generation for each code block; we'll keep
556 * track of the longest byte code block, so that after code
557 * generation is complete, we'll know the minimum size we need for
558 * each code pool page.
559 */
560 void note_bytecode(ulong len);
561
562 /*
563 * Notify the code generator that we're replacing an object (via the
564 * "replace" statement) at the given stream offset. We'll mark the
565 * data in the stream as deleted so that we don't write it to the
566 * image file.
567 */
568 void notify_replace_object(ulong stream_ofs);
569
570 /*
571 * Write to an object file. The compiler calls this after all
572 * parsing and code generation are completed to write an object
573 * file, which can then be linked with other object files to create
574 * an image file.
575 */
576 void write_to_object_file(class CVmFile *object_fp,
577 class CTcMake *make_obj);
578
579 /*
580 * Load an object file. Returns zero on success, non-zero on error.
581 */
582 int load_object_file(CVmFile *fp, const textchar_t *fname);
583
584 /*
585 * Write the image file. The compiler calls this after all parsing
586 * and code generation are completed to write an image file. We
587 * must apply all fixups, assign the code and constant pool layouts,
588 * and write the data to the image file.
589 */
590 void write_to_image(class CVmFile *image_fp, uchar data_xor_mask,
591 const char tool_data[4]);
592
593 /* generate synthesized code during linking */
594 void build_synthesized_code();
595
596 /* generate code for a dictionary object */
597 void gen_code_for_dict(class CTcDictEntry *dict);
598
599 /* generate code for a grammar production object */
600 void gen_code_for_gramprod(class CTcGramProdEntry *prod);
601
602 /* get the maximum string/list/bytecode lengths */
603 size_t get_max_str_len() const { return max_str_len_; }
604 size_t get_max_list_cnt() const { return max_list_cnt_; }
605 size_t get_max_bytecode_len() const { return max_bytecode_len_; }
606
607 /*
608 * Add a debug line record. If we're in debug mode, this will clear
609 * the peephole optimizer to ensure that the line record doesn't get
610 * confused due to compression of opcodes.
611 */
612 void add_line_rec(class CTcTokFileDesc *file, long linenum);
613
614 /* write an opcode to the output stream */
615 void write_op(uchar opc);
616
617 /* write a CALLPROP instruction */
618 void write_callprop(int argc, int varargs, vm_prop_id_t prop);
619
620 /*
621 * Determine if we can skip an opcode for peephole optimization.
622 * We'll look at the previous opcode to determine if this opcode is
623 * reachable, and we'll indicate that we should suppress the new
624 * opcode if not.
625 */
626 int can_skip_op();
627
628 /*
629 * Add a string to the constant pool, and create a fixup for the
630 * item for a reference from the given stream at the given offset.
631 */
632 void add_const_str(const char *str, size_t len,
633 class CTcDataStream *ds, ulong ofs);
634
635 /*
636 * Add a list to the constant pool, and create a fixup for the item
637 * for a reference from the given stream at the given offset.
638 */
639 void add_const_list(class CTPNList *lst,
640 class CTcDataStream *ds, ulong ofs);
641
642 /*
643 * Write a constant value (in the compiler's internal
644 * representation, a CTcConstVal structure) to a given buffer in T3
645 * image file DATA_HOLDER format. Write at a given offset, or at
646 * the current write offset.
647 */
648 void write_const_as_dh(class CTcDataStream *ds, ulong ofs,
649 const class CTcConstVal *src);
650 void write_const_as_dh(class CTcDataStream *ds,
651 const class CTcConstVal *src);
652
653 /*
654 * Clear the peephole optimizer state. This must be invoked
655 * whenever a jump label is defined. We can't combine an
656 * instruction at a jump destination with anything previous: the
657 * instruction at a jump destination must be generated as-is, rather
658 * than being combined with the preceding instruction, since someone
659 * could jump directly to it.
660 */
661 void clear_peephole()
662 {
663 last_op_ = OPC_NOP;
664 second_last_op_ = OPC_NOP;
665 }
666
667 /* get the last opcode we generated */
668 uchar get_last_op() const { return last_op_; }
669
670 /*
671 * Remove the last JMP instruction. This is used when we detect
672 * that we just generated a JMP ahead to the very next instruction,
673 * in which case we can eliminate the JMP, since it has no effect.
674 */
675 void remove_last_jmp();
676
677 /*
678 * Stack depth counting. While we're generating code for a code
679 * block (a function or method), we'll keep track of our stack push
680 * and pop operations, so that we can monitor the maximum stack
681 * depth. In order for the stack depth to be calculable at compile
682 * time, the code generator must take care that each individual
683 * statement is stack-neutral (i.e, the stack comes out of each
684 * statement at the same depth as when it entered the statement), so
685 * that jumps, iterations, and other variables we can't analyze
686 * statically can be ignored.
687 */
688
689 /*
690 * reset the stack depth counters - call this at the start
691 * generating of each code block
692 */
693 void reset_sp_depth() { sp_depth_ = max_sp_depth_ = 0; }
694
695 /*
696 * get the maximum stack depth for the current function - use this
697 * when finished generating a code block to determine the maximum
698 * stack space needed by the code block
699 */
700 int get_max_sp_depth() const { return max_sp_depth_; }
701
702 /* get the current stack depth */
703 int get_sp_depth() const { return sp_depth_; }
704
705 /* record a push - increments the current stack depth */
706 void note_push() { note_push(1); }
707
708 /* record a push of a given number of stack elements */
709 void note_push(int cnt)
710 {
711 sp_depth_ += cnt;
712 if (sp_depth_ > max_sp_depth_)
713 max_sp_depth_ = sp_depth_;
714 }
715
716 /* record a pop - decrements the current stack depth */
717 void note_pop() { note_pop(1); }
718
719 /* record a pop of a given number of stack elements */
720 void note_pop(int cnt) { sp_depth_ -= cnt; }
721
722 /* record a full stack reset back to function entry conditions */
723 void note_rst() { sp_depth_ = 0; }
724
725 /*
726 * do post-call cleanup: generate a named argument table pointer if
727 * needed, remove the named arguments from the stack
728 */
729 void post_call_cleanup(const struct CTcNamedArgs *named_args);
730
731 /*
732 * Open/close a method/function. "Open" generates a placeholder method
733 * header and sets up our generator globals to prepare for a new
734 * method. "Close" goes back and fills in the final method header
735 * based on the code generated since "Open".
736 */
737 void open_method(class CTcCodeStream *stream,
738 class CTcSymbol *fixup_owner_sym,
739 struct CTcAbsFixup **fixup_list_head,
740 class CTPNCodeBody *code_body,
741 class CTcPrsSymtab *goto_tab,
742 int argc, int opt_argc, int varargs,
743 int is_constructor, int is_op_overload,
744 int is_self_available,
745 struct tct3_method_gen_ctx *ctx);
746 void close_method(int local_cnt,
747 class CTcPrsSymtab *local_symtab,
748 class CTcTokFileDesc *end_desc, long end_linenum,
749 struct tct3_method_gen_ctx *ctx,
750 struct CTcNamedArgTab *named_arg_tab_head);
751 void close_method_cleanup(struct tct3_method_gen_ctx *ctx);
752
753 /*
754 * Generate a TadsObject header to a data stream
755 */
756 void open_tadsobj(struct tct3_tadsobj_ctx *ctx,
757 CTcDataStream *stream,
758 vm_obj_id_t obj_id, int sc_cnt, int prop_cnt,
759 unsigned int internal_flags, unsigned int vm_flags);
760 void close_tadsobj(struct tct3_tadsobj_ctx *ctx);
761
762 /*
763 * Linker support: ensure that the given intrinsic class has a modifier
764 * object. If there's no modifier, we'll create one and add code for
765 * it to the intrinsic class modifier stream.
766 */
767 void linker_ensure_mod_obj(CTcSymMetaclass *mc_sym);
768 void linker_ensure_mod_obj(const char *name, size_t len);
769
770 /*
771 * get my exception table object - this is used to construct a
772 * method's exception table during code generation, and to write the
773 * table to the code stream
774 */
775 CTcT3ExcTable *get_exc_table() { return &exc_table_; }
776
777 /* determine if we're compiling a constructor */
778 int is_in_constructor() const { return in_constructor_; }
779 void set_in_constructor(int f) { in_constructor_ = f; }
780
781 /* determine if we're compiling an operator overload method */
782 int is_in_op_overload() const { return in_op_overload_; }
783 void set_in_op_overload(int f) { in_op_overload_ = f; }
784
785 /*
786 * set the method offset - the code body object calls this when it's
787 * about to start generating code to let us know the offset of the
788 * current method
789 */
790 void set_method_ofs(ulong ofs);
791
792 /*
793 * Add a debug line table to our list. We keep track of all of the
794 * debug line record tables in the program, so that we can store the
795 * list in the object file. We need this information in the object
796 * file because each debug line record table in an object file must
797 * be fixed up at link time after loading the object file.
798 */
799 void add_debug_line_table(ulong ofs);
800
801 /*
802 * Set dynamic (run-time) compilation mode. This mode must be used for
803 * code compiled during program execution, such as for an "eval()"
804 * facility. In dynamic compilation, all pool addresses are already
805 * resolved from the loaded program, and we can't add anything to any
806 * of the constant or code pools.
807 */
808 void set_dyn_eval() { eval_for_dyn_ = TRUE; }
809
810 /*
811 * Set debug evaluation mode. If 'speculative' is true, it means
812 * that we're generating an expression for speculative evaluation,
813 * in which case the evaluation must fail if it would have any side
814 * effects (such as calling a method, displaying a string, or
815 * assigning a value). 'stack_level' is the enclosing stack level
816 * at which to evaluate the expression; 0 is the last active
817 * non-debug stack level, 1 is the first enclosing level, and so on.
818 */
819 void set_debug_eval(int speculative, int level)
820 {
821 /* note that we're evaluating for the debugger */
822 eval_for_debug_ = TRUE;
823
824 /* this is a special type of run-time dynamic compilation */
825 eval_for_dyn_ = TRUE;
826
827 /* note the speculative mode */
828 speculative_ = speculative;
829
830 /* note the stack level */
831 debug_stack_level_ = level;
832 }
833
834 /* set normal evaluation mode */
835 void set_normal_eval() { eval_for_debug_ = eval_for_dyn_ = FALSE; }
836
837 /* determine if we're in dynamic/debugger evaluation mode */
838 int is_eval_for_dyn() const { return eval_for_dyn_; }
839 int is_eval_for_debug() const { return eval_for_debug_; }
840
841 /* determine if we're in speculative evaluation mode */
842 int is_speculative() const { return eval_for_debug_ && speculative_; }
843
844 /* get the active debugger stack level */
845 int get_debug_stack_level() const { return debug_stack_level_; }
846
847 /*
848 * Generate a BigNumber object, returning the object ID. The input
849 * text gives the source representation of the number.
850 */
851 vm_obj_id_t gen_bignum_obj(const char *txt, size_t len, int promoted);
852
853 /* generate a RexPattern object */
854 vm_obj_id_t gen_rexpat_obj(const char *txt, size_t len);
855
856 private:
857 /* eliminate jump-to-jump sequences */
858 void remove_jumps_to_jumps(class CTcCodeStream *str, ulong start_ofs);
859
860 /*
861 * Calculate pool layouts. This is called after all code generation
862 * is completed; at this point, the T3 code generator can determine
863 * how the code pages will be laid out, since we now know the size
864 * of the largest single chunk of code.
865 *
866 * We'll fill in *first_static_page with the page number in the code
867 * pool of the first page of code containing static initializers.
868 * We group all of the static initializer code together at the end
869 * of the code pool to allow the pre-initialization re-writer to
870 * omit all of the static code pages from the final image file.
871 */
872 void calc_pool_layouts(size_t *first_static_page);
873
874 /*
875 * Write a TADS object stream to the image file. This routine will
876 * fix up the property table in each object to put the table in
877 * sorted order.
878 */
879 void write_tads_objects_to_image(class CTcDataStream *obj_stream,
880 class CVmImageWriter *image_writer,
881 int metaclass_idx);
882
883 /*
884 * write the TADS objects of one particular type - transient or
885 * persistent - to the image file
886 */
887 void write_tads_objects_to_image(CTcDataStream *os,
888 CVmImageWriter *image_writer, int meta_idx, int trans);
889
890 /*
891 * Write an object stream of non-TADS objects to the image file.
892 * This writes the objects as-is, without looking into their
893 * contents at all.
894 */
895 void write_nontads_objs_to_image(class CTcDataStream *obj_stream,
896 class CVmImageWriter *image_writer,
897 int metaclass_idx, int large_obs);
898
899 /*
900 * Sort an object's property table, and compress the table to remove
901 * deleted properties. Returns the final size of the object data to
902 * write to the image file, which could differ from the original
903 * size, because we might remove property slots from the property
904 * data. If we do change the size of the property table, we'll
905 * update the stream data to reflect the new property count and
906 * metaclass data size.
907 */
908 size_t sort_object_prop_table(class CTcDataStream *obj_stream,
909 ulong start_ofs);
910
911 /* write the function-set dependency table to an object file */
912 void write_funcdep_to_object_file(class CVmFile *fp);
913
914 /* write the metaclass dependency table to an object file */
915 void write_metadep_to_object_file(class CVmFile *fp);
916
917 /* load the function set dependency table from an object file */
918 void load_funcdep_from_object_file(class CVmFile *fp,
919 const textchar_t *fname);
920
921 /* load the metaclass dependency table from an object file */
922 void load_metadep_from_object_file(class CVmFile *fp,
923 const textchar_t *fname);
924
925 /* look up a required or optional property by name */
926 vm_prop_id_t look_up_prop(const char *propname, int required,
927 int err_if_undef, int err_if_not_prop);
928
929 /* build the IntrinsicClass instances */
930 void build_intrinsic_class_objs(CTcDataStream *str);
931
932 /* build the source file line maps */
933 void build_source_line_maps();
934
935 /* build the local symbol records */
936 void build_local_symbol_records(class CTcCodeStream *cs,
937 class CVmHashTable *tab);
938
939 /* build the multi-method initializer list */
940 void build_multimethod_initializers();
941
942 /* symbol table enumerator callback for the multi-method initializers */
943 static void multimethod_init_cb(void *ctx, CTcSymbol *sym);
944
945 /* symbol table enumerator callback for the multi-method stubs */
946 static void multimethod_stub_cb(void *ctx, CTcSymbol *sym);
947
948 /* write an overloaded operator property export */
949 void write_op_export(CVmImageWriter *image_writer,
950 class CTcSymProp *prop);
951
952 /* write the static initializer list to the image file */
953 void write_static_init_list(CVmImageWriter *image_writer,
954 ulong main_cs_size);
955
956 /* write the list of source file descriptors to an image file */
957 void write_sources_to_image(class CVmImageWriter *image_writer);
958
959 /* write the global symbol table to an object file */
960 void write_global_symbols_to_image(class CVmImageWriter *image_writer);
961
962 /* write the method header list to the image file */
963 void write_method_list_to_image(class CVmImageWriter *image_writer);
964
965 /* write macro definitions to the image file */
966 void write_macros_to_image(class CVmImageWriter *image_writer);
967
968 /* write the list of source file descriptors to an object file */
969 void write_sources_to_object_file(class CVmFile *fp);
970
971 /*
972 * read the list of sources from an object file, adding the sources
973 * to the tokenizer's internal list
974 */
975 void read_sources_from_object_file(class CVmFile *fp);
976
977 /* load debug records from an object file */
978 void load_debug_records_from_object_file(class CVmFile *fp,
979 const textchar_t *fname,
980 ulong main_cs_start_ofs,
981 ulong static_cs_start_ofs);
982
983 /* fix up a debug line record table for the object file */
984 void fix_up_debug_line_table(class CTcCodeStream *cs,
985 ulong line_table_ofs, int first_filedesc);
986
987 /* hash table enumerator callback - generate dictionary code */
988 static void enum_dict_gen_cb(void *ctx, class CVmHashEntry *entry);
989
990
991 /* most recent opcodes we've written, for peephole optimization */
992 uchar last_op_;
993 uchar second_last_op_;
994
995 /* maximum constant string length seen during parsing */
996 size_t max_str_len_;
997
998 /* maximum list element count seen during parsing */
999 size_t max_list_cnt_;
1000
1001 /* maximum byte code block generated during code generation */
1002 size_t max_bytecode_len_;
1003
1004 /* head and tail of metaclass list */
1005 tc_meta_entry *meta_head_;
1006 tc_meta_entry *meta_tail_;
1007
1008 /* number of entries in metaclass list so far */
1009 int meta_cnt_;
1010
1011 /* head and tail of function set list */
1012 tc_fnset_entry *fnset_head_;
1013 tc_fnset_entry *fnset_tail_;
1014
1015 /* number of function sets in the list */
1016 int fnset_cnt_;
1017
1018 /* next available global property ID */
1019 vm_prop_id_t next_prop_;
1020
1021 /* next available global object ID */
1022 vm_obj_id_t next_obj_;
1023
1024 /* current stack depth */
1025 int sp_depth_;
1026
1027 /* maximum stack depth in current code block */
1028 int max_sp_depth_;
1029
1030 /* exception table for current code block */
1031 CTcT3ExcTable exc_table_;
1032
1033 /* constant pool layout manager */
1034 CTcStreamLayout const_layout_;
1035
1036 /* code pool layout manager */
1037 CTcStreamLayout code_layout_;
1038
1039 /* first/last page of debug line list */
1040 tct3_debug_line_page *debug_line_head_;
1041 tct3_debug_line_page *debug_line_tail_;
1042
1043 /* total number of debug line list entries used so far */
1044 ulong debug_line_cnt_;
1045
1046 /*
1047 * Object ID of the multi-method static initializer object. This will
1048 * be set by build_multimethod_initializers() if we end up creating any
1049 * registration code.
1050 */
1051 vm_obj_id_t mminit_obj_;
1052
1053 /*
1054 * property sorting buffer - this is space we allocate to copy an
1055 * object's property table for sorting
1056 */
1057 char *sort_buf_;
1058 size_t sort_buf_size_;
1059
1060 /* flag: we're currently compiling a constructor */
1061 uint in_constructor_ : 1;
1062
1063 /* flag: we're currently compiling an operator overload method */
1064 uint in_op_overload_ : 1;
1065
1066 /* flag: we're generating code for dynamic (run-time) compilation */
1067 uint eval_for_dyn_ : 1;
1068
1069 /* flag: we're generating an expression for debugger use */
1070 uint eval_for_debug_ : 1;
1071
1072 /* flag: we're generating a debugger speculative evaluation expression */
1073 uint speculative_ : 1;
1074
1075 /*
1076 * debugger active stack context level - valid when eval_for_debug_
1077 * is true
1078 */
1079 int debug_stack_level_;
1080
1081 /*
1082 * String interning hash table. This is a table of short string
1083 * literals that we've generated into the data segment. Whenever we
1084 * generate a new string literal, we'll check this table to see if
1085 * we've previously stored the identical string. If so, we'll simply
1086 * use the original string rather than generating a new copy. This can
1087 * reduce the size of the object file by eliminating duplication of
1088 * common short strings.
1089 *
1090 * Note that string interning has the potential to change run-time
1091 * semantics in some other languages, but not in TADS. There are two
1092 * common issues in other languages. First, in C/C++, a string
1093 * constant is technically a writable buffer. This means that two
1094 * distinct string literals in the source code really need to be
1095 * treated as distinct memory locations, even if they have identical
1096 * contents, because the program might write to one buffer and expect
1097 * the other to remain unchanged. This doesn't apply to TADS because
1098 * string literals are strictly read-only. Second, strings in many
1099 * languages are objects with reference semantics for comparisons; two
1100 * distinct source-code strings must therefore have distinct reference
1101 * identities. String comparisons in TADS are always by value, so
1102 * there's no need for distinct references if two strings have
1103 * identical contents.
1104 */
1105 class CVmHashTable *strtab_;
1106
1107 /*
1108 * Static table of image file metaclass dependency indices for the
1109 * pre-defined metaclasses (i.e., the metaclasses that the compiler
1110 * specifically generates code for). When we compile a program, these
1111 * are determined by the compiler simply according to the order in
1112 * which it builds its own initial table of the known metaclasses.
1113 * When we're debugging, we need to get these values from the image
1114 * file.
1115 *
1116 * This is a simple translation table - we translate from our internal
1117 * index (a TCT3_METAID_xxx value) to the corresponding dependency
1118 * index in the actual image file. So, we just need as many of these
1119 * as there TCT3_METAID_xxx indices. We never need these for any
1120 * additional metaclasses that might exist - we only care about the
1121 * ones that the compiler specifically knows about in advance.
1122 */
1123 int predef_meta_idx_[TCT3_METAID_LAST + 1];
1124 };
1125
1126 /* ------------------------------------------------------------------------ */
1127 /*
1128 * Method generator context
1129 */
1130 struct tct3_method_gen_ctx
1131 {
1132 /* output code stream */
1133 class CTcCodeStream *stream;
1134
1135 /* stream anchor */
1136 struct CTcStreamAnchor *anchor;
1137
1138 /* method header offset in stream */
1139 ulong method_ofs;
1140
1141 /* starting and ending code offset in stream */
1142 ulong code_start_ofs;
1143 ulong code_end_ofs;
1144
1145 /* enclosing code body */
1146 class CTPNCodeBody *old_code_body;
1147 };
1148
1149 /* ------------------------------------------------------------------------ */
1150 /*
1151 * TadsObject header writer context
1152 */
1153 struct tct3_tadsobj_ctx
1154 {
1155 /* start of object header in data stream */
1156 ulong obj_ofs;
1157
1158 /* data stream to which we're writing the object */
1159 CTcDataStream *stream;
1160 };
1161
1162 /* ------------------------------------------------------------------------ */
1163 /*
1164 * Named arguments information. This keeps track of the named arguments
1165 * for a generated call.
1166 */
1167 struct CTcNamedArgs
1168 {
1169 /* number of named arguments */
1170 int cnt;
1171
1172 /* argument list */
1173 class CTPNArglist *args;
1174 };
1175
1176
1177 #endif /* TCT3_H */
1178