-
-
Notifications
You must be signed in to change notification settings - Fork 83
/
compile.scm
6285 lines (5754 loc) · 263 KB
/
compile.scm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;;
;;; compile.scm - The compiler
;;;
;;; Copyright (c) 2004-2014 Shiro Kawai <shiro@acm.org>
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;;
;;; 1. Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;;
;;; 2. Redistributions in binary form must reproduce the above copyright
;;; notice, this list of conditions and the following disclaimer in the
;;; documentation and/or other materials provided with the distribution.
;;;
;;; 3. Neither the name of the authors nor the names of its contributors
;;; may be used to endorse or promote products derived from this
;;; software without specific prior written permission.
;;;
;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
;;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
;;; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
;;; TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
;;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
;;; LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
;;;
(declare) ;; a dummy form to suppress generation of "sci" file
(define-module gauche.internal
(use util.match)
)
(select-module gauche.internal)
(inline-stub
(declcode
(.include <gauche/class.h>
<gauche/code.h>
<gauche/vminsn.h>
<gauche/priv/macroP.h>
<gauche/priv/builtin-syms.h>)))
;;; THE COMPILER
;;;
;;; The main entry point is COMPILE, defined under "Entry point" section.
;;;
;;; compile :: Sexpr, Module -> CompiledCode
;;;
;;; Gauche compiles programs at runtime, so we don't want to spend too
;;; much time in compilation, while we still want to generate as efficient
;;; code as possible.
;;;
;;; Structure of the compiler
;;;
;;; We have several passes, outlined here. See the header of each
;;; section for the details.
;;;
;;; Pass 1 (Parsing):
;;; - Converts Sexpr into an intermediate form (IForm).
;;; - Macros and global inlinable functions are expanded.
;;; - Global constant variables are substituted to its value.
;;; - Variable bindings are resolved. Local variables are marked
;;; according to its usage (# of reference count and set count).
;;; - Constant expressons are folded.
;;;
;;; Pass 2 (Variable and closure optimization):
;;; - Traverses IForm and modify the tree to optimize it.
;;; - Limited beta-substitution (local variable substitution and
;;; inline local functions for the obvious cases).
;;; - Analyze local function usage and optimize away closures whenever
;;; possible. For example, local tail recursions are converted to
;;; loops here.
;;; - NB: This pass can make IForm a directed graph, possibly contains
;;; cycles.
;;;
;;; Pass 3 (Constant folding and branch & call optimization):
;;; - Precompute compile-time constants. This is here because Pass2's
;;; inlining and substitution allow further precomputation.
;;; - Certain $IF nodes are modified for less jump instructions
;;; (see pass3/$IF)
;;; - Eliminates redundant $LET and $SEQs introduced by constant folding.
;;; - Look into $CALL nodes for further optimization; the above
;;; optimizations may allow further inlining.
;;;
;;; Pass 4 (Lambda lifting)
;;; - At this point, remaining $LAMBDA nodes are the ones we absolutely
;;; needed. For every $LAMBDA node we find free local variables;
;;; the lvars introduced outside of the $LAMBDA. The result is set
;;; in $lambda-free-lvars slot. Then we determine $LAMBDA nodes
;;; that does not need to form a closure. They are assigned to
;;; fresh global identifier ($lambda-lifted-var is set to it).
;;; References to this $lambda node through local variables are
;;; substituted to the reference of this global identifier.
;;;
;;; Pass 5 (Code generation):
;;; - Traverses IForm and generate VM instructions.
;;; - Perform instruction combining.
;;; - Perform simple-minded jump optimization.
;;; - Some final constant foldings are done here, too.
;;; - NB: This pass modifies $LABEL node while traversing IForm:
;;; $label-label is set to the label number.
(include "compile-0")
;;=====================================================================
;; Compile-time constants
;;
;; used by env-lookup-int
;; NB: We'll get rid of PATTERN variable lookup after we replace the
;; macro system, then the distinction of LEXICAL/SYNTAX lookup can be
;; specified by a boolean flag and we can drop these constants.
(eval-when (:compile-toplevel)
(define-constant LEXICAL 0)
(define-constant SYNTAX 1)
(define-constant PATTERN 2))
;; Max # of argument passed *literally*. This is limited by
;; VM stack size, for we need to expand args into stack.
;; Note that if arguments are 'apply'ed, usually we don't have
;; this limit since most of those args are not expanded but passed
;; to the function as the rest parameter.
;; The number is related to SCM_VM_STACK_SIZE but we can't directly
;; link to it because of cross compilation. In future maybe we can
;; make it customizable by command line args or something.
(define-constant MAX_LITERAL_ARG_COUNT 8192)
;; used by pass5/$DEFINE.
;; This should match the values in src/gauche/module.h. We intentionally
;; avoid referring to the C value,
;; via (inline-stub (define-enum SCM_BINDING_CONST) ...), since doing so
;; would complicate the compilation process in case we need to change those
;; constants. (Compile.scm is compiled by the host gauche which refers to
;; the old value.)
(define-constant SCM_BINDING_CONST 2)
(define-constant SCM_BINDING_INLINABLE 4)
;; IForm tags
(define-enum .intermediate-tags.
$DEFINE
$LREF
$LSET
$GREF
$GSET
$CONST
$IF
$LET
$RECEIVE
$LAMBDA
$LABEL
$PROMISE
$SEQ
$CALL
$ASM
$CONS
$APPEND
$VECTOR
$LIST->VECTOR
$LIST
$LIST*
$MEMV
$EQ?
$EQV?
$IT
)
;; Define constants for VM instructions.
;; The 'eval-when' trick is to let the host compiler (that is compiling this
;; compiler) know those constants.
(eval-when (:compile-toplevel)
(use gauche.vm.insn)
(define-macro (define-insn-constants)
(let1 name&codes
(map (^[insn] (cons (car insn) (ref (cdr insn)'code)))
(class-slot-ref <vm-insn-info> 'all-insns))
`(begin
,@(map (^[n&c] `(define-constant ,(car n&c) ,(cdr n&c)))
name&codes)
(define-constant .insn-alist. ',name&codes)
)))
(define-insn-constants)
)
;; Maximum size of $LAMBDA node we allow to duplicate and inline.
(define-constant SMALL_LAMBDA_SIZE 12)
(define-inline (variable? arg) (or (symbol? arg) (identifier? arg)))
(define-inline (variable-or-keyword? arg)
(or (symbol? arg) (keyword? arg) (identifier? arg)))
;;============================================================
;; Data structures
;;
;; Local variables (lvar)
;;
;; Slots:
;; name - name of the variable (symbol)
;; initval - initialized value
;; ref-count - in how many places this variable is referefnced?
;; set-count - in how many places this variable is set!
;;
(define-simple-struct lvar 'lvar make-lvar
(name
(initval (undefined))
(ref-count 0)
(set-count 0)))
(define (make-lvar+ name) ;; procedure version of constructor, for mapping
(make-lvar name))
(define-inline (lvar? obj) (and (vector? obj) (eq? (vector-ref obj 0) 'lvar)))
(define (lvar-reset lvar)
(lvar-ref-count-set! lvar 0)
(lvar-set-count-set! lvar 0))
(define-inline (lvar-immutable? lvar)
(= (lvar-set-count lvar) 0))
;; Returns IForm if this lvar has initval and it never changes. Only valid
;; after lvar reference counting is done (that is, after pass1, and after
;; each reset-lvars call.
(define (lvar-const-value lvar)
(and (lvar-immutable? lvar)
(vector? (lvar-initval lvar))
(lvar-initval lvar)))
;; implemented in C for better performance.
(inline-stub
;; offsets must be in sync with lvar definition above
"#define LVAR_OFFSET_TAG 0"
"#define LVAR_OFFSET_NAME 1"
"#define LVAR_OFFSET_INITVAL 2"
"#define LVAR_OFFSET_REF_COUNT 3"
"#define LVAR_OFFSET_SET_COUNT 4"
"#define LVAR_SIZE 5"
;; Specialized routine for (map (lambda (name) (make-lvar name)) objs)
(define-cproc %map-make-lvar (names)
(let* ((h SCM_NIL) (t SCM_NIL))
(dolist [name names]
(let* ([v (Scm_MakeVector LVAR_SIZE '0)])
(set! (SCM_VECTOR_ELEMENT v LVAR_OFFSET_TAG) 'lvar
(SCM_VECTOR_ELEMENT v LVAR_OFFSET_NAME) name
(SCM_VECTOR_ELEMENT v LVAR_OFFSET_INITVAL) SCM_UNDEFINED)
(SCM_APPEND1 h t v)))
(result h)))
(define-cise-stmt update!
[(_ offset delta)
`(let* ([i::int (SCM_INT_VALUE (SCM_VECTOR_ELEMENT lvar ,offset))])
(set! (SCM_VECTOR_ELEMENT lvar ,offset) (SCM_MAKE_INT (+ i ,delta))))])
(define-cproc lvar-ref++! (lvar) ::<void> (update! LVAR_OFFSET_REF_COUNT +1))
(define-cproc lvar-ref--! (lvar) ::<void> (update! LVAR_OFFSET_REF_COUNT -1))
(define-cproc lvar-set++! (lvar) ::<void> (update! LVAR_OFFSET_SET_COUNT +1))
)
;; Compile-time environment (cenv)
;;
;; Slots:
;; module - The 'current-module' to resolve global binding.
;; frames - List of local frames. Each local frame has a form:
;; (<type> (<name> . <obj>) ...)
;;
;; <type> <obj>
;; ----------------------------------------------
;; 0 <lvar> ;; lexical binding
;; 1 <macro> ;; syntactic binding
;; 2 <pvar> ;; pattern variable
;;
;; Constants LEXICAL, SYNTAX and PATTERN are defined
;; to represent <type> for the convenience.
;;
;; exp-name - The "name" of the current expression, that is, the
;; name of the variable the result of the current
;; expression is to be bound. This slot may contain
;; an identifier (for global binding) or a lvar (for
;; local binding). This slot may be #f.
;;
;; current-proc - Holds the information of the current
;; compilig procedure. It accumulates information needed
;; in later stages for the optimization. This slot may
;; be #f.
;;
;; source-path - While processing included file, this slot is set to
;; the full path of the included filename.
(define-simple-struct cenv #f %make-cenv
(module frames exp-name current-proc (source-path (current-load-path))))
(define (make-cenv module :optional (frames '()) (exp-name #f))
(%make-cenv module frames exp-name))
;; Some cenv-related proceduers are in C for better performance.
(inline-stub
;; env-lookup-int :: Name, LookupAs, Module, [Frame] -> Var
;; where Var = Lvar | Identifier | Macro
;;
;; PERFORMANCE KLUDGE:
;; - We assume the frame structure is well-formed, so skip some tests.
;; - We assume 'lookupAs' and the car of each frame are small non-negative
;; integers, so we directly compare them without unboxing them.
(define-cfn env-lookup-int (name lookup-as module::ScmModule* frames) :static
;; First, we look up the identifier directly
(when (SCM_IDENTIFIERP name)
(dopairs [fp1 frames]
(when (> (SCM_CAAR fp1) lookup-as) ; see PERFORMANCE KLUDGE above
(continue))
;; inline assq here to squeeze performance.
(dolist [vp (SCM_CDAR fp1)]
(when (SCM_EQ name (SCM_CAR vp)) (return (SCM_CDR vp))))))
;; Now we 'strip' the identifier's wrapping
(let* ([name-ident?::int (SCM_IDENTIFIERP name)]
[env (?: name-ident?
(-> (SCM_IDENTIFIER name) env)
frames)]
[true-name (?: name-ident?
(SCM_OBJ (-> (SCM_IDENTIFIER name) name))
name)])
(dopairs [fp env]
(when (> (SCM_CAAR fp) lookup-as) ; see PERFORMANCE KLUDGE above
(continue))
;; inline assq here to squeeze performance.
(dolist [vp (SCM_CDAR fp)]
(when (SCM_EQ true-name (SCM_CAR vp)) (return (SCM_CDR vp)))))
(if (SCM_SYMBOLP name)
(return (Scm_MakeIdentifier (SCM_SYMBOL name) module '()))
(begin
(SCM_ASSERT (SCM_IDENTIFIERP name))
(return name)))))
;; Internal API - used while macro expansion
(define-cproc env-lookup (name module frames)
(result (env-lookup-int name (SCM_MAKE_INT 1) ;; SYNTAX
(SCM_MODULE module) frames)))
;; Internal API - for faster CENV lookup
(define-cproc cenv-lookup-syntax (cenv name)
(result
(env-lookup-int name (SCM_MAKE_INT 1) ; SYNTAX
(SCM_MODULE (SCM_VECTOR_ELEMENT cenv 0)) ; module
(SCM_VECTOR_ELEMENT cenv 1)))) ; frames
;; Internal API - for faster CENV lookup
(define-cproc cenv-lookup-variable (cenv name)
(result
(env-lookup-int name (SCM_MAKE_INT 0) ; LEXICAL
(SCM_MODULE (SCM_VECTOR_ELEMENT cenv 0)) ; module
(SCM_VECTOR_ELEMENT cenv 1)))) ; frames
;; Check if Cenv is toplevel or not.
;;
;; (define (cenv-toplevel? cenv)
;; (not (any (lambda (frame) (eqv? (car frame) LEXICAL))
;; (cenv-frames cenv))))
;;
(define-cproc cenv-toplevel? (cenv)
(SCM_ASSERT (SCM_VECTORP cenv))
(dolist [fp (SCM_VECTOR_ELEMENT cenv 1)]
(if (== (SCM_CAR fp) '0) (return '#f)))
(return '#t))
)
(define-macro (cenv-copy-except cenv . kvs)
`(%make-cenv ,(get-keyword :module kvs `(cenv-module ,cenv))
,(get-keyword :frames kvs `(cenv-frames ,cenv))
,(get-keyword :exp-name kvs `(cenv-exp-name ,cenv))
,(get-keyword :current-proc kvs `(cenv-current-proc ,cenv))
,(get-keyword :source-path kvs `(cenv-source-path ,cenv))))
(define-macro (make-bottom-cenv . maybe-module)
(if (null? maybe-module)
`(%make-cenv (vm-current-module) '())
`(%make-cenv ,(car maybe-module) '())))
(define-inline (cenv-swap-module cenv mod)
(cenv-copy-except cenv :module mod))
(define-inline (cenv-extend cenv frame type)
(cenv-copy-except cenv :frames (acons type frame (cenv-frames cenv))))
(define-inline (cenv-extend/proc cenv frame type proc)
(cenv-copy-except cenv :frames (acons type frame (cenv-frames cenv))
:current-proc proc))
(define-inline (cenv-add-name cenv name)
(cenv-copy-except cenv :exp-name name))
(define-inline (cenv-add-name/source cenv name source)
(cenv-copy-except cenv :exp-name name :source-path source))
(define-inline (cenv-sans-name cenv)
(if (cenv-exp-name cenv)
(cenv-copy-except cenv :exp-name #f)
cenv))
(define-inline (cenv-extend/name cenv frame type name)
(cenv-copy-except cenv :frames (acons type frame (cenv-frames cenv))
:exp-name name))
(define-inline (cenv-swap-source cenv source)
(cenv-copy-except cenv :source-path source))
;; Intermediate tree form (IForm)
;;
;; We first convert the program into an intermediate tree form (IForm),
;; which is in principle similar to A-normal form, but has more
;; convenience node types specific to our VM. IForm is represented
;; by a nested vectors, whose first element shows the type of the node.
;;
;; The following table is an overview of the structure. See
;; [IForm Definitions] section below for the detailed specification.
;;
;; <top-iform> :=
;; <iform>
;; #($define <src> <flags> <id> <iform>)
;;
;; <iform> :=
;; #($lref <lvar>) ;; local variable reference
;; #($lset <lvar> <iform>) ;; local variable modification
;; #($gref <id>) ;; global variable reference
;; #($gset <id> <iform>) ;; global variable modification
;; #($const <obj>) ;; constant literal
;; #($if <src> <iform> <iform+> <iform+>) ;; branch
;; #($let <src> <type> (<lvar> ...) (<iform> ...) <iform>) ;; local binding
;; #($receive <src> <reqarg> <optarg> (<lvar> ...) <iform> <iform>)
;; ;; local binding (mv)
;; #($lambda <src> <name> <reqarg> <optarg> (<lvar> ...) <iform> <flag>)
;; ;; closure
;; #($label <src> <label> <iform>) ;; merge point of local call. see below.
;; #($promise <src> <expr>) ;; promise
;; #($seq (<iform> ...)) ;; sequencing
;; #($call <src> <proc-expr> (<arg-expr> ...) <flag>) ;; procedure call
;; #($asm <src> <insn> (<arg> ...)) ;; inline assembler
;; #($cons <src> <ca> <cd>) ;; used in quasiquote
;; #($append <src> <ca> <cd>) ;; ditto
;; #($vector <src> (<elt> ...)) ;; ditto
;; #($list->vector <src> <list>) ;; ditto
;; #($list <src> (<elt> ...)) ;; ditto
;; #($list* <src> (<elt> ...)) ;; ditto
;; #($memv <src> <obj> <list>) ;; used in case
;; #($eq? <src> <x> <y>) ;; ditto
;; #($eqv? <src> <x> <y>) ;; ditto
;;
;; <iform+> :=
;; <iform>
;; #($it) ;; refer to the value in the last test clause.
;;
;; NB: <src> slot keeps the information of the original source, and
;; will be used to generate debug info. Normally it holds the
;; relevant source code, or #f if there's no relevant code.
;;
;; NB: the actual value of the first element is an integer instead of
;; a symbol, which allows us to use vector dispatch instead
;; of case expressions.
;;
;; NB: The nodes are destructively modified during compilation, in order
;; to keep allocations minimal. Nodes shouldn't be shared, for
;; side-effects may vary depends on the path to the node. The only
;; exception is $label node.
(define-macro (iform-tag iform)
`(vector-ref ,iform 0))
;; check intermediate tag
(define-macro (has-tag? iform tag)
`(eqv? (vector-ref ,iform 0) ,tag))
;; [IForm Definitions]
;; $define <src> <flags> <id> <expr>
;; Global definition. Binds the result of <expr> to the global
;; identifier <id>.
(define-simple-struct $define $DEFINE $define
(src ; original source for debugging
flags ; a list of flags. Currently, only the following flag
; is supported:
; const : the binding is constant.
id ; global identifier
expr ; expression IForm
))
;; $lref <lvar>
;; Local variable reference.
(define-simple-struct $lref $LREF #f
(lvar ; lvar struct.
))
(define-inline ($lref lvar) (lvar-ref++! lvar) (vector $LREF lvar))
(define-inline ($lref? iform) (has-tag? iform $LREF))
;; $lset <lvar> <expr>
;; Local variable assignment. The result of <expr> is set to <lvar>.
(define-simple-struct $lset $LSET #f
(lvar ; lvar struct
expr ; IForm
))
(define-inline ($lset lvar expr)
(lvar-set++! lvar) (vector $LSET lvar expr))
;; $gref <id>
;; Global variable reference.
(define-simple-struct $gref $GREF $gref
(id ; identifier
))
;; $gset <id> <iform>
;; Global variable assignment.
(define-simple-struct $gset $GSET $gset
(id ; identifier
expr ; IForm
))
;; $const <value>
;; Constant.
(define-simple-struct $const $CONST $const
(value ; Scheme value
))
(define-inline ($const? x) (has-tag? x $CONST))
;; common cases
(define $const-undef (let1 x ($const (undefined)) (^[] x)))
(define $const-nil (let1 x ($const '()) (^[] x)))
(define $const-f (let1 x ($const #f) (^[] x)))
(define $const-t (let1 x ($const #t) (^[] x)))
;; $if <src> <test> <then> <else>
;; Conditional.
;; A special IForm, $it, can appear in either <then> or <else>
;; clause; it is no-op and indicates that the result(s) of <test>
;; should be carried over.
(define-simple-struct $if $IF $if
(src ; original source for debugging
test ; IForm for test expression
then ; IForm for then expression
else ; IForm for else expression
))
;; $let <src> <type> <lvars> <inits> <body>
;; Binding construct. let, letrec, and inlined closure is represented
;; by this node (let* is expanded to the nested $let in pass 1).
(define-simple-struct $let $LET $let
(src ; original source for debugging
type ; indicates scope: 'let for normal let, 'rec[*] for letrec[*],
lvars ; list of lvars
inits ; list of IForms to initialize lvars
body ; IForm for the body
))
;; $receive <src> <reqargs> <optarg> <lvars> <expr> <body>
;; Multiple value binding construct.
(define-simple-struct $receive $RECEIVE $receive
(src ; original source for debugging
reqargs ; # of required args
optarg ; 0 or 1, # of optional arg
lvars ; list of lvars
expr ; IForm for the expr to yield multiple values
body ; IForm for the body
))
;; $lambda <src> <reqargs> <optarg> <lvars> <body> [<flag>]
;; Closure.
;; $lambda has a couple of transient slots, which are used only
;; during the optimization paths and not be saved by pack-iform.
(define-simple-struct $lambda $LAMBDA $lambda
(src ; original source for debugging
name ; inferred name of this closure
reqargs ; # of required args
optarg ; 0 or 1, # of optional arg
lvars ; list of lvars
body ; IForm for the body
flag ; Marks some special state of this node.
; 'dissolved: indicates that this lambda has been
; inline expanded.
; 'used: indicates that this lambda has been already dealt
; with, and need to be eliminated. This one is
; specifically used for communication between
; pass2/$CALL and pass2/$LET.
; <packed-iform> : inlinable lambda
;; The following slots are used temporarily during pass2-5, and
;; need not be saved when packed.
(calls '()) ; list of call sites
(free-lvars '()) ; list of free local variables
(lifted-var #f) ; if this $LAMBDA is lifted to the toplevel, this slot
; contains an lvar to which the toplevel closure
; is to be bound. See pass 4.
))
;; $label <src> <label> <body>
;; This kind of IForm node is introduced in Pass2 to record a shared
;; node. It marks the destination of LOCAL-ENV-JUMP, and also is
;; created during $if optimization.
(define-simple-struct $label $LABEL $label
(src ; original source for debugging
label ; label. #f in Pass 2. Assigned in Pass 5.
body ; IForm for the body
))
;; $seq <body>
;; Sequensing. <body> is a list of IForms.
;; The compile tries to avoid creating $seq node if <body> has only
;; one expression, but optimization paths may introduce such a $seq node.
;; There can also be an empty $seq node, ($seq '()).
(define-simple-struct $seq $SEQ #f
(body ; list of IForms
))
(define-inline ($seq exprs)
(if (and (pair? exprs) (null? (cdr exprs)))
(car exprs)
(vector $SEQ exprs)))
;; $call <src> <proc> <args> [<flag>]
;; Call a procedure.
;; See the "Closure optimization" section in Pass 2 for the detailed
;; description.
(define-simple-struct $call $CALL $call
(src ; original source for debugging
proc ; IForm for the procedure to call.
args ; list of IForms for arguments.
flag ; #f, 'local, 'embed, 'jump, 'rec or 'tail-rec.
;; Transient slots
(renv '()) ; runtime env. used in embed calls to record depth of env
; in Pass 5.
))
(define-inline ($call? iform) (has-tag? iform $CALL))
;; $asm <src> <insn> <args>
;; Inlined assembly code.
(define-simple-struct $asm $ASM $asm
(src ; original source for debugging
insn ; instruction (<code> [<param> ...])
args ; list of IForms
))
;; $promise <src> <expr>
;; OBSOLETED. We keep $promise during 0.9.x releases since it
;; can appear in the packed IForm of the inlined procedures.
;; Will go in 1.0.
(define-simple-struct $promise $PROMISE $promise
(src ; original source for debugging
expr ; IForm
))
;; $it
;; A special node. See the explanation of $if above.
(define $it (let ((c `#(,$IT))) (^[] c)))
(define-inline ($it? x) (has-tag? x $IT))
;; The followings are builtin version of standard procedures.
;;
(define-simple-struct $cons $CONS #f (src arg0 arg1))
;; quasiquote tends to generate nested $cons, which can be
;; packed to $list or $list*.
(define ($cons o x y)
(if (has-tag? y $CONS)
(receive (type elts) ($cons-pack y)
(vector type o (cons x elts)))
(vector $CONS o x y)))
(define ($cons-pack elt)
(cond
[(equal? elt ($const-nil)) (values $LIST '())]
[(has-tag? elt $CONS)
(receive (type elts) ($cons-pack (vector-ref elt 3))
(values type (cons (vector-ref elt 2) elts)))]
[else (values $LIST* (list elt))]))
(define-simple-struct $append $APPEND $append (src arg0 arg1))
(define-simple-struct $memv $MEMV $memv (src arg0 arg1))
(define-simple-struct $eq? $EQ? $eq? (src arg0 arg1))
(define-simple-struct $eqv? $EQV? $eqv? (src arg0 arg1))
(define-simple-struct $vector $VECTOR $vector (src args))
(define-simple-struct $list $LIST $list (src args))
(define-simple-struct $list* $LIST* $list* (src args))
(define-simple-struct $list->vector $LIST->VECTOR $list->vector (src arg0))
;; common accessors
(define-macro ($*-src iform) `(vector-ref ,iform 1))
(define-macro ($*-args iform) `(vector-ref ,iform 2))
(define-macro ($*-arg0 iform) `(vector-ref ,iform 2))
(define-macro ($*-arg1 iform) `(vector-ref ,iform 3))
(define-macro ($*-args-set! iform val) `(vector-set! ,iform 2 ,val))
(define-macro ($*-arg0-set! iform val) `(vector-set! ,iform 2 ,val))
(define-macro ($*-arg1-set! iform val) `(vector-set! ,iform 3 ,val))
;; look up symbolic name of iform tag (for debugging)
(define (iform-tag-name tag)
(let loop ((p .intermediate-tags.))
(cond [(null? p) #f]
[(eqv? (cdar p) tag) (caar p)]
[else (loop (cdr p))])))
;; look up symbolic name of VM instruction (for debugging)
;; (The proper way to realize this is using gauche.vm.insn, but we can't
;; use it from comp.scm)
(define (insn-name code)
(let loop ((p .insn-alist.))
(cond [(null? p) #f]
[(eqv? (cdar p) code) (caar p)]
[else (loop (cdr p))])))
;; prettyprinter of intermediate form
(define (pp-iform iform :optional (lines +inf.0))
(let/cc return
(define labels '()) ;; alist of label node and count
(define (indent count) (dotimes [i count] (write-char #\space)))
(define (id->string id)
(format "~a#~a" (module-name (slot-ref id'module)) (slot-ref id'name)))
(define (lvar->string lvar)
(format "~a.~a~a" (variable-name (lvar-name lvar))
(lvar-ref-count lvar)
(make-string (lvar-set-count lvar) #\!)))
(define (nl ind)
(newline) (dec! lines) (when (zero? lines) (return)) (indent ind))
(let rec ([ind 0] [iform iform])
(case/unquote
(iform-tag iform)
[($DEFINE) (format #t "($define ~a ~a" ($define-flags iform)
(id->string ($define-id iform)))
(nl (+ ind 2))
(rec (+ ind 2) ($define-expr iform)) (display ")")]
[($LREF) (format #t "($lref ~a)" (lvar->string ($lref-lvar iform)))]
[($LSET) (format #t "($lset ~a" (lvar->string ($lset-lvar iform)))
(nl (+ ind 2))
(rec (+ ind 2) ($lset-expr iform)) (display ")")]
[($GREF) (format #t "($gref ~a)" (id->string ($gref-id iform)))]
[($GSET) (format #t "($gset ~a" (id->string ($gset-id iform)))
(nl (+ ind 2))
(rec (+ ind 2) ($gset-expr iform)) (display ")")]
[($CONST) (format #t "($const ~s)" ($const-value iform))]
[($IF) (display "($if ")
(rec (+ ind 5) ($if-test iform)) (nl (+ ind 2))
(rec (+ ind 2) ($if-then iform)) (nl (+ ind 2))
(rec (+ ind 2) ($if-else iform)) (display ")")]
[($LET)
(let* ([hdr (format "($let~a ("
(case ($let-type iform)
[(let) ""] [(rec) "rec"] [(rec*) "rec*"]))]
[xind (+ ind (string-length hdr))]
[first #t])
(display hdr)
(for-each (^[var init]
(if first (set! first #f) (nl xind))
(let1 z (format "[~a " (lvar->string var))
(display z)
(rec (+ xind (string-length z)) init)
(display "]")))
($let-lvars iform) ($let-inits iform))
(display ")") (nl (+ ind 2))
(rec (+ ind 2) ($let-body iform)) (display ")"))]
[($RECEIVE)
(format #t "($receive ~a" (map lvar->string ($receive-lvars iform)))
(nl (+ ind 4))
(rec (+ ind 4) ($receive-expr iform)) (nl (+ ind 2))
(rec (+ ind 2) ($receive-body iform)) (display ")")]
[($LAMBDA) (format #t "($lambda[~a.~a~a] ~a" ($lambda-name iform)
(length ($lambda-calls iform))
(if (vector? ($lambda-flag iform)) " inlinable" "")
(map lvar->string ($lambda-lvars iform)))
(nl (+ ind 2))
(rec (+ ind 2) ($lambda-body iform)) (display ")")]
[($LABEL) (if-let1 p (assq iform labels)
(format #t "label#~a" (cdr p))
(let1 num (length labels)
(push! labels (cons iform num))
(format #t "($label #~a" num)
(nl (+ ind 2))
(rec (+ ind 2) ($label-body iform)) (display ")")))]
[($SEQ) (format #t "($seq")
(for-each (^n (nl (+ ind 2)) (rec (+ ind 2) n)) ($seq-body iform))
(display ")")]
[($CALL) (let1 pre (if-let1 flag ($call-flag iform)
(format "($call[~a] " flag)
"($call ")
(format #t pre)
(rec (+ ind (string-length pre)) ($call-proc iform))
(for-each (^n (nl (+ ind 2)) (rec (+ ind 2) n))
($call-args iform))
(display ")"))]
[($ASM)
(let* ([insn ($asm-insn iform)]
[args ($asm-args iform)]
[hdr (format "($asm ~a" (cons (insn-name (car insn))
(cdr insn)))])
(display hdr)
(case (length args)
[(0)]
[(1) (display " ") (rec (+ ind (string-length hdr) 1) (car args))]
[else (for-each (^n (nl (+ ind 2)) (rec (+ ind 2) n))
($asm-args iform))])
(display ")"))]
[($PROMISE) (display "($promise ")
(rec (+ ind 10) ($promise-expr iform))
(display ")")]
[($IT) (display "($it)")]
[($CONS $APPEND $MEMV $EQ? $EQV?)
(let* ([s (format "(~a " (iform-tag-name (iform-tag iform)))]
[ind (+ ind (string-length s))])
(display s)
(rec ind (vector-ref iform 2)) (nl ind)
(rec ind (vector-ref iform 3)) (display ")"))]
[($LIST $LIST* $VECTOR)
(display (format "(~a " (iform-tag-name (iform-tag iform))))
(dolist [elt (vector-ref iform 2)] (nl (+ ind 2)) (rec (+ ind 2) elt))
(display ")")]
[($LIST->VECTOR)
(display "($LIST->VECTOR ")
(rec (+ ind 14) (vector-ref iform 2))
(display ")")]
[else (error "pp-iform: unknown tag:" (iform-tag iform))]))
(newline)))
;; Sometimes we need to save IForm for later use (e.g. procedure inlining)
;; We pack an IForm into a vector, instead of keeping it as is, since:
;; - For separate compilation, the saved form has to become a static
;; literal, keeping it's topology. The compiler unifies equal?-literals,
;; so we can't just rely on it. We also need to traverse the IForm to
;; make sure everything is serializable, anyway.
;; - IForm is destructively modified by pass 2, so we need to copy it
;; every time it is used.
;;
;; Packed IForm is a vector, with the references are represented by indices.
(define (pack-iform iform)
(define dict (make-hash-table 'eq?))
(define r '())
(define c 1)
(define (put! iform . objs)
(rlet1 head c
(hash-table-put! dict iform head)
(dolist [obj objs] (push! r obj) (inc! c))))
(define (get-ref iform)
(or (hash-table-get dict iform #f) (pack-iform-rec iform)))
(define (pack-iform-rec iform)
(case/unquote
(iform-tag iform)
[($DEFINE) (put! iform $DEFINE ($*-src iform)
($define-flags iform) ($define-id iform)
(get-ref ($define-expr iform)))]
[($LREF) (put! iform $LREF (get-ref ($lref-lvar iform)))]
[($LSET) (put! iform $LSET
(get-ref ($lset-lvar iform)) (get-ref ($lset-expr iform)))]
[($GREF) (put! iform $GREF ($gref-id iform))]
[($GSET) (put! iform $GSET ($gset-id iform) (get-ref ($gset-expr iform)))]
[($CONST)(put! iform $CONST ($const-value iform))]
[($IF) (put! iform $IF ($*-src iform)
(get-ref ($if-test iform))
(get-ref ($if-then iform))
(get-ref ($if-else iform)))]
[($LET) (put! iform (iform-tag iform) ($*-src iform) ($let-type iform)
(map get-ref ($let-lvars iform))
(map get-ref ($let-inits iform))
(get-ref ($let-body iform)))]
[($RECEIVE) (put! iform $RECEIVE ($*-src iform)
($receive-reqargs iform) ($receive-optarg iform)
(map get-ref ($receive-lvars iform))
(get-ref ($receive-expr iform))
(get-ref ($receive-body iform)))]
[($LAMBDA) (put! iform $LAMBDA ($*-src iform)
($lambda-name iform) ($lambda-reqargs iform)
($lambda-optarg iform)
(map get-ref ($lambda-lvars iform))
(get-ref ($lambda-body iform))
($lambda-flag iform))]
[($LABEL) (put! iform $LABEL ($*-src iform) #f
(get-ref ($label-body iform)))]
[($SEQ) (put! iform $SEQ (map get-ref ($seq-body iform)))]
[($CALL) (put! iform $CALL ($*-src iform)
(get-ref ($call-proc iform))
(map get-ref ($call-args iform))
($call-flag iform))]
[($ASM) (put! iform $ASM ($*-src iform)
($asm-insn iform)
(map get-ref ($asm-args iform)))]
[($IT) (put! iform $IT)]
[($PROMISE)(put! iform $PROMISE ($*-src iform)
(get-ref ($promise-expr iform)))]
[($CONS $APPEND $MEMV $EQ? $EQV?)
(put! iform (iform-tag iform) ($*-src iform)
(get-ref ($*-arg0 iform))
(get-ref ($*-arg1 iform)))]
[($VECTOR $LIST $LIST*)
(put! iform (iform-tag iform) ($*-src iform)
(map get-ref ($*-args iform)))]
[($LIST->VECTOR)
(put! iform (iform-tag iform) ($*-src iform)
(get-ref ($*-arg0 iform)))]
[('lvar)
(put! iform 'lvar (lvar-name iform))]
[else
(errorf "[internal-error] unknown IForm in pack-iform: ~S" iform)]
))
;; main body of pack-iform
(let* ([start (pack-iform-rec iform)]
[vec (make-vector c)])
(do ([i (- c 1) (- i 1)]
[r r (cdr r)])
[(null? r)]
(vector-set! vec i (car r)))
(vector-set! vec 0 start)
vec))
(define (unpack-iform ivec)
(let-syntax ([V (syntax-rules ()
[(V ix) (vector-ref ivec ix)]
[(V ix off) (vector-ref ivec (+ ix off))])])
(define dict (make-hash-table 'eqv?))
(define (unpack-rec ref)
(cond [(hash-table-get dict ref #f)]
[else (rlet1 body (unpack-body ref)
(hash-table-put! dict ref body))]))
(define (unpack-body i)
(case/unquote
(V i)
[($DEFINE) ($define (V i 1) (V i 2) (V i 3) (unpack-rec (V i 4)))]
[($LREF) ($lref (unpack-rec (V i 1)))]
[($LSET) ($lset (unpack-rec (V i 1)) (unpack-rec (V i 2)))]
[($GREF) ($gref (V i 1))]
[($GSET) ($gset (V i 1) (unpack-rec (V i 2)))]
[($CONST) ($const (V i 1))]
[($IF) ($if (V i 1) (unpack-rec (V i 2))
(unpack-rec (V i 3)) (unpack-rec (V i 4)))]
[($LET) (rlet1 unpacked
($let (V i 1) (V i 2)
(map unpack-rec (V i 3)) (map unpack-rec (V i 4))
(unpack-rec (V i 5)))
(ifor-each2 (^(lv in) (lvar-initval-set! lv in))
($let-lvars unpacked) ($let-inits unpacked)))]
[($RECEIVE) ($receive (V i 1) (V i 2) (V i 3)
(map unpack-rec (V i 4)) (unpack-rec (V i 5))
(unpack-rec (V i 6)))]
[($LAMBDA) ($lambda (V i 1) (V i 2) (V i 3) (V i 4)
(map unpack-rec (V i 5))
(unpack-rec (V i 6)) (V i 7))]
[($LABEL) ($label (V i 1) (V i 2) (unpack-rec (V i 3)))]
[($SEQ) ($seq (map unpack-rec (V i 1)))]
[($CALL) ($call (V i 1) (unpack-rec (V i 2))
(map unpack-rec (V i 3)) (V i 4))]
[($ASM) ($asm (V i 1) (V i 2) (map unpack-rec (V i 3)))]
[($PROMISE) ($promise (V i 1) (unpack-rec (V i 2)))]
[($IT) ($it)]
[($CONS $APPEND $MEMV $EQ? $EQV?)
(vector (V i) (V i 1) (unpack-rec (V i 2)) (unpack-rec (V i 3)))]
[($VECTOR $LIST $LIST*) (vector (V i) (V i 1) (map unpack-rec (V i 2)))]
[($LIST->VECTOR) (vector (V i) (V i 1) (unpack-rec (V i 2)))]
[('lvar) (make-lvar (V i 1))]
[else (errorf "[internal error] unpack-iform: ivec broken at ~a: ~S"
i ivec)]))
(unpack-rec (V 0))))
;; Counts the size (approx # of nodes) of the iform.
(define (iform-count-size-upto iform limit)
(define (rec iform cnt)
(letrec-syntax ([sum-items
(syntax-rules (*)
[(_ cnt) cnt]
[(_ cnt (* item1) item2 ...)
(let1 s1 (rec-list item1 cnt)
(if (>= s1 limit) limit (sum-items s1 item2 ...)))]
[(_ cnt item1 item2 ...)
(let1 s1 (rec item1 cnt)
(if (>= s1 limit) limit (sum-items s1 item2 ...)))])])
(case/unquote
(iform-tag iform)
[($DEFINE) (sum-items (+ cnt 1) ($define-expr iform))]
[($LREF $GREF $CONST) (+ cnt 1)]
[($LSET) (sum-items (+ cnt 1) ($lset-expr iform))]
[($GSET) (sum-items (+ cnt 1) ($gset-expr iform))]
[($IF) (sum-items (+ cnt 1) ($if-test iform)
($if-then iform) ($if-else iform))]
[($LET) (sum-items (+ cnt 1) (* ($let-inits iform)) ($let-body iform))]
[($RECEIVE)
(sum-items (+ cnt 1) ($receive-expr iform) ($receive-body iform))]
[($LAMBDA) (sum-items (+ cnt 1) ($lambda-body iform))]
[($LABEL) (sum-items cnt ($label-body iform))]
[($SEQ) (sum-items cnt (* ($seq-body iform)))]
[($CALL) (sum-items (+ cnt 1) ($call-proc iform) (* ($call-args iform)))]
[($ASM) (sum-items (+ cnt 1) (* ($asm-args iform)))]
[($PROMISE)(sum-items (+ cnt 1) ($promise-expr iform))]
[($CONS $APPEND $MEMV $EQ? $EQV?)
(sum-items (+ cnt 1) ($*-arg0 iform) ($*-arg1 iform))]
[($VECTOR $LIST $LIST*) (sum-items (+ cnt 1) (* ($*-args iform)))]
[($LIST->VECTOR) (sum-items (+ cnt 1) ($*-arg0 iform))]
[($IT) cnt]
[else
(error "[internal error] iform-count-size-upto: unknown iform tag:"
(iform-tag iform))]