Merge remote-tracking branch 'origin/stable-2.0'
[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 (let ()
352 (define (env-folder x env)
353 (match x
354 (($ <toplevel-define> _ name)
355 (vhash-consq name #t env))
356 (($ <seq> _ head tail)
357 (env-folder tail (env-folder head env)))
358 (_ env)))
359 (env-folder exp vlist-null)))
360
361 (define (local-toplevel? name)
362 (vhash-assq name local-toplevel-env))
363
364 ;; gensym -> <var>
365 ;; renamed-term -> original-term
366 ;;
367 (define store (build-var-table exp))
368
369 (define (record-new-temporary! name sym refcount)
370 (set! store (vhash-consq sym (make-var name sym refcount #f) store)))
371
372 (define (lookup-var sym)
373 (let ((v (vhash-assq sym store)))
374 (if v (cdr v) (error "unbound var" sym (vlist->list store)))))
375
376 (define (fresh-gensyms vars)
377 (map (lambda (var)
378 (let ((new (gensym (string-append (symbol->string (var-name var))
379 " "))))
380 (set! store (vhash-consq new var store))
381 new))
382 vars))
383
384 (define (assigned-lexical? sym)
385 (var-set? (lookup-var sym)))
386
387 (define (lexical-refcount sym)
388 (var-refcount (lookup-var sym)))
389
390 ;; ORIG has been alpha-renamed to NEW. Analyze NEW and record a link
391 ;; from it to ORIG.
392 ;;
393 (define (record-source-expression! orig new)
394 (set! store (vhash-consq new (source-expression orig) store))
395 new)
396
397 ;; Find the source expression corresponding to NEW. Used to detect
398 ;; recursive inlining attempts.
399 ;;
400 (define (source-expression new)
401 (let ((x (vhash-assq new store)))
402 (if x (cdr x) new)))
403
404 (define* (residualize-lexical op #:optional ctx val)
405 (log 'residualize op)
406 (set-operand-residualize?! op #t)
407 (if (eq? ctx 'value)
408 (set-operand-residual-value! op val))
409 (make-lexical-ref #f (var-name (operand-var op)) (operand-sym op)))
410
411 (define (apply-primitive name args)
412 ;; todo: further optimize commutative primitives
413 (catch #t
414 (lambda ()
415 (call-with-values
416 (lambda ()
417 (apply (module-ref the-scm-module name) args))
418 (lambda results
419 (values #t results))))
420 (lambda _
421 (values #f '()))))
422
423 (define (make-values src values)
424 (match values
425 ((single) single) ; 1 value
426 ((_ ...) ; 0, or 2 or more values
427 (make-primcall src 'values values))))
428
429 (define (fold-constants src name args ctx)
430 (define (residualize-call)
431 (make-primcall src name args))
432 (cond
433 ((every const? args)
434 (let-values (((success? values)
435 (apply-primitive name (map const-exp args))))
436 (log 'fold success? values name args)
437 (if success?
438 (case ctx
439 ((effect) (make-void src))
440 ((test)
441 ;; Values truncation: only take the first
442 ;; value.
443 (if (pair? values)
444 (make-const src (car values))
445 (make-values src '())))
446 (else
447 (make-values src (map (cut make-const src <>) values))))
448 (residualize-call))))
449 ((and (eq? ctx 'effect) (types-check? name args))
450 (make-void #f))
451 (else
452 (residualize-call))))
453
454 (define (inline-values exp src names gensyms body)
455 (let loop ((exp exp))
456 (match exp
457 ;; Some expression types are always singly-valued.
458 ((or ($ <const>)
459 ($ <void>)
460 ($ <lambda>)
461 ($ <lexical-ref>)
462 ($ <toplevel-ref>)
463 ($ <module-ref>)
464 ($ <primitive-ref>)
465 ($ <dynref>)
466 ($ <lexical-set>) ; FIXME: these set! expressions
467 ($ <toplevel-set>) ; could return zero values in
468 ($ <toplevel-define>) ; the future
469 ($ <module-set>) ;
470 ($ <dynset>)) ;
471 (and (= (length names) 1)
472 (make-let src names gensyms (list exp) body)))
473 (($ <primcall> src (? singly-valued-primitive? name))
474 (and (= (length names) 1)
475 (make-let src names gensyms (list exp) body)))
476
477 ;; Statically-known number of values.
478 (($ <primcall> src 'values vals)
479 (and (= (length names) (length vals))
480 (make-let src names gensyms vals body)))
481
482 ;; Not going to copy code into both branches.
483 (($ <conditional>) #f)
484
485 ;; Bail on other applications.
486 (($ <call>) #f)
487 (($ <primcall>) #f)
488
489 ;; Bail on prompt and abort.
490 (($ <prompt>) #f)
491 (($ <abort>) #f)
492
493 ;; Propagate to tail positions.
494 (($ <let> src names gensyms vals body)
495 (let ((body (loop body)))
496 (and body
497 (make-let src names gensyms vals body))))
498 (($ <letrec> src in-order? names gensyms vals body)
499 (let ((body (loop body)))
500 (and body
501 (make-letrec src in-order? names gensyms vals body))))
502 (($ <fix> src names gensyms vals body)
503 (let ((body (loop body)))
504 (and body
505 (make-fix src names gensyms vals body))))
506 (($ <let-values> src exp
507 ($ <lambda-case> src2 req opt rest kw inits gensyms body #f))
508 (let ((body (loop body)))
509 (and body
510 (make-let-values src exp
511 (make-lambda-case src2 req opt rest kw
512 inits gensyms body #f)))))
513 (($ <dynwind> src winder body unwinder)
514 (let ((body (loop body)))
515 (and body
516 (make-dynwind src winder body unwinder))))
517 (($ <dynlet> src fluids vals body)
518 (let ((body (loop body)))
519 (and body
520 (make-dynlet src fluids vals body))))
521 (($ <seq> src head tail)
522 (let ((tail (loop tail)))
523 (and tail (make-seq src head tail)))))))
524
525 (define (constant-expression? x)
526 ;; Return true if X is constant, for the purposes of copying or
527 ;; elision---i.e., if it is known to have no effects, does not
528 ;; allocate storage for a mutable object, and does not access
529 ;; mutable data (like `car' or toplevel references).
530 (let loop ((x x))
531 (match x
532 (($ <void>) #t)
533 (($ <const>) #t)
534 (($ <lambda>) #t)
535 (($ <lambda-case> _ req opt rest kw inits syms body alternate)
536 (and (not (any assigned-lexical? syms))
537 (every loop inits) (loop body)
538 (or (not alternate) (loop alternate))))
539 (($ <lexical-ref> _ _ gensym)
540 (not (assigned-lexical? gensym)))
541 (($ <primitive-ref>) #t)
542 (($ <conditional> _ condition subsequent alternate)
543 (and (loop condition) (loop subsequent) (loop alternate)))
544 (($ <primcall> _ name args)
545 (and (effect-free-primitive? name)
546 (not (constructor-primitive? name))
547 (types-check? name args)
548 (if (accessor-primitive? name)
549 (every const? args)
550 (every loop args))))
551 (($ <call> _ ($ <lambda> _ _ body) args)
552 (and (loop body) (every loop args)))
553 (($ <seq> _ head tail)
554 (and (loop head) (loop tail)))
555 (($ <let> _ _ syms vals body)
556 (and (not (any assigned-lexical? syms))
557 (every loop vals) (loop body)))
558 (($ <letrec> _ _ _ syms vals body)
559 (and (not (any assigned-lexical? syms))
560 (every loop vals) (loop body)))
561 (($ <fix> _ _ _ vals body)
562 (and (every loop vals) (loop body)))
563 (($ <let-values> _ exp body)
564 (and (loop exp) (loop body)))
565 (($ <prompt> _ tag body handler)
566 (and (loop tag) (loop body) (loop handler)))
567 (_ #f))))
568
569 (define (prune-bindings ops in-order? body counter ctx build-result)
570 ;; This helper handles both `let' and `letrec'/`fix'. In the latter
571 ;; cases we need to make sure that if referenced binding A needs
572 ;; as-yet-unreferenced binding B, that B is processed for value.
573 ;; Likewise if C, when processed for effect, needs otherwise
574 ;; unreferenced D, then D needs to be processed for value too.
575 ;;
576 (define (referenced? op)
577 ;; When we visit lambdas in operator context, we just copy them,
578 ;; as we will process their body later. However this does have
579 ;; the problem that any free var referenced by the lambda is not
580 ;; marked as needing residualization. Here we hack around this
581 ;; and treat all bindings as referenced if we are in operator
582 ;; context.
583 (or (eq? ctx 'operator) (operand-residualize? op)))
584
585 ;; values := (op ...)
586 ;; effects := (op ...)
587 (define (residualize values effects)
588 ;; Note, values and effects are reversed.
589 (cond
590 (in-order?
591 (let ((values (filter operand-residual-value ops)))
592 (if (null? values)
593 body
594 (build-result (map (compose var-name operand-var) values)
595 (map operand-sym values)
596 (map operand-residual-value values)
597 body))))
598 (else
599 (let ((body
600 (if (null? effects)
601 body
602 (let ((effect-vals (map operand-residual-value effects)))
603 (list->seq #f (reverse (cons body effect-vals)))))))
604 (if (null? values)
605 body
606 (let ((values (reverse values)))
607 (build-result (map (compose var-name operand-var) values)
608 (map operand-sym values)
609 (map operand-residual-value values)
610 body)))))))
611
612 ;; old := (bool ...)
613 ;; values := (op ...)
614 ;; effects := ((op . value) ...)
615 (let prune ((old (map referenced? ops)) (values '()) (effects '()))
616 (let lp ((ops* ops) (values values) (effects effects))
617 (cond
618 ((null? ops*)
619 (let ((new (map referenced? ops)))
620 (if (not (equal? new old))
621 (prune new values '())
622 (residualize values
623 (map (lambda (op val)
624 (set-operand-residual-value! op val)
625 op)
626 (map car effects) (map cdr effects))))))
627 (else
628 (let ((op (car ops*)))
629 (cond
630 ((memq op values)
631 (lp (cdr ops*) values effects))
632 ((operand-residual-value op)
633 (lp (cdr ops*) (cons op values) effects))
634 ((referenced? op)
635 (set-operand-residual-value! op (visit-operand op counter 'value))
636 (lp (cdr ops*) (cons op values) effects))
637 (else
638 (lp (cdr ops*)
639 values
640 (let ((effect (visit-operand op counter 'effect)))
641 (if (void? effect)
642 effects
643 (acons op effect effects))))))))))))
644
645 (define (small-expression? x limit)
646 (let/ec k
647 (tree-il-fold
648 (lambda (x res) ; leaf
649 (1+ res))
650 (lambda (x res) ; down
651 (1+ res))
652 (lambda (x res) ; up
653 (if (< res limit)
654 res
655 (k #f)))
656 0 x)
657 #t))
658
659 (define (extend-env sym op env)
660 (vhash-consq (operand-sym op) op (vhash-consq sym op env)))
661
662 (let loop ((exp exp)
663 (env vlist-null) ; vhash of gensym -> <operand>
664 (counter #f) ; inlined call stack
665 (ctx 'value)) ; effect, value, test, operator, or call
666 (define (lookup var)
667 (cond
668 ((vhash-assq var env) => cdr)
669 (else (error "unbound var" var))))
670
671 (define (visit exp ctx)
672 (loop exp env counter ctx))
673
674 (define (for-value exp) (visit exp 'value))
675 (define (for-test exp) (visit exp 'test))
676 (define (for-effect exp) (visit exp 'effect))
677 (define (for-call exp) (visit exp 'call))
678 (define (for-tail exp) (visit exp ctx))
679
680 (if counter
681 (record-effort! counter))
682
683 (log 'visit ctx (and=> counter effort-counter)
684 (unparse-tree-il exp))
685
686 (match exp
687 (($ <const>)
688 (case ctx
689 ((effect) (make-void #f))
690 (else exp)))
691 (($ <void>)
692 (case ctx
693 ((test) (make-const #f #t))
694 (else exp)))
695 (($ <lexical-ref> _ _ gensym)
696 (log 'begin-copy gensym)
697 (let ((op (lookup gensym)))
698 (cond
699 ((eq? ctx 'effect)
700 (log 'lexical-for-effect gensym)
701 (make-void #f))
702 ((eq? ctx 'call)
703 ;; Don't propagate copies if we are residualizing a call.
704 (log 'residualize-lexical-call gensym op)
705 (residualize-lexical op))
706 ((var-set? (operand-var op))
707 ;; Assigned lexicals don't copy-propagate.
708 (log 'assigned-var gensym op)
709 (residualize-lexical op))
710 ((not (operand-copyable? op))
711 ;; We already know that this operand is not copyable.
712 (log 'not-copyable gensym op)
713 (residualize-lexical op))
714 ((and=> (operand-constant-value op)
715 (lambda (x) (or (const? x) (void? x) (primitive-ref? x))))
716 ;; A cache hit.
717 (let ((val (operand-constant-value op)))
718 (log 'memoized-constant gensym val)
719 (for-tail val)))
720 ((visit-operand op counter ctx recursive-effort-limit operand-size-limit)
721 =>
722 ;; If we end up deciding to residualize this value instead of
723 ;; copying it, save that residualized value.
724 (lambda (val)
725 (cond
726 ((not (constant-expression? val))
727 (log 'not-constant gensym op)
728 ;; At this point, ctx is operator, test, or value. A
729 ;; value that is non-constant in one context will be
730 ;; non-constant in the others, so it's safe to record
731 ;; that here, and avoid future visits.
732 (set-operand-copyable?! op #f)
733 (residualize-lexical op ctx val))
734 ((or (const? val)
735 (void? val)
736 (primitive-ref? val))
737 ;; Always propagate simple values that cannot lead to
738 ;; code bloat.
739 (log 'copy-simple gensym val)
740 ;; It could be this constant is the result of folding.
741 ;; If that is the case, cache it. This helps loop
742 ;; unrolling get farther.
743 (if (eq? ctx 'value)
744 (begin
745 (log 'memoize-constant gensym val)
746 (set-operand-constant-value! op val)))
747 val)
748 ((= 1 (var-refcount (operand-var op)))
749 ;; Always propagate values referenced only once.
750 (log 'copy-single gensym val)
751 val)
752 ;; FIXME: do demand-driven size accounting rather than
753 ;; these heuristics.
754 ((eq? ctx 'operator)
755 ;; A pure expression in the operator position. Inline
756 ;; if it's a lambda that's small enough.
757 (if (and (lambda? val)
758 (small-expression? val operator-size-limit))
759 (begin
760 (log 'copy-operator gensym val)
761 val)
762 (begin
763 (log 'too-big-for-operator gensym val)
764 (residualize-lexical op ctx val))))
765 (else
766 ;; A pure expression, processed for call or for value.
767 ;; Don't inline lambdas, because they will probably won't
768 ;; fold because we don't know the operator.
769 (if (and (small-expression? val value-size-limit)
770 (not (tree-il-any lambda? val)))
771 (begin
772 (log 'copy-value gensym val)
773 val)
774 (begin
775 (log 'too-big-or-has-lambda gensym val)
776 (residualize-lexical op ctx val)))))))
777 (else
778 ;; Visit failed. Either the operand isn't bound, as in
779 ;; lambda formal parameters, or the copy was aborted.
780 (log 'unbound-or-aborted gensym op)
781 (residualize-lexical op)))))
782 (($ <lexical-set> src name gensym exp)
783 (let ((op (lookup gensym)))
784 (if (zero? (var-refcount (operand-var op)))
785 (let ((exp (for-effect exp)))
786 (if (void? exp)
787 exp
788 (make-seq src exp (make-void #f))))
789 (begin
790 (set-operand-residualize?! op #t)
791 (make-lexical-set src name (operand-sym op) (for-value exp))))))
792 (($ <let> src names gensyms vals body)
793 (let* ((vars (map lookup-var gensyms))
794 (new (fresh-gensyms vars))
795 (ops (make-bound-operands vars new vals
796 (lambda (exp counter ctx)
797 (loop exp env counter ctx))))
798 (env (fold extend-env env gensyms ops))
799 (body (loop body env counter ctx)))
800 (cond
801 ((const? body)
802 (for-tail (list->seq src (append vals (list body)))))
803 ((and (lexical-ref? body)
804 (memq (lexical-ref-gensym body) new))
805 (let ((sym (lexical-ref-gensym body))
806 (pairs (map cons new vals)))
807 ;; (let ((x foo) (y bar) ...) x) => (begin bar ... foo)
808 (for-tail
809 (list->seq
810 src
811 (append (map cdr (alist-delete sym pairs eq?))
812 (list (assq-ref pairs sym)))))))
813 (else
814 ;; Only include bindings for which lexical references
815 ;; have been residualized.
816 (prune-bindings ops #f body counter ctx
817 (lambda (names gensyms vals body)
818 (if (null? names) (error "what!" names))
819 (make-let src names gensyms vals body)))))))
820 (($ <letrec> src in-order? names gensyms vals body)
821 ;; Note the difference from the `let' case: here we use letrec*
822 ;; so that the `visit' procedure for the new operands closes over
823 ;; an environment that includes the operands.
824 (letrec* ((visit (lambda (exp counter ctx)
825 (loop exp env* counter ctx)))
826 (vars (map lookup-var gensyms))
827 (new (fresh-gensyms vars))
828 (ops (make-bound-operands vars new vals visit))
829 (env* (fold extend-env env gensyms ops))
830 (body* (visit body counter ctx)))
831 (if (and (const? body*) (every constant-expression? vals))
832 ;; We may have folded a loop completely, even though there
833 ;; might be cyclical references between the bound values.
834 ;; Handle this degenerate case specially.
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 (let ((pre (for-value winder))
868 (body (for-tail body))
869 (post (for-value unwinder)))
870 (cond
871 ((not (constant-expression? pre))
872 (cond
873 ((not (constant-expression? post))
874 (let ((pre-sym (gensym "pre ")) (post-sym (gensym "post ")))
875 (record-new-temporary! 'pre pre-sym 1)
876 (record-new-temporary! 'post post-sym 1)
877 (make-let src '(pre post) (list pre-sym post-sym) (list pre post)
878 (make-dynwind src
879 (make-lexical-ref #f 'pre pre-sym)
880 body
881 (make-lexical-ref #f 'post post-sym)))))
882 (else
883 (let ((pre-sym (gensym "pre ")))
884 (record-new-temporary! 'pre pre-sym 1)
885 (make-let src '(pre) (list pre-sym) (list pre)
886 (make-dynwind src
887 (make-lexical-ref #f 'pre pre-sym)
888 body
889 post))))))
890 ((not (constant-expression? post))
891 (let ((post-sym (gensym "post ")))
892 (record-new-temporary! 'post post-sym 1)
893 (make-let src '(post) (list post-sym) (list post)
894 (make-dynwind src
895 pre
896 body
897 (make-lexical-ref #f 'post post-sym)))))
898 (else
899 (make-dynwind src pre body post)))))
900 (($ <dynlet> src fluids vals body)
901 (make-dynlet src (map for-value fluids) (map for-value vals)
902 (for-tail body)))
903 (($ <dynref> src fluid)
904 (make-dynref src (for-value fluid)))
905 (($ <dynset> src fluid exp)
906 (make-dynset src (for-value fluid) (for-value exp)))
907 (($ <toplevel-ref> src (? effect-free-primitive? name))
908 exp)
909 (($ <toplevel-ref>)
910 ;; todo: open private local bindings.
911 exp)
912 (($ <module-ref> src module (? effect-free-primitive? name) #f)
913 (let ((module (false-if-exception
914 (resolve-module module #:ensure #f))))
915 (if (module? module)
916 (let ((var (module-variable module name)))
917 (if (eq? var (module-variable the-scm-module name))
918 (make-primitive-ref src name)
919 exp))
920 exp)))
921 (($ <module-ref>)
922 exp)
923 (($ <module-set> src mod name public? exp)
924 (make-module-set src mod name public? (for-value exp)))
925 (($ <toplevel-define> src name exp)
926 (make-toplevel-define src name (for-value exp)))
927 (($ <toplevel-set> src name exp)
928 (make-toplevel-set src name (for-value exp)))
929 (($ <primitive-ref>)
930 (case ctx
931 ((effect) (make-void #f))
932 ((test) (make-const #f #t))
933 (else exp)))
934 (($ <conditional> src condition subsequent alternate)
935 (let ((condition (for-test condition)))
936 (if (const? condition)
937 (if (const-exp condition)
938 (for-tail subsequent)
939 (for-tail alternate))
940 (make-conditional src condition
941 (for-tail subsequent)
942 (for-tail alternate)))))
943 (($ <primcall> src '@call-with-values
944 (producer
945 ($ <lambda> _ _
946 (and consumer
947 ;; No optional or kwargs.
948 ($ <lambda-case>
949 _ req #f rest #f () gensyms body #f)))))
950 (for-tail (make-let-values src (make-call src producer '())
951 consumer)))
952
953 (($ <primcall> src (? constructor-primitive? name) args)
954 (cond
955 ((and (memq ctx '(effect test))
956 (match (cons name args)
957 ((or ('cons _ _)
958 ('list . _)
959 ('vector . _)
960 ('make-prompt-tag)
961 ('make-prompt-tag ($ <const> _ (? string?))))
962 #t)
963 (_ #f)))
964 ;; Some expressions can be folded without visiting the
965 ;; arguments for value.
966 (let ((res (if (eq? ctx 'effect)
967 (make-void #f)
968 (make-const #f #t))))
969 (for-tail (list->seq src (append args (list res))))))
970 (else
971 (match (cons name (map for-value args))
972 (('cons x ($ <const> _ ()))
973 (make-primcall src 'list (list x)))
974 (('cons x ($ <primcall> _ 'list elts))
975 (make-primcall src 'list (cons x elts)))
976 ((name . args)
977 (make-primcall src name args))))))
978
979 (($ <primcall> src (? accessor-primitive? name) args)
980 (match (cons name (map for-value args))
981 ;; FIXME: these for-tail recursions could take place outside
982 ;; an effort counter.
983 (('car ($ <primcall> src 'cons (head tail)))
984 (for-tail (make-seq src tail head)))
985 (('cdr ($ <primcall> src 'cons (head tail)))
986 (for-tail (make-seq src head tail)))
987 (('car ($ <primcall> src 'list (head . tail)))
988 (for-tail (list->seq src (append tail (list head)))))
989 (('cdr ($ <primcall> src 'list (head . tail)))
990 (for-tail (make-seq src head (make-primcall #f 'list tail))))
991
992 (('car ($ <const> src (head . tail)))
993 (for-tail (make-const src head)))
994 (('cdr ($ <const> src (head . tail)))
995 (for-tail (make-const src tail)))
996 (((or 'memq 'memv) k ($ <const> _ (elts ...)))
997 ;; FIXME: factor
998 (case ctx
999 ((effect)
1000 (for-tail
1001 (make-seq src k (make-void #f))))
1002 ((test)
1003 (cond
1004 ((const? k)
1005 ;; A shortcut. The `else' case would handle it, but
1006 ;; this way is faster.
1007 (let ((member (case name ((memq) memq) ((memv) memv))))
1008 (make-const #f (and (member (const-exp k) elts) #t))))
1009 ((null? elts)
1010 (for-tail
1011 (make-seq src k (make-const #f #f))))
1012 (else
1013 (let ((t (gensym "t "))
1014 (eq (if (eq? name 'memq) 'eq? 'eqv?)))
1015 (record-new-temporary! 't t (length elts))
1016 (for-tail
1017 (make-let
1018 src (list 't) (list t) (list k)
1019 (let lp ((elts elts))
1020 (define test
1021 (make-primcall #f eq
1022 (list (make-lexical-ref #f 't t)
1023 (make-const #f (car elts)))))
1024 (if (null? (cdr elts))
1025 test
1026 (make-conditional src test
1027 (make-const #f #t)
1028 (lp (cdr elts)))))))))))
1029 (else
1030 (cond
1031 ((const? k)
1032 (let ((member (case name ((memq) memq) ((memv) memv))))
1033 (make-const #f (member (const-exp k) elts))))
1034 ((null? elts)
1035 (for-tail (make-seq src k (make-const #f #f))))
1036 (else
1037 (make-primcall src name (list k (make-const #f elts))))))))
1038 ((name . args)
1039 (fold-constants src name args ctx))))
1040
1041 (($ <primcall> src (? effect-free-primitive? name) args)
1042 (fold-constants src name (map for-value args) ctx))
1043
1044 (($ <primcall> src name args)
1045 (make-primcall src name (map for-value args)))
1046
1047 (($ <call> src orig-proc orig-args)
1048 ;; todo: augment the global env with specialized functions
1049 (let ((proc (visit orig-proc 'operator)))
1050 (match proc
1051 (($ <primitive-ref> _ name)
1052 (for-tail (make-primcall src name orig-args)))
1053 (($ <lambda> _ _
1054 ($ <lambda-case> _ req opt #f #f inits gensyms body #f))
1055 ;; Simple case: no rest, no keyword arguments.
1056 ;; todo: handle the more complex cases
1057 (let* ((nargs (length orig-args))
1058 (nreq (length req))
1059 (nopt (if opt (length opt) 0))
1060 (key (source-expression proc)))
1061 (cond
1062 ((or (< nargs nreq) (> nargs (+ nreq nopt)))
1063 ;; An error, or effecting arguments.
1064 (make-call src (for-call orig-proc) (map for-value orig-args)))
1065 ((or (and=> (find-counter key counter) counter-recursive?)
1066 (lambda? orig-proc))
1067 ;; A recursive call, or a lambda in the operator
1068 ;; position of the source expression. Process again in
1069 ;; tail context.
1070 ;;
1071 ;; In the recursive case, mark intervening counters as
1072 ;; recursive, so we can handle a toplevel counter that
1073 ;; recurses mutually with some other procedure.
1074 ;; Otherwise, the next time we see the other procedure,
1075 ;; the effort limit would be clamped to 100.
1076 ;;
1077 (let ((found (find-counter key counter)))
1078 (if (and found (counter-recursive? found))
1079 (let lp ((counter counter))
1080 (if (not (eq? counter found))
1081 (begin
1082 (set-counter-recursive?! counter #t)
1083 (lp (counter-prev counter)))))))
1084
1085 (log 'inline-recurse key)
1086 (loop (make-let src (append req (or opt '()))
1087 gensyms
1088 (append orig-args
1089 (drop inits (- nargs nreq)))
1090 body)
1091 env counter ctx))
1092 (else
1093 ;; An integration at the top-level, the first
1094 ;; recursion of a recursive procedure, or a nested
1095 ;; integration of a procedure that hasn't been seen
1096 ;; yet.
1097 (log 'inline-begin exp)
1098 (let/ec k
1099 (define (abort)
1100 (log 'inline-abort exp)
1101 (k (make-call src (for-call orig-proc)
1102 (map for-value orig-args))))
1103 (define new-counter
1104 (cond
1105 ;; These first two cases will transfer effort
1106 ;; from the current counter into the new
1107 ;; counter.
1108 ((find-counter key counter)
1109 => (lambda (prev)
1110 (make-recursive-counter recursive-effort-limit
1111 operand-size-limit
1112 prev counter)))
1113 (counter
1114 (make-nested-counter abort key counter))
1115 ;; This case opens a new account, effectively
1116 ;; printing money. It should only do so once
1117 ;; for each call site in the source program.
1118 (else
1119 (make-top-counter effort-limit operand-size-limit
1120 abort key))))
1121 (define result
1122 (loop (make-let src (append req (or opt '()))
1123 gensyms
1124 (append orig-args
1125 (drop inits (- nargs nreq)))
1126 body)
1127 env new-counter ctx))
1128
1129 (if counter
1130 ;; The nested inlining attempt succeeded.
1131 ;; Deposit the unspent effort and size back
1132 ;; into the current counter.
1133 (transfer! new-counter counter))
1134
1135 (log 'inline-end result exp)
1136 result)))))
1137 (_
1138 (make-call src (for-call orig-proc) (map for-value orig-args))))))
1139 (($ <lambda> src meta body)
1140 (case ctx
1141 ((effect) (make-void #f))
1142 ((test) (make-const #f #t))
1143 ((operator) exp)
1144 (else (record-source-expression!
1145 exp
1146 (make-lambda src meta (for-tail body))))))
1147 (($ <lambda-case> src req opt rest kw inits gensyms body alt)
1148 (let* ((vars (map lookup-var gensyms))
1149 (new (fresh-gensyms vars))
1150 (env (fold extend-env env gensyms
1151 (make-unbound-operands vars new)))
1152 (new-sym (lambda (old)
1153 (operand-sym (cdr (vhash-assq old env))))))
1154 (make-lambda-case src req opt rest
1155 (match kw
1156 ((aok? (kw name old) ...)
1157 (cons aok? (map list kw name (map new-sym old))))
1158 (_ #f))
1159 (map (cut loop <> env counter 'value) inits)
1160 new
1161 (loop body env counter ctx)
1162 (and alt (for-tail alt)))))
1163 (($ <seq> src head tail)
1164 (let ((head (for-effect head))
1165 (tail (for-tail tail)))
1166 (if (void? head)
1167 tail
1168 (make-seq src
1169 (if (and (seq? head)
1170 (void? (seq-tail head)))
1171 (seq-head head)
1172 head)
1173 tail))))
1174 (($ <prompt> src tag body handler)
1175 (define (singly-used-definition x)
1176 (cond
1177 ((and (lexical-ref? x)
1178 ;; Only fetch definitions with single uses.
1179 (= (lexical-refcount (lexical-ref-gensym x)) 1)
1180 (lookup (lexical-ref-gensym x)))
1181 => (lambda (x)
1182 (singly-used-definition (visit-operand x counter 'value 10 10))))
1183 (else x)))
1184 (match (singly-used-definition tag)
1185 (($ <primcall> _ 'make-prompt-tag (or () ((? constant-expression?))))
1186 ;; There is no way that an <abort> could know the tag
1187 ;; for this <prompt>, so we can elide the <prompt>
1188 ;; entirely.
1189 (for-tail body))
1190 (_
1191 (make-prompt src (for-value tag) (for-tail body)
1192 (for-value handler)))))
1193 (($ <abort> src tag args tail)
1194 (make-abort src (for-value tag) (map for-value args)
1195 (for-value tail))))))