fold constants with accessors
[bpt/guile.git] / module / language / tree-il / peval.scm
1 ;;; Tree-IL partial evaluator
2
3 ;; Copyright (C) 2011 Free Software Foundation, Inc.
4
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.
9 ;;;;
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.
14 ;;;;
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
18
19 (define-module (language tree-il peval)
20 #:use-module (language tree-il)
21 #:use-module (language tree-il primitives)
22 #:use-module (ice-9 vlist)
23 #:use-module (ice-9 match)
24 #:use-module (srfi srfi-1)
25 #:use-module (srfi srfi-9)
26 #:use-module (srfi srfi-11)
27 #:use-module (srfi srfi-26)
28 #:export (peval))
29
30 ;;;
31 ;;; Partial evaluation is Guile's most important source-to-source
32 ;;; optimization pass. It performs copy propagation, dead code
33 ;;; elimination, inlining, and constant folding, all while preserving
34 ;;; the order of effects in the residual program.
35 ;;;
36 ;;; For more on partial evaluation, see William Cook’s excellent
37 ;;; tutorial on partial evaluation at DSL 2011, called “Build your own
38 ;;; partial evaluator in 90 minutes”[0].
39 ;;;
40 ;;; Our implementation of this algorithm was heavily influenced by
41 ;;; Waddell and Dybvig's paper, "Fast and Effective Procedure Inlining",
42 ;;; IU CS Dept. TR 484.
43 ;;;
44 ;;; [0] http://www.cs.utexas.edu/~wcook/tutorial/.
45 ;;;
46
47 ;; First, some helpers.
48 ;;
49 (define-syntax *logging* (identifier-syntax #f))
50
51 ;; For efficiency we define *logging* to inline to #f, so that the call
52 ;; to log* gets optimized out. If you want to log, uncomment these
53 ;; lines:
54 ;;
55 ;; (define %logging #f)
56 ;; (define-syntax *logging* (identifier-syntax %logging))
57 ;;
58 ;; Then you can change %logging at runtime.
59
60 (define-syntax log
61 (syntax-rules (quote)
62 ((log 'event arg ...)
63 (if (and *logging*
64 (or (eq? *logging* #t)
65 (memq 'event *logging*)))
66 (log* 'event arg ...)))))
67
68 (define (log* event . args)
69 (let ((pp (module-ref (resolve-interface '(ice-9 pretty-print))
70 'pretty-print)))
71 (pp `(log ,event . ,args))
72 (newline)
73 (values)))
74
75 (define-syntax-rule (let/ec k e e* ...)
76 (let ((tag (make-prompt-tag)))
77 (call-with-prompt
78 tag
79 (lambda ()
80 (let ((k (lambda args (apply abort-to-prompt tag args))))
81 e e* ...))
82 (lambda (_ res) res))))
83
84 (define (tree-il-any proc exp)
85 (let/ec k
86 (tree-il-fold (lambda (exp res)
87 (let ((res (proc exp)))
88 (if res (k res) #f)))
89 (lambda (exp res)
90 (let ((res (proc exp)))
91 (if res (k res) #f)))
92 (lambda (exp res) #f)
93 #f exp)))
94
95 (define (vlist-any proc vlist)
96 (let ((len (vlist-length vlist)))
97 (let lp ((i 0))
98 (and (< i len)
99 (or (proc (vlist-ref vlist i))
100 (lp (1+ i)))))))
101
102 ;; Peval will do a one-pass analysis on the source program to determine
103 ;; the set of assigned lexicals, and to identify unreferenced and
104 ;; singly-referenced lexicals.
105 ;;
106 (define-record-type <var>
107 (make-var name gensym refcount set?)
108 var?
109 (name var-name)
110 (gensym var-gensym)
111 (refcount var-refcount set-var-refcount!)
112 (set? var-set? set-var-set?!))
113
114 (define* (build-var-table exp #:optional (table vlist-null))
115 (tree-il-fold
116 (lambda (exp res)
117 (match exp
118 (($ <lexical-ref> src name gensym)
119 (let ((var (cdr (vhash-assq gensym res))))
120 (set-var-refcount! var (1+ (var-refcount var)))
121 res))
122 (_ res)))
123 (lambda (exp res)
124 (match exp
125 (($ <lambda-case> src req opt rest kw init gensyms body alt)
126 (fold (lambda (name sym res)
127 (vhash-consq sym (make-var name sym 0 #f) res))
128 res
129 (append req (or opt '()) (if rest (list rest) '())
130 (match kw
131 ((aok? (kw name sym) ...) name)
132 (_ '())))
133 gensyms))
134 (($ <let> src names gensyms vals body)
135 (fold (lambda (name sym res)
136 (vhash-consq sym (make-var name sym 0 #f) res))
137 res names gensyms))
138 (($ <letrec> src in-order? names gensyms vals body)
139 (fold (lambda (name sym res)
140 (vhash-consq sym (make-var name sym 0 #f) res))
141 res names gensyms))
142 (($ <fix> src names gensyms vals body)
143 (fold (lambda (name sym res)
144 (vhash-consq sym (make-var name sym 0 #f) res))
145 res names gensyms))
146 (($ <lexical-set> src name gensym exp)
147 (set-var-set?! (cdr (vhash-assq gensym res)) #t)
148 res)
149 (_ res)))
150 (lambda (exp res) res)
151 table exp))
152
153 ;; Counters are data structures used to limit the effort that peval
154 ;; spends on particular inlining attempts. Each call site in the source
155 ;; program is allocated some amount of effort. If peval exceeds the
156 ;; effort counter while attempting to inline a call site, it aborts the
157 ;; inlining attempt and residualizes a call instead.
158 ;;
159 ;; As there is a fixed number of call sites, that makes `peval' O(N) in
160 ;; the number of call sites in the source program.
161 ;;
162 ;; Counters should limit the size of the residual program as well, but
163 ;; currently this is not implemented.
164 ;;
165 ;; At the top level, before seeing any peval call, there is no counter,
166 ;; because inlining will terminate as there is no recursion. When peval
167 ;; sees a call at the top level, it will make a new counter, allocating
168 ;; it some amount of effort and size.
169 ;;
170 ;; This top-level effort counter effectively "prints money". Within a
171 ;; toplevel counter, no more effort is printed ex nihilo; for a nested
172 ;; inlining attempt to proceed, effort must be transferred from the
173 ;; toplevel counter to the nested counter.
174 ;;
175 ;; Via `data' and `prev', counters form a linked list, terminating in a
176 ;; toplevel counter. In practice `data' will be the a pointer to the
177 ;; source expression of the procedure being inlined.
178 ;;
179 ;; In this way peval can detect a recursive inlining attempt, by walking
180 ;; back on the `prev' links looking for matching `data'. Recursive
181 ;; counters receive a more limited effort allocation, as we don't want
182 ;; to spend all of the effort for a toplevel inlining site on loops.
183 ;; Also, recursive counters don't need a prompt at each inlining site:
184 ;; either the call chain folds entirely, or it will be residualized at
185 ;; its original call.
186 ;;
187 (define-record-type <counter>
188 (%make-counter effort size continuation recursive? data prev)
189 counter?
190 (effort effort-counter)
191 (size size-counter)
192 (continuation counter-continuation)
193 (recursive? counter-recursive? set-counter-recursive?!)
194 (data counter-data)
195 (prev counter-prev))
196
197 (define (abort-counter c)
198 ((counter-continuation c)))
199
200 (define (record-effort! c)
201 (let ((e (effort-counter c)))
202 (if (zero? (variable-ref e))
203 (abort-counter c)
204 (variable-set! e (1- (variable-ref e))))))
205
206 (define (record-size! c)
207 (let ((s (size-counter c)))
208 (if (zero? (variable-ref s))
209 (abort-counter c)
210 (variable-set! s (1- (variable-ref s))))))
211
212 (define (find-counter data counter)
213 (and counter
214 (if (eq? data (counter-data counter))
215 counter
216 (find-counter data (counter-prev counter)))))
217
218 (define* (transfer! from to #:optional
219 (effort (variable-ref (effort-counter from)))
220 (size (variable-ref (size-counter from))))
221 (define (transfer-counter! from-v to-v amount)
222 (let* ((from-balance (variable-ref from-v))
223 (to-balance (variable-ref to-v))
224 (amount (min amount from-balance)))
225 (variable-set! from-v (- from-balance amount))
226 (variable-set! to-v (+ to-balance amount))))
227
228 (transfer-counter! (effort-counter from) (effort-counter to) effort)
229 (transfer-counter! (size-counter from) (size-counter to) size))
230
231 (define (make-top-counter effort-limit size-limit continuation data)
232 (%make-counter (make-variable effort-limit)
233 (make-variable size-limit)
234 continuation
235 #t
236 data
237 #f))
238
239 (define (make-nested-counter continuation data current)
240 (let ((c (%make-counter (make-variable 0)
241 (make-variable 0)
242 continuation
243 #f
244 data
245 current)))
246 (transfer! current c)
247 c))
248
249 (define (make-recursive-counter effort-limit size-limit orig current)
250 (let ((c (%make-counter (make-variable 0)
251 (make-variable 0)
252 (counter-continuation orig)
253 #t
254 (counter-data orig)
255 current)))
256 (transfer! current c effort-limit size-limit)
257 c))
258
259 ;; Operand structures allow bindings to be processed lazily instead of
260 ;; eagerly. By doing so, hopefully we can get process them in a way
261 ;; appropriate to their use contexts. Operands also prevent values from
262 ;; being visited multiple times, wasting effort.
263 ;;
264 ;; TODO: Record value size in operand structure?
265 ;;
266 (define-record-type <operand>
267 (%make-operand var sym visit source visit-count residualize?
268 copyable? residual-value constant-value)
269 operand?
270 (var operand-var)
271 (sym operand-sym)
272 (visit %operand-visit)
273 (source operand-source)
274 (visit-count operand-visit-count set-operand-visit-count!)
275 (residualize? operand-residualize? set-operand-residualize?!)
276 (copyable? operand-copyable? set-operand-copyable?!)
277 (residual-value operand-residual-value set-operand-residual-value!)
278 (constant-value operand-constant-value set-operand-constant-value!))
279
280 (define* (make-operand var sym #:optional source visit)
281 ;; Bound operands are considered copyable until we prove otherwise.
282 (%make-operand var sym visit source 0 #f (and source #t) #f #f))
283
284 (define (make-bound-operands vars syms sources visit)
285 (map (lambda (x y z) (make-operand x y z visit)) vars syms sources))
286
287 (define (make-unbound-operands vars syms)
288 (map make-operand vars syms))
289
290 (define* (visit-operand op counter ctx #:optional effort-limit size-limit)
291 ;; Peval is O(N) in call sites of the source program. However,
292 ;; visiting an operand can introduce new call sites. If we visit an
293 ;; operand outside a counter -- i.e., outside an inlining attempt --
294 ;; this can lead to divergence. So, if we are visiting an operand to
295 ;; try to copy it, and there is no counter, make a new one.
296 ;;
297 ;; This will only happen at most as many times as there are lexical
298 ;; references in the source program.
299 (and (zero? (operand-visit-count op))
300 (dynamic-wind
301 (lambda ()
302 (set-operand-visit-count! op (1+ (operand-visit-count op))))
303 (lambda ()
304 (and (operand-source op)
305 (if (or counter (and (not effort-limit) (not size-limit)))
306 ((%operand-visit op) (operand-source op) counter ctx)
307 (let/ec k
308 (define (abort) (k #f))
309 ((%operand-visit op)
310 (operand-source op)
311 (make-top-counter effort-limit size-limit abort op)
312 ctx)))))
313 (lambda ()
314 (set-operand-visit-count! op (1- (operand-visit-count op)))))))
315
316 ;; A helper for constant folding.
317 ;;
318 (define (types-check? primitive-name args)
319 (case primitive-name
320 ((values) #t)
321 ((not pair? null? list? symbol? vector? struct?)
322 (= (length args) 1))
323 ((eq? eqv? equal?)
324 (= (length args) 2))
325 ;; FIXME: add more cases?
326 (else #f)))
327
328 (define* (peval exp #:optional (cenv (current-module)) (env vlist-null)
329 #:key
330 (operator-size-limit 40)
331 (operand-size-limit 20)
332 (value-size-limit 10)
333 (effort-limit 500)
334 (recursive-effort-limit 100))
335 "Partially evaluate EXP in compilation environment CENV, with
336 top-level bindings from ENV and return the resulting expression."
337
338 ;; This is a simple partial evaluator. It effectively performs
339 ;; constant folding, copy propagation, dead code elimination, and
340 ;; inlining.
341
342 ;; TODO:
343 ;;
344 ;; Propagate copies across toplevel bindings, if we can prove the
345 ;; bindings to be immutable.
346 ;;
347 ;; Specialize lambda expressions with invariant arguments.
348
349 (define local-toplevel-env
350 ;; The top-level environment of the module being compiled.
351 (match exp
352 (($ <toplevel-define> _ name)
353 (vhash-consq name #t env))
354 (($ <sequence> _ exps)
355 (fold (lambda (x r)
356 (match x
357 (($ <toplevel-define> _ name)
358 (vhash-consq name #t r))
359 (_ r)))
360 env
361 exps))
362 (_ env)))
363
364 (define (local-toplevel? name)
365 (vhash-assq name local-toplevel-env))
366
367 ;; gensym -> <var>
368 ;; renamed-term -> original-term
369 ;;
370 (define store (build-var-table exp))
371
372 (define (record-new-temporary! name sym refcount)
373 (set! store (vhash-consq sym (make-var name sym refcount #f) store)))
374
375 (define (lookup-var sym)
376 (let ((v (vhash-assq sym store)))
377 (if v (cdr v) (error "unbound var" sym (vlist->list store)))))
378
379 (define (fresh-gensyms vars)
380 (map (lambda (var)
381 (let ((new (gensym (string-append (symbol->string (var-name var))
382 " "))))
383 (set! store (vhash-consq new var store))
384 new))
385 vars))
386
387 (define (assigned-lexical? sym)
388 (var-set? (lookup-var sym)))
389
390 (define (lexical-refcount sym)
391 (var-refcount (lookup-var sym)))
392
393 ;; ORIG has been alpha-renamed to NEW. Analyze NEW and record a link
394 ;; from it to ORIG.
395 ;;
396 (define (record-source-expression! orig new)
397 (set! store (vhash-consq new (source-expression orig) store))
398 new)
399
400 ;; Find the source expression corresponding to NEW. Used to detect
401 ;; recursive inlining attempts.
402 ;;
403 (define (source-expression new)
404 (let ((x (vhash-assq new store)))
405 (if x (cdr x) new)))
406
407 (define* (residualize-lexical op #:optional ctx val)
408 (log 'residualize op)
409 (set-operand-residualize?! op #t)
410 (if (eq? ctx 'value)
411 (set-operand-residual-value! op val))
412 (make-lexical-ref #f (var-name (operand-var op)) (operand-sym op)))
413
414 (define (apply-primitive name args)
415 ;; todo: further optimize commutative primitives
416 (catch #t
417 (lambda ()
418 (call-with-values
419 (lambda ()
420 (apply (module-ref the-scm-module name) args))
421 (lambda results
422 (values #t results))))
423 (lambda _
424 (values #f '()))))
425
426 (define (make-values src values)
427 (match values
428 ((single) single) ; 1 value
429 ((_ ...) ; 0, or 2 or more values
430 (make-application src (make-primitive-ref src 'values)
431 values))))
432
433 (define (fold-constants src name args ctx)
434 (define (residualize-call)
435 (make-application src (make-primitive-ref #f name) args))
436 (cond
437 ((every const? args)
438 (let-values (((success? values)
439 (apply-primitive name (map const-exp args))))
440 (log 'fold success? values name args)
441 (if success?
442 (case ctx
443 ((effect) (make-void src))
444 ((test)
445 ;; Values truncation: only take the first
446 ;; value.
447 (if (pair? values)
448 (make-const src (car values))
449 (make-values src '())))
450 (else
451 (make-values src (map (cut make-const src <>) values))))
452 (residualize-call))))
453 ((and (eq? ctx 'effect) (types-check? name args))
454 (make-void #f))
455 (else
456 (residualize-call))))
457
458 (define (inline-values exp src names gensyms body)
459 (let loop ((exp exp))
460 (match exp
461 ;; Some expression types are always singly-valued.
462 ((or ($ <const>)
463 ($ <void>)
464 ($ <lambda>)
465 ($ <lexical-ref>)
466 ($ <toplevel-ref>)
467 ($ <module-ref>)
468 ($ <primitive-ref>)
469 ($ <dynref>)
470 ($ <lexical-set>) ; FIXME: these set! expressions
471 ($ <toplevel-set>) ; could return zero values in
472 ($ <toplevel-define>) ; the future
473 ($ <module-set>) ;
474 ($ <dynset>)) ;
475 (and (= (length names) 1)
476 (make-let src names gensyms (list exp) body)))
477 (($ <application> src
478 ($ <primitive-ref> _ (? singly-valued-primitive? name)))
479 (and (= (length names) 1)
480 (make-let src names gensyms (list exp) body)))
481
482 ;; Statically-known number of values.
483 (($ <application> src ($ <primitive-ref> _ 'values) vals)
484 (and (= (length names) (length vals))
485 (make-let src names gensyms vals body)))
486
487 ;; Not going to copy code into both branches.
488 (($ <conditional>) #f)
489
490 ;; Bail on other applications.
491 (($ <application>) #f)
492
493 ;; Bail on prompt and abort.
494 (($ <prompt>) #f)
495 (($ <abort>) #f)
496
497 ;; Propagate to tail positions.
498 (($ <let> src names gensyms vals body)
499 (let ((body (loop body)))
500 (and body
501 (make-let src names gensyms vals body))))
502 (($ <letrec> src in-order? names gensyms vals body)
503 (let ((body (loop body)))
504 (and body
505 (make-letrec src in-order? names gensyms vals body))))
506 (($ <fix> src names gensyms vals body)
507 (let ((body (loop body)))
508 (and body
509 (make-fix src names gensyms vals body))))
510 (($ <let-values> src exp
511 ($ <lambda-case> src2 req opt rest kw inits gensyms body #f))
512 (let ((body (loop body)))
513 (and body
514 (make-let-values src exp
515 (make-lambda-case src2 req opt rest kw
516 inits gensyms body #f)))))
517 (($ <dynwind> src winder body unwinder)
518 (let ((body (loop body)))
519 (and body
520 (make-dynwind src winder body unwinder))))
521 (($ <dynlet> src fluids vals body)
522 (let ((body (loop body)))
523 (and body
524 (make-dynlet src fluids vals body))))
525 (($ <sequence> src exps)
526 (match exps
527 ((head ... tail)
528 (let ((tail (loop tail)))
529 (and tail
530 (make-sequence src (append head (list tail)))))))))))
531
532 (define (constant-expression? x)
533 ;; Return true if X is constant---i.e., if it is known to have no
534 ;; effects, does not allocate storage for a mutable object, and does
535 ;; not access mutable data (like `car' or toplevel references).
536 (let loop ((x x))
537 (match x
538 (($ <void>) #t)
539 (($ <const>) #t)
540 (($ <lambda>) #t)
541 (($ <lambda-case> _ req opt rest kw inits _ body alternate)
542 (and (every loop inits) (loop body)
543 (or (not alternate) (loop alternate))))
544 (($ <lexical-ref> _ _ gensym)
545 (not (assigned-lexical? gensym)))
546 (($ <primitive-ref>) #t)
547 (($ <conditional> _ condition subsequent alternate)
548 (and (loop condition) (loop subsequent) (loop alternate)))
549 (($ <application> _ ($ <primitive-ref> _ name) args)
550 (and (effect-free-primitive? name)
551 (not (constructor-primitive? name))
552 (not (accessor-primitive? name))
553 (types-check? name args)
554 (every loop args)))
555 (($ <application> _ ($ <lambda> _ _ body) args)
556 (and (loop body) (every loop args)))
557 (($ <sequence> _ exps)
558 (every loop exps))
559 (($ <let> _ _ _ vals body)
560 (and (every loop vals) (loop body)))
561 (($ <letrec> _ _ _ _ vals body)
562 (and (every loop vals) (loop body)))
563 (($ <fix> _ _ _ vals body)
564 (and (every loop vals) (loop body)))
565 (($ <let-values> _ exp body)
566 (and (loop exp) (loop body)))
567 (($ <prompt> _ tag body handler)
568 (and (loop tag) (loop body) (loop handler)))
569 (_ #f))))
570
571 (define (prune-bindings ops in-order? body counter ctx build-result)
572 ;; This helper handles both `let' and `letrec'/`fix'. In the latter
573 ;; cases we need to make sure that if referenced binding A needs
574 ;; as-yet-unreferenced binding B, that B is processed for value.
575 ;; Likewise if C, when processed for effect, needs otherwise
576 ;; unreferenced D, then D needs to be processed for value too.
577 ;;
578 (define (referenced? op)
579 ;; When we visit lambdas in operator context, we just copy them,
580 ;; as we will process their body later. However this does have
581 ;; the problem that any free var referenced by the lambda is not
582 ;; marked as needing residualization. Here we hack around this
583 ;; and treat all bindings as referenced if we are in operator
584 ;; context.
585 (or (eq? ctx 'operator) (operand-residualize? op)))
586
587 ;; values := (op ...)
588 ;; effects := (op ...)
589 (define (residualize values effects)
590 ;; Note, values and effects are reversed.
591 (cond
592 (in-order?
593 (let ((values (filter operand-residual-value ops)))
594 (if (null? values)
595 body
596 (build-result (map (compose var-name operand-var) values)
597 (map operand-sym values)
598 (map operand-residual-value values)
599 body))))
600 (else
601 (let ((body
602 (if (null? effects)
603 body
604 (let ((effect-vals (map operand-residual-value effects)))
605 (make-sequence #f (reverse (cons body effect-vals)))))))
606 (if (null? values)
607 body
608 (let ((values (reverse values)))
609 (build-result (map (compose var-name operand-var) values)
610 (map operand-sym values)
611 (map operand-residual-value values)
612 body)))))))
613
614 ;; old := (bool ...)
615 ;; values := (op ...)
616 ;; effects := ((op . value) ...)
617 (let prune ((old (map referenced? ops)) (values '()) (effects '()))
618 (let lp ((ops* ops) (values values) (effects effects))
619 (cond
620 ((null? ops*)
621 (let ((new (map referenced? ops)))
622 (if (not (equal? new old))
623 (prune new values '())
624 (residualize values
625 (map (lambda (op val)
626 (set-operand-residual-value! op val)
627 op)
628 (map car effects) (map cdr effects))))))
629 (else
630 (let ((op (car ops*)))
631 (cond
632 ((memq op values)
633 (lp (cdr ops*) values effects))
634 ((operand-residual-value op)
635 (lp (cdr ops*) (cons op values) effects))
636 ((referenced? op)
637 (set-operand-residual-value! op (visit-operand op counter 'value))
638 (lp (cdr ops*) (cons op values) effects))
639 (else
640 (lp (cdr ops*)
641 values
642 (let ((effect (visit-operand op counter 'effect)))
643 (if (void? effect)
644 effects
645 (acons op effect effects))))))))))))
646
647 (define (small-expression? x limit)
648 (let/ec k
649 (tree-il-fold
650 (lambda (x res) ; leaf
651 (1+ res))
652 (lambda (x res) ; down
653 (1+ res))
654 (lambda (x res) ; up
655 (if (< res limit)
656 res
657 (k #f)))
658 0 x)
659 #t))
660
661 (define (extend-env sym op env)
662 (vhash-consq (operand-sym op) op (vhash-consq sym op env)))
663
664 (let loop ((exp exp)
665 (env vlist-null) ; vhash of gensym -> <operand>
666 (counter #f) ; inlined call stack
667 (ctx 'value)) ; effect, value, test, operator, or call
668 (define (lookup var)
669 (cond
670 ((vhash-assq var env) => cdr)
671 (else (error "unbound var" var))))
672
673 (define (visit exp ctx)
674 (loop exp env counter ctx))
675
676 (define (for-value exp) (visit exp 'value))
677 (define (for-test exp) (visit exp 'test))
678 (define (for-effect exp) (visit exp 'effect))
679 (define (for-call exp) (visit exp 'call))
680 (define (for-tail exp) (visit exp ctx))
681
682 (if counter
683 (record-effort! counter))
684
685 (log 'visit ctx (and=> counter effort-counter)
686 (unparse-tree-il exp))
687
688 (match exp
689 (($ <const>)
690 (case ctx
691 ((effect) (make-void #f))
692 (else exp)))
693 (($ <void>)
694 (case ctx
695 ((test) (make-const #f #t))
696 (else exp)))
697 (($ <lexical-ref> _ _ gensym)
698 (log 'begin-copy gensym)
699 (let ((op (lookup gensym)))
700 (cond
701 ((eq? ctx 'effect)
702 (log 'lexical-for-effect gensym)
703 (make-void #f))
704 ((eq? ctx 'call)
705 ;; Don't propagate copies if we are residualizing a call.
706 (log 'residualize-lexical-call gensym op)
707 (residualize-lexical op))
708 ((var-set? (operand-var op))
709 ;; Assigned lexicals don't copy-propagate.
710 (log 'assigned-var gensym op)
711 (residualize-lexical op))
712 ((not (operand-copyable? op))
713 ;; We already know that this operand is not copyable.
714 (log 'not-copyable gensym op)
715 (residualize-lexical op))
716 ((and=> (operand-constant-value op)
717 (lambda (x) (or (const? x) (void? x) (primitive-ref? x))))
718 ;; A cache hit.
719 (let ((val (operand-constant-value op)))
720 (log 'memoized-constant gensym val)
721 (for-tail val)))
722 ((visit-operand op counter ctx recursive-effort-limit operand-size-limit)
723 =>
724 ;; If we end up deciding to residualize this value instead of
725 ;; copying it, save that residualized value.
726 (lambda (val)
727 (cond
728 ((not (constant-expression? val))
729 (log 'not-constant gensym op)
730 ;; At this point, ctx is operator, test, or value. A
731 ;; value that is non-constant in one context will be
732 ;; non-constant in the others, so it's safe to record
733 ;; that here, and avoid future visits.
734 (set-operand-copyable?! op #f)
735 (residualize-lexical op ctx val))
736 ((or (const? val)
737 (void? val)
738 (primitive-ref? val))
739 ;; Always propagate simple values that cannot lead to
740 ;; code bloat.
741 (log 'copy-simple gensym val)
742 ;; It could be this constant is the result of folding.
743 ;; If that is the case, cache it. This helps loop
744 ;; unrolling get farther.
745 (if (eq? ctx 'value)
746 (begin
747 (log 'memoize-constant gensym val)
748 (set-operand-constant-value! op val)))
749 val)
750 ((= 1 (var-refcount (operand-var op)))
751 ;; Always propagate values referenced only once.
752 (log 'copy-single gensym val)
753 val)
754 ;; FIXME: do demand-driven size accounting rather than
755 ;; these heuristics.
756 ((eq? ctx 'operator)
757 ;; A pure expression in the operator position. Inline
758 ;; if it's a lambda that's small enough.
759 (if (and (lambda? val)
760 (small-expression? val operator-size-limit))
761 (begin
762 (log 'copy-operator gensym val)
763 val)
764 (begin
765 (log 'too-big-for-operator gensym val)
766 (residualize-lexical op ctx val))))
767 (else
768 ;; A pure expression, processed for call or for value.
769 ;; Don't inline lambdas, because they will probably won't
770 ;; fold because we don't know the operator.
771 (if (and (small-expression? val value-size-limit)
772 (not (tree-il-any lambda? val)))
773 (begin
774 (log 'copy-value gensym val)
775 val)
776 (begin
777 (log 'too-big-or-has-lambda gensym val)
778 (residualize-lexical op ctx val)))))))
779 (else
780 ;; Visit failed. Either the operand isn't bound, as in
781 ;; lambda formal parameters, or the copy was aborted.
782 (log 'unbound-or-aborted gensym op)
783 (residualize-lexical op)))))
784 (($ <lexical-set> src name gensym exp)
785 (let ((op (lookup gensym)))
786 (if (zero? (var-refcount (operand-var op)))
787 (let ((exp (for-effect exp)))
788 (if (void? exp)
789 exp
790 (make-sequence src (list exp (make-void #f)))))
791 (begin
792 (set-operand-residualize?! op #t)
793 (make-lexical-set src name (operand-sym op) (for-value exp))))))
794 (($ <let> src names gensyms vals body)
795 (let* ((vars (map lookup-var gensyms))
796 (new (fresh-gensyms vars))
797 (ops (make-bound-operands vars new vals
798 (lambda (exp counter ctx)
799 (loop exp env counter ctx))))
800 (env (fold extend-env env gensyms ops))
801 (body (loop body env counter ctx)))
802 (cond
803 ((const? body)
804 (for-tail (make-sequence src (append vals (list body)))))
805 ((and (lexical-ref? body)
806 (memq (lexical-ref-gensym body) new))
807 (let ((sym (lexical-ref-gensym body))
808 (pairs (map cons new vals)))
809 ;; (let ((x foo) (y bar) ...) x) => (begin bar ... foo)
810 (for-tail
811 (make-sequence
812 src
813 (append (map cdr (alist-delete sym pairs eq?))
814 (list (assq-ref pairs sym)))))))
815 (else
816 ;; Only include bindings for which lexical references
817 ;; have been residualized.
818 (prune-bindings ops #f body counter ctx
819 (lambda (names gensyms vals body)
820 (if (null? names) (error "what!" names))
821 (make-let src names gensyms vals body)))))))
822 (($ <letrec> src in-order? names gensyms vals body)
823 ;; Note the difference from the `let' case: here we use letrec*
824 ;; so that the `visit' procedure for the new operands closes over
825 ;; an environment that includes the operands.
826 (letrec* ((visit (lambda (exp counter ctx)
827 (loop exp env* counter ctx)))
828 (vars (map lookup-var gensyms))
829 (new (fresh-gensyms vars))
830 (ops (make-bound-operands vars new vals visit))
831 (env* (fold extend-env env gensyms ops))
832 (body* (visit body counter ctx)))
833 (if (and (const? body*)
834 (every constant-expression? vals))
835 body*
836 (prune-bindings ops in-order? body* counter ctx
837 (lambda (names gensyms vals body)
838 (make-letrec src in-order?
839 names gensyms vals body))))))
840 (($ <fix> src names gensyms vals body)
841 (letrec* ((visit (lambda (exp counter ctx)
842 (loop exp env* counter ctx)))
843 (vars (map lookup-var gensyms))
844 (new (fresh-gensyms vars))
845 (ops (make-bound-operands vars new vals visit))
846 (env* (fold extend-env env gensyms ops))
847 (body* (visit body counter ctx)))
848 (if (const? body*)
849 body*
850 (prune-bindings ops #f body* counter ctx
851 (lambda (names gensyms vals body)
852 (make-fix src names gensyms vals body))))))
853 (($ <let-values> lv-src producer consumer)
854 ;; Peval the producer, then try to inline the consumer into
855 ;; the producer. If that succeeds, peval again. Otherwise
856 ;; reconstruct the let-values, pevaling the consumer.
857 (let ((producer (for-value producer)))
858 (or (match consumer
859 (($ <lambda-case> src req #f #f #f () gensyms body #f)
860 (cond
861 ((inline-values producer src req gensyms body)
862 => for-tail)
863 (else #f)))
864 (_ #f))
865 (make-let-values lv-src producer (for-tail consumer)))))
866 (($ <dynwind> src winder body unwinder)
867 (make-dynwind src (for-value winder) (for-tail body)
868 (for-value unwinder)))
869 (($ <dynlet> src fluids vals body)
870 (make-dynlet src (map for-value fluids) (map for-value vals)
871 (for-tail body)))
872 (($ <dynref> src fluid)
873 (make-dynref src (for-value fluid)))
874 (($ <dynset> src fluid exp)
875 (make-dynset src (for-value fluid) (for-value exp)))
876 (($ <toplevel-ref> src (? effect-free-primitive? name))
877 (if (local-toplevel? name)
878 exp
879 (let ((exp (resolve-primitives! exp cenv)))
880 (if (primitive-ref? exp)
881 (for-tail exp)
882 exp))))
883 (($ <toplevel-ref>)
884 ;; todo: open private local bindings.
885 exp)
886 (($ <module-ref> src module (? effect-free-primitive? name) #f)
887 (let ((module (false-if-exception
888 (resolve-module module #:ensure #f))))
889 (if (module? module)
890 (let ((var (module-variable module name)))
891 (if (eq? var (module-variable the-scm-module name))
892 (make-primitive-ref src name)
893 exp))
894 exp)))
895 (($ <module-ref>)
896 exp)
897 (($ <module-set> src mod name public? exp)
898 (make-module-set src mod name public? (for-value exp)))
899 (($ <toplevel-define> src name exp)
900 (make-toplevel-define src name (for-value exp)))
901 (($ <toplevel-set> src name exp)
902 (make-toplevel-set src name (for-value exp)))
903 (($ <primitive-ref>)
904 (case ctx
905 ((effect) (make-void #f))
906 ((test) (make-const #f #t))
907 (else exp)))
908 (($ <conditional> src condition subsequent alternate)
909 (let ((condition (for-test condition)))
910 (if (const? condition)
911 (if (const-exp condition)
912 (for-tail subsequent)
913 (for-tail alternate))
914 (make-conditional src condition
915 (for-tail subsequent)
916 (for-tail alternate)))))
917 (($ <application> src
918 ($ <primitive-ref> _ '@call-with-values)
919 (producer
920 ($ <lambda> _ _
921 (and consumer
922 ;; No optional or kwargs.
923 ($ <lambda-case>
924 _ req #f rest #f () gensyms body #f)))))
925 (for-tail (make-let-values src (make-application src producer '())
926 consumer)))
927
928 (($ <application> src orig-proc orig-args)
929 ;; todo: augment the global env with specialized functions
930 (let ((proc (visit orig-proc 'operator)))
931 (match proc
932 (($ <primitive-ref> _ (? constructor-primitive? name))
933 (cond
934 ((and (memq ctx '(effect test))
935 (match (cons name orig-args)
936 ((or ('cons _ _)
937 ('list . _)
938 ('vector . _)
939 ('make-prompt-tag)
940 ('make-prompt-tag ($ <const> _ (? string?))))
941 #t)
942 (_ #f)))
943 ;; Some expressions can be folded without visiting the
944 ;; arguments for value.
945 (let ((res (if (eq? ctx 'effect)
946 (make-void #f)
947 (make-const #f #t))))
948 (for-tail (make-sequence src (append orig-args (list res))))))
949 (else
950 (match (cons name (map for-value orig-args))
951 (('cons head tail)
952 (match tail
953 (($ <const> src ())
954 (make-application src (make-primitive-ref #f 'list)
955 (list head)))
956 (($ <application> src ($ <primitive-ref> _ 'list) elts)
957 (make-application src (make-primitive-ref #f 'list)
958 (cons head elts)))
959 (_ (make-application src proc (list head tail)))))
960 ((_ . args)
961 (make-application src proc args))))))
962 (($ <primitive-ref> _ (? accessor-primitive? name))
963 (match (cons name (map for-value orig-args))
964 ;; FIXME: these for-tail recursions could take place outside
965 ;; an effort counter.
966 (('car ($ <application> src ($ <primitive-ref> _ 'cons) (head tail)))
967 (for-tail (make-sequence src (list tail head))))
968 (('cdr ($ <application> src ($ <primitive-ref> _ 'cons) (head tail)))
969 (for-tail (make-sequence src (list head tail))))
970 (('car ($ <application> src ($ <primitive-ref> _ 'list) (head . tail)))
971 (for-tail (make-sequence src (append tail (list head)))))
972 (('cdr ($ <application> src ($ <primitive-ref> _ 'list) (head . tail)))
973 (for-tail (make-sequence
974 src
975 (list head
976 (make-application
977 src (make-primitive-ref #f 'list) tail)))))
978
979 (('car ($ <const> src (head . tail)))
980 (for-tail (make-const src head)))
981 (('cdr ($ <const> src (head . tail)))
982 (for-tail (make-const src tail)))
983 (((or 'memq 'memv) k ($ <const> _ (elts ...)))
984 ;; FIXME: factor
985 (case ctx
986 ((effect)
987 (for-tail
988 (make-sequence src (list k (make-void #f)))))
989 ((test)
990 (cond
991 ((const? k)
992 ;; A shortcut. The `else' case would handle it, but
993 ;; this way is faster.
994 (let ((member (case name ((memq) memq) ((memv) memv))))
995 (make-const #f (and (member (const-exp k) elts) #t))))
996 ((null? elts)
997 (for-tail
998 (make-sequence src (list k (make-const #f #f)))))
999 (else
1000 (let ((t (gensym "t "))
1001 (eq (if (eq? name 'memq) 'eq? 'eqv?)))
1002 (record-new-temporary! 't t (length elts))
1003 (for-tail
1004 (make-let
1005 src (list 't) (list t) (list k)
1006 (let lp ((elts elts))
1007 (define test
1008 (make-application
1009 #f (make-primitive-ref #f eq)
1010 (list (make-lexical-ref #f 't t)
1011 (make-const #f (car elts)))))
1012 (if (null? (cdr elts))
1013 test
1014 (make-conditional src test
1015 (make-const #f #t)
1016 (lp (cdr elts)))))))))))
1017 (else
1018 (cond
1019 ((const? k)
1020 (let ((member (case name ((memq) memq) ((memv) memv))))
1021 (make-const #f (member (const-exp k) elts))))
1022 ((null? elts)
1023 (for-tail (make-sequence src (list k (make-const #f #f)))))
1024 (else
1025 (make-application src proc (list k (make-const #f elts))))))))
1026 ((_ . args)
1027 (or (fold-constants src name args ctx)
1028 (make-application src proc args)))))
1029 (($ <primitive-ref> _ (? effect-free-primitive? name))
1030 (let ((args (map for-value orig-args)))
1031 (or (fold-constants src name args ctx)
1032 (make-application src proc args))))
1033 (($ <lambda> _ _
1034 ($ <lambda-case> _ req opt #f #f inits gensyms body #f))
1035 ;; Simple case: no rest, no keyword arguments.
1036 ;; todo: handle the more complex cases
1037 (let* ((nargs (length orig-args))
1038 (nreq (length req))
1039 (nopt (if opt (length opt) 0))
1040 (key (source-expression proc)))
1041 (cond
1042 ((or (< nargs nreq) (> nargs (+ nreq nopt)))
1043 ;; An error, or effecting arguments.
1044 (make-application src (for-call orig-proc)
1045 (map for-value orig-args)))
1046 ((or (and=> (find-counter key counter) counter-recursive?)
1047 (lambda? orig-proc))
1048 ;; A recursive call, or a lambda in the operator
1049 ;; position of the source expression. Process again in
1050 ;; tail context.
1051 ;;
1052 ;; In the recursive case, mark intervening counters as
1053 ;; recursive, so we can handle a toplevel counter that
1054 ;; recurses mutually with some other procedure.
1055 ;; Otherwise, the next time we see the other procedure,
1056 ;; the effort limit would be clamped to 100.
1057 ;;
1058 (let ((found (find-counter key counter)))
1059 (if (and found (counter-recursive? found))
1060 (let lp ((counter counter))
1061 (if (not (eq? counter found))
1062 (begin
1063 (set-counter-recursive?! counter #t)
1064 (lp (counter-prev counter)))))))
1065
1066 (log 'inline-recurse key)
1067 (loop (make-let src (append req (or opt '()))
1068 gensyms
1069 (append orig-args
1070 (drop inits (- nargs nreq)))
1071 body)
1072 env counter ctx))
1073 (else
1074 ;; An integration at the top-level, the first
1075 ;; recursion of a recursive procedure, or a nested
1076 ;; integration of a procedure that hasn't been seen
1077 ;; yet.
1078 (log 'inline-begin exp)
1079 (let/ec k
1080 (define (abort)
1081 (log 'inline-abort exp)
1082 (k (make-application src (for-call orig-proc)
1083 (map for-value orig-args))))
1084 (define new-counter
1085 (cond
1086 ;; These first two cases will transfer effort
1087 ;; from the current counter into the new
1088 ;; counter.
1089 ((find-counter key counter)
1090 => (lambda (prev)
1091 (make-recursive-counter recursive-effort-limit
1092 operand-size-limit
1093 prev counter)))
1094 (counter
1095 (make-nested-counter abort key counter))
1096 ;; This case opens a new account, effectively
1097 ;; printing money. It should only do so once
1098 ;; for each call site in the source program.
1099 (else
1100 (make-top-counter effort-limit operand-size-limit
1101 abort key))))
1102 (define result
1103 (loop (make-let src (append req (or opt '()))
1104 gensyms
1105 (append orig-args
1106 (drop inits (- nargs nreq)))
1107 body)
1108 env new-counter ctx))
1109
1110 (if counter
1111 ;; The nested inlining attempt succeeded.
1112 ;; Deposit the unspent effort and size back
1113 ;; into the current counter.
1114 (transfer! new-counter counter))
1115
1116 (log 'inline-end result exp)
1117 result)))))
1118 (_
1119 (make-application src (for-call orig-proc)
1120 (map for-value orig-args))))))
1121 (($ <lambda> src meta body)
1122 (case ctx
1123 ((effect) (make-void #f))
1124 ((test) (make-const #f #t))
1125 ((operator) exp)
1126 (else (record-source-expression!
1127 exp
1128 (make-lambda src meta (for-tail body))))))
1129 (($ <lambda-case> src req opt rest kw inits gensyms body alt)
1130 (let* ((vars (map lookup-var gensyms))
1131 (new (fresh-gensyms vars))
1132 (env (fold extend-env env gensyms
1133 (make-unbound-operands vars new)))
1134 (new-sym (lambda (old)
1135 (operand-sym (cdr (vhash-assq old env))))))
1136 (make-lambda-case src req opt rest
1137 (match kw
1138 ((aok? (kw name old) ...)
1139 (cons aok? (map list kw name (map new-sym old))))
1140 (_ #f))
1141 (map (cut loop <> env counter 'value) inits)
1142 new
1143 (loop body env counter ctx)
1144 (and alt (for-tail alt)))))
1145 (($ <sequence> src exps)
1146 (let lp ((exps exps) (effects '()))
1147 (match exps
1148 ((last)
1149 (if (null? effects)
1150 (for-tail last)
1151 (make-sequence
1152 src
1153 (reverse (cons (for-tail last) effects)))))
1154 ((head . rest)
1155 (let ((head (for-effect head)))
1156 (cond
1157 ((sequence? head)
1158 (lp (append (sequence-exps head) rest) effects))
1159 ((void? head)
1160 (lp rest effects))
1161 (else
1162 (lp rest (cons head effects)))))))))
1163 (($ <prompt> src tag body handler)
1164 (define (singly-used-definition x)
1165 (cond
1166 ((and (lexical-ref? x)
1167 ;; Only fetch definitions with single uses.
1168 (= (lexical-refcount (lexical-ref-gensym x)) 1)
1169 (lookup (lexical-ref-gensym x)))
1170 => (lambda (x)
1171 (singly-used-definition (visit-operand x counter 'value 10 10))))
1172 (else x)))
1173 (match (singly-used-definition tag)
1174 (($ <application> _ ($ <primitive-ref> _ 'make-prompt-tag)
1175 (or () ((? constant-expression?))))
1176 ;; There is no way that an <abort> could know the tag
1177 ;; for this <prompt>, so we can elide the <prompt>
1178 ;; entirely.
1179 (for-tail body))
1180 (_
1181 (make-prompt src (for-value tag) (for-tail body)
1182 (for-value handler)))))
1183 (($ <abort> src tag args tail)
1184 (make-abort src (for-value tag) (map for-value args)
1185 (for-value tail))))))