1 ;;; Tree-IL partial evaluator
3 ;; Copyright (C) 2011, 2012 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 (language tree-il effects)
23 #:use-module (ice-9 vlist)
24 #:use-module (ice-9 match)
25 #:use-module (srfi srfi-1)
26 #:use-module (srfi srfi-9)
27 #:use-module (srfi srfi-11)
28 #:use-module (srfi srfi-26)
32 ;;; Partial evaluation is Guile's most important source-to-source
33 ;;; optimization pass. It performs copy propagation, dead code
34 ;;; elimination, inlining, and constant folding, all while preserving
35 ;;; the order of effects in the residual program.
37 ;;; For more on partial evaluation, see William Cook’s excellent
38 ;;; tutorial on partial evaluation at DSL 2011, called “Build your own
39 ;;; partial evaluator in 90 minutes”[0].
41 ;;; Our implementation of this algorithm was heavily influenced by
42 ;;; Waddell and Dybvig's paper, "Fast and Effective Procedure Inlining",
43 ;;; IU CS Dept. TR 484.
45 ;;; [0] http://www.cs.utexas.edu/~wcook/tutorial/.
48 ;; First, some helpers.
50 (define-syntax *logging* (identifier-syntax #f))
52 ;; For efficiency we define *logging* to inline to #f, so that the call
53 ;; to log* gets optimized out. If you want to log, uncomment these
56 ;; (define %logging #f)
57 ;; (define-syntax *logging* (identifier-syntax %logging))
59 ;; Then you can change %logging at runtime.
65 (or (eq? *logging* #t)
66 (memq 'event *logging*)))
67 (log* 'event arg ...)))))
69 (define (log* event . args)
70 (let ((pp (module-ref (resolve-interface '(ice-9 pretty-print))
72 (pp `(log ,event . ,args))
76 (define-syntax-rule (let/ec k e e* ...)
77 (let ((tag (make-prompt-tag)))
81 (let ((k (lambda args (apply abort-to-prompt tag args))))
83 (lambda (_ res) res))))
85 (define (tree-il-any proc exp)
87 (tree-il-fold (lambda (exp res)
88 (let ((res (proc exp)))
91 (let ((res (proc exp)))
96 (define (vlist-any proc vlist)
97 (let ((len (vlist-length vlist)))
100 (or (proc (vlist-ref vlist i))
103 (define (singly-valued-expression? exp)
106 (($ <lexical-ref>) #t)
108 (($ <lexical-ref>) #t)
109 (($ <primitive-ref>) #t)
110 (($ <module-ref>) #t)
111 (($ <toplevel-ref>) #t)
113 ($ <primitive-ref> _ (? singly-valued-primitive?))) #t)
114 (($ <application> _ ($ <primitive-ref> _ 'values) (val)) #t)
118 (define (truncate-values x)
119 "Discard all but the first value of X."
120 (if (singly-valued-expression? x)
122 (make-application (tree-il-src x)
123 (make-primitive-ref #f 'values)
126 ;; Peval will do a one-pass analysis on the source program to determine
127 ;; the set of assigned lexicals, and to identify unreferenced and
128 ;; singly-referenced lexicals.
130 (define-record-type <var>
131 (make-var name gensym refcount set?)
135 (refcount var-refcount set-var-refcount!)
136 (set? var-set? set-var-set?!))
138 (define* (build-var-table exp #:optional (table vlist-null))
142 (($ <lexical-ref> src name gensym)
143 (let ((var (cdr (vhash-assq gensym res))))
144 (set-var-refcount! var (1+ (var-refcount var)))
149 (($ <lambda-case> src req opt rest kw init gensyms body alt)
150 (fold (lambda (name sym res)
151 (vhash-consq sym (make-var name sym 0 #f) res))
153 (append req (or opt '()) (if rest (list rest) '())
155 ((aok? (kw name sym) ...) name)
158 (($ <let> src names gensyms vals body)
159 (fold (lambda (name sym res)
160 (vhash-consq sym (make-var name sym 0 #f) res))
162 (($ <letrec> src in-order? names gensyms vals body)
163 (fold (lambda (name sym res)
164 (vhash-consq sym (make-var name sym 0 #f) res))
166 (($ <fix> src names gensyms vals body)
167 (fold (lambda (name sym res)
168 (vhash-consq sym (make-var name sym 0 #f) res))
170 (($ <lexical-set> src name gensym exp)
171 (set-var-set?! (cdr (vhash-assq gensym res)) #t)
174 (lambda (exp res) res)
177 ;; Counters are data structures used to limit the effort that peval
178 ;; spends on particular inlining attempts. Each call site in the source
179 ;; program is allocated some amount of effort. If peval exceeds the
180 ;; effort counter while attempting to inline a call site, it aborts the
181 ;; inlining attempt and residualizes a call instead.
183 ;; As there is a fixed number of call sites, that makes `peval' O(N) in
184 ;; the number of call sites in the source program.
186 ;; Counters should limit the size of the residual program as well, but
187 ;; currently this is not implemented.
189 ;; At the top level, before seeing any peval call, there is no counter,
190 ;; because inlining will terminate as there is no recursion. When peval
191 ;; sees a call at the top level, it will make a new counter, allocating
192 ;; it some amount of effort and size.
194 ;; This top-level effort counter effectively "prints money". Within a
195 ;; toplevel counter, no more effort is printed ex nihilo; for a nested
196 ;; inlining attempt to proceed, effort must be transferred from the
197 ;; toplevel counter to the nested counter.
199 ;; Via `data' and `prev', counters form a linked list, terminating in a
200 ;; toplevel counter. In practice `data' will be the a pointer to the
201 ;; source expression of the procedure being inlined.
203 ;; In this way peval can detect a recursive inlining attempt, by walking
204 ;; back on the `prev' links looking for matching `data'. Recursive
205 ;; counters receive a more limited effort allocation, as we don't want
206 ;; to spend all of the effort for a toplevel inlining site on loops.
207 ;; Also, recursive counters don't need a prompt at each inlining site:
208 ;; either the call chain folds entirely, or it will be residualized at
209 ;; its original call.
211 (define-record-type <counter>
212 (%make-counter effort size continuation recursive? data prev)
214 (effort effort-counter)
216 (continuation counter-continuation)
217 (recursive? counter-recursive? set-counter-recursive?!)
221 (define (abort-counter c)
222 ((counter-continuation c)))
224 (define (record-effort! c)
225 (let ((e (effort-counter c)))
226 (if (zero? (variable-ref e))
228 (variable-set! e (1- (variable-ref e))))))
230 (define (record-size! c)
231 (let ((s (size-counter c)))
232 (if (zero? (variable-ref s))
234 (variable-set! s (1- (variable-ref s))))))
236 (define (find-counter data counter)
238 (if (eq? data (counter-data counter))
240 (find-counter data (counter-prev counter)))))
242 (define* (transfer! from to #:optional
243 (effort (variable-ref (effort-counter from)))
244 (size (variable-ref (size-counter from))))
245 (define (transfer-counter! from-v to-v amount)
246 (let* ((from-balance (variable-ref from-v))
247 (to-balance (variable-ref to-v))
248 (amount (min amount from-balance)))
249 (variable-set! from-v (- from-balance amount))
250 (variable-set! to-v (+ to-balance amount))))
252 (transfer-counter! (effort-counter from) (effort-counter to) effort)
253 (transfer-counter! (size-counter from) (size-counter to) size))
255 (define (make-top-counter effort-limit size-limit continuation data)
256 (%make-counter (make-variable effort-limit)
257 (make-variable size-limit)
263 (define (make-nested-counter continuation data current)
264 (let ((c (%make-counter (make-variable 0)
270 (transfer! current c)
273 (define (make-recursive-counter effort-limit size-limit orig current)
274 (let ((c (%make-counter (make-variable 0)
276 (counter-continuation orig)
280 (transfer! current c effort-limit size-limit)
283 ;; Operand structures allow bindings to be processed lazily instead of
284 ;; eagerly. By doing so, hopefully we can get process them in a way
285 ;; appropriate to their use contexts. Operands also prevent values from
286 ;; being visited multiple times, wasting effort.
288 ;; TODO: Record value size in operand structure?
290 (define-record-type <operand>
291 (%make-operand var sym visit source visit-count residualize?
292 copyable? residual-value constant-value)
296 (visit %operand-visit)
297 (source operand-source)
298 (visit-count operand-visit-count set-operand-visit-count!)
299 (residualize? operand-residualize? set-operand-residualize?!)
300 (copyable? operand-copyable? set-operand-copyable?!)
301 (residual-value operand-residual-value %set-operand-residual-value!)
302 (constant-value operand-constant-value set-operand-constant-value!))
304 (define* (make-operand var sym #:optional source visit)
305 ;; Bind SYM to VAR, with value SOURCE. Unassigned bound operands are
306 ;; considered copyable until we prove otherwise. If we have a source
307 ;; expression, truncate it to one value. Copy propagation does not
308 ;; work on multiply-valued expressions.
309 (let ((source (and=> source truncate-values)))
310 (%make-operand var sym visit source 0 #f
311 (and source (not (var-set? var))) #f #f)))
313 (define (make-bound-operands vars syms sources visit)
314 (map (lambda (x y z) (make-operand x y z visit)) vars syms sources))
316 (define (make-unbound-operands vars syms)
317 (map make-operand vars syms))
319 (define (set-operand-residual-value! op val)
320 (%set-operand-residual-value!
323 (($ <application> src ($ <primitive-ref> _ 'values) (first))
324 ;; The continuation of a residualized binding does not need the
325 ;; introduced `values' node, so undo the effects of truncation.
330 (define* (visit-operand op counter ctx #:optional effort-limit size-limit)
331 ;; Peval is O(N) in call sites of the source program. However,
332 ;; visiting an operand can introduce new call sites. If we visit an
333 ;; operand outside a counter -- i.e., outside an inlining attempt --
334 ;; this can lead to divergence. So, if we are visiting an operand to
335 ;; try to copy it, and there is no counter, make a new one.
337 ;; This will only happen at most as many times as there are lexical
338 ;; references in the source program.
339 (and (zero? (operand-visit-count op))
342 (set-operand-visit-count! op (1+ (operand-visit-count op))))
344 (and (operand-source op)
345 (if (or counter (and (not effort-limit) (not size-limit)))
346 ((%operand-visit op) (operand-source op) counter ctx)
348 (define (abort) (k #f))
351 (make-top-counter effort-limit size-limit abort op)
354 (set-operand-visit-count! op (1- (operand-visit-count op)))))))
356 ;; A helper for constant folding.
358 (define (types-check? primitive-name args)
361 ((not pair? null? list? symbol? vector? struct?)
365 ;; FIXME: add more cases?
368 (define* (peval exp #:optional (cenv (current-module)) (env vlist-null)
370 (operator-size-limit 40)
371 (operand-size-limit 20)
372 (value-size-limit 10)
374 (recursive-effort-limit 100))
375 "Partially evaluate EXP in compilation environment CENV, with
376 top-level bindings from ENV and return the resulting expression."
378 ;; This is a simple partial evaluator. It effectively performs
379 ;; constant folding, copy propagation, dead code elimination, and
384 ;; Propagate copies across toplevel bindings, if we can prove the
385 ;; bindings to be immutable.
387 ;; Specialize lambda expressions with invariant arguments.
389 (define local-toplevel-env
390 ;; The top-level environment of the module being compiled.
392 (($ <toplevel-define> _ name)
393 (vhash-consq name #t env))
394 (($ <sequence> _ exps)
397 (($ <toplevel-define> _ name)
398 (vhash-consq name #t r))
404 (define (local-toplevel? name)
405 (vhash-assq name local-toplevel-env))
408 ;; renamed-term -> original-term
410 (define store (build-var-table exp))
412 (define (record-new-temporary! name sym refcount)
413 (set! store (vhash-consq sym (make-var name sym refcount #f) store)))
415 (define (lookup-var sym)
416 (let ((v (vhash-assq sym store)))
417 (if v (cdr v) (error "unbound var" sym (vlist->list store)))))
419 (define (fresh-gensyms vars)
421 (let ((new (gensym (string-append (symbol->string (var-name var))
423 (set! store (vhash-consq new var store))
427 (define (assigned-lexical? sym)
428 (var-set? (lookup-var sym)))
430 (define (lexical-refcount sym)
431 (var-refcount (lookup-var sym)))
433 ;; ORIG has been alpha-renamed to NEW. Analyze NEW and record a link
436 (define (record-source-expression! orig new)
437 (set! store (vhash-consq new (source-expression orig) store))
440 ;; Find the source expression corresponding to NEW. Used to detect
441 ;; recursive inlining attempts.
443 (define (source-expression new)
444 (let ((x (vhash-assq new store)))
447 (define* (residualize-lexical op #:optional ctx val)
448 (log 'residualize op)
449 (set-operand-residualize?! op #t)
450 (if (memq ctx '(value values))
451 (set-operand-residual-value! op val))
452 (make-lexical-ref #f (var-name (operand-var op)) (operand-sym op)))
454 (define (fold-constants src name args ctx)
455 (define (apply-primitive name args)
456 ;; todo: further optimize commutative primitives
461 (apply (module-ref the-scm-module name) args))
463 (values #t results))))
467 (define (make-values src values)
469 ((single) single) ; 1 value
470 ((_ ...) ; 0, or 2 or more values
471 (make-application src (make-primitive-ref src 'values)
473 (define (residualize-call)
474 (make-application src (make-primitive-ref #f name) args))
477 (let-values (((success? values)
478 (apply-primitive name (map const-exp args))))
479 (log 'fold success? values name args)
482 ((effect) (make-void src))
484 ;; Values truncation: only take the first
487 (make-const src (car values))
488 (make-values src '())))
490 (make-values src (map (cut make-const src <>) values))))
491 (residualize-call))))
492 ((and (eq? ctx 'effect) (types-check? name args))
495 (residualize-call))))
497 (define (inline-values exp src names gensyms body)
498 (let loop ((exp exp))
500 ;; Some expression types are always singly-valued.
509 ($ <lexical-set>) ; FIXME: these set! expressions
510 ($ <toplevel-set>) ; could return zero values in
511 ($ <toplevel-define>) ; the future
514 (and (= (length names) 1)
515 (make-let src names gensyms (list exp) body)))
516 (($ <application> src
517 ($ <primitive-ref> _ (? singly-valued-primitive? name)))
518 (and (= (length names) 1)
519 (make-let src names gensyms (list exp) body)))
521 ;; Statically-known number of values.
522 (($ <application> src ($ <primitive-ref> _ 'values) vals)
523 (and (= (length names) (length vals))
524 (make-let src names gensyms vals body)))
526 ;; Not going to copy code into both branches.
527 (($ <conditional>) #f)
529 ;; Bail on other applications.
530 (($ <application>) #f)
532 ;; Bail on prompt and abort.
536 ;; Propagate to tail positions.
537 (($ <let> src names gensyms vals body)
538 (let ((body (loop body)))
540 (make-let src names gensyms vals body))))
541 (($ <letrec> src in-order? names gensyms vals body)
542 (let ((body (loop body)))
544 (make-letrec src in-order? names gensyms vals body))))
545 (($ <fix> src names gensyms vals body)
546 (let ((body (loop body)))
548 (make-fix src names gensyms vals body))))
549 (($ <let-values> src exp
550 ($ <lambda-case> src2 req opt rest kw inits gensyms body #f))
551 (let ((body (loop body)))
553 (make-let-values src exp
554 (make-lambda-case src2 req opt rest kw
555 inits gensyms body #f)))))
556 (($ <dynwind> src winder body unwinder)
557 (let ((body (loop body)))
559 (make-dynwind src winder body unwinder))))
560 (($ <dynlet> src fluids vals body)
561 (let ((body (loop body)))
563 (make-dynlet src fluids vals body))))
564 (($ <sequence> src exps)
567 (let ((tail (loop tail)))
569 (make-sequence src (append head (list tail)))))))))))
571 (define compute-effects
572 (make-effects-analyzer assigned-lexical?))
574 (define (constant-expression? x)
575 ;; Return true if X is constant, for the purposes of copying or
576 ;; elision---i.e., if it is known to have no effects, does not
577 ;; allocate storage for a mutable object, and does not access
578 ;; mutable data (like `car' or toplevel references).
579 (constant? (compute-effects x)))
581 (define (prune-bindings ops in-order? body counter ctx build-result)
582 ;; This helper handles both `let' and `letrec'/`fix'. In the latter
583 ;; cases we need to make sure that if referenced binding A needs
584 ;; as-yet-unreferenced binding B, that B is processed for value.
585 ;; Likewise if C, when processed for effect, needs otherwise
586 ;; unreferenced D, then D needs to be processed for value too.
588 (define (referenced? op)
589 ;; When we visit lambdas in operator context, we just copy them,
590 ;; as we will process their body later. However this does have
591 ;; the problem that any free var referenced by the lambda is not
592 ;; marked as needing residualization. Here we hack around this
593 ;; and treat all bindings as referenced if we are in operator
595 (or (eq? ctx 'operator) (operand-residualize? op)))
597 ;; values := (op ...)
598 ;; effects := (op ...)
599 (define (residualize values effects)
600 ;; Note, values and effects are reversed.
603 (let ((values (filter operand-residual-value ops)))
606 (build-result (map (compose var-name operand-var) values)
607 (map operand-sym values)
608 (map operand-residual-value values)
614 (let ((effect-vals (map operand-residual-value effects)))
615 (make-sequence #f (reverse (cons body effect-vals)))))))
618 (let ((values (reverse values)))
619 (build-result (map (compose var-name operand-var) values)
620 (map operand-sym values)
621 (map operand-residual-value values)
625 ;; values := (op ...)
626 ;; effects := ((op . value) ...)
627 (let prune ((old (map referenced? ops)) (values '()) (effects '()))
628 (let lp ((ops* ops) (values values) (effects effects))
631 (let ((new (map referenced? ops)))
632 (if (not (equal? new old))
633 (prune new values '())
635 (map (lambda (op val)
636 (set-operand-residual-value! op val)
638 (map car effects) (map cdr effects))))))
640 (let ((op (car ops*)))
643 (lp (cdr ops*) values effects))
644 ((operand-residual-value op)
645 (lp (cdr ops*) (cons op values) effects))
647 (set-operand-residual-value! op (visit-operand op counter 'value))
648 (lp (cdr ops*) (cons op values) effects))
652 (let ((effect (visit-operand op counter 'effect)))
655 (acons op effect effects))))))))))))
657 (define (small-expression? x limit)
660 (lambda (x res) ; leaf
662 (lambda (x res) ; down
671 (define (extend-env sym op env)
672 (vhash-consq (operand-sym op) op (vhash-consq sym op env)))
675 (env vlist-null) ; vhash of gensym -> <operand>
676 (counter #f) ; inlined call stack
677 (ctx 'values)) ; effect, value, values, test, operator, or call
680 ((vhash-assq var env) => cdr)
681 (else (error "unbound var" var))))
683 (define (visit exp ctx)
684 (loop exp env counter ctx))
686 (define (for-value exp) (visit exp 'value))
687 (define (for-values exp) (visit exp 'values))
688 (define (for-test exp) (visit exp 'test))
689 (define (for-effect exp) (visit exp 'effect))
690 (define (for-call exp) (visit exp 'call))
691 (define (for-tail exp) (visit exp ctx))
694 (record-effort! counter))
696 (log 'visit ctx (and=> counter effort-counter)
697 (unparse-tree-il exp))
702 ((effect) (make-void #f))
706 ((test) (make-const #f #t))
708 (($ <lexical-ref> _ _ gensym)
709 (log 'begin-copy gensym)
710 (let ((op (lookup gensym)))
713 (log 'lexical-for-effect gensym)
716 ;; Don't propagate copies if we are residualizing a call.
717 (log 'residualize-lexical-call gensym op)
718 (residualize-lexical op))
719 ((var-set? (operand-var op))
720 ;; Assigned lexicals don't copy-propagate.
721 (log 'assigned-var gensym op)
722 (residualize-lexical op))
723 ((not (operand-copyable? op))
724 ;; We already know that this operand is not copyable.
725 (log 'not-copyable gensym op)
726 (residualize-lexical op))
727 ((and=> (operand-constant-value op)
728 (lambda (x) (or (const? x) (void? x) (primitive-ref? x))))
730 (let ((val (operand-constant-value op)))
731 (log 'memoized-constant gensym val)
733 ((visit-operand op counter (if (eq? ctx 'values) 'value ctx)
734 recursive-effort-limit operand-size-limit)
736 ;; If we end up deciding to residualize this value instead of
737 ;; copying it, save that residualized value.
740 ((not (constant-expression? val))
741 (log 'not-constant gensym op)
742 ;; At this point, ctx is operator, test, or value. A
743 ;; value that is non-constant in one context will be
744 ;; non-constant in the others, so it's safe to record
745 ;; that here, and avoid future visits.
746 (set-operand-copyable?! op #f)
747 (residualize-lexical op ctx val))
750 (primitive-ref? val))
751 ;; Always propagate simple values that cannot lead to
753 (log 'copy-simple gensym val)
754 ;; It could be this constant is the result of folding.
755 ;; If that is the case, cache it. This helps loop
756 ;; unrolling get farther.
757 (if (or (eq? ctx 'value) (eq? ctx 'values))
759 (log 'memoize-constant gensym val)
760 (set-operand-constant-value! op val)))
762 ((= 1 (var-refcount (operand-var op)))
763 ;; Always propagate values referenced only once.
764 (log 'copy-single gensym val)
766 ;; FIXME: do demand-driven size accounting rather than
769 ;; A pure expression in the operator position. Inline
770 ;; if it's a lambda that's small enough.
771 (if (and (lambda? val)
772 (small-expression? val operator-size-limit))
774 (log 'copy-operator gensym val)
777 (log 'too-big-for-operator gensym val)
778 (residualize-lexical op ctx val))))
780 ;; A pure expression, processed for call or for value.
781 ;; Don't inline lambdas, because they will probably won't
782 ;; fold because we don't know the operator.
783 (if (and (small-expression? val value-size-limit)
784 (not (tree-il-any lambda? val)))
786 (log 'copy-value gensym val)
789 (log 'too-big-or-has-lambda gensym val)
790 (residualize-lexical op ctx val)))))))
792 ;; Visit failed. Either the operand isn't bound, as in
793 ;; lambda formal parameters, or the copy was aborted.
794 (log 'unbound-or-aborted gensym op)
795 (residualize-lexical op)))))
796 (($ <lexical-set> src name gensym exp)
797 (let ((op (lookup gensym)))
798 (if (zero? (var-refcount (operand-var op)))
799 (let ((exp (for-effect exp)))
802 (make-sequence src (list exp (make-void #f)))))
804 (set-operand-residualize?! op #t)
805 (make-lexical-set src name (operand-sym op) (for-value exp))))))
806 (($ <let> src names gensyms vals body)
807 (let* ((vars (map lookup-var gensyms))
808 (new (fresh-gensyms vars))
809 (ops (make-bound-operands vars new vals
810 (lambda (exp counter ctx)
811 (loop exp env counter ctx))))
812 (env (fold extend-env env gensyms ops))
813 (body (loop body env counter ctx)))
816 (for-tail (make-sequence src (append vals (list body)))))
817 ((and (lexical-ref? body)
818 (memq (lexical-ref-gensym body) new))
819 (let ((sym (lexical-ref-gensym body))
820 (pairs (map cons new vals)))
821 ;; (let ((x foo) (y bar) ...) x) => (begin bar ... foo)
825 (append (map cdr (alist-delete sym pairs eq?))
826 (list (assq-ref pairs sym)))))))
828 ;; Only include bindings for which lexical references
829 ;; have been residualized.
830 (prune-bindings ops #f body counter ctx
831 (lambda (names gensyms vals body)
832 (if (null? names) (error "what!" names))
833 (make-let src names gensyms vals body)))))))
834 (($ <letrec> src in-order? names gensyms vals body)
835 ;; Note the difference from the `let' case: here we use letrec*
836 ;; so that the `visit' procedure for the new operands closes over
837 ;; an environment that includes the operands.
838 (letrec* ((visit (lambda (exp counter ctx)
839 (loop exp env* counter ctx)))
840 (vars (map lookup-var gensyms))
841 (new (fresh-gensyms vars))
842 (ops (make-bound-operands vars new vals visit))
843 (env* (fold extend-env env gensyms ops))
844 (body* (visit body counter ctx)))
845 (if (and (const? body*) (every constant-expression? vals))
846 ;; We may have folded a loop completely, even though there
847 ;; might be cyclical references between the bound values.
848 ;; Handle this degenerate case specially.
850 (prune-bindings ops in-order? body* counter ctx
851 (lambda (names gensyms vals body)
852 (make-letrec src in-order?
853 names gensyms vals body))))))
854 (($ <fix> src names gensyms vals body)
855 (letrec* ((visit (lambda (exp counter ctx)
856 (loop exp env* counter ctx)))
857 (vars (map lookup-var gensyms))
858 (new (fresh-gensyms vars))
859 (ops (make-bound-operands vars new vals visit))
860 (env* (fold extend-env env gensyms ops))
861 (body* (visit body counter ctx)))
864 (prune-bindings ops #f body* counter ctx
865 (lambda (names gensyms vals body)
866 (make-fix src names gensyms vals body))))))
867 (($ <let-values> lv-src producer consumer)
868 ;; Peval the producer, then try to inline the consumer into
869 ;; the producer. If that succeeds, peval again. Otherwise
870 ;; reconstruct the let-values, pevaling the consumer.
871 (let ((producer (for-values producer)))
873 (($ <lambda-case> src req #f #f #f () gensyms body #f)
875 ((inline-values producer src req gensyms body)
879 (make-let-values lv-src producer (for-tail consumer)))))
880 (($ <dynwind> src winder body unwinder)
881 (let ((pre (for-value winder))
882 (body (for-tail body))
883 (post (for-value unwinder)))
885 ((not (constant-expression? pre))
887 ((not (constant-expression? post))
888 (let ((pre-sym (gensym "pre-")) (post-sym (gensym "post-")))
889 (record-new-temporary! 'pre pre-sym 1)
890 (record-new-temporary! 'post post-sym 1)
891 (make-let src '(pre post) (list pre-sym post-sym) (list pre post)
893 (make-lexical-ref #f 'pre pre-sym)
895 (make-lexical-ref #f 'post post-sym)))))
897 (let ((pre-sym (gensym "pre-")))
898 (record-new-temporary! 'pre pre-sym 1)
899 (make-let src '(pre) (list pre-sym) (list pre)
901 (make-lexical-ref #f 'pre pre-sym)
904 ((not (constant-expression? post))
905 (let ((post-sym (gensym "post-")))
906 (record-new-temporary! 'post post-sym 1)
907 (make-let src '(post) (list post-sym) (list post)
911 (make-lexical-ref #f 'post post-sym)))))
913 (make-dynwind src pre body post)))))
914 (($ <dynlet> src fluids vals body)
915 (make-dynlet src (map for-value fluids) (map for-value vals)
917 (($ <dynref> src fluid)
918 (make-dynref src (for-value fluid)))
919 (($ <dynset> src fluid exp)
920 (make-dynset src (for-value fluid) (for-value exp)))
921 (($ <toplevel-ref> src (? effect-free-primitive? name))
922 (if (local-toplevel? name)
924 (let ((exp (resolve-primitives! exp cenv)))
925 (if (primitive-ref? exp)
929 ;; todo: open private local bindings.
931 (($ <module-ref> src module (? effect-free-primitive? name) #f)
932 (let ((module (false-if-exception
933 (resolve-module module #:ensure #f))))
935 (let ((var (module-variable module name)))
936 (if (eq? var (module-variable the-scm-module name))
937 (make-primitive-ref src name)
942 (($ <module-set> src mod name public? exp)
943 (make-module-set src mod name public? (for-value exp)))
944 (($ <toplevel-define> src name exp)
945 (make-toplevel-define src name (for-value exp)))
946 (($ <toplevel-set> src name exp)
947 (make-toplevel-set src name (for-value exp)))
950 ((effect) (make-void #f))
951 ((test) (make-const #f #t))
953 (($ <conditional> src condition subsequent alternate)
954 (match (for-test condition)
957 (for-tail subsequent)
958 (for-tail alternate)))
959 ;; Swap the arms of (if (not FOO) A B), to simplify.
960 (($ <application> _ ($ <primitive-ref> _ 'not) (c))
961 (make-conditional src c
963 (for-tail subsequent)))
965 (make-conditional src c
966 (for-tail subsequent)
967 (for-tail alternate)))))
968 (($ <application> src
969 ($ <primitive-ref> _ '@call-with-values)
973 ;; No optional or kwargs.
975 _ req #f rest #f () gensyms body #f)))))
976 (for-tail (make-let-values src (make-application src producer '())
978 (($ <application> src ($ <primitive-ref> _ 'values) exps)
981 (if (eq? ctx 'effect)
985 (let ((vals (map for-value exps)))
987 ((value test effect) #t)
988 (else (null? (cdr vals))))
989 (every singly-valued-expression? vals))
990 (for-tail (make-sequence src (append (cdr vals) (list (car vals)))))
991 (make-application src (make-primitive-ref #f 'values) vals))))))
992 (($ <application> src orig-proc orig-args)
993 ;; todo: augment the global env with specialized functions
994 (let ((proc (visit orig-proc 'operator)))
996 (($ <primitive-ref> _ (? constructor-primitive? name))
998 ((and (memq ctx '(effect test))
999 (match (cons name orig-args)
1004 ('make-prompt-tag ($ <const> _ (? string?))))
1007 ;; Some expressions can be folded without visiting the
1008 ;; arguments for value.
1009 (let ((res (if (eq? ctx 'effect)
1011 (make-const #f #t))))
1012 (for-tail (make-sequence src (append orig-args (list res))))))
1014 (match (cons name (map for-value orig-args))
1017 (($ <const> src (? (cut eq? <> '())))
1018 (make-application src (make-primitive-ref #f 'list)
1020 (($ <application> src ($ <primitive-ref> _ 'list) elts)
1021 (make-application src (make-primitive-ref #f 'list)
1023 (_ (make-application src proc (list head tail)))))
1025 (make-application src proc args))))))
1026 (($ <primitive-ref> _ (? accessor-primitive? name))
1027 (match (cons name (map for-value orig-args))
1028 ;; FIXME: these for-tail recursions could take place outside
1029 ;; an effort counter.
1030 (('car ($ <application> src ($ <primitive-ref> _ 'cons) (head tail)))
1031 (for-tail (make-sequence src (list tail head))))
1032 (('cdr ($ <application> src ($ <primitive-ref> _ 'cons) (head tail)))
1033 (for-tail (make-sequence src (list head tail))))
1034 (('car ($ <application> src ($ <primitive-ref> _ 'list) (head . tail)))
1035 (for-tail (make-sequence src (append tail (list head)))))
1036 (('cdr ($ <application> src ($ <primitive-ref> _ 'list) (head . tail)))
1037 (for-tail (make-sequence
1041 src (make-primitive-ref #f 'list) tail)))))
1043 (('car ($ <const> src (head . tail)))
1044 (for-tail (make-const src head)))
1045 (('cdr ($ <const> src (head . tail)))
1046 (for-tail (make-const src tail)))
1047 (((or 'memq 'memv) k ($ <const> _ (elts ...)))
1052 (make-sequence src (list k (make-void #f)))))
1056 ;; A shortcut. The `else' case would handle it, but
1057 ;; this way is faster.
1058 (let ((member (case name ((memq) memq) ((memv) memv))))
1059 (make-const #f (and (member (const-exp k) elts) #t))))
1062 (make-sequence src (list k (make-const #f #f)))))
1064 (let ((t (gensym "t-"))
1065 (eq (if (eq? name 'memq) 'eq? 'eqv?)))
1066 (record-new-temporary! 't t (length elts))
1069 src (list 't) (list t) (list k)
1070 (let lp ((elts elts))
1073 #f (make-primitive-ref #f eq)
1074 (list (make-lexical-ref #f 't t)
1075 (make-const #f (car elts)))))
1076 (if (null? (cdr elts))
1078 (make-conditional src test
1080 (lp (cdr elts)))))))))))
1084 (let ((member (case name ((memq) memq) ((memv) memv))))
1085 (make-const #f (member (const-exp k) elts))))
1087 (for-tail (make-sequence src (list k (make-const #f #f)))))
1089 (make-application src proc (list k (make-const #f elts))))))))
1091 (or (fold-constants src name args ctx)
1092 (make-application src proc args)))))
1093 (($ <primitive-ref> _ (? effect-free-primitive? name))
1094 (let ((args (map for-value orig-args)))
1095 (or (fold-constants src name args ctx)
1096 (make-application src proc args))))
1098 ($ <lambda-case> _ req opt #f #f inits gensyms body #f))
1099 ;; Simple case: no rest, no keyword arguments.
1100 ;; todo: handle the more complex cases
1101 (let* ((nargs (length orig-args))
1103 (nopt (if opt (length opt) 0))
1104 (key (source-expression proc)))
1106 ((or (< nargs nreq) (> nargs (+ nreq nopt)))
1107 ;; An error, or effecting arguments.
1108 (make-application src (for-call orig-proc)
1109 (map for-value orig-args)))
1110 ((or (and=> (find-counter key counter) counter-recursive?)
1111 (lambda? orig-proc))
1112 ;; A recursive call, or a lambda in the operator
1113 ;; position of the source expression. Process again in
1116 ;; In the recursive case, mark intervening counters as
1117 ;; recursive, so we can handle a toplevel counter that
1118 ;; recurses mutually with some other procedure.
1119 ;; Otherwise, the next time we see the other procedure,
1120 ;; the effort limit would be clamped to 100.
1122 (let ((found (find-counter key counter)))
1123 (if (and found (counter-recursive? found))
1124 (let lp ((counter counter))
1125 (if (not (eq? counter found))
1127 (set-counter-recursive?! counter #t)
1128 (lp (counter-prev counter)))))))
1130 (log 'inline-recurse key)
1131 (loop (make-let src (append req (or opt '()))
1134 (drop inits (- nargs nreq)))
1138 ;; An integration at the top-level, the first
1139 ;; recursion of a recursive procedure, or a nested
1140 ;; integration of a procedure that hasn't been seen
1142 (log 'inline-begin exp)
1145 (log 'inline-abort exp)
1146 (k (make-application src (for-call orig-proc)
1147 (map for-value orig-args))))
1150 ;; These first two cases will transfer effort
1151 ;; from the current counter into the new
1153 ((find-counter key counter)
1155 (make-recursive-counter recursive-effort-limit
1159 (make-nested-counter abort key counter))
1160 ;; This case opens a new account, effectively
1161 ;; printing money. It should only do so once
1162 ;; for each call site in the source program.
1164 (make-top-counter effort-limit operand-size-limit
1167 (loop (make-let src (append req (or opt '()))
1170 (drop inits (- nargs nreq)))
1172 env new-counter ctx))
1175 ;; The nested inlining attempt succeeded.
1176 ;; Deposit the unspent effort and size back
1177 ;; into the current counter.
1178 (transfer! new-counter counter))
1180 (log 'inline-end result exp)
1183 (make-application src (for-call orig-proc)
1184 (map for-value orig-args))))))
1185 (($ <lambda> src meta body)
1187 ((effect) (make-void #f))
1188 ((test) (make-const #f #t))
1190 (else (record-source-expression!
1192 (make-lambda src meta (for-values body))))))
1193 (($ <lambda-case> src req opt rest kw inits gensyms body alt)
1194 (define (lift-applied-lambda body gensyms)
1195 (and (not opt) rest (not kw)
1198 ($ <primitive-ref> _ '@apply)
1199 (($ <lambda> _ _ lcase)
1200 ($ <lexical-ref> _ _ sym)
1202 (and (equal? sym gensyms)
1203 (not (lambda-case-alternate lcase))
1206 (let* ((vars (map lookup-var gensyms))
1207 (new (fresh-gensyms vars))
1208 (env (fold extend-env env gensyms
1209 (make-unbound-operands vars new)))
1210 (new-sym (lambda (old)
1211 (operand-sym (cdr (vhash-assq old env)))))
1212 (body (loop body env counter ctx)))
1214 ;; (lambda args (apply (lambda ...) args)) => (lambda ...)
1215 (lift-applied-lambda body new)
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)
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))))))