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 use-count
292 copyable? residual-value constant-value alias-value)
296 (visit %operand-visit)
297 (source operand-source)
298 (visit-count operand-visit-count set-operand-visit-count!)
299 (use-count operand-use-count set-operand-use-count!)
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!)
303 (alias-value operand-alias-value set-operand-alias-value!))
305 (define* (make-operand var sym #:optional source visit alias)
306 ;; Bind SYM to VAR, with value SOURCE. Unassigned bound operands are
307 ;; considered copyable until we prove otherwise. If we have a source
308 ;; expression, truncate it to one value. Copy propagation does not
309 ;; work on multiply-valued expressions.
310 (let ((source (and=> source truncate-values)))
311 (%make-operand var sym visit source 0 0
312 (and source (not (var-set? var))) #f #f
313 (and (not (var-set? var)) alias))))
315 (define* (make-bound-operands vars syms sources visit #:optional aliases)
317 (map (lambda (name sym source alias)
318 (make-operand name sym source visit alias))
319 vars syms sources aliases)
320 (map (lambda (name sym source)
321 (make-operand name sym source visit #f))
324 (define (make-unbound-operands vars syms)
325 (map make-operand vars syms))
327 (define (set-operand-residual-value! op val)
328 (%set-operand-residual-value!
331 (($ <application> src ($ <primitive-ref> _ 'values) (first))
332 ;; The continuation of a residualized binding does not need the
333 ;; introduced `values' node, so undo the effects of truncation.
338 (define* (visit-operand op counter ctx #:optional effort-limit size-limit)
339 ;; Peval is O(N) in call sites of the source program. However,
340 ;; visiting an operand can introduce new call sites. If we visit an
341 ;; operand outside a counter -- i.e., outside an inlining attempt --
342 ;; this can lead to divergence. So, if we are visiting an operand to
343 ;; try to copy it, and there is no counter, make a new one.
345 ;; This will only happen at most as many times as there are lexical
346 ;; references in the source program.
347 (and (zero? (operand-visit-count op))
350 (set-operand-visit-count! op (1+ (operand-visit-count op))))
352 (and (operand-source op)
353 (if (or counter (and (not effort-limit) (not size-limit)))
354 ((%operand-visit op) (operand-source op) counter ctx)
357 ;; If we abort when visiting the value in a
358 ;; fresh context, we won't succeed in any future
359 ;; attempt, so don't try to copy it again.
360 (set-operand-copyable?! op #f)
364 (make-top-counter effort-limit size-limit abort op)
367 (set-operand-visit-count! op (1- (operand-visit-count op)))))))
369 ;; A helper for constant folding.
371 (define (types-check? primitive-name args)
374 ((not pair? null? list? symbol? vector? struct?)
378 ;; FIXME: add more cases?
381 (define* (peval exp #:optional (cenv (current-module)) (env vlist-null)
383 (operator-size-limit 40)
384 (operand-size-limit 20)
385 (value-size-limit 10)
387 (recursive-effort-limit 100))
388 "Partially evaluate EXP in compilation environment CENV, with
389 top-level bindings from ENV and return the resulting expression."
391 ;; This is a simple partial evaluator. It effectively performs
392 ;; constant folding, copy propagation, dead code elimination, and
397 ;; Propagate copies across toplevel bindings, if we can prove the
398 ;; bindings to be immutable.
400 ;; Specialize lambda expressions with invariant arguments.
402 (define local-toplevel-env
403 ;; The top-level environment of the module being compiled.
405 (($ <toplevel-define> _ name)
406 (vhash-consq name #t env))
407 (($ <sequence> _ exps)
410 (($ <toplevel-define> _ name)
411 (vhash-consq name #t r))
417 (define (local-toplevel? name)
418 (vhash-assq name local-toplevel-env))
421 ;; renamed-term -> original-term
423 (define store (build-var-table exp))
425 (define (record-new-temporary! name sym refcount)
426 (set! store (vhash-consq sym (make-var name sym refcount #f) store)))
428 (define (lookup-var sym)
429 (let ((v (vhash-assq sym store)))
430 (if v (cdr v) (error "unbound var" sym (vlist->list store)))))
432 (define (fresh-gensyms vars)
434 (let ((new (gensym (string-append (symbol->string (var-name var))
436 (set! store (vhash-consq new var store))
440 (define (assigned-lexical? sym)
441 (var-set? (lookup-var sym)))
443 (define (lexical-refcount sym)
444 (var-refcount (lookup-var sym)))
446 ;; ORIG has been alpha-renamed to NEW. Analyze NEW and record a link
449 (define (record-source-expression! orig new)
450 (set! store (vhash-consq new (source-expression orig) store))
453 ;; Find the source expression corresponding to NEW. Used to detect
454 ;; recursive inlining attempts.
456 (define (source-expression new)
457 (let ((x (vhash-assq new store)))
460 (define (record-operand-use op)
461 (set-operand-use-count! op (1+ (operand-use-count op))))
463 (define (unrecord-operand-uses op n)
464 (let ((count (- (operand-use-count op) n)))
466 (set-operand-residual-value! op #f))
467 (set-operand-use-count! op count)))
469 (define* (residualize-lexical op #:optional ctx val)
470 (log 'residualize op)
471 (record-operand-use op)
472 (if (memq ctx '(value values))
473 (set-operand-residual-value! op val))
474 (make-lexical-ref #f (var-name (operand-var op)) (operand-sym op)))
476 (define (fold-constants src name args ctx)
477 (define (apply-primitive name args)
478 ;; todo: further optimize commutative primitives
483 (apply (module-ref the-scm-module name) args))
485 (values #t results))))
489 (define (make-values src values)
491 ((single) single) ; 1 value
492 ((_ ...) ; 0, or 2 or more values
493 (make-application src (make-primitive-ref src 'values)
495 (define (residualize-call)
496 (make-application src (make-primitive-ref #f name) args))
499 (let-values (((success? values)
500 (apply-primitive name (map const-exp args))))
501 (log 'fold success? values name args)
504 ((effect) (make-void src))
506 ;; Values truncation: only take the first
509 (make-const src (car values))
510 (make-values src '())))
512 (make-values src (map (cut make-const src <>) values))))
513 (residualize-call))))
514 ((and (eq? ctx 'effect) (types-check? name args))
517 (residualize-call))))
519 (define (inline-values exp src names gensyms body)
520 (let loop ((exp exp))
522 ;; Some expression types are always singly-valued.
531 ($ <lexical-set>) ; FIXME: these set! expressions
532 ($ <toplevel-set>) ; could return zero values in
533 ($ <toplevel-define>) ; the future
536 (and (= (length names) 1)
537 (make-let src names gensyms (list exp) body)))
538 (($ <application> src
539 ($ <primitive-ref> _ (? singly-valued-primitive? name)))
540 (and (= (length names) 1)
541 (make-let src names gensyms (list exp) body)))
543 ;; Statically-known number of values.
544 (($ <application> src ($ <primitive-ref> _ 'values) vals)
545 (and (= (length names) (length vals))
546 (make-let src names gensyms vals body)))
548 ;; Not going to copy code into both branches.
549 (($ <conditional>) #f)
551 ;; Bail on other applications.
552 (($ <application>) #f)
554 ;; Bail on prompt and abort.
558 ;; Propagate to tail positions.
559 (($ <let> src names gensyms vals body)
560 (let ((body (loop body)))
562 (make-let src names gensyms vals body))))
563 (($ <letrec> src in-order? names gensyms vals body)
564 (let ((body (loop body)))
566 (make-letrec src in-order? names gensyms vals body))))
567 (($ <fix> src names gensyms vals body)
568 (let ((body (loop body)))
570 (make-fix src names gensyms vals body))))
571 (($ <let-values> src exp
572 ($ <lambda-case> src2 req opt rest kw inits gensyms body #f))
573 (let ((body (loop body)))
575 (make-let-values src exp
576 (make-lambda-case src2 req opt rest kw
577 inits gensyms body #f)))))
578 (($ <dynwind> src winder body unwinder)
579 (let ((body (loop body)))
581 (make-dynwind src winder body unwinder))))
582 (($ <dynlet> src fluids vals body)
583 (let ((body (loop body)))
585 (make-dynlet src fluids vals body))))
586 (($ <sequence> src exps)
589 (let ((tail (loop tail)))
591 (make-sequence src (append head (list tail)))))))))))
593 (define compute-effects
594 (make-effects-analyzer assigned-lexical?))
596 (define (constant-expression? x)
597 ;; Return true if X is constant, for the purposes of copying or
598 ;; elision---i.e., if it is known to have no effects, does not
599 ;; allocate storage for a mutable object, and does not access
600 ;; mutable data (like `car' or toplevel references).
601 (constant? (compute-effects x)))
603 (define (prune-bindings ops in-order? body counter ctx build-result)
604 ;; This helper handles both `let' and `letrec'/`fix'. In the latter
605 ;; cases we need to make sure that if referenced binding A needs
606 ;; as-yet-unreferenced binding B, that B is processed for value.
607 ;; Likewise if C, when processed for effect, needs otherwise
608 ;; unreferenced D, then D needs to be processed for value too.
610 (define (referenced? op)
611 ;; When we visit lambdas in operator context, we just copy them,
612 ;; as we will process their body later. However this does have
613 ;; the problem that any free var referenced by the lambda is not
614 ;; marked as needing residualization. Here we hack around this
615 ;; and treat all bindings as referenced if we are in operator
617 (or (eq? ctx 'operator)
618 (not (zero? (operand-use-count op)))))
620 ;; values := (op ...)
621 ;; effects := (op ...)
622 (define (residualize values effects)
623 ;; Note, values and effects are reversed.
626 (let ((values (filter operand-residual-value ops)))
629 (build-result (map (compose var-name operand-var) values)
630 (map operand-sym values)
631 (map operand-residual-value values)
637 (let ((effect-vals (map operand-residual-value effects)))
638 (make-sequence #f (reverse (cons body effect-vals)))))))
641 (let ((values (reverse values)))
642 (build-result (map (compose var-name operand-var) values)
643 (map operand-sym values)
644 (map operand-residual-value values)
648 ;; values := (op ...)
649 ;; effects := ((op . value) ...)
650 (let prune ((old (map referenced? ops)) (values '()) (effects '()))
651 (let lp ((ops* ops) (values values) (effects effects))
654 (let ((new (map referenced? ops)))
655 (if (not (equal? new old))
656 (prune new values '())
658 (map (lambda (op val)
659 (set-operand-residual-value! op val)
661 (map car effects) (map cdr effects))))))
663 (let ((op (car ops*)))
666 (lp (cdr ops*) values effects))
667 ((operand-residual-value op)
668 (lp (cdr ops*) (cons op values) effects))
670 (set-operand-residual-value! op (visit-operand op counter 'value))
671 (lp (cdr ops*) (cons op values) effects))
675 (let ((effect (visit-operand op counter 'effect)))
678 (acons op effect effects))))))))))))
680 (define (small-expression? x limit)
683 (lambda (x res) ; leaf
685 (lambda (x res) ; down
694 (define (extend-env sym op env)
695 (vhash-consq (operand-sym op) op (vhash-consq sym op env)))
698 (env vlist-null) ; vhash of gensym -> <operand>
699 (counter #f) ; inlined call stack
700 (ctx 'values)) ; effect, value, values, test, operator, or call
703 ((vhash-assq var env) => cdr)
704 (else (error "unbound var" var))))
706 (define (visit exp ctx)
707 (loop exp env counter ctx))
709 (define (for-value exp) (visit exp 'value))
710 (define (for-values exp) (visit exp 'values))
711 (define (for-test exp) (visit exp 'test))
712 (define (for-effect exp) (visit exp 'effect))
713 (define (for-call exp) (visit exp 'call))
714 (define (for-tail exp) (visit exp ctx))
717 (record-effort! counter))
719 (log 'visit ctx (and=> counter effort-counter)
720 (unparse-tree-il exp))
725 ((effect) (make-void #f))
729 ((test) (make-const #f #t))
731 (($ <lexical-ref> _ _ gensym)
732 (log 'begin-copy gensym)
733 (let ((op (lookup gensym)))
736 (log 'lexical-for-effect gensym)
738 ((operand-alias-value op)
739 ;; This is an unassigned operand that simply aliases some
740 ;; other operand. Recurse to avoid residualizing the leaf
744 ;; Don't propagate copies if we are residualizing a call.
745 (log 'residualize-lexical-call gensym op)
746 (residualize-lexical op))
747 ((var-set? (operand-var op))
748 ;; Assigned lexicals don't copy-propagate.
749 (log 'assigned-var gensym op)
750 (residualize-lexical op))
751 ((not (operand-copyable? op))
752 ;; We already know that this operand is not copyable.
753 (log 'not-copyable gensym op)
754 (residualize-lexical op))
755 ((and=> (operand-constant-value op)
756 (lambda (x) (or (const? x) (void? x) (primitive-ref? x))))
758 (let ((val (operand-constant-value op)))
759 (log 'memoized-constant gensym val)
761 ((visit-operand op counter (if (eq? ctx 'values) 'value ctx)
762 recursive-effort-limit operand-size-limit)
764 ;; If we end up deciding to residualize this value instead of
765 ;; copying it, save that residualized value.
768 ((not (constant-expression? val))
769 (log 'not-constant gensym op)
770 ;; At this point, ctx is operator, test, or value. A
771 ;; value that is non-constant in one context will be
772 ;; non-constant in the others, so it's safe to record
773 ;; that here, and avoid future visits.
774 (set-operand-copyable?! op #f)
775 (residualize-lexical op ctx val))
778 (primitive-ref? val))
779 ;; Always propagate simple values that cannot lead to
781 (log 'copy-simple gensym val)
782 ;; It could be this constant is the result of folding.
783 ;; If that is the case, cache it. This helps loop
784 ;; unrolling get farther.
785 (if (or (eq? ctx 'value) (eq? ctx 'values))
787 (log 'memoize-constant gensym val)
788 (set-operand-constant-value! op val)))
790 ((= 1 (var-refcount (operand-var op)))
791 ;; Always propagate values referenced only once.
792 (log 'copy-single gensym val)
794 ;; FIXME: do demand-driven size accounting rather than
797 ;; A pure expression in the operator position. Inline
798 ;; if it's a lambda that's small enough.
799 (if (and (lambda? val)
800 (small-expression? val operator-size-limit))
802 (log 'copy-operator gensym val)
805 (log 'too-big-for-operator gensym val)
806 (residualize-lexical op ctx val))))
808 ;; A pure expression, processed for call or for value.
809 ;; Don't inline lambdas, because they will probably won't
810 ;; fold because we don't know the operator.
811 (if (and (small-expression? val value-size-limit)
812 (not (tree-il-any lambda? val)))
814 (log 'copy-value gensym val)
817 (log 'too-big-or-has-lambda gensym val)
818 (residualize-lexical op ctx val)))))))
820 ;; Visit failed. Either the operand isn't bound, as in
821 ;; lambda formal parameters, or the copy was aborted.
822 (log 'unbound-or-aborted gensym op)
823 (residualize-lexical op)))))
824 (($ <lexical-set> src name gensym exp)
825 (let ((op (lookup gensym)))
826 (if (zero? (var-refcount (operand-var op)))
827 (let ((exp (for-effect exp)))
830 (make-sequence src (list exp (make-void #f)))))
832 (record-operand-use op)
833 (make-lexical-set src name (operand-sym op) (for-value exp))))))
834 (($ <let> src names gensyms vals body)
835 (define (compute-alias exp)
836 ;; It's very common for macros to introduce something like:
838 ;; ((lambda (x y) ...) x-exp y-exp)
840 ;; In that case you might end up trying to inline something like:
842 ;; (let ((x x-exp) (y y-exp)) ...)
844 ;; But if x-exp is itself a lexical-ref that aliases some much
845 ;; larger expression, perhaps it will fail to inline due to
846 ;; size. However we don't want to introduce a useless alias
847 ;; (in this case, x). So if the RHS of a let expression is a
848 ;; lexical-ref, we record that expression. If we end up having
849 ;; to residualize X, then instead we residualize X-EXP, as long
850 ;; as it isn't assigned.
853 (($ <lexical-ref> _ _ sym)
854 (let ((op (lookup sym)))
855 (and (not (var-set? (operand-var op)))
856 (or (operand-alias-value op)
860 (let* ((vars (map lookup-var gensyms))
861 (new (fresh-gensyms vars))
862 (ops (make-bound-operands vars new vals
863 (lambda (exp counter ctx)
864 (loop exp env counter ctx))
865 (map compute-alias vals)))
866 (env (fold extend-env env gensyms ops))
867 (body (loop body env counter ctx)))
870 (for-tail (make-sequence src (append vals (list body)))))
871 ((and (lexical-ref? body)
872 (memq (lexical-ref-gensym body) new))
873 (let ((sym (lexical-ref-gensym body))
874 (pairs (map cons new vals)))
875 ;; (let ((x foo) (y bar) ...) x) => (begin bar ... foo)
879 (append (map cdr (alist-delete sym pairs eq?))
880 (list (assq-ref pairs sym)))))))
882 ;; Only include bindings for which lexical references
883 ;; have been residualized.
884 (prune-bindings ops #f body counter ctx
885 (lambda (names gensyms vals body)
886 (if (null? names) (error "what!" names))
887 (make-let src names gensyms vals body)))))))
888 (($ <letrec> src in-order? names gensyms vals body)
889 ;; Note the difference from the `let' case: here we use letrec*
890 ;; so that the `visit' procedure for the new operands closes over
891 ;; an environment that includes the operands. Also we don't try
892 ;; to elide aliases, because we can't sensibly reduce something
893 ;; like (letrec ((a b) (b a)) a).
894 (letrec* ((visit (lambda (exp counter ctx)
895 (loop exp env* counter ctx)))
896 (vars (map lookup-var gensyms))
897 (new (fresh-gensyms vars))
898 (ops (make-bound-operands vars new vals visit))
899 (env* (fold extend-env env gensyms ops))
900 (body* (visit body counter ctx)))
901 (if (and (const? body*) (every constant-expression? vals))
902 ;; We may have folded a loop completely, even though there
903 ;; might be cyclical references between the bound values.
904 ;; Handle this degenerate case specially.
906 (prune-bindings ops in-order? body* counter ctx
907 (lambda (names gensyms vals body)
908 (make-letrec src in-order?
909 names gensyms vals body))))))
910 (($ <fix> src names gensyms vals body)
911 (letrec* ((visit (lambda (exp counter ctx)
912 (loop exp env* counter ctx)))
913 (vars (map lookup-var gensyms))
914 (new (fresh-gensyms vars))
915 (ops (make-bound-operands vars new vals visit))
916 (env* (fold extend-env env gensyms ops))
917 (body* (visit body counter ctx)))
920 (prune-bindings ops #f body* counter ctx
921 (lambda (names gensyms vals body)
922 (make-fix src names gensyms vals body))))))
923 (($ <let-values> lv-src producer consumer)
924 ;; Peval the producer, then try to inline the consumer into
925 ;; the producer. If that succeeds, peval again. Otherwise
926 ;; reconstruct the let-values, pevaling the consumer.
927 (let ((producer (for-values producer)))
929 (($ <lambda-case> src req #f #f #f () gensyms body #f)
931 ((inline-values producer src req gensyms body)
935 (make-let-values lv-src producer (for-tail consumer)))))
936 (($ <dynwind> src winder body unwinder)
937 (let ((pre (for-value winder))
938 (body (for-tail body))
939 (post (for-value unwinder)))
941 ((not (constant-expression? pre))
943 ((not (constant-expression? post))
944 (let ((pre-sym (gensym "pre-")) (post-sym (gensym "post-")))
945 (record-new-temporary! 'pre pre-sym 1)
946 (record-new-temporary! 'post post-sym 1)
947 (make-let src '(pre post) (list pre-sym post-sym) (list pre post)
949 (make-lexical-ref #f 'pre pre-sym)
951 (make-lexical-ref #f 'post post-sym)))))
953 (let ((pre-sym (gensym "pre-")))
954 (record-new-temporary! 'pre pre-sym 1)
955 (make-let src '(pre) (list pre-sym) (list pre)
957 (make-lexical-ref #f 'pre pre-sym)
960 ((not (constant-expression? post))
961 (let ((post-sym (gensym "post-")))
962 (record-new-temporary! 'post post-sym 1)
963 (make-let src '(post) (list post-sym) (list post)
967 (make-lexical-ref #f 'post post-sym)))))
969 (make-dynwind src pre body post)))))
970 (($ <dynlet> src fluids vals body)
971 (make-dynlet src (map for-value fluids) (map for-value vals)
973 (($ <dynref> src fluid)
974 (make-dynref src (for-value fluid)))
975 (($ <dynset> src fluid exp)
976 (make-dynset src (for-value fluid) (for-value exp)))
977 (($ <toplevel-ref> src (? effect-free-primitive? name))
978 (if (local-toplevel? name)
980 (let ((exp (resolve-primitives! exp cenv)))
981 (if (primitive-ref? exp)
985 ;; todo: open private local bindings.
987 (($ <module-ref> src module (? effect-free-primitive? name) #f)
988 (let ((module (false-if-exception
989 (resolve-module module #:ensure #f))))
991 (let ((var (module-variable module name)))
992 (if (eq? var (module-variable the-scm-module name))
993 (make-primitive-ref src name)
998 (($ <module-set> src mod name public? exp)
999 (make-module-set src mod name public? (for-value exp)))
1000 (($ <toplevel-define> src name exp)
1001 (make-toplevel-define src name (for-value exp)))
1002 (($ <toplevel-set> src name exp)
1003 (make-toplevel-set src name (for-value exp)))
1004 (($ <primitive-ref>)
1006 ((effect) (make-void #f))
1007 ((test) (make-const #f #t))
1009 (($ <conditional> src condition subsequent alternate)
1010 (define (call-with-failure-thunk exp proc)
1012 (($ <application> _ _ ()) (proc exp))
1013 (($ <const>) (proc exp))
1014 (($ <void>) (proc exp))
1015 (($ <lexical-ref>) (proc exp))
1017 (let ((t (gensym "failure-")))
1018 (record-new-temporary! 'failure t 2)
1020 src (list 'failure) (list t)
1024 (make-lambda-case #f '() #f #f #f '() '() exp #f)))
1025 (proc (make-application #f (make-lexical-ref #f 'failure t)
1027 (define (simplify-conditional c)
1029 ;; Swap the arms of (if (not FOO) A B), to simplify.
1030 (($ <conditional> src
1031 ($ <application> _ ($ <primitive-ref> _ 'not) (pred))
1032 subsequent alternate)
1033 (simplify-conditional
1034 (make-conditional src pred alternate subsequent)))
1035 ;; Special cases for common tests in the predicates of chains
1036 ;; of if expressions.
1037 (($ <conditional> src
1038 ($ <conditional> src* outer-test inner-test ($ <const> _ #f))
1041 (let lp ((alternate alternate))
1043 ;; Lift a common repeated test out of a chain of if
1045 (($ <conditional> _ (? (cut tree-il=? outer-test <>))
1046 other-subsequent alternate)
1049 (simplify-conditional
1050 (make-conditional src* inner-test inner-subsequent
1053 ;; Likewise, but punching through any surrounding
1054 ;; failure continuations.
1055 (($ <let> let-src (name) (sym) ((and thunk ($ <lambda>))) body)
1057 let-src (list name) (list sym) (list thunk)
1059 ;; Otherwise, rotate AND tests to expose a simple
1060 ;; condition in the front. Although this may result in
1061 ;; lexically binding failure thunks, the thunks will be
1062 ;; compiled to labels allocation, so there's no actual
1065 (call-with-failure-thunk
1070 (simplify-conditional
1071 (make-conditional src* inner-test inner-subsequent failure))
1074 (match (for-test condition)
1077 (for-tail subsequent)
1078 (for-tail alternate)))
1080 (simplify-conditional
1081 (make-conditional src c (for-tail subsequent)
1082 (for-tail alternate))))))
1083 (($ <application> src
1084 ($ <primitive-ref> _ '@call-with-values)
1088 ;; No optional or kwargs.
1090 _ req #f rest #f () gensyms body #f)))))
1091 (for-tail (make-let-values src (make-application src producer '())
1093 (($ <application> src ($ <primitive-ref> _ 'values) exps)
1096 (if (eq? ctx 'effect)
1100 (let ((vals (map for-value exps)))
1102 ((value test effect) #t)
1103 (else (null? (cdr vals))))
1104 (every singly-valued-expression? vals))
1105 (for-tail (make-sequence src (append (cdr vals) (list (car vals)))))
1106 (make-application src (make-primitive-ref #f 'values) vals))))))
1107 (($ <application> src (and apply ($ <primitive-ref> _ (or 'apply '@apply)))
1108 (proc args ... tail))
1109 (match (for-value tail)
1110 (($ <const> _ (args* ...))
1111 (let ((args* (map (lambda (x) (make-const #f x)) args*)))
1112 (for-tail (make-application src proc (append args args*)))))
1113 (($ <application> _ ($ <primitive-ref> _ 'list) args*)
1114 (for-tail (make-application src proc (append args args*))))
1116 (let ((args (append (map for-value args) (list tail))))
1117 (make-application src apply (cons (for-value proc) args))))))
1118 (($ <application> src orig-proc orig-args)
1119 ;; todo: augment the global env with specialized functions
1120 (let ((proc (visit orig-proc 'operator)))
1122 (($ <primitive-ref> _ (? constructor-primitive? name))
1124 ((and (memq ctx '(effect test))
1125 (match (cons name orig-args)
1130 ('make-prompt-tag ($ <const> _ (? string?))))
1133 ;; Some expressions can be folded without visiting the
1134 ;; arguments for value.
1135 (let ((res (if (eq? ctx 'effect)
1137 (make-const #f #t))))
1138 (for-tail (make-sequence src (append orig-args (list res))))))
1140 (match (cons name (map for-value orig-args))
1143 (($ <const> src (? (cut eq? <> '())))
1144 (make-application src (make-primitive-ref #f 'list)
1146 (($ <application> src ($ <primitive-ref> _ 'list) elts)
1147 (make-application src (make-primitive-ref #f 'list)
1149 (_ (make-application src proc (list head tail)))))
1151 (make-application src proc args))))))
1152 (($ <primitive-ref> _ (? accessor-primitive? name))
1153 (match (cons name (map for-value orig-args))
1154 ;; FIXME: these for-tail recursions could take place outside
1155 ;; an effort counter.
1156 (('car ($ <application> src ($ <primitive-ref> _ 'cons) (head tail)))
1157 (for-tail (make-sequence src (list tail head))))
1158 (('cdr ($ <application> src ($ <primitive-ref> _ 'cons) (head tail)))
1159 (for-tail (make-sequence src (list head tail))))
1160 (('car ($ <application> src ($ <primitive-ref> _ 'list) (head . tail)))
1161 (for-tail (make-sequence src (append tail (list head)))))
1162 (('cdr ($ <application> src ($ <primitive-ref> _ 'list) (head . tail)))
1163 (for-tail (make-sequence
1167 src (make-primitive-ref #f 'list) tail)))))
1169 (('car ($ <const> src (head . tail)))
1170 (for-tail (make-const src head)))
1171 (('cdr ($ <const> src (head . tail)))
1172 (for-tail (make-const src tail)))
1173 (((or 'memq 'memv) k ($ <const> _ (elts ...)))
1178 (make-sequence src (list k (make-void #f)))))
1182 ;; A shortcut. The `else' case would handle it, but
1183 ;; this way is faster.
1184 (let ((member (case name ((memq) memq) ((memv) memv))))
1185 (make-const #f (and (member (const-exp k) elts) #t))))
1188 (make-sequence src (list k (make-const #f #f)))))
1190 (let ((t (gensym "t-"))
1191 (eq (if (eq? name 'memq) 'eq? 'eqv?)))
1192 (record-new-temporary! 't t (length elts))
1195 src (list 't) (list t) (list k)
1196 (let lp ((elts elts))
1199 #f (make-primitive-ref #f eq)
1200 (list (make-lexical-ref #f 't t)
1201 (make-const #f (car elts)))))
1202 (if (null? (cdr elts))
1204 (make-conditional src test
1206 (lp (cdr elts)))))))))))
1210 (let ((member (case name ((memq) memq) ((memv) memv))))
1211 (make-const #f (member (const-exp k) elts))))
1213 (for-tail (make-sequence src (list k (make-const #f #f)))))
1215 (make-application src proc (list k (make-const #f elts))))))))
1217 (or (fold-constants src name args ctx)
1218 (make-application src proc args)))))
1219 (($ <primitive-ref> _ (? effect-free-primitive? name))
1220 (let ((args (map for-value orig-args)))
1221 (or (fold-constants src name args ctx)
1222 (make-application src proc args))))
1224 ($ <lambda-case> _ req opt #f #f inits gensyms body #f))
1225 ;; Simple case: no rest, no keyword arguments.
1226 ;; todo: handle the more complex cases
1227 (let* ((nargs (length orig-args))
1229 (nopt (if opt (length opt) 0))
1230 (key (source-expression proc)))
1232 ((or (< nargs nreq) (> nargs (+ nreq nopt)))
1233 ;; An error, or effecting arguments.
1234 (make-application src (for-call orig-proc)
1235 (map for-value orig-args)))
1236 ((or (and=> (find-counter key counter) counter-recursive?)
1237 (lambda? orig-proc))
1238 ;; A recursive call, or a lambda in the operator
1239 ;; position of the source expression. Process again in
1242 ;; In the recursive case, mark intervening counters as
1243 ;; recursive, so we can handle a toplevel counter that
1244 ;; recurses mutually with some other procedure.
1245 ;; Otherwise, the next time we see the other procedure,
1246 ;; the effort limit would be clamped to 100.
1248 (let ((found (find-counter key counter)))
1249 (if (and found (counter-recursive? found))
1250 (let lp ((counter counter))
1251 (if (not (eq? counter found))
1253 (set-counter-recursive?! counter #t)
1254 (lp (counter-prev counter)))))))
1256 (log 'inline-recurse key)
1257 (loop (make-let src (append req (or opt '()))
1260 (drop inits (- nargs nreq)))
1264 ;; An integration at the top-level, the first
1265 ;; recursion of a recursive procedure, or a nested
1266 ;; integration of a procedure that hasn't been seen
1268 (log 'inline-begin exp)
1271 (log 'inline-abort exp)
1272 (k (make-application src (for-call orig-proc)
1273 (map for-value orig-args))))
1276 ;; These first two cases will transfer effort
1277 ;; from the current counter into the new
1279 ((find-counter key counter)
1281 (make-recursive-counter recursive-effort-limit
1285 (make-nested-counter abort key counter))
1286 ;; This case opens a new account, effectively
1287 ;; printing money. It should only do so once
1288 ;; for each call site in the source program.
1290 (make-top-counter effort-limit operand-size-limit
1293 (loop (make-let src (append req (or opt '()))
1296 (drop inits (- nargs nreq)))
1298 env new-counter ctx))
1301 ;; The nested inlining attempt succeeded.
1302 ;; Deposit the unspent effort and size back
1303 ;; into the current counter.
1304 (transfer! new-counter counter))
1306 (log 'inline-end result exp)
1309 (make-application src (for-call orig-proc)
1310 (map for-value orig-args))))))
1311 (($ <lambda> src meta body)
1313 ((effect) (make-void #f))
1314 ((test) (make-const #f #t))
1316 (else (record-source-expression!
1318 (make-lambda src meta (for-values body))))))
1319 (($ <lambda-case> src req opt rest kw inits gensyms body alt)
1320 (define (lift-applied-lambda body gensyms)
1321 (and (not opt) rest (not kw)
1324 ($ <primitive-ref> _ '@apply)
1325 (($ <lambda> _ _ lcase)
1326 ($ <lexical-ref> _ _ sym)
1328 (and (equal? sym gensyms)
1329 (not (lambda-case-alternate lcase))
1332 (let* ((vars (map lookup-var gensyms))
1333 (new (fresh-gensyms vars))
1334 (env (fold extend-env env gensyms
1335 (make-unbound-operands vars new)))
1336 (new-sym (lambda (old)
1337 (operand-sym (cdr (vhash-assq old env)))))
1338 (body (loop body env counter ctx)))
1340 ;; (lambda args (apply (lambda ...) args)) => (lambda ...)
1341 (lift-applied-lambda body new)
1342 (make-lambda-case src req opt rest
1344 ((aok? (kw name old) ...)
1345 (cons aok? (map list kw name (map new-sym old))))
1347 (map (cut loop <> env counter 'value) inits)
1350 (and alt (for-tail alt))))))
1351 (($ <sequence> src exps)
1352 (let lp ((exps exps) (effects '()))
1359 (reverse (cons (for-tail last) effects)))))
1361 (let ((head (for-effect head)))
1364 (lp (append (sequence-exps head) rest) effects))
1368 (lp rest (cons head effects)))))))))
1369 (($ <prompt> src tag body handler)
1370 (define (make-prompt-tag? x)
1372 (($ <application> _ ($ <primitive-ref> _ 'make-prompt-tag)
1373 (or () ((? constant-expression?))))
1376 (define (find-definition x n-aliases)
1380 ((lookup (lexical-ref-gensym x))
1382 (let ((y (or (operand-residual-value op)
1383 (visit-operand op counter 'value 10 10))))
1385 ((and (lexical-ref? y)
1386 (= (lexical-refcount (lexical-ref-gensym x)) 1))
1387 ;; X is a simple alias for Y. Recurse, regardless of
1388 ;; the number of aliases we were expecting.
1389 (find-definition y n-aliases))
1390 ((= (lexical-refcount (lexical-ref-gensym x)) n-aliases)
1391 ;; We found a definition that is aliased the right
1392 ;; number of times. We still recurse in case it is a
1394 (values (find-definition y 1)
1397 ;; We can't account for our aliases.
1400 ;; A formal parameter. Can't say anything about that.
1403 ;; Not a lexical: success, but only if we are looking for an
1406 (else (values #f #f))))
1408 (let ((tag (for-value tag))
1409 (body (for-tail body)))
1411 ((find-definition tag 1)
1413 (make-prompt-tag? val))
1415 ;; There is no way that an <abort> could know the tag
1416 ;; for this <prompt>, so we can elide the <prompt>
1418 (unrecord-operand-uses op 1)
1420 ((find-definition tag 2)
1422 (and (make-prompt-tag? val)
1424 (tree-il=? (abort-tag body) tag)))
1426 ;; (let ((t (make-prompt-tag)))
1427 ;; (call-with-prompt t
1428 ;; (lambda () (abort-to-prompt t val ...))
1429 ;; (lambda (k arg ...) e ...)))
1430 ;; => (let-values (((k arg ...) (values values val ...)))
1432 (unrecord-operand-uses op 2)
1436 (make-application #f (make-primitive-ref #f 'apply)
1437 `(,(make-primitive-ref #f 'values)
1438 ,(make-primitive-ref #f 'values)
1440 ,(abort-tail body)))
1441 (for-value handler)))))
1443 (make-prompt src tag body (for-value handler))))))
1444 (($ <abort> src tag args tail)
1445 (make-abort src (for-value tag) (map for-value args)
1446 (for-value tail))))))