1 ;;; Tree-IL partial evaluator
3 ;; Copyright (C) 2011 Free Software Foundation, Inc.
5 ;;;; This library is free software; you can redistribute it and/or
6 ;;;; modify it under the terms of the GNU Lesser General Public
7 ;;;; License as published by the Free Software Foundation; either
8 ;;;; version 3 of the License, or (at your option) any later version.
10 ;;;; This library is distributed in the hope that it will be useful,
11 ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
12 ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 ;;;; Lesser General Public License for more details.
15 ;;;; You should have received a copy of the GNU Lesser General Public
16 ;;;; License along with this library; if not, write to the Free Software
17 ;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19 (define-module (language tree-il peval)
20 #:use-module (language tree-il)
21 #:use-module (language tree-il primitives)
22 #:use-module (ice-9 vlist)
23 #:use-module (ice-9 match)
24 #:use-module (srfi srfi-1)
25 #:use-module (srfi srfi-9)
26 #:use-module (srfi srfi-11)
27 #:use-module (srfi srfi-26)
31 ;;; Partial evaluation is Guile's most important source-to-source
32 ;;; optimization pass. It performs copy propagation, dead code
33 ;;; elimination, inlining, and constant folding, all while preserving
34 ;;; the order of effects in the residual program.
36 ;;; For more on partial evaluation, see William Cook’s excellent
37 ;;; tutorial on partial evaluation at DSL 2011, called “Build your own
38 ;;; partial evaluator in 90 minutes”[0].
40 ;;; Our implementation of this algorithm was heavily influenced by
41 ;;; Waddell and Dybvig's paper, "Fast and Effective Procedure Inlining",
42 ;;; IU CS Dept. TR 484.
44 ;;; [0] http://www.cs.utexas.edu/~wcook/tutorial/.
47 ;; First, some helpers.
49 (define-syntax *logging* (identifier-syntax #f))
51 ;; For efficiency we define *logging* to inline to #f, so that the call
52 ;; to log* gets optimized out. If you want to log, uncomment these
55 ;; (define %logging #f)
56 ;; (define-syntax *logging* (identifier-syntax %logging))
58 ;; Then you can change %logging at runtime.
64 (or (eq? *logging* #t)
65 (memq 'event *logging*)))
66 (log* 'event arg ...)))))
68 (define (log* event . args)
69 (let ((pp (module-ref (resolve-interface '(ice-9 pretty-print))
71 (pp `(log ,event . ,args))
75 (define-syntax-rule (let/ec k e e* ...)
76 (let ((tag (make-prompt-tag)))
80 (let ((k (lambda args (apply abort-to-prompt tag args))))
82 (lambda (_ res) res))))
84 (define (tree-il-any proc exp)
86 (tree-il-fold (lambda (exp res)
87 (let ((res (proc exp)))
90 (let ((res (proc exp)))
95 (define (vlist-any proc vlist)
96 (let ((len (vlist-length vlist)))
99 (or (proc (vlist-ref vlist i))
102 (define (truncate-values x)
103 "Discard all but the first value of X."
107 (($ <lexical-ref>) x)
109 (($ <lexical-ref>) x)
110 (($ <primitive-ref>) x)
112 (($ <toplevel-ref>) x)
113 (($ <conditional> src condition subsequent alternate)
114 (make-conditional src condition (loop subsequent) (loop alternate)))
115 (($ <application> _ ($ <primitive-ref> _ 'values) (first _ ...))
117 (($ <application> _ ($ <primitive-ref> _ 'values) (val))
119 (($ <application> src
120 (and prim ($ <primitive-ref> _ (? singly-valued-primitive?)))
122 (make-application src prim (map loop args)))
123 (($ <application> src proc args)
124 (make-application src proc (map loop args)))
125 (($ <sequence> src (exps ... last))
126 (make-sequence src (append exps (list (loop last)))))
128 (($ <dynlet> src fluids vals body)
129 (make-dynlet src fluids vals (loop body)))
130 (($ <let> src names gensyms vals body)
131 (make-let src names gensyms vals (loop body)))
132 (($ <letrec> src in-order? names gensyms vals body)
133 (make-letrec src in-order? names gensyms vals (loop body)))
134 (($ <fix> src names gensyms vals body)
135 (make-fix src names gensyms vals body))
136 (($ <let-values> src exp body)
137 (make-let-values src exp (loop body)))
139 (make-application (tree-il-src x)
140 (make-primitive-ref #f 'values)
143 ;; Peval will do a one-pass analysis on the source program to determine
144 ;; the set of assigned lexicals, and to identify unreferenced and
145 ;; singly-referenced lexicals.
147 (define-record-type <var>
148 (make-var name gensym refcount set?)
152 (refcount var-refcount set-var-refcount!)
153 (set? var-set? set-var-set?!))
155 (define* (build-var-table exp #:optional (table vlist-null))
159 (($ <lexical-ref> src name gensym)
160 (let ((var (cdr (vhash-assq gensym res))))
161 (set-var-refcount! var (1+ (var-refcount var)))
166 (($ <lambda-case> src req opt rest kw init gensyms body alt)
167 (fold (lambda (name sym res)
168 (vhash-consq sym (make-var name sym 0 #f) res))
170 (append req (or opt '()) (if rest (list rest) '())
172 ((aok? (kw name sym) ...) name)
175 (($ <let> src names gensyms vals body)
176 (fold (lambda (name sym res)
177 (vhash-consq sym (make-var name sym 0 #f) res))
179 (($ <letrec> src in-order? names gensyms vals body)
180 (fold (lambda (name sym res)
181 (vhash-consq sym (make-var name sym 0 #f) res))
183 (($ <fix> src names gensyms vals body)
184 (fold (lambda (name sym res)
185 (vhash-consq sym (make-var name sym 0 #f) res))
187 (($ <lexical-set> src name gensym exp)
188 (set-var-set?! (cdr (vhash-assq gensym res)) #t)
191 (lambda (exp res) res)
194 ;; Counters are data structures used to limit the effort that peval
195 ;; spends on particular inlining attempts. Each call site in the source
196 ;; program is allocated some amount of effort. If peval exceeds the
197 ;; effort counter while attempting to inline a call site, it aborts the
198 ;; inlining attempt and residualizes a call instead.
200 ;; As there is a fixed number of call sites, that makes `peval' O(N) in
201 ;; the number of call sites in the source program.
203 ;; Counters should limit the size of the residual program as well, but
204 ;; currently this is not implemented.
206 ;; At the top level, before seeing any peval call, there is no counter,
207 ;; because inlining will terminate as there is no recursion. When peval
208 ;; sees a call at the top level, it will make a new counter, allocating
209 ;; it some amount of effort and size.
211 ;; This top-level effort counter effectively "prints money". Within a
212 ;; toplevel counter, no more effort is printed ex nihilo; for a nested
213 ;; inlining attempt to proceed, effort must be transferred from the
214 ;; toplevel counter to the nested counter.
216 ;; Via `data' and `prev', counters form a linked list, terminating in a
217 ;; toplevel counter. In practice `data' will be the a pointer to the
218 ;; source expression of the procedure being inlined.
220 ;; In this way peval can detect a recursive inlining attempt, by walking
221 ;; back on the `prev' links looking for matching `data'. Recursive
222 ;; counters receive a more limited effort allocation, as we don't want
223 ;; to spend all of the effort for a toplevel inlining site on loops.
224 ;; Also, recursive counters don't need a prompt at each inlining site:
225 ;; either the call chain folds entirely, or it will be residualized at
226 ;; its original call.
228 (define-record-type <counter>
229 (%make-counter effort size continuation recursive? data prev)
231 (effort effort-counter)
233 (continuation counter-continuation)
234 (recursive? counter-recursive? set-counter-recursive?!)
238 (define (abort-counter c)
239 ((counter-continuation c)))
241 (define (record-effort! c)
242 (let ((e (effort-counter c)))
243 (if (zero? (variable-ref e))
245 (variable-set! e (1- (variable-ref e))))))
247 (define (record-size! c)
248 (let ((s (size-counter c)))
249 (if (zero? (variable-ref s))
251 (variable-set! s (1- (variable-ref s))))))
253 (define (find-counter data counter)
255 (if (eq? data (counter-data counter))
257 (find-counter data (counter-prev counter)))))
259 (define* (transfer! from to #:optional
260 (effort (variable-ref (effort-counter from)))
261 (size (variable-ref (size-counter from))))
262 (define (transfer-counter! from-v to-v amount)
263 (let* ((from-balance (variable-ref from-v))
264 (to-balance (variable-ref to-v))
265 (amount (min amount from-balance)))
266 (variable-set! from-v (- from-balance amount))
267 (variable-set! to-v (+ to-balance amount))))
269 (transfer-counter! (effort-counter from) (effort-counter to) effort)
270 (transfer-counter! (size-counter from) (size-counter to) size))
272 (define (make-top-counter effort-limit size-limit continuation data)
273 (%make-counter (make-variable effort-limit)
274 (make-variable size-limit)
280 (define (make-nested-counter continuation data current)
281 (let ((c (%make-counter (make-variable 0)
287 (transfer! current c)
290 (define (make-recursive-counter effort-limit size-limit orig current)
291 (let ((c (%make-counter (make-variable 0)
293 (counter-continuation orig)
297 (transfer! current c effort-limit size-limit)
300 ;; Operand structures allow bindings to be processed lazily instead of
301 ;; eagerly. By doing so, hopefully we can get process them in a way
302 ;; appropriate to their use contexts. Operands also prevent values from
303 ;; being visited multiple times, wasting effort.
305 ;; TODO: Record value size in operand structure?
307 (define-record-type <operand>
308 (%make-operand var sym visit source visit-count residualize?
309 copyable? residual-value constant-value)
313 (visit %operand-visit)
314 (source operand-source)
315 (visit-count operand-visit-count set-operand-visit-count!)
316 (residualize? operand-residualize? set-operand-residualize?!)
317 (copyable? operand-copyable? set-operand-copyable?!)
318 (residual-value operand-residual-value set-operand-residual-value!)
319 (constant-value operand-constant-value set-operand-constant-value!))
321 (define* (make-operand var sym #:optional source visit)
322 ;; Bind SYM to VAR, with value SOURCE.
323 ;; Bound operands are considered copyable until we prove otherwise.
324 (let ((source (if source (truncate-values source) source)))
325 (%make-operand var sym visit source 0 #f (and source #t) #f #f)))
327 (define (make-bound-operands vars syms sources visit)
328 (map (lambda (x y z) (make-operand x y z visit)) vars syms sources))
330 (define (make-unbound-operands vars syms)
331 (map make-operand vars syms))
333 (define* (visit-operand op counter ctx #:optional effort-limit size-limit)
334 ;; Peval is O(N) in call sites of the source program. However,
335 ;; visiting an operand can introduce new call sites. If we visit an
336 ;; operand outside a counter -- i.e., outside an inlining attempt --
337 ;; this can lead to divergence. So, if we are visiting an operand to
338 ;; try to copy it, and there is no counter, make a new one.
340 ;; This will only happen at most as many times as there are lexical
341 ;; references in the source program.
342 (and (zero? (operand-visit-count op))
345 (set-operand-visit-count! op (1+ (operand-visit-count op))))
347 (and (operand-source op)
348 (if (or counter (and (not effort-limit) (not size-limit)))
349 ((%operand-visit op) (operand-source op) counter ctx)
351 (define (abort) (k #f))
354 (make-top-counter effort-limit size-limit abort op)
357 (set-operand-visit-count! op (1- (operand-visit-count op)))))))
359 ;; A helper for constant folding.
361 (define (types-check? primitive-name args)
364 ((not pair? null? list? symbol? vector? struct?)
368 ;; FIXME: add more cases?
371 (define* (peval exp #:optional (cenv (current-module)) (env vlist-null)
373 (operator-size-limit 40)
374 (operand-size-limit 20)
375 (value-size-limit 10)
377 (recursive-effort-limit 100))
378 "Partially evaluate EXP in compilation environment CENV, with
379 top-level bindings from ENV and return the resulting expression."
381 ;; This is a simple partial evaluator. It effectively performs
382 ;; constant folding, copy propagation, dead code elimination, and
387 ;; Propagate copies across toplevel bindings, if we can prove the
388 ;; bindings to be immutable.
390 ;; Specialize lambda expressions with invariant arguments.
392 (define local-toplevel-env
393 ;; The top-level environment of the module being compiled.
395 (($ <toplevel-define> _ name)
396 (vhash-consq name #t env))
397 (($ <sequence> _ exps)
400 (($ <toplevel-define> _ name)
401 (vhash-consq name #t r))
407 (define (local-toplevel? name)
408 (vhash-assq name local-toplevel-env))
411 ;; renamed-term -> original-term
413 (define store (build-var-table exp))
415 (define (record-new-temporary! name sym refcount)
416 (set! store (vhash-consq sym (make-var name sym refcount #f) store)))
418 (define (lookup-var sym)
419 (let ((v (vhash-assq sym store)))
420 (if v (cdr v) (error "unbound var" sym (vlist->list store)))))
422 (define (fresh-gensyms vars)
424 (let ((new (gensym (string-append (symbol->string (var-name var))
426 (set! store (vhash-consq new var store))
430 (define (assigned-lexical? sym)
431 (var-set? (lookup-var sym)))
433 (define (lexical-refcount sym)
434 (var-refcount (lookup-var sym)))
436 ;; ORIG has been alpha-renamed to NEW. Analyze NEW and record a link
439 (define (record-source-expression! orig new)
440 (set! store (vhash-consq new (source-expression orig) store))
443 ;; Find the source expression corresponding to NEW. Used to detect
444 ;; recursive inlining attempts.
446 (define (source-expression new)
447 (let ((x (vhash-assq new store)))
450 (define* (residualize-lexical op #:optional ctx val)
451 (log 'residualize op)
452 (set-operand-residualize?! op #t)
454 (set-operand-residual-value! op val))
455 (make-lexical-ref #f (var-name (operand-var op)) (operand-sym op)))
457 (define (apply-primitive name args)
458 ;; todo: further optimize commutative primitives
463 (apply (module-ref the-scm-module name) args))
465 (values #t results))))
469 (define (make-values src values)
471 ((single) single) ; 1 value
472 ((_ ...) ; 0, or 2 or more values
473 (make-application src (make-primitive-ref src 'values)
476 (define (fold-constants src name args ctx)
477 (define (residualize-call)
478 (make-application src (make-primitive-ref #f name) args))
481 (let-values (((success? values)
482 (apply-primitive name (map const-exp args))))
483 (log 'fold success? values name args)
486 ((effect) (make-void src))
488 ;; Values truncation: only take the first
491 (make-const src (car values))
492 (make-values src '())))
494 (make-values src (map (cut make-const src <>) values))))
495 (residualize-call))))
496 ((and (eq? ctx 'effect) (types-check? name args))
499 (residualize-call))))
501 (define (inline-values exp src names gensyms body)
502 (let loop ((exp exp))
504 ;; Some expression types are always singly-valued.
513 ($ <lexical-set>) ; FIXME: these set! expressions
514 ($ <toplevel-set>) ; could return zero values in
515 ($ <toplevel-define>) ; the future
518 (and (= (length names) 1)
519 (make-let src names gensyms (list exp) body)))
520 (($ <application> src
521 ($ <primitive-ref> _ (? singly-valued-primitive? name)))
522 (and (= (length names) 1)
523 (make-let src names gensyms (list exp) body)))
525 ;; Statically-known number of values.
526 (($ <application> src ($ <primitive-ref> _ 'values) vals)
527 (and (= (length names) (length vals))
528 (make-let src names gensyms vals body)))
530 ;; Not going to copy code into both branches.
531 (($ <conditional>) #f)
533 ;; Bail on other applications.
534 (($ <application>) #f)
536 ;; Bail on prompt and abort.
540 ;; Propagate to tail positions.
541 (($ <let> src names gensyms vals body)
542 (let ((body (loop body)))
544 (make-let src names gensyms vals body))))
545 (($ <letrec> src in-order? names gensyms vals body)
546 (let ((body (loop body)))
548 (make-letrec src in-order? names gensyms vals body))))
549 (($ <fix> src names gensyms vals body)
550 (let ((body (loop body)))
552 (make-fix src names gensyms vals body))))
553 (($ <let-values> src exp
554 ($ <lambda-case> src2 req opt rest kw inits gensyms body #f))
555 (let ((body (loop body)))
557 (make-let-values src exp
558 (make-lambda-case src2 req opt rest kw
559 inits gensyms body #f)))))
560 (($ <dynwind> src winder body unwinder)
561 (let ((body (loop body)))
563 (make-dynwind src winder body unwinder))))
564 (($ <dynlet> src fluids vals body)
565 (let ((body (loop body)))
567 (make-dynlet src fluids vals body))))
568 (($ <sequence> src exps)
571 (let ((tail (loop tail)))
573 (make-sequence src (append head (list tail)))))))))))
575 (define (constant-expression? x)
576 ;; Return true if X is constant, for the purposes of copying or
577 ;; elision---i.e., if it is known to have no effects, does not
578 ;; allocate storage for a mutable object, and does not access
579 ;; mutable data (like `car' or toplevel references).
585 (($ <lambda-case> _ req opt rest kw inits syms body alternate)
586 (and (not (any assigned-lexical? syms))
587 (every loop inits) (loop body)
588 (or (not alternate) (loop alternate))))
589 (($ <lexical-ref> _ _ gensym)
590 (not (assigned-lexical? gensym)))
591 (($ <primitive-ref>) #t)
592 (($ <conditional> _ condition subsequent alternate)
593 (and (loop condition) (loop subsequent) (loop alternate)))
594 (($ <application> _ ($ <primitive-ref> _ name) args)
595 (and (effect-free-primitive? name)
596 (not (constructor-primitive? name))
597 (not (accessor-primitive? name))
598 (types-check? name args)
600 (($ <application> _ ($ <lambda> _ _ body) args)
601 (and (loop body) (every loop args)))
602 (($ <sequence> _ exps)
604 (($ <let> _ _ syms vals body)
605 (and (not (any assigned-lexical? syms))
606 (every loop vals) (loop body)))
607 (($ <letrec> _ _ _ syms vals body)
608 (and (not (any assigned-lexical? syms))
609 (every loop vals) (loop body)))
610 (($ <fix> _ _ _ vals body)
611 (and (every loop vals) (loop body)))
612 (($ <let-values> _ exp body)
613 (and (loop exp) (loop body)))
614 (($ <prompt> _ tag body handler)
615 (and (loop tag) (loop body) (loop handler)))
618 (define (prune-bindings ops in-order? body counter ctx build-result)
619 ;; This helper handles both `let' and `letrec'/`fix'. In the latter
620 ;; cases we need to make sure that if referenced binding A needs
621 ;; as-yet-unreferenced binding B, that B is processed for value.
622 ;; Likewise if C, when processed for effect, needs otherwise
623 ;; unreferenced D, then D needs to be processed for value too.
625 (define (referenced? op)
626 ;; When we visit lambdas in operator context, we just copy them,
627 ;; as we will process their body later. However this does have
628 ;; the problem that any free var referenced by the lambda is not
629 ;; marked as needing residualization. Here we hack around this
630 ;; and treat all bindings as referenced if we are in operator
632 (or (eq? ctx 'operator) (operand-residualize? op)))
634 ;; values := (op ...)
635 ;; effects := (op ...)
636 (define (residualize values effects)
637 ;; Note, values and effects are reversed.
640 (let ((values (filter operand-residual-value ops)))
643 (build-result (map (compose var-name operand-var) values)
644 (map operand-sym values)
645 (map operand-residual-value values)
651 (let ((effect-vals (map operand-residual-value effects)))
652 (make-sequence #f (reverse (cons body effect-vals)))))))
655 (let ((values (reverse values)))
656 (build-result (map (compose var-name operand-var) values)
657 (map operand-sym values)
658 (map operand-residual-value values)
662 ;; values := (op ...)
663 ;; effects := ((op . value) ...)
664 (let prune ((old (map referenced? ops)) (values '()) (effects '()))
665 (let lp ((ops* ops) (values values) (effects effects))
668 (let ((new (map referenced? ops)))
669 (if (not (equal? new old))
670 (prune new values '())
672 (map (lambda (op val)
673 (set-operand-residual-value! op val)
675 (map car effects) (map cdr effects))))))
677 (let ((op (car ops*)))
680 (lp (cdr ops*) values effects))
681 ((operand-residual-value op)
682 (lp (cdr ops*) (cons op values) effects))
684 (set-operand-residual-value! op (visit-operand op counter 'value))
685 (lp (cdr ops*) (cons op values) effects))
689 (let ((effect (visit-operand op counter 'effect)))
692 (acons op effect effects))))))))))))
694 (define (small-expression? x limit)
697 (lambda (x res) ; leaf
699 (lambda (x res) ; down
708 (define (extend-env sym op env)
709 (vhash-consq (operand-sym op) op (vhash-consq sym op env)))
712 (env vlist-null) ; vhash of gensym -> <operand>
713 (counter #f) ; inlined call stack
714 (ctx 'value)) ; effect, value, test, operator, or call
717 ((vhash-assq var env) => cdr)
718 (else (error "unbound var" var))))
720 (define (visit exp ctx)
721 (loop exp env counter ctx))
723 (define (for-value exp) (visit exp 'value))
724 (define (for-test exp) (visit exp 'test))
725 (define (for-effect exp) (visit exp 'effect))
726 (define (for-call exp) (visit exp 'call))
727 (define (for-tail exp) (visit exp ctx))
730 (record-effort! counter))
732 (log 'visit ctx (and=> counter effort-counter)
733 (unparse-tree-il exp))
738 ((effect) (make-void #f))
742 ((test) (make-const #f #t))
744 (($ <lexical-ref> _ _ gensym)
745 (log 'begin-copy gensym)
746 (let ((op (lookup gensym)))
749 (log 'lexical-for-effect gensym)
752 ;; Don't propagate copies if we are residualizing a call.
753 (log 'residualize-lexical-call gensym op)
754 (residualize-lexical op))
755 ((var-set? (operand-var op))
756 ;; Assigned lexicals don't copy-propagate.
757 (log 'assigned-var gensym op)
758 (residualize-lexical op))
759 ((not (operand-copyable? op))
760 ;; We already know that this operand is not copyable.
761 (log 'not-copyable gensym op)
762 (residualize-lexical op))
763 ((and=> (operand-constant-value op)
764 (lambda (x) (or (const? x) (void? x) (primitive-ref? x))))
766 (let ((val (operand-constant-value op)))
767 (log 'memoized-constant gensym val)
769 ((visit-operand op counter ctx recursive-effort-limit operand-size-limit)
771 ;; If we end up deciding to residualize this value instead of
772 ;; copying it, save that residualized value.
775 ((not (constant-expression? val))
776 (log 'not-constant gensym op)
777 ;; At this point, ctx is operator, test, or value. A
778 ;; value that is non-constant in one context will be
779 ;; non-constant in the others, so it's safe to record
780 ;; that here, and avoid future visits.
781 (set-operand-copyable?! op #f)
782 (residualize-lexical op ctx val))
785 (primitive-ref? val))
786 ;; Always propagate simple values that cannot lead to
788 (log 'copy-simple gensym val)
789 ;; It could be this constant is the result of folding.
790 ;; If that is the case, cache it. This helps loop
791 ;; unrolling get farther.
794 (log 'memoize-constant gensym val)
795 (set-operand-constant-value! op val)))
797 ((= 1 (var-refcount (operand-var op)))
798 ;; Always propagate values referenced only once.
799 (log 'copy-single gensym val)
801 ;; FIXME: do demand-driven size accounting rather than
804 ;; A pure expression in the operator position. Inline
805 ;; if it's a lambda that's small enough.
806 (if (and (lambda? val)
807 (small-expression? val operator-size-limit))
809 (log 'copy-operator gensym val)
812 (log 'too-big-for-operator gensym val)
813 (residualize-lexical op ctx val))))
815 ;; A pure expression, processed for call or for value.
816 ;; Don't inline lambdas, because they will probably won't
817 ;; fold because we don't know the operator.
818 (if (and (small-expression? val value-size-limit)
819 (not (tree-il-any lambda? val)))
821 (log 'copy-value gensym val)
824 (log 'too-big-or-has-lambda gensym val)
825 (residualize-lexical op ctx val)))))))
827 ;; Visit failed. Either the operand isn't bound, as in
828 ;; lambda formal parameters, or the copy was aborted.
829 (log 'unbound-or-aborted gensym op)
830 (residualize-lexical op)))))
831 (($ <lexical-set> src name gensym exp)
832 (let ((op (lookup gensym)))
833 (if (zero? (var-refcount (operand-var op)))
834 (let ((exp (for-effect exp)))
837 (make-sequence src (list exp (make-void #f)))))
839 (set-operand-residualize?! op #t)
840 (make-lexical-set src name (operand-sym op) (for-value exp))))))
841 (($ <let> src names gensyms vals body)
842 (let* ((vars (map lookup-var gensyms))
843 (new (fresh-gensyms vars))
844 (ops (make-bound-operands vars new vals
845 (lambda (exp counter ctx)
846 (loop exp env counter ctx))))
847 (env (fold extend-env env gensyms ops))
848 (body (loop body env counter ctx)))
851 (for-tail (make-sequence src (append vals (list body)))))
852 ((and (lexical-ref? body)
853 (memq (lexical-ref-gensym body) new))
854 (let ((sym (lexical-ref-gensym body))
855 (pairs (map cons new vals)))
856 ;; (let ((x foo) (y bar) ...) x) => (begin bar ... foo)
860 (append (map cdr (alist-delete sym pairs eq?))
861 (list (assq-ref pairs sym)))))))
863 ;; Only include bindings for which lexical references
864 ;; have been residualized.
865 (prune-bindings ops #f body counter ctx
866 (lambda (names gensyms vals body)
867 (if (null? names) (error "what!" names))
868 (make-let src names gensyms vals body)))))))
869 (($ <letrec> src in-order? names gensyms vals body)
870 ;; Note the difference from the `let' case: here we use letrec*
871 ;; so that the `visit' procedure for the new operands closes over
872 ;; an environment that includes the operands.
873 (letrec* ((visit (lambda (exp counter ctx)
874 (loop exp env* counter ctx)))
875 (vars (map lookup-var gensyms))
876 (new (fresh-gensyms vars))
877 (ops (make-bound-operands vars new vals visit))
878 (env* (fold extend-env env gensyms ops))
879 (body* (visit body counter ctx)))
880 (if (and (const? body*) (every constant-expression? vals))
881 ;; We may have folded a loop completely, even though there
882 ;; might be cyclical references between the bound values.
883 ;; Handle this degenerate case specially.
885 (prune-bindings ops in-order? body* counter ctx
886 (lambda (names gensyms vals body)
887 (make-letrec src in-order?
888 names gensyms vals body))))))
889 (($ <fix> src names gensyms vals body)
890 (letrec* ((visit (lambda (exp counter ctx)
891 (loop exp env* counter ctx)))
892 (vars (map lookup-var gensyms))
893 (new (fresh-gensyms vars))
894 (ops (make-bound-operands vars new vals visit))
895 (env* (fold extend-env env gensyms ops))
896 (body* (visit body counter ctx)))
899 (prune-bindings ops #f body* counter ctx
900 (lambda (names gensyms vals body)
901 (make-fix src names gensyms vals body))))))
902 (($ <let-values> lv-src producer consumer)
903 ;; Peval the producer, then try to inline the consumer into
904 ;; the producer. If that succeeds, peval again. Otherwise
905 ;; reconstruct the let-values, pevaling the consumer.
906 (let ((producer (for-value producer)))
908 (($ <lambda-case> src req #f #f #f () gensyms body #f)
910 ((inline-values producer src req gensyms body)
914 (make-let-values lv-src producer (for-tail consumer)))))
915 (($ <dynwind> src winder body unwinder)
916 (let ((pre (for-value winder))
917 (body (for-tail body))
918 (post (for-value unwinder)))
920 ((not (constant-expression? pre))
922 ((not (constant-expression? post))
923 (let ((pre-sym (gensym "pre ")) (post-sym (gensym "post ")))
924 (record-new-temporary! 'pre pre-sym 1)
925 (record-new-temporary! 'post post-sym 1)
926 (make-let src '(pre post) (list pre-sym post-sym) (list pre post)
928 (make-lexical-ref #f 'pre pre-sym)
930 (make-lexical-ref #f 'post post-sym)))))
932 (let ((pre-sym (gensym "pre ")))
933 (record-new-temporary! 'pre pre-sym 1)
934 (make-let src '(pre) (list pre-sym) (list pre)
936 (make-lexical-ref #f 'pre pre-sym)
939 ((not (constant-expression? post))
940 (let ((post-sym (gensym "post ")))
941 (record-new-temporary! 'post post-sym 1)
942 (make-let src '(post) (list post-sym) (list post)
946 (make-lexical-ref #f 'post post-sym)))))
948 (make-dynwind src pre body post)))))
949 (($ <dynlet> src fluids vals body)
950 (make-dynlet src (map for-value fluids) (map for-value vals)
952 (($ <dynref> src fluid)
953 (make-dynref src (for-value fluid)))
954 (($ <dynset> src fluid exp)
955 (make-dynset src (for-value fluid) (for-value exp)))
956 (($ <toplevel-ref> src (? effect-free-primitive? name))
957 (if (local-toplevel? name)
959 (let ((exp (resolve-primitives! exp cenv)))
960 (if (primitive-ref? exp)
964 ;; todo: open private local bindings.
966 (($ <module-ref> src module (? effect-free-primitive? name) #f)
967 (let ((module (false-if-exception
968 (resolve-module module #:ensure #f))))
970 (let ((var (module-variable module name)))
971 (if (eq? var (module-variable the-scm-module name))
972 (make-primitive-ref src name)
977 (($ <module-set> src mod name public? exp)
978 (make-module-set src mod name public? (for-value exp)))
979 (($ <toplevel-define> src name exp)
980 (make-toplevel-define src name (for-value exp)))
981 (($ <toplevel-set> src name exp)
982 (make-toplevel-set src name (for-value exp)))
985 ((effect) (make-void #f))
986 ((test) (make-const #f #t))
988 (($ <conditional> src condition subsequent alternate)
989 (let ((condition (for-test condition)))
990 (if (const? condition)
991 (if (const-exp condition)
992 (for-tail subsequent)
993 (for-tail alternate))
994 (make-conditional src condition
995 (for-tail subsequent)
996 (for-tail alternate)))))
997 (($ <application> src
998 ($ <primitive-ref> _ '@call-with-values)
1002 ;; No optional or kwargs.
1004 _ req #f rest #f () gensyms body #f)))))
1005 (for-tail (make-let-values src (make-application src producer '())
1008 (($ <application> src orig-proc orig-args)
1009 ;; todo: augment the global env with specialized functions
1010 (let ((proc (visit orig-proc 'operator)))
1012 (($ <primitive-ref> _ (? constructor-primitive? name))
1014 ((and (memq ctx '(effect test))
1015 (match (cons name orig-args)
1020 ('make-prompt-tag ($ <const> _ (? string?))))
1023 ;; Some expressions can be folded without visiting the
1024 ;; arguments for value.
1025 (let ((res (if (eq? ctx 'effect)
1027 (make-const #f #t))))
1028 (for-tail (make-sequence src (append orig-args (list res))))))
1030 (match (cons name (map for-value orig-args))
1034 (make-application src (make-primitive-ref #f 'list)
1036 (($ <application> src ($ <primitive-ref> _ 'list) elts)
1037 (make-application src (make-primitive-ref #f 'list)
1039 (_ (make-application src proc (list head tail)))))
1041 (make-application src proc args))))))
1042 (($ <primitive-ref> _ (? accessor-primitive? name))
1043 (match (cons name (map for-value orig-args))
1044 ;; FIXME: these for-tail recursions could take place outside
1045 ;; an effort counter.
1046 (('car ($ <application> src ($ <primitive-ref> _ 'cons) (head tail)))
1047 (for-tail (make-sequence src (list tail head))))
1048 (('cdr ($ <application> src ($ <primitive-ref> _ 'cons) (head tail)))
1049 (for-tail (make-sequence src (list head tail))))
1050 (('car ($ <application> src ($ <primitive-ref> _ 'list) (head . tail)))
1051 (for-tail (make-sequence src (append tail (list head)))))
1052 (('cdr ($ <application> src ($ <primitive-ref> _ 'list) (head . tail)))
1053 (for-tail (make-sequence
1057 src (make-primitive-ref #f 'list) tail)))))
1059 (('car ($ <const> src (head . tail)))
1060 (for-tail (make-const src head)))
1061 (('cdr ($ <const> src (head . tail)))
1062 (for-tail (make-const src tail)))
1063 (((or 'memq 'memv) k ($ <const> _ (elts ...)))
1068 (make-sequence src (list k (make-void #f)))))
1072 ;; A shortcut. The `else' case would handle it, but
1073 ;; this way is faster.
1074 (let ((member (case name ((memq) memq) ((memv) memv))))
1075 (make-const #f (and (member (const-exp k) elts) #t))))
1078 (make-sequence src (list k (make-const #f #f)))))
1080 (let ((t (gensym "t "))
1081 (eq (if (eq? name 'memq) 'eq? 'eqv?)))
1082 (record-new-temporary! 't t (length elts))
1085 src (list 't) (list t) (list k)
1086 (let lp ((elts elts))
1089 #f (make-primitive-ref #f eq)
1090 (list (make-lexical-ref #f 't t)
1091 (make-const #f (car elts)))))
1092 (if (null? (cdr elts))
1094 (make-conditional src test
1096 (lp (cdr elts)))))))))))
1100 (let ((member (case name ((memq) memq) ((memv) memv))))
1101 (make-const #f (member (const-exp k) elts))))
1103 (for-tail (make-sequence src (list k (make-const #f #f)))))
1105 (make-application src proc (list k (make-const #f elts))))))))
1107 (or (fold-constants src name args ctx)
1108 (make-application src proc args)))))
1109 (($ <primitive-ref> _ (? effect-free-primitive? name))
1110 (let ((args (map for-value orig-args)))
1111 (or (fold-constants src name args ctx)
1112 (make-application src proc args))))
1114 ($ <lambda-case> _ req opt #f #f inits gensyms body #f))
1115 ;; Simple case: no rest, no keyword arguments.
1116 ;; todo: handle the more complex cases
1117 (let* ((nargs (length orig-args))
1119 (nopt (if opt (length opt) 0))
1120 (key (source-expression proc)))
1122 ((or (< nargs nreq) (> nargs (+ nreq nopt)))
1123 ;; An error, or effecting arguments.
1124 (make-application src (for-call orig-proc)
1125 (map for-value orig-args)))
1126 ((or (and=> (find-counter key counter) counter-recursive?)
1127 (lambda? orig-proc))
1128 ;; A recursive call, or a lambda in the operator
1129 ;; position of the source expression. Process again in
1132 ;; In the recursive case, mark intervening counters as
1133 ;; recursive, so we can handle a toplevel counter that
1134 ;; recurses mutually with some other procedure.
1135 ;; Otherwise, the next time we see the other procedure,
1136 ;; the effort limit would be clamped to 100.
1138 (let ((found (find-counter key counter)))
1139 (if (and found (counter-recursive? found))
1140 (let lp ((counter counter))
1141 (if (not (eq? counter found))
1143 (set-counter-recursive?! counter #t)
1144 (lp (counter-prev counter)))))))
1146 (log 'inline-recurse key)
1147 (loop (make-let src (append req (or opt '()))
1150 (drop inits (- nargs nreq)))
1154 ;; An integration at the top-level, the first
1155 ;; recursion of a recursive procedure, or a nested
1156 ;; integration of a procedure that hasn't been seen
1158 (log 'inline-begin exp)
1161 (log 'inline-abort exp)
1162 (k (make-application src (for-call orig-proc)
1163 (map for-value orig-args))))
1166 ;; These first two cases will transfer effort
1167 ;; from the current counter into the new
1169 ((find-counter key counter)
1171 (make-recursive-counter recursive-effort-limit
1175 (make-nested-counter abort key counter))
1176 ;; This case opens a new account, effectively
1177 ;; printing money. It should only do so once
1178 ;; for each call site in the source program.
1180 (make-top-counter effort-limit operand-size-limit
1183 (loop (make-let src (append req (or opt '()))
1186 (drop inits (- nargs nreq)))
1188 env new-counter ctx))
1191 ;; The nested inlining attempt succeeded.
1192 ;; Deposit the unspent effort and size back
1193 ;; into the current counter.
1194 (transfer! new-counter counter))
1196 (log 'inline-end result exp)
1199 (make-application src (for-call orig-proc)
1200 (map for-value orig-args))))))
1201 (($ <lambda> src meta body)
1203 ((effect) (make-void #f))
1204 ((test) (make-const #f #t))
1206 (else (record-source-expression!
1208 (make-lambda src meta (for-tail body))))))
1209 (($ <lambda-case> src req opt rest kw inits gensyms body alt)
1210 (let* ((vars (map lookup-var gensyms))
1211 (new (fresh-gensyms vars))
1212 (env (fold extend-env env gensyms
1213 (make-unbound-operands vars new)))
1214 (new-sym (lambda (old)
1215 (operand-sym (cdr (vhash-assq old env))))))
1216 (make-lambda-case src req opt rest
1218 ((aok? (kw name old) ...)
1219 (cons aok? (map list kw name (map new-sym old))))
1221 (map (cut loop <> env counter 'value) inits)
1223 (loop body env counter ctx)
1224 (and alt (for-tail alt)))))
1225 (($ <sequence> src exps)
1226 (let lp ((exps exps) (effects '()))
1233 (reverse (cons (for-tail last) effects)))))
1235 (let ((head (for-effect head)))
1238 (lp (append (sequence-exps head) rest) effects))
1242 (lp rest (cons head effects)))))))))
1243 (($ <prompt> src tag body handler)
1244 (define (singly-used-definition x)
1246 ((and (lexical-ref? x)
1247 ;; Only fetch definitions with single uses.
1248 (= (lexical-refcount (lexical-ref-gensym x)) 1)
1249 (lookup (lexical-ref-gensym x)))
1251 (singly-used-definition (visit-operand x counter 'value 10 10))))
1253 (match (singly-used-definition tag)
1254 (($ <application> _ ($ <primitive-ref> _ 'make-prompt-tag)
1255 (or () ((? constant-expression?))))
1256 ;; There is no way that an <abort> could know the tag
1257 ;; for this <prompt>, so we can elide the <prompt>
1261 (make-prompt src (for-value tag) (for-tail body)
1262 (for-value handler)))))
1263 (($ <abort> src tag args tail)
1264 (make-abort src (for-value tag) (map for-value args)
1265 (for-value tail))))))