1 ;;; Tree-IL partial evaluator
3 ;; Copyright (C) 2011, 2012, 2013 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)
29 #:use-module (ice-9 control)
33 ;;; Partial evaluation is Guile's most important source-to-source
34 ;;; optimization pass. It performs copy propagation, dead code
35 ;;; elimination, inlining, and constant folding, all while preserving
36 ;;; the order of effects in the residual program.
38 ;;; For more on partial evaluation, see William Cook’s excellent
39 ;;; tutorial on partial evaluation at DSL 2011, called “Build your own
40 ;;; partial evaluator in 90 minutes”[0].
42 ;;; Our implementation of this algorithm was heavily influenced by
43 ;;; Waddell and Dybvig's paper, "Fast and Effective Procedure Inlining",
44 ;;; IU CS Dept. TR 484.
46 ;;; [0] http://www.cs.utexas.edu/~wcook/tutorial/.
49 ;; First, some helpers.
51 (define-syntax *logging* (identifier-syntax #f))
53 ;; For efficiency we define *logging* to inline to #f, so that the call
54 ;; to log* gets optimized out. If you want to log, uncomment these
57 ;; (define %logging #f)
58 ;; (define-syntax *logging* (identifier-syntax %logging))
60 ;; Then you can change %logging at runtime.
66 (or (eq? *logging* #t)
67 (memq 'event *logging*)))
68 (log* 'event arg ...)))))
70 (define (log* event . args)
71 (let ((pp (module-ref (resolve-interface '(ice-9 pretty-print))
73 (pp `(log ,event . ,args))
77 (define (tree-il-any proc exp)
79 (tree-il-fold (lambda (exp res)
80 (let ((res (proc exp)))
85 (define (vlist-any proc vlist)
86 (let ((len (vlist-length vlist)))
89 (or (proc (vlist-ref vlist i))
92 (define (singly-valued-expression? exp)
95 (($ <lexical-ref>) #t)
97 (($ <lexical-ref>) #t)
98 (($ <primitive-ref>) #t)
100 (($ <toplevel-ref>) #t)
101 (($ <primcall> _ (? singly-valued-primitive?)) #t)
102 (($ <primcall> _ 'values (val)) #t)
104 (($ <conditional> _ test consequent alternate)
105 (and (singly-valued-expression? consequent)
106 (singly-valued-expression? alternate)))
109 (define (truncate-values x)
110 "Discard all but the first value of X."
111 (if (singly-valued-expression? x)
113 (make-primcall (tree-il-src x) 'values (list x))))
115 ;; Peval will do a one-pass analysis on the source program to determine
116 ;; the set of assigned lexicals, and to identify unreferenced and
117 ;; singly-referenced lexicals.
119 (define-record-type <var>
120 (make-var name gensym refcount set?)
124 (refcount var-refcount set-var-refcount!)
125 (set? var-set? set-var-set?!))
127 (define* (build-var-table exp #:optional (table vlist-null))
131 (($ <lexical-ref> src name gensym)
132 (let ((var (cdr (vhash-assq gensym res))))
133 (set-var-refcount! var (1+ (var-refcount var)))
135 (($ <lambda-case> src req opt rest kw init gensyms body alt)
136 (fold (lambda (name sym res)
137 (vhash-consq sym (make-var name sym 0 #f) res))
139 (append req (or opt '()) (if rest (list rest) '())
141 ((aok? (kw name sym) ...) name)
144 (($ <let> src names gensyms vals body)
145 (fold (lambda (name sym res)
146 (vhash-consq sym (make-var name sym 0 #f) res))
148 (($ <letrec> src in-order? names gensyms vals body)
149 (fold (lambda (name sym res)
150 (vhash-consq sym (make-var name sym 0 #f) res))
152 (($ <fix> src names gensyms vals body)
153 (fold (lambda (name sym res)
154 (vhash-consq sym (make-var name sym 0 #f) res))
156 (($ <lexical-set> src name gensym exp)
157 (set-var-set?! (cdr (vhash-assq gensym res)) #t)
160 (lambda (exp res) res)
163 ;; Counters are data structures used to limit the effort that peval
164 ;; spends on particular inlining attempts. Each call site in the source
165 ;; program is allocated some amount of effort. If peval exceeds the
166 ;; effort counter while attempting to inline a call site, it aborts the
167 ;; inlining attempt and residualizes a call instead.
169 ;; As there is a fixed number of call sites, that makes `peval' O(N) in
170 ;; the number of call sites in the source program.
172 ;; Counters should limit the size of the residual program as well, but
173 ;; currently this is not implemented.
175 ;; At the top level, before seeing any peval call, there is no counter,
176 ;; because inlining will terminate as there is no recursion. When peval
177 ;; sees a call at the top level, it will make a new counter, allocating
178 ;; it some amount of effort and size.
180 ;; This top-level effort counter effectively "prints money". Within a
181 ;; toplevel counter, no more effort is printed ex nihilo; for a nested
182 ;; inlining attempt to proceed, effort must be transferred from the
183 ;; toplevel counter to the nested counter.
185 ;; Via `data' and `prev', counters form a linked list, terminating in a
186 ;; toplevel counter. In practice `data' will be the a pointer to the
187 ;; source expression of the procedure being inlined.
189 ;; In this way peval can detect a recursive inlining attempt, by walking
190 ;; back on the `prev' links looking for matching `data'. Recursive
191 ;; counters receive a more limited effort allocation, as we don't want
192 ;; to spend all of the effort for a toplevel inlining site on loops.
193 ;; Also, recursive counters don't need a prompt at each inlining site:
194 ;; either the call chain folds entirely, or it will be residualized at
195 ;; its original call.
197 (define-record-type <counter>
198 (%make-counter effort size continuation recursive? data prev)
200 (effort effort-counter)
202 (continuation counter-continuation)
203 (recursive? counter-recursive? set-counter-recursive?!)
207 (define (abort-counter c)
208 ((counter-continuation c)))
210 (define (record-effort! c)
211 (let ((e (effort-counter c)))
212 (if (zero? (variable-ref e))
214 (variable-set! e (1- (variable-ref e))))))
216 (define (record-size! c)
217 (let ((s (size-counter c)))
218 (if (zero? (variable-ref s))
220 (variable-set! s (1- (variable-ref s))))))
222 (define (find-counter data counter)
224 (if (eq? data (counter-data counter))
226 (find-counter data (counter-prev counter)))))
228 (define* (transfer! from to #:optional
229 (effort (variable-ref (effort-counter from)))
230 (size (variable-ref (size-counter from))))
231 (define (transfer-counter! from-v to-v amount)
232 (let* ((from-balance (variable-ref from-v))
233 (to-balance (variable-ref to-v))
234 (amount (min amount from-balance)))
235 (variable-set! from-v (- from-balance amount))
236 (variable-set! to-v (+ to-balance amount))))
238 (transfer-counter! (effort-counter from) (effort-counter to) effort)
239 (transfer-counter! (size-counter from) (size-counter to) size))
241 (define (make-top-counter effort-limit size-limit continuation data)
242 (%make-counter (make-variable effort-limit)
243 (make-variable size-limit)
249 (define (make-nested-counter continuation data current)
250 (let ((c (%make-counter (make-variable 0)
256 (transfer! current c)
259 (define (make-recursive-counter effort-limit size-limit orig current)
260 (let ((c (%make-counter (make-variable 0)
262 (counter-continuation orig)
266 (transfer! current c effort-limit size-limit)
269 ;; Operand structures allow bindings to be processed lazily instead of
270 ;; eagerly. By doing so, hopefully we can get process them in a way
271 ;; appropriate to their use contexts. Operands also prevent values from
272 ;; being visited multiple times, wasting effort.
274 ;; TODO: Record value size in operand structure?
276 (define-record-type <operand>
277 (%make-operand var sym visit source visit-count use-count
278 copyable? residual-value constant-value alias-value)
282 (visit %operand-visit)
283 (source operand-source)
284 (visit-count operand-visit-count set-operand-visit-count!)
285 (use-count operand-use-count set-operand-use-count!)
286 (copyable? operand-copyable? set-operand-copyable?!)
287 (residual-value operand-residual-value %set-operand-residual-value!)
288 (constant-value operand-constant-value set-operand-constant-value!)
289 (alias-value operand-alias-value set-operand-alias-value!))
291 (define* (make-operand var sym #:optional source visit alias)
292 ;; Bind SYM to VAR, with value SOURCE. Unassigned bound operands are
293 ;; considered copyable until we prove otherwise. If we have a source
294 ;; expression, truncate it to one value. Copy propagation does not
295 ;; work on multiply-valued expressions.
296 (let ((source (and=> source truncate-values)))
297 (%make-operand var sym visit source 0 0
298 (and source (not (var-set? var))) #f #f
299 (and (not (var-set? var)) alias))))
301 (define* (make-bound-operands vars syms sources visit #:optional aliases)
303 (map (lambda (name sym source alias)
304 (make-operand name sym source visit alias))
305 vars syms sources aliases)
306 (map (lambda (name sym source)
307 (make-operand name sym source visit #f))
310 (define (make-unbound-operands vars syms)
311 (map make-operand vars syms))
313 (define (set-operand-residual-value! op val)
314 (%set-operand-residual-value!
317 (($ <primcall> src 'values (first))
318 ;; The continuation of a residualized binding does not need the
319 ;; introduced `values' node, so undo the effects of truncation.
324 (define* (visit-operand op counter ctx #:optional effort-limit size-limit)
325 ;; Peval is O(N) in call sites of the source program. However,
326 ;; visiting an operand can introduce new call sites. If we visit an
327 ;; operand outside a counter -- i.e., outside an inlining attempt --
328 ;; this can lead to divergence. So, if we are visiting an operand to
329 ;; try to copy it, and there is no counter, make a new one.
331 ;; This will only happen at most as many times as there are lexical
332 ;; references in the source program.
333 (and (zero? (operand-visit-count op))
336 (set-operand-visit-count! op (1+ (operand-visit-count op))))
338 (and (operand-source op)
339 (if (or counter (and (not effort-limit) (not size-limit)))
340 ((%operand-visit op) (operand-source op) counter ctx)
343 ;; If we abort when visiting the value in a
344 ;; fresh context, we won't succeed in any future
345 ;; attempt, so don't try to copy it again.
346 (set-operand-copyable?! op #f)
350 (make-top-counter effort-limit size-limit abort op)
353 (set-operand-visit-count! op (1- (operand-visit-count op)))))))
355 ;; A helper for constant folding.
357 (define (types-check? primitive-name args)
360 ((not pair? null? list? symbol? vector? struct?)
364 ;; FIXME: add more cases?
367 (define* (peval exp #:optional (cenv (current-module)) (env vlist-null)
369 (operator-size-limit 40)
370 (operand-size-limit 20)
371 (value-size-limit 10)
373 (recursive-effort-limit 100))
374 "Partially evaluate EXP in compilation environment CENV, with
375 top-level bindings from ENV and return the resulting expression."
377 ;; This is a simple partial evaluator. It effectively performs
378 ;; constant folding, copy propagation, dead code elimination, and
383 ;; Propagate copies across toplevel bindings, if we can prove the
384 ;; bindings to be immutable.
386 ;; Specialize lambda expressions with invariant arguments.
388 (define local-toplevel-env
389 ;; The top-level environment of the module being compiled.
391 (define (env-folder x env)
393 (($ <toplevel-define> _ name)
394 (vhash-consq name #t env))
395 (($ <seq> _ head tail)
396 (env-folder tail (env-folder head env)))
398 (env-folder exp vlist-null)))
400 (define (local-toplevel? name)
401 (vhash-assq name local-toplevel-env))
404 ;; renamed-term -> original-term
406 (define store (build-var-table exp))
408 (define (record-new-temporary! name sym refcount)
409 (set! store (vhash-consq sym (make-var name sym refcount #f) store)))
411 (define (lookup-var sym)
412 (let ((v (vhash-assq sym store)))
413 (if v (cdr v) (error "unbound var" sym (vlist->list store)))))
415 (define (fresh-gensyms vars)
417 (let ((new (gensym (string-append (symbol->string (var-name var))
419 (set! store (vhash-consq new var store))
423 (define (fresh-temporaries ls)
425 (let ((new (gensym "tmp ")))
426 (record-new-temporary! 'tmp new 1)
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 (record-operand-use op)
451 (set-operand-use-count! op (1+ (operand-use-count op))))
453 (define (unrecord-operand-uses op n)
454 (let ((count (- (operand-use-count op) n)))
456 (set-operand-residual-value! op #f))
457 (set-operand-use-count! op count)))
459 (define* (residualize-lexical op #:optional ctx val)
460 (log 'residualize op)
461 (record-operand-use op)
462 (if (memq ctx '(value values))
463 (set-operand-residual-value! op val))
464 (make-lexical-ref #f (var-name (operand-var op)) (operand-sym op)))
466 (define (fold-constants src name args ctx)
467 (define (apply-primitive name args)
468 ;; todo: further optimize commutative primitives
473 (apply (module-ref the-scm-module name) args))
475 (values #t results))))
478 (define (make-values src values)
480 ((single) single) ; 1 value
481 ((_ ...) ; 0, or 2 or more values
482 (make-primcall src 'values values))))
483 (define (residualize-call)
484 (make-primcall src name args))
487 (let-values (((success? values)
488 (apply-primitive name (map const-exp args))))
489 (log 'fold success? values name args)
492 ((effect) (make-void src))
494 ;; Values truncation: only take the first
497 (make-const src (car values))
498 (make-values src '())))
500 (make-values src (map (cut make-const src <>) values))))
501 (residualize-call))))
502 ((and (eq? ctx 'effect) (types-check? name args))
505 (residualize-call))))
507 (define (inline-values src exp nmin nmax consumer)
508 (let loop ((exp exp))
510 ;; Some expression types are always singly-valued.
518 ($ <lexical-set>) ; FIXME: these set! expressions
519 ($ <toplevel-set>) ; could return zero values in
520 ($ <toplevel-define>) ; the future
523 ($ <primcall> src (? singly-valued-primitive?)))
524 (and (<= nmin 1) (or (not nmax) (>= nmax 1))
525 (make-call src (make-lambda #f '() consumer) (list exp))))
527 ;; Statically-known number of values.
528 (($ <primcall> src 'values vals)
529 (and (<= nmin (length vals)) (or (not nmax) (>= nmax (length vals)))
530 (make-call src (make-lambda #f '() consumer) vals)))
532 ;; Not going to copy code into both branches.
533 (($ <conditional>) #f)
535 ;; Bail on other applications.
539 ;; Bail on prompt and abort.
543 ;; Propagate to tail positions.
544 (($ <let> src names gensyms vals body)
545 (let ((body (loop body)))
547 (make-let src names gensyms vals body))))
548 (($ <letrec> src in-order? names gensyms vals body)
549 (let ((body (loop body)))
551 (make-letrec src in-order? names gensyms vals body))))
552 (($ <fix> src names gensyms vals body)
553 (let ((body (loop body)))
555 (make-fix src names gensyms vals body))))
556 (($ <let-values> src exp
557 ($ <lambda-case> src2 req opt rest kw inits gensyms body #f))
558 (let ((body (loop body)))
560 (make-let-values src exp
561 (make-lambda-case src2 req opt rest kw
562 inits gensyms body #f)))))
563 (($ <dynlet> src fluids vals body)
564 (let ((body (loop body)))
566 (make-dynlet src fluids vals body))))
567 (($ <seq> src head tail)
568 (let ((tail (loop tail)))
569 (and tail (make-seq src head 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)
596 (not (zero? (operand-use-count op)))))
598 ;; values := (op ...)
599 ;; effects := (op ...)
600 (define (residualize values effects)
601 ;; Note, values and effects are reversed.
604 (let ((values (filter operand-residual-value ops)))
607 (build-result (map (compose var-name operand-var) values)
608 (map operand-sym values)
609 (map operand-residual-value values)
615 (let ((effect-vals (map operand-residual-value effects)))
616 (list->seq #f (reverse (cons body effect-vals)))))))
619 (let ((values (reverse values)))
620 (build-result (map (compose var-name operand-var) values)
621 (map operand-sym values)
622 (map operand-residual-value values)
626 ;; values := (op ...)
627 ;; effects := ((op . value) ...)
628 (let prune ((old (map referenced? ops)) (values '()) (effects '()))
629 (let lp ((ops* ops) (values values) (effects effects))
632 (let ((new (map referenced? ops)))
633 (if (not (equal? new old))
634 (prune new values '())
636 (map (lambda (op val)
637 (set-operand-residual-value! op val)
639 (map car effects) (map cdr effects))))))
641 (let ((op (car ops*)))
644 (lp (cdr ops*) values effects))
645 ((operand-residual-value op)
646 (lp (cdr ops*) (cons op values) effects))
648 (set-operand-residual-value! op (visit-operand op counter 'value))
649 (lp (cdr ops*) (cons op values) effects))
653 (let ((effect (visit-operand op counter 'effect)))
656 (acons op effect effects))))))))))))
658 (define (small-expression? x limit)
661 (lambda (x res) ; down
670 (define (extend-env sym op env)
671 (vhash-consq (operand-sym op) op (vhash-consq sym op env)))
674 (env vlist-null) ; vhash of gensym -> <operand>
675 (counter #f) ; inlined call stack
676 (ctx 'values)) ; effect, value, values, test, operator, or call
679 ((vhash-assq var env) => cdr)
680 (else (error "unbound var" var))))
682 ;; Find a value referenced a specific number of times. This is a hack
683 ;; that's used for propagating fresh data structures like rest lists and
684 ;; prompt tags. Usually we wouldn't copy consed data, but we can do so in
685 ;; some special cases like `apply' or prompts if we can account
686 ;; for all of its uses.
688 ;; You don't want to use this in general because it introduces a slight
689 ;; nonlinearity by running peval again (though with a small effort and size
692 (define (find-definition x n-aliases)
696 ((lookup (lexical-ref-gensym x))
698 (let ((y (or (operand-residual-value op)
699 (visit-operand op counter 'value 10 10)
700 (operand-source op))))
702 ((and (lexical-ref? y)
703 (= (lexical-refcount (lexical-ref-gensym x)) 1))
704 ;; X is a simple alias for Y. Recurse, regardless of
705 ;; the number of aliases we were expecting.
706 (find-definition y n-aliases))
707 ((= (lexical-refcount (lexical-ref-gensym x)) n-aliases)
708 ;; We found a definition that is aliased the right
709 ;; number of times. We still recurse in case it is a
711 (values (find-definition y 1)
714 ;; We can't account for our aliases.
717 ;; A formal parameter. Can't say anything about that.
720 ;; Not a lexical: success, but only if we are looking for an
723 (else (values #f #f))))
725 (define (visit exp ctx)
726 (loop exp env counter ctx))
728 (define (for-value exp) (visit exp 'value))
729 (define (for-values exp) (visit exp 'values))
730 (define (for-test exp) (visit exp 'test))
731 (define (for-effect exp) (visit exp 'effect))
732 (define (for-call exp) (visit exp 'call))
733 (define (for-tail exp) (visit exp ctx))
736 (record-effort! counter))
738 (log 'visit ctx (and=> counter effort-counter)
739 (unparse-tree-il exp))
744 ((effect) (make-void #f))
748 ((test) (make-const #f #t))
750 (($ <lexical-ref> _ _ gensym)
751 (log 'begin-copy gensym)
752 (let ((op (lookup gensym)))
755 (log 'lexical-for-effect gensym)
757 ((operand-alias-value op)
758 ;; This is an unassigned operand that simply aliases some
759 ;; other operand. Recurse to avoid residualizing the leaf
763 ;; Don't propagate copies if we are residualizing a call.
764 (log 'residualize-lexical-call gensym op)
765 (residualize-lexical op))
766 ((var-set? (operand-var op))
767 ;; Assigned lexicals don't copy-propagate.
768 (log 'assigned-var gensym op)
769 (residualize-lexical op))
770 ((not (operand-copyable? op))
771 ;; We already know that this operand is not copyable.
772 (log 'not-copyable gensym op)
773 (residualize-lexical op))
774 ((and=> (operand-constant-value op)
775 (lambda (x) (or (const? x) (void? x) (primitive-ref? x))))
777 (let ((val (operand-constant-value op)))
778 (log 'memoized-constant gensym val)
780 ((visit-operand op counter (if (eq? ctx 'values) 'value ctx)
781 recursive-effort-limit operand-size-limit)
783 ;; If we end up deciding to residualize this value instead of
784 ;; copying it, save that residualized value.
787 ((not (constant-expression? val))
788 (log 'not-constant gensym op)
789 ;; At this point, ctx is operator, test, or value. A
790 ;; value that is non-constant in one context will be
791 ;; non-constant in the others, so it's safe to record
792 ;; that here, and avoid future visits.
793 (set-operand-copyable?! op #f)
794 (residualize-lexical op ctx val))
797 (primitive-ref? val))
798 ;; Always propagate simple values that cannot lead to
800 (log 'copy-simple gensym val)
801 ;; It could be this constant is the result of folding.
802 ;; If that is the case, cache it. This helps loop
803 ;; unrolling get farther.
804 (if (or (eq? ctx 'value) (eq? ctx 'values))
806 (log 'memoize-constant gensym val)
807 (set-operand-constant-value! op val)))
809 ((= 1 (var-refcount (operand-var op)))
810 ;; Always propagate values referenced only once.
811 (log 'copy-single gensym val)
813 ;; FIXME: do demand-driven size accounting rather than
816 ;; A pure expression in the operator position. Inline
817 ;; if it's a lambda that's small enough.
818 (if (and (lambda? val)
819 (small-expression? val operator-size-limit))
821 (log 'copy-operator gensym val)
824 (log 'too-big-for-operator gensym val)
825 (residualize-lexical op ctx val))))
827 ;; A pure expression, processed for call or for value.
828 ;; Don't inline lambdas, because they will probably won't
829 ;; fold because we don't know the operator.
830 (if (and (small-expression? val value-size-limit)
831 (not (tree-il-any lambda? val)))
833 (log 'copy-value gensym val)
836 (log 'too-big-or-has-lambda gensym val)
837 (residualize-lexical op ctx val)))))))
839 ;; Visit failed. Either the operand isn't bound, as in
840 ;; lambda formal parameters, or the copy was aborted.
841 (log 'unbound-or-aborted gensym op)
842 (residualize-lexical op)))))
843 (($ <lexical-set> src name gensym exp)
844 (let ((op (lookup gensym)))
845 (if (zero? (var-refcount (operand-var op)))
846 (let ((exp (for-effect exp)))
849 (make-seq src exp (make-void #f))))
851 (record-operand-use op)
852 (make-lexical-set src name (operand-sym op) (for-value exp))))))
855 (gensyms ... rest-sym)
856 (vals ... ($ <primcall> _ 'list rest-args))
857 ($ <primcall> asrc 'apply
860 (? (cut eq? <> rest))
862 (and (eq? sym rest-sym)
863 (= (lexical-refcount sym) 1))))))))
864 (let* ((tmps (make-list (length rest-args) 'tmp))
865 (tmp-syms (fresh-temporaries tmps)))
869 (append gensyms tmp-syms)
870 (append vals rest-args)
875 (map (cut make-lexical-ref #f <> <>)
877 (($ <let> src names gensyms vals body)
878 (define (compute-alias exp)
879 ;; It's very common for macros to introduce something like:
881 ;; ((lambda (x y) ...) x-exp y-exp)
883 ;; In that case you might end up trying to inline something like:
885 ;; (let ((x x-exp) (y y-exp)) ...)
887 ;; But if x-exp is itself a lexical-ref that aliases some much
888 ;; larger expression, perhaps it will fail to inline due to
889 ;; size. However we don't want to introduce a useless alias
890 ;; (in this case, x). So if the RHS of a let expression is a
891 ;; lexical-ref, we record that expression. If we end up having
892 ;; to residualize X, then instead we residualize X-EXP, as long
893 ;; as it isn't assigned.
896 (($ <lexical-ref> _ _ sym)
897 (let ((op (lookup sym)))
898 (and (not (var-set? (operand-var op)))
899 (or (operand-alias-value op)
903 (let* ((vars (map lookup-var gensyms))
904 (new (fresh-gensyms vars))
905 (ops (make-bound-operands vars new vals
906 (lambda (exp counter ctx)
907 (loop exp env counter ctx))
908 (map compute-alias vals)))
909 (env (fold extend-env env gensyms ops))
910 (body (loop body env counter ctx)))
913 (for-tail (list->seq src (append vals (list body)))))
914 ((and (lexical-ref? body)
915 (memq (lexical-ref-gensym body) new))
916 (let ((sym (lexical-ref-gensym body))
917 (pairs (map cons new vals)))
918 ;; (let ((x foo) (y bar) ...) x) => (begin bar ... foo)
922 (append (map cdr (alist-delete sym pairs eq?))
923 (list (assq-ref pairs sym)))))))
925 ;; Only include bindings for which lexical references
926 ;; have been residualized.
927 (prune-bindings ops #f body counter ctx
928 (lambda (names gensyms vals body)
929 (if (null? names) (error "what!" names))
930 (make-let src names gensyms vals body)))))))
931 (($ <letrec> src in-order? names gensyms vals body)
932 ;; Note the difference from the `let' case: here we use letrec*
933 ;; so that the `visit' procedure for the new operands closes over
934 ;; an environment that includes the operands. Also we don't try
935 ;; to elide aliases, because we can't sensibly reduce something
936 ;; like (letrec ((a b) (b a)) a).
937 (letrec* ((visit (lambda (exp counter ctx)
938 (loop exp env* counter ctx)))
939 (vars (map lookup-var gensyms))
940 (new (fresh-gensyms vars))
941 (ops (make-bound-operands vars new vals visit))
942 (env* (fold extend-env env gensyms ops))
943 (body* (visit body counter ctx)))
944 (if (and (const? body*) (every constant-expression? vals))
945 ;; We may have folded a loop completely, even though there
946 ;; might be cyclical references between the bound values.
947 ;; Handle this degenerate case specially.
949 (prune-bindings ops in-order? body* counter ctx
950 (lambda (names gensyms vals body)
951 (make-letrec src in-order?
952 names gensyms vals body))))))
953 (($ <fix> src names gensyms vals body)
954 (letrec* ((visit (lambda (exp counter ctx)
955 (loop exp env* counter ctx)))
956 (vars (map lookup-var gensyms))
957 (new (fresh-gensyms vars))
958 (ops (make-bound-operands vars new vals visit))
959 (env* (fold extend-env env gensyms ops))
960 (body* (visit body counter ctx)))
963 (prune-bindings ops #f body* counter ctx
964 (lambda (names gensyms vals body)
965 (make-fix src names gensyms vals body))))))
966 (($ <let-values> lv-src producer consumer)
967 ;; Peval the producer, then try to inline the consumer into
968 ;; the producer. If that succeeds, peval again. Otherwise
969 ;; reconstruct the let-values, pevaling the consumer.
970 (let ((producer (for-values producer)))
972 (($ <lambda-case> src (req-name) #f #f #f () (req-sym) body #f)
974 (make-let src (list req-name) (list req-sym) (list producer)
976 ((and ($ <lambda-case> src () #f rest #f () (rest-sym) body #f)
977 (? (lambda _ (singly-valued-expression? producer))))
978 (let ((tmp (gensym "tmp ")))
979 (record-new-temporary! 'tmp tmp 1)
982 src (list 'tmp) (list tmp) (list producer)
984 src (list rest) (list rest-sym)
986 (make-primcall #f 'list
987 (list (make-lexical-ref #f 'tmp tmp))))
989 (($ <lambda-case> src req opt rest #f inits gensyms body #f)
990 (let* ((nmin (length req))
991 (nmax (and (not rest) (+ nmin (if opt (length opt) 0)))))
993 ((inline-values lv-src producer nmin nmax consumer)
997 (make-let-values lv-src producer (for-tail consumer)))))
998 (($ <dynlet> src fluids vals body)
999 (make-dynlet src (map for-value fluids) (map for-value vals)
1001 (($ <dynset> src fluid exp)
1002 (make-dynset src (for-value fluid) (for-value exp)))
1003 (($ <toplevel-ref> src (? effect-free-primitive? name))
1006 ;; todo: open private local bindings.
1008 (($ <module-ref> src module (? effect-free-primitive? name) #f)
1009 (let ((module (false-if-exception
1010 (resolve-module module #:ensure #f))))
1011 (if (module? module)
1012 (let ((var (module-variable module name)))
1013 (if (eq? var (module-variable the-scm-module name))
1014 (make-primitive-ref src name)
1019 (($ <module-set> src mod name public? exp)
1020 (make-module-set src mod name public? (for-value exp)))
1021 (($ <toplevel-define> src name exp)
1022 (make-toplevel-define src name (for-value exp)))
1023 (($ <toplevel-set> src name exp)
1024 (make-toplevel-set src name (for-value exp)))
1025 (($ <primitive-ref>)
1027 ((effect) (make-void #f))
1028 ((test) (make-const #f #t))
1030 (($ <conditional> src condition subsequent alternate)
1031 (define (call-with-failure-thunk exp proc)
1033 (($ <call> _ _ ()) (proc exp))
1034 (($ <primcall> _ _ ()) (proc exp))
1035 (($ <const>) (proc exp))
1036 (($ <void>) (proc exp))
1037 (($ <lexical-ref>) (proc exp))
1039 (let ((t (gensym "failure-")))
1040 (record-new-temporary! 'failure t 2)
1042 src (list 'failure) (list t)
1046 (make-lambda-case #f '() #f #f #f '() '() exp #f)))
1047 (proc (make-call #f (make-lexical-ref #f 'failure t)
1049 (define (simplify-conditional c)
1051 ;; Swap the arms of (if (not FOO) A B), to simplify.
1052 (($ <conditional> src ($ <primcall> _ 'not (pred))
1053 subsequent alternate)
1054 (simplify-conditional
1055 (make-conditional src pred alternate subsequent)))
1056 ;; Special cases for common tests in the predicates of chains
1057 ;; of if expressions.
1058 (($ <conditional> src
1059 ($ <conditional> src* outer-test inner-test ($ <const> _ #f))
1062 (let lp ((alternate alternate))
1064 ;; Lift a common repeated test out of a chain of if
1066 (($ <conditional> _ (? (cut tree-il=? outer-test <>))
1067 other-subsequent alternate)
1070 (simplify-conditional
1071 (make-conditional src* inner-test inner-subsequent
1074 ;; Likewise, but punching through any surrounding
1075 ;; failure continuations.
1076 (($ <let> let-src (name) (sym) ((and thunk ($ <lambda>))) body)
1078 let-src (list name) (list sym) (list thunk)
1080 ;; Otherwise, rotate AND tests to expose a simple
1081 ;; condition in the front. Although this may result in
1082 ;; lexically binding failure thunks, the thunks will be
1083 ;; compiled to labels allocation, so there's no actual
1086 (call-with-failure-thunk
1091 (simplify-conditional
1092 (make-conditional src* inner-test inner-subsequent failure))
1095 (match (for-test condition)
1098 (for-tail subsequent)
1099 (for-tail alternate)))
1101 (simplify-conditional
1102 (make-conditional src c (for-tail subsequent)
1103 (for-tail alternate))))))
1104 (($ <primcall> src 'call-with-values
1108 ;; No optional or kwargs.
1110 _ req #f rest #f () gensyms body #f)))))
1111 (for-tail (make-let-values src (make-call src producer '())
1113 (($ <primcall> src 'dynamic-wind (w thunk u))
1114 (define (with-temporaries exps refcount k)
1115 (let* ((pairs (map (match-lambda
1116 ((and exp (? constant-expression?))
1119 (let ((sym (gensym "tmp ")))
1120 (record-new-temporary! 'tmp sym refcount)
1123 (tmps (filter car pairs)))
1128 (make-list (length tmps) 'tmp)
1131 (k (map (match-lambda
1134 (make-lexical-ref #f 'tmp sym)))
1136 (define (make-begin0 src first second)
1140 (let ((vals (gensym "vals ")))
1141 (record-new-temporary! 'vals vals 1)
1144 '() #f 'vals #f '() (list vals)
1148 (make-primcall #f 'apply
1150 (make-primitive-ref #f 'values)
1151 (make-lexical-ref #f 'vals vals))))
1164 ;; fixme: introduce logic to fold thunk?
1165 (make-primcall src 'thunk? (list u))
1166 (make-call src w '())
1170 (make-const #f 'wrong-type-arg)
1171 (make-const #f "dynamic-wind")
1172 (make-const #f "Wrong type (expecting thunk): ~S")
1173 (make-primcall #f 'list (list u))
1174 (make-primcall #f 'list (list u)))))
1175 (make-primcall src 'wind (list w u)))
1177 (make-call src thunk '())
1179 (make-primcall src 'unwind '())
1180 (make-call src u '())))))))))
1182 (($ <primcall> src 'values exps)
1185 (if (eq? ctx 'effect)
1189 (let ((vals (map for-value exps)))
1191 ((value test effect) #t)
1192 (else (null? (cdr vals))))
1193 (every singly-valued-expression? vals))
1194 (for-tail (list->seq src (append (cdr vals) (list (car vals)))))
1195 (make-primcall src 'values vals))))))
1197 (($ <primcall> src 'apply (proc args ... tail))
1198 (let lp ((tail* (find-definition tail 1)) (speculative? #t))
1199 (define (copyable? x)
1200 ;; Inlining a result from find-definition effectively copies it,
1201 ;; relying on the let-pruning to remove its original binding. We
1202 ;; shouldn't copy non-constant expressions.
1203 (or (not speculative?) (constant-expression? x)))
1205 (($ <const> _ (args* ...))
1206 (let ((args* (map (cut make-const #f <>) args*)))
1207 (for-tail (make-call src proc (append args args*)))))
1208 (($ <primcall> _ 'cons
1209 ((and head (? copyable?)) (and tail (? copyable?))))
1210 (for-tail (make-primcall src 'apply
1212 (append args (list head tail))))))
1213 (($ <primcall> _ 'list
1214 (and args* ((? copyable?) ...)))
1215 (for-tail (make-call src proc (append args args*))))
1218 (lp (for-value tail) #f)
1219 (let ((args (append (map for-value args) (list tail*))))
1220 (make-primcall src 'apply
1221 (cons (for-value proc) args))))))))
1223 (($ <primcall> src (? constructor-primitive? name) args)
1225 ((and (memq ctx '(effect test))
1226 (match (cons name args)
1231 ('make-prompt-tag ($ <const> _ (? string?))))
1234 ;; Some expressions can be folded without visiting the
1235 ;; arguments for value.
1236 (let ((res (if (eq? ctx 'effect)
1238 (make-const #f #t))))
1239 (for-tail (list->seq src (append args (list res))))))
1241 (match (cons name (map for-value args))
1242 (('cons x ($ <const> _ (? (cut eq? <> '()))))
1243 (make-primcall src 'list (list x)))
1244 (('cons x ($ <primcall> _ 'list elts))
1245 (make-primcall src 'list (cons x elts)))
1247 (make-primcall src name args))))))
1249 (($ <primcall> src 'thunk? (proc))
1250 (match (for-value proc)
1251 (($ <lambda> _ _ ($ <lambda-case> _ req))
1252 (for-tail (make-const src (null? req))))
1255 ((effect) (make-void src))
1256 (else (make-primcall src 'thunk? (list proc)))))))
1258 (($ <primcall> src (? accessor-primitive? name) args)
1259 (match (cons name (map for-value args))
1260 ;; FIXME: these for-tail recursions could take place outside
1261 ;; an effort counter.
1262 (('car ($ <primcall> src 'cons (head tail)))
1263 (for-tail (make-seq src tail head)))
1264 (('cdr ($ <primcall> src 'cons (head tail)))
1265 (for-tail (make-seq src head tail)))
1266 (('car ($ <primcall> src 'list (head . tail)))
1267 (for-tail (list->seq src (append tail (list head)))))
1268 (('cdr ($ <primcall> src 'list (head . tail)))
1269 (for-tail (make-seq src head (make-primcall #f 'list tail))))
1271 (('car ($ <const> src (head . tail)))
1272 (for-tail (make-const src head)))
1273 (('cdr ($ <const> src (head . tail)))
1274 (for-tail (make-const src tail)))
1275 (((or 'memq 'memv) k ($ <const> _ (elts ...)))
1280 (make-seq src k (make-void #f))))
1284 ;; A shortcut. The `else' case would handle it, but
1285 ;; this way is faster.
1286 (let ((member (case name ((memq) memq) ((memv) memv))))
1287 (make-const #f (and (member (const-exp k) elts) #t))))
1290 (make-seq src k (make-const #f #f))))
1292 (let ((t (gensym "t "))
1293 (eq (if (eq? name 'memq) 'eq? 'eqv?)))
1294 (record-new-temporary! 't t (length elts))
1297 src (list 't) (list t) (list k)
1298 (let lp ((elts elts))
1300 (make-primcall #f eq
1301 (list (make-lexical-ref #f 't t)
1302 (make-const #f (car elts)))))
1303 (if (null? (cdr elts))
1305 (make-conditional src test
1307 (lp (cdr elts)))))))))))
1311 (let ((member (case name ((memq) memq) ((memv) memv))))
1312 (make-const #f (member (const-exp k) elts))))
1314 (for-tail (make-seq src k (make-const #f #f))))
1316 (make-primcall src name (list k (make-const #f elts))))))))
1318 (fold-constants src name args ctx))))
1320 (($ <primcall> src (? equality-primitive? name) (a b))
1321 (let ((val-a (for-value a))
1322 (val-b (for-value b)))
1323 (log 'equality-primitive name val-a val-b)
1324 (cond ((and (lexical-ref? val-a) (lexical-ref? val-b)
1325 (eq? (lexical-ref-gensym val-a)
1326 (lexical-ref-gensym val-b)))
1327 (for-tail (make-const #f #t)))
1329 (fold-constants src name (list val-a val-b) ctx)))))
1331 (($ <primcall> src (? effect-free-primitive? name) args)
1332 (fold-constants src name (map for-value args) ctx))
1334 (($ <primcall> src name args)
1335 (make-primcall src name (map for-value args)))
1337 (($ <call> src orig-proc orig-args)
1338 ;; todo: augment the global env with specialized functions
1339 (let revisit-proc ((proc (visit orig-proc 'operator)))
1341 (($ <primitive-ref> _ name)
1342 (for-tail (make-primcall src name orig-args)))
1344 ($ <lambda-case> _ req opt rest #f inits gensyms body #f))
1345 ;; Simple case: no keyword arguments.
1346 ;; todo: handle the more complex cases
1347 (let* ((nargs (length orig-args))
1349 (nopt (if opt (length opt) 0))
1350 (key (source-expression proc)))
1351 (define (inlined-call)
1355 (if rest (list rest) '()))
1357 (if (> nargs (+ nreq nopt))
1358 (append (list-head orig-args (+ nreq nopt))
1362 (drop orig-args (+ nreq nopt)))))
1364 (drop inits (- nargs nreq))
1366 (list (make-const #f '()))
1371 ((or (< nargs nreq) (and (not rest) (> nargs (+ nreq nopt))))
1372 ;; An error, or effecting arguments.
1373 (make-call src (for-call orig-proc) (map for-value orig-args)))
1374 ((or (and=> (find-counter key counter) counter-recursive?)
1375 (lambda? orig-proc))
1376 ;; A recursive call, or a lambda in the operator
1377 ;; position of the source expression. Process again in
1380 ;; In the recursive case, mark intervening counters as
1381 ;; recursive, so we can handle a toplevel counter that
1382 ;; recurses mutually with some other procedure.
1383 ;; Otherwise, the next time we see the other procedure,
1384 ;; the effort limit would be clamped to 100.
1386 (let ((found (find-counter key counter)))
1387 (if (and found (counter-recursive? found))
1388 (let lp ((counter counter))
1389 (if (not (eq? counter found))
1391 (set-counter-recursive?! counter #t)
1392 (lp (counter-prev counter)))))))
1394 (log 'inline-recurse key)
1395 (loop (inlined-call) env counter ctx))
1397 ;; An integration at the top-level, the first
1398 ;; recursion of a recursive procedure, or a nested
1399 ;; integration of a procedure that hasn't been seen
1401 (log 'inline-begin exp)
1404 (log 'inline-abort exp)
1405 (k (make-call src (for-call orig-proc)
1406 (map for-value orig-args))))
1409 ;; These first two cases will transfer effort
1410 ;; from the current counter into the new
1412 ((find-counter key counter)
1414 (make-recursive-counter recursive-effort-limit
1418 (make-nested-counter abort key counter))
1419 ;; This case opens a new account, effectively
1420 ;; printing money. It should only do so once
1421 ;; for each call site in the source program.
1423 (make-top-counter effort-limit operand-size-limit
1426 (loop (inlined-call) env new-counter ctx))
1429 ;; The nested inlining attempt succeeded.
1430 ;; Deposit the unspent effort and size back
1431 ;; into the current counter.
1432 (transfer! new-counter counter))
1434 (log 'inline-end result exp)
1436 (($ <let> _ _ _ vals _)
1437 ;; Attempt to inline `let' in the operator position.
1439 ;; We have to re-visit the proc in value mode, since the
1440 ;; `let' bindings might have been introduced or renamed,
1441 ;; whereas the lambda (if any) in operator position has not
1443 (if (or (and-map constant-expression? vals)
1444 (and-map constant-expression? orig-args))
1445 ;; The arguments and the let-bound values commute.
1446 (match (for-value orig-proc)
1447 (($ <let> lsrc names syms vals body)
1448 (log 'inline-let orig-proc)
1450 (make-let lsrc names syms vals
1451 (make-call src body orig-args))))
1452 ;; It's possible for a `let' to go away after the
1453 ;; visit due to the fact that visiting a procedure in
1454 ;; value context will prune unused bindings, whereas
1455 ;; visiting in operator mode can't because it doesn't
1456 ;; traverse through lambdas. In that case re-visit
1458 (proc (revisit-proc proc)))
1459 (make-call src (for-call orig-proc)
1460 (map for-value orig-args))))
1462 (make-call src (for-call orig-proc) (map for-value orig-args))))))
1463 (($ <lambda> src meta body)
1465 ((effect) (make-void #f))
1466 ((test) (make-const #f #t))
1468 (else (record-source-expression!
1470 (make-lambda src meta (and body (for-values body)))))))
1471 (($ <lambda-case> src req opt rest kw inits gensyms body alt)
1472 (define (lift-applied-lambda body gensyms)
1473 (and (not opt) rest (not kw)
1475 (($ <primcall> _ 'apply
1476 (($ <lambda> _ _ (and lcase ($ <lambda-case>)))
1477 ($ <lexical-ref> _ _ sym)
1479 (and (equal? sym gensyms)
1480 (not (lambda-case-alternate lcase))
1483 (let* ((vars (map lookup-var gensyms))
1484 (new (fresh-gensyms vars))
1485 (env (fold extend-env env gensyms
1486 (make-unbound-operands vars new)))
1487 (new-sym (lambda (old)
1488 (operand-sym (cdr (vhash-assq old env)))))
1489 (body (loop body env counter ctx)))
1491 ;; (lambda args (apply (lambda ...) args)) => (lambda ...)
1492 (lift-applied-lambda body new)
1493 (make-lambda-case src req opt rest
1495 ((aok? (kw name old) ...)
1496 (cons aok? (map list kw name (map new-sym old))))
1498 (map (cut loop <> env counter 'value) inits)
1501 (and alt (for-tail alt))))))
1502 (($ <seq> src head tail)
1503 (let ((head (for-effect head))
1504 (tail (for-tail tail)))
1508 (if (and (seq? head)
1509 (void? (seq-tail head)))
1513 (($ <prompt> src tag body handler)
1514 (define (make-prompt-tag? x)
1516 (($ <primcall> _ 'make-prompt-tag (or () ((? constant-expression?))))
1520 (let ((tag (for-value tag))
1521 (body (for-tail body)))
1523 ((find-definition tag 1)
1525 (make-prompt-tag? val))
1527 ;; There is no way that an <abort> could know the tag
1528 ;; for this <prompt>, so we can elide the <prompt>
1530 (unrecord-operand-uses op 1)
1532 ((find-definition tag 2)
1534 (and (make-prompt-tag? val)
1536 (tree-il=? (abort-tag body) tag)))
1538 ;; (let ((t (make-prompt-tag)))
1539 ;; (call-with-prompt t
1540 ;; (lambda () (abort-to-prompt t val ...))
1541 ;; (lambda (k arg ...) e ...)))
1542 ;; => (let-values (((k arg ...) (values values val ...)))
1544 (unrecord-operand-uses op 2)
1548 (make-primcall #f 'apply
1549 `(,(make-primitive-ref #f 'values)
1550 ,(make-primitive-ref #f 'values)
1552 ,(abort-tail body)))
1553 (for-value handler)))))
1555 (make-prompt src tag body (for-value handler))))))
1556 (($ <abort> src tag args tail)
1557 (make-abort src (for-value tag) (map for-value args)
1558 (for-value tail))))))