more rest argument inlining improvements
[bpt/guile.git] / module / language / tree-il / peval.scm
1 ;;; Tree-IL partial evaluator
2
3 ;; Copyright (C) 2011, 2012, 2013 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 (language tree-il effects)
23 #:use-module (ice-9 vlist)
24 #:use-module (ice-9 match)
25 #:use-module (srfi srfi-1)
26 #:use-module (srfi srfi-9)
27 #:use-module (srfi srfi-11)
28 #:use-module (srfi srfi-26)
29 #:export (peval))
30
31 ;;;
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.
36 ;;;
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].
40 ;;;
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.
44 ;;;
45 ;;; [0] http://www.cs.utexas.edu/~wcook/tutorial/.
46 ;;;
47
48 ;; First, some helpers.
49 ;;
50 (define-syntax *logging* (identifier-syntax #f))
51
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
54 ;; lines:
55 ;;
56 ;; (define %logging #f)
57 ;; (define-syntax *logging* (identifier-syntax %logging))
58 ;;
59 ;; Then you can change %logging at runtime.
60
61 (define-syntax log
62 (syntax-rules (quote)
63 ((log 'event arg ...)
64 (if (and *logging*
65 (or (eq? *logging* #t)
66 (memq 'event *logging*)))
67 (log* 'event arg ...)))))
68
69 (define (log* event . args)
70 (let ((pp (module-ref (resolve-interface '(ice-9 pretty-print))
71 'pretty-print)))
72 (pp `(log ,event . ,args))
73 (newline)
74 (values)))
75
76 (define-syntax-rule (let/ec k e e* ...)
77 (let ((tag (make-prompt-tag)))
78 (call-with-prompt
79 tag
80 (lambda ()
81 (let ((k (lambda args (apply abort-to-prompt tag args))))
82 e e* ...))
83 (lambda (_ res) res))))
84
85 (define (tree-il-any proc exp)
86 (let/ec k
87 (tree-il-fold (lambda (exp res)
88 (let ((res (proc exp)))
89 (if res (k res) #f)))
90 (lambda (exp res)
91 (let ((res (proc exp)))
92 (if res (k res) #f)))
93 (lambda (exp res) #f)
94 #f exp)))
95
96 (define (vlist-any proc vlist)
97 (let ((len (vlist-length vlist)))
98 (let lp ((i 0))
99 (and (< i len)
100 (or (proc (vlist-ref vlist i))
101 (lp (1+ i)))))))
102
103 (define (singly-valued-expression? exp)
104 (match exp
105 (($ <const>) #t)
106 (($ <lexical-ref>) #t)
107 (($ <void>) #t)
108 (($ <lexical-ref>) #t)
109 (($ <primitive-ref>) #t)
110 (($ <module-ref>) #t)
111 (($ <toplevel-ref>) #t)
112 (($ <application> _
113 ($ <primitive-ref> _ (? singly-valued-primitive?))) #t)
114 (($ <application> _ ($ <primitive-ref> _ 'values) (val)) #t)
115 (($ <lambda>) #t)
116 (else #f)))
117
118 (define (truncate-values x)
119 "Discard all but the first value of X."
120 (if (singly-valued-expression? x)
121 x
122 (make-application (tree-il-src x)
123 (make-primitive-ref #f 'values)
124 (list x))))
125
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.
129 ;;
130 (define-record-type <var>
131 (make-var name gensym refcount set?)
132 var?
133 (name var-name)
134 (gensym var-gensym)
135 (refcount var-refcount set-var-refcount!)
136 (set? var-set? set-var-set?!))
137
138 (define* (build-var-table exp #:optional (table vlist-null))
139 (tree-il-fold
140 (lambda (exp res)
141 (match exp
142 (($ <lexical-ref> src name gensym)
143 (let ((var (cdr (vhash-assq gensym res))))
144 (set-var-refcount! var (1+ (var-refcount var)))
145 res))
146 (_ res)))
147 (lambda (exp res)
148 (match exp
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))
152 res
153 (append req (or opt '()) (if rest (list rest) '())
154 (match kw
155 ((aok? (kw name sym) ...) name)
156 (_ '())))
157 gensyms))
158 (($ <let> src names gensyms vals body)
159 (fold (lambda (name sym res)
160 (vhash-consq sym (make-var name sym 0 #f) res))
161 res names gensyms))
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))
165 res names gensyms))
166 (($ <fix> src names gensyms vals body)
167 (fold (lambda (name sym res)
168 (vhash-consq sym (make-var name sym 0 #f) res))
169 res names gensyms))
170 (($ <lexical-set> src name gensym exp)
171 (set-var-set?! (cdr (vhash-assq gensym res)) #t)
172 res)
173 (_ res)))
174 (lambda (exp res) res)
175 table exp))
176
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.
182 ;;
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.
185 ;;
186 ;; Counters should limit the size of the residual program as well, but
187 ;; currently this is not implemented.
188 ;;
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.
193 ;;
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.
198 ;;
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.
202 ;;
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.
210 ;;
211 (define-record-type <counter>
212 (%make-counter effort size continuation recursive? data prev)
213 counter?
214 (effort effort-counter)
215 (size size-counter)
216 (continuation counter-continuation)
217 (recursive? counter-recursive? set-counter-recursive?!)
218 (data counter-data)
219 (prev counter-prev))
220
221 (define (abort-counter c)
222 ((counter-continuation c)))
223
224 (define (record-effort! c)
225 (let ((e (effort-counter c)))
226 (if (zero? (variable-ref e))
227 (abort-counter c)
228 (variable-set! e (1- (variable-ref e))))))
229
230 (define (record-size! c)
231 (let ((s (size-counter c)))
232 (if (zero? (variable-ref s))
233 (abort-counter c)
234 (variable-set! s (1- (variable-ref s))))))
235
236 (define (find-counter data counter)
237 (and counter
238 (if (eq? data (counter-data counter))
239 counter
240 (find-counter data (counter-prev counter)))))
241
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))))
251
252 (transfer-counter! (effort-counter from) (effort-counter to) effort)
253 (transfer-counter! (size-counter from) (size-counter to) size))
254
255 (define (make-top-counter effort-limit size-limit continuation data)
256 (%make-counter (make-variable effort-limit)
257 (make-variable size-limit)
258 continuation
259 #t
260 data
261 #f))
262
263 (define (make-nested-counter continuation data current)
264 (let ((c (%make-counter (make-variable 0)
265 (make-variable 0)
266 continuation
267 #f
268 data
269 current)))
270 (transfer! current c)
271 c))
272
273 (define (make-recursive-counter effort-limit size-limit orig current)
274 (let ((c (%make-counter (make-variable 0)
275 (make-variable 0)
276 (counter-continuation orig)
277 #t
278 (counter-data orig)
279 current)))
280 (transfer! current c effort-limit size-limit)
281 c))
282
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.
287 ;;
288 ;; TODO: Record value size in operand structure?
289 ;;
290 (define-record-type <operand>
291 (%make-operand var sym visit source visit-count use-count
292 copyable? residual-value constant-value alias-value)
293 operand?
294 (var operand-var)
295 (sym operand-sym)
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!))
304
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))))
314
315 (define* (make-bound-operands vars syms sources visit #:optional aliases)
316 (if 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))
322 vars syms sources)))
323
324 (define (make-unbound-operands vars syms)
325 (map make-operand vars syms))
326
327 (define (set-operand-residual-value! op val)
328 (%set-operand-residual-value!
329 op
330 (match val
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.
334 first)
335 (else
336 val))))
337
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.
344 ;;
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))
348 (dynamic-wind
349 (lambda ()
350 (set-operand-visit-count! op (1+ (operand-visit-count op))))
351 (lambda ()
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)
355 (let/ec k
356 (define (abort)
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)
361 (k #f))
362 ((%operand-visit op)
363 (operand-source op)
364 (make-top-counter effort-limit size-limit abort op)
365 ctx)))))
366 (lambda ()
367 (set-operand-visit-count! op (1- (operand-visit-count op)))))))
368
369 ;; A helper for constant folding.
370 ;;
371 (define (types-check? primitive-name args)
372 (case primitive-name
373 ((values) #t)
374 ((not pair? null? list? symbol? vector? struct?)
375 (= (length args) 1))
376 ((eq? eqv? equal?)
377 (= (length args) 2))
378 ;; FIXME: add more cases?
379 (else #f)))
380
381 (define* (peval exp #:optional (cenv (current-module)) (env vlist-null)
382 #:key
383 (operator-size-limit 40)
384 (operand-size-limit 20)
385 (value-size-limit 10)
386 (effort-limit 500)
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."
390
391 ;; This is a simple partial evaluator. It effectively performs
392 ;; constant folding, copy propagation, dead code elimination, and
393 ;; inlining.
394
395 ;; TODO:
396 ;;
397 ;; Propagate copies across toplevel bindings, if we can prove the
398 ;; bindings to be immutable.
399 ;;
400 ;; Specialize lambda expressions with invariant arguments.
401
402 (define local-toplevel-env
403 ;; The top-level environment of the module being compiled.
404 (match exp
405 (($ <toplevel-define> _ name)
406 (vhash-consq name #t env))
407 (($ <sequence> _ exps)
408 (fold (lambda (x r)
409 (match x
410 (($ <toplevel-define> _ name)
411 (vhash-consq name #t r))
412 (_ r)))
413 env
414 exps))
415 (_ env)))
416
417 (define (local-toplevel? name)
418 (vhash-assq name local-toplevel-env))
419
420 ;; gensym -> <var>
421 ;; renamed-term -> original-term
422 ;;
423 (define store (build-var-table exp))
424
425 (define (record-new-temporary! name sym refcount)
426 (set! store (vhash-consq sym (make-var name sym refcount #f) store)))
427
428 (define (lookup-var sym)
429 (let ((v (vhash-assq sym store)))
430 (if v (cdr v) (error "unbound var" sym (vlist->list store)))))
431
432 (define (fresh-gensyms vars)
433 (map (lambda (var)
434 (let ((new (gensym (string-append (symbol->string (var-name var))
435 " "))))
436 (set! store (vhash-consq new var store))
437 new))
438 vars))
439
440 (define (assigned-lexical? sym)
441 (var-set? (lookup-var sym)))
442
443 (define (lexical-refcount sym)
444 (var-refcount (lookup-var sym)))
445
446 ;; ORIG has been alpha-renamed to NEW. Analyze NEW and record a link
447 ;; from it to ORIG.
448 ;;
449 (define (record-source-expression! orig new)
450 (set! store (vhash-consq new (source-expression orig) store))
451 new)
452
453 ;; Find the source expression corresponding to NEW. Used to detect
454 ;; recursive inlining attempts.
455 ;;
456 (define (source-expression new)
457 (let ((x (vhash-assq new store)))
458 (if x (cdr x) new)))
459
460 (define (record-operand-use op)
461 (set-operand-use-count! op (1+ (operand-use-count op))))
462
463 (define (unrecord-operand-uses op n)
464 (let ((count (- (operand-use-count op) n)))
465 (when (zero? count)
466 (set-operand-residual-value! op #f))
467 (set-operand-use-count! op count)))
468
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)))
475
476 (define (fold-constants src name args ctx)
477 (define (apply-primitive name args)
478 ;; todo: further optimize commutative primitives
479 (catch #t
480 (lambda ()
481 (call-with-values
482 (lambda ()
483 (apply (module-ref the-scm-module name) args))
484 (lambda results
485 (values #t results))))
486 (lambda _
487 (values #f '()))))
488
489 (define (make-values src values)
490 (match values
491 ((single) single) ; 1 value
492 ((_ ...) ; 0, or 2 or more values
493 (make-application src (make-primitive-ref src 'values)
494 values))))
495 (define (residualize-call)
496 (make-application src (make-primitive-ref #f name) args))
497 (cond
498 ((every const? args)
499 (let-values (((success? values)
500 (apply-primitive name (map const-exp args))))
501 (log 'fold success? values name args)
502 (if success?
503 (case ctx
504 ((effect) (make-void src))
505 ((test)
506 ;; Values truncation: only take the first
507 ;; value.
508 (if (pair? values)
509 (make-const src (car values))
510 (make-values src '())))
511 (else
512 (make-values src (map (cut make-const src <>) values))))
513 (residualize-call))))
514 ((and (eq? ctx 'effect) (types-check? name args))
515 (make-void #f))
516 (else
517 (residualize-call))))
518
519 (define (inline-values exp src names gensyms body)
520 (let loop ((exp exp))
521 (match exp
522 ;; Some expression types are always singly-valued.
523 ((or ($ <const>)
524 ($ <void>)
525 ($ <lambda>)
526 ($ <lexical-ref>)
527 ($ <toplevel-ref>)
528 ($ <module-ref>)
529 ($ <primitive-ref>)
530 ($ <dynref>)
531 ($ <lexical-set>) ; FIXME: these set! expressions
532 ($ <toplevel-set>) ; could return zero values in
533 ($ <toplevel-define>) ; the future
534 ($ <module-set>) ;
535 ($ <dynset>)) ;
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)))
542
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)))
547
548 ;; Not going to copy code into both branches.
549 (($ <conditional>) #f)
550
551 ;; Bail on other applications.
552 (($ <application>) #f)
553
554 ;; Bail on prompt and abort.
555 (($ <prompt>) #f)
556 (($ <abort>) #f)
557
558 ;; Propagate to tail positions.
559 (($ <let> src names gensyms vals body)
560 (let ((body (loop body)))
561 (and body
562 (make-let src names gensyms vals body))))
563 (($ <letrec> src in-order? names gensyms vals body)
564 (let ((body (loop body)))
565 (and body
566 (make-letrec src in-order? names gensyms vals body))))
567 (($ <fix> src names gensyms vals body)
568 (let ((body (loop body)))
569 (and 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)))
574 (and 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)))
580 (and body
581 (make-dynwind src winder body unwinder))))
582 (($ <dynlet> src fluids vals body)
583 (let ((body (loop body)))
584 (and body
585 (make-dynlet src fluids vals body))))
586 (($ <sequence> src exps)
587 (match exps
588 ((head ... tail)
589 (let ((tail (loop tail)))
590 (and tail
591 (make-sequence src (append head (list tail)))))))))))
592
593 (define compute-effects
594 (make-effects-analyzer assigned-lexical?))
595
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)))
602
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.
609 ;;
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
616 ;; context.
617 (or (eq? ctx 'operator)
618 (not (zero? (operand-use-count op)))))
619
620 ;; values := (op ...)
621 ;; effects := (op ...)
622 (define (residualize values effects)
623 ;; Note, values and effects are reversed.
624 (cond
625 (in-order?
626 (let ((values (filter operand-residual-value ops)))
627 (if (null? values)
628 body
629 (build-result (map (compose var-name operand-var) values)
630 (map operand-sym values)
631 (map operand-residual-value values)
632 body))))
633 (else
634 (let ((body
635 (if (null? effects)
636 body
637 (let ((effect-vals (map operand-residual-value effects)))
638 (make-sequence #f (reverse (cons body effect-vals)))))))
639 (if (null? values)
640 body
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)
645 body)))))))
646
647 ;; old := (bool ...)
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))
652 (cond
653 ((null? ops*)
654 (let ((new (map referenced? ops)))
655 (if (not (equal? new old))
656 (prune new values '())
657 (residualize values
658 (map (lambda (op val)
659 (set-operand-residual-value! op val)
660 op)
661 (map car effects) (map cdr effects))))))
662 (else
663 (let ((op (car ops*)))
664 (cond
665 ((memq op values)
666 (lp (cdr ops*) values effects))
667 ((operand-residual-value op)
668 (lp (cdr ops*) (cons op values) effects))
669 ((referenced? op)
670 (set-operand-residual-value! op (visit-operand op counter 'value))
671 (lp (cdr ops*) (cons op values) effects))
672 (else
673 (lp (cdr ops*)
674 values
675 (let ((effect (visit-operand op counter 'effect)))
676 (if (void? effect)
677 effects
678 (acons op effect effects))))))))))))
679
680 (define (small-expression? x limit)
681 (let/ec k
682 (tree-il-fold
683 (lambda (x res) ; leaf
684 (1+ res))
685 (lambda (x res) ; down
686 (1+ res))
687 (lambda (x res) ; up
688 (if (< res limit)
689 res
690 (k #f)))
691 0 x)
692 #t))
693
694 (define (extend-env sym op env)
695 (vhash-consq (operand-sym op) op (vhash-consq sym op env)))
696
697 (let loop ((exp exp)
698 (env vlist-null) ; vhash of gensym -> <operand>
699 (counter #f) ; inlined call stack
700 (ctx 'values)) ; effect, value, values, test, operator, or call
701 (define (lookup var)
702 (cond
703 ((vhash-assq var env) => cdr)
704 (else (error "unbound var" var))))
705
706 ;; Find a value referenced a specific number of times. This is a hack
707 ;; that's used for propagating fresh data structures like rest lists and
708 ;; prompt tags. Usually we wouldn't copy consed data, but we can do so in
709 ;; some special cases like `apply' or prompts if we can account
710 ;; for all of its uses.
711 ;;
712 ;; You don't want to use this in general because it introduces a slight
713 ;; nonlinearity by running peval again (though with a small effort and size
714 ;; counter).
715 ;;
716 (define (find-definition x n-aliases)
717 (cond
718 ((lexical-ref? x)
719 (cond
720 ((lookup (lexical-ref-gensym x))
721 => (lambda (op)
722 (let ((y (or (operand-residual-value op)
723 (visit-operand op counter 'value 10 10)
724 (operand-source op))))
725 (cond
726 ((and (lexical-ref? y)
727 (= (lexical-refcount (lexical-ref-gensym x)) 1))
728 ;; X is a simple alias for Y. Recurse, regardless of
729 ;; the number of aliases we were expecting.
730 (find-definition y n-aliases))
731 ((= (lexical-refcount (lexical-ref-gensym x)) n-aliases)
732 ;; We found a definition that is aliased the right
733 ;; number of times. We still recurse in case it is a
734 ;; lexical.
735 (values (find-definition y 1)
736 op))
737 (else
738 ;; We can't account for our aliases.
739 (values #f #f))))))
740 (else
741 ;; A formal parameter. Can't say anything about that.
742 (values #f #f))))
743 ((= n-aliases 1)
744 ;; Not a lexical: success, but only if we are looking for an
745 ;; unaliased value.
746 (values x #f))
747 (else (values #f #f))))
748
749 (define (visit exp ctx)
750 (loop exp env counter ctx))
751
752 (define (for-value exp) (visit exp 'value))
753 (define (for-values exp) (visit exp 'values))
754 (define (for-test exp) (visit exp 'test))
755 (define (for-effect exp) (visit exp 'effect))
756 (define (for-call exp) (visit exp 'call))
757 (define (for-tail exp) (visit exp ctx))
758
759 (if counter
760 (record-effort! counter))
761
762 (log 'visit ctx (and=> counter effort-counter)
763 (unparse-tree-il exp))
764
765 (match exp
766 (($ <const>)
767 (case ctx
768 ((effect) (make-void #f))
769 (else exp)))
770 (($ <void>)
771 (case ctx
772 ((test) (make-const #f #t))
773 (else exp)))
774 (($ <lexical-ref> _ _ gensym)
775 (log 'begin-copy gensym)
776 (let ((op (lookup gensym)))
777 (cond
778 ((eq? ctx 'effect)
779 (log 'lexical-for-effect gensym)
780 (make-void #f))
781 ((operand-alias-value op)
782 ;; This is an unassigned operand that simply aliases some
783 ;; other operand. Recurse to avoid residualizing the leaf
784 ;; binding.
785 => for-tail)
786 ((eq? ctx 'call)
787 ;; Don't propagate copies if we are residualizing a call.
788 (log 'residualize-lexical-call gensym op)
789 (residualize-lexical op))
790 ((var-set? (operand-var op))
791 ;; Assigned lexicals don't copy-propagate.
792 (log 'assigned-var gensym op)
793 (residualize-lexical op))
794 ((not (operand-copyable? op))
795 ;; We already know that this operand is not copyable.
796 (log 'not-copyable gensym op)
797 (residualize-lexical op))
798 ((and=> (operand-constant-value op)
799 (lambda (x) (or (const? x) (void? x) (primitive-ref? x))))
800 ;; A cache hit.
801 (let ((val (operand-constant-value op)))
802 (log 'memoized-constant gensym val)
803 (for-tail val)))
804 ((visit-operand op counter (if (eq? ctx 'values) 'value ctx)
805 recursive-effort-limit operand-size-limit)
806 =>
807 ;; If we end up deciding to residualize this value instead of
808 ;; copying it, save that residualized value.
809 (lambda (val)
810 (cond
811 ((not (constant-expression? val))
812 (log 'not-constant gensym op)
813 ;; At this point, ctx is operator, test, or value. A
814 ;; value that is non-constant in one context will be
815 ;; non-constant in the others, so it's safe to record
816 ;; that here, and avoid future visits.
817 (set-operand-copyable?! op #f)
818 (residualize-lexical op ctx val))
819 ((or (const? val)
820 (void? val)
821 (primitive-ref? val))
822 ;; Always propagate simple values that cannot lead to
823 ;; code bloat.
824 (log 'copy-simple gensym val)
825 ;; It could be this constant is the result of folding.
826 ;; If that is the case, cache it. This helps loop
827 ;; unrolling get farther.
828 (if (or (eq? ctx 'value) (eq? ctx 'values))
829 (begin
830 (log 'memoize-constant gensym val)
831 (set-operand-constant-value! op val)))
832 val)
833 ((= 1 (var-refcount (operand-var op)))
834 ;; Always propagate values referenced only once.
835 (log 'copy-single gensym val)
836 val)
837 ;; FIXME: do demand-driven size accounting rather than
838 ;; these heuristics.
839 ((eq? ctx 'operator)
840 ;; A pure expression in the operator position. Inline
841 ;; if it's a lambda that's small enough.
842 (if (and (lambda? val)
843 (small-expression? val operator-size-limit))
844 (begin
845 (log 'copy-operator gensym val)
846 val)
847 (begin
848 (log 'too-big-for-operator gensym val)
849 (residualize-lexical op ctx val))))
850 (else
851 ;; A pure expression, processed for call or for value.
852 ;; Don't inline lambdas, because they will probably won't
853 ;; fold because we don't know the operator.
854 (if (and (small-expression? val value-size-limit)
855 (not (tree-il-any lambda? val)))
856 (begin
857 (log 'copy-value gensym val)
858 val)
859 (begin
860 (log 'too-big-or-has-lambda gensym val)
861 (residualize-lexical op ctx val)))))))
862 (else
863 ;; Visit failed. Either the operand isn't bound, as in
864 ;; lambda formal parameters, or the copy was aborted.
865 (log 'unbound-or-aborted gensym op)
866 (residualize-lexical op)))))
867 (($ <lexical-set> src name gensym exp)
868 (let ((op (lookup gensym)))
869 (if (zero? (var-refcount (operand-var op)))
870 (let ((exp (for-effect exp)))
871 (if (void? exp)
872 exp
873 (make-sequence src (list exp (make-void #f)))))
874 (begin
875 (record-operand-use op)
876 (make-lexical-set src name (operand-sym op) (for-value exp))))))
877 (($ <let> src names gensyms vals body)
878 (define (compute-alias exp)
879 ;; It's very common for macros to introduce something like:
880 ;;
881 ;; ((lambda (x y) ...) x-exp y-exp)
882 ;;
883 ;; In that case you might end up trying to inline something like:
884 ;;
885 ;; (let ((x x-exp) (y y-exp)) ...)
886 ;;
887 ;; But if x-exp is itself a lexical-ref that aliases some much
888 ;; larger expression, perhaps it will fail to inline due to
889 ;; size. However we don't want to introduce a useless alias
890 ;; (in this case, x). So if the RHS of a let expression is a
891 ;; lexical-ref, we record that expression. If we end up having
892 ;; to residualize X, then instead we residualize X-EXP, as long
893 ;; as it isn't assigned.
894 ;;
895 (match exp
896 (($ <lexical-ref> _ _ sym)
897 (let ((op (lookup sym)))
898 (and (not (var-set? (operand-var op)))
899 (or (operand-alias-value op)
900 exp))))
901 (_ #f)))
902
903 (let* ((vars (map lookup-var gensyms))
904 (new (fresh-gensyms vars))
905 (ops (make-bound-operands vars new vals
906 (lambda (exp counter ctx)
907 (loop exp env counter ctx))
908 (map compute-alias vals)))
909 (env (fold extend-env env gensyms ops))
910 (body (loop body env counter ctx)))
911 (cond
912 ((const? body)
913 (for-tail (make-sequence src (append vals (list body)))))
914 ((and (lexical-ref? body)
915 (memq (lexical-ref-gensym body) new))
916 (let ((sym (lexical-ref-gensym body))
917 (pairs (map cons new vals)))
918 ;; (let ((x foo) (y bar) ...) x) => (begin bar ... foo)
919 (for-tail
920 (make-sequence
921 src
922 (append (map cdr (alist-delete sym pairs eq?))
923 (list (assq-ref pairs sym)))))))
924 (else
925 ;; Only include bindings for which lexical references
926 ;; have been residualized.
927 (prune-bindings ops #f body counter ctx
928 (lambda (names gensyms vals body)
929 (if (null? names) (error "what!" names))
930 (make-let src names gensyms vals body)))))))
931 (($ <letrec> src in-order? names gensyms vals body)
932 ;; Note the difference from the `let' case: here we use letrec*
933 ;; so that the `visit' procedure for the new operands closes over
934 ;; an environment that includes the operands. Also we don't try
935 ;; to elide aliases, because we can't sensibly reduce something
936 ;; like (letrec ((a b) (b a)) a).
937 (letrec* ((visit (lambda (exp counter ctx)
938 (loop exp env* counter ctx)))
939 (vars (map lookup-var gensyms))
940 (new (fresh-gensyms vars))
941 (ops (make-bound-operands vars new vals visit))
942 (env* (fold extend-env env gensyms ops))
943 (body* (visit body counter ctx)))
944 (if (and (const? body*) (every constant-expression? vals))
945 ;; We may have folded a loop completely, even though there
946 ;; might be cyclical references between the bound values.
947 ;; Handle this degenerate case specially.
948 body*
949 (prune-bindings ops in-order? body* counter ctx
950 (lambda (names gensyms vals body)
951 (make-letrec src in-order?
952 names gensyms vals body))))))
953 (($ <fix> src names gensyms vals body)
954 (letrec* ((visit (lambda (exp counter ctx)
955 (loop exp env* counter ctx)))
956 (vars (map lookup-var gensyms))
957 (new (fresh-gensyms vars))
958 (ops (make-bound-operands vars new vals visit))
959 (env* (fold extend-env env gensyms ops))
960 (body* (visit body counter ctx)))
961 (if (const? body*)
962 body*
963 (prune-bindings ops #f body* counter ctx
964 (lambda (names gensyms vals body)
965 (make-fix src names gensyms vals body))))))
966 (($ <let-values> lv-src producer consumer)
967 ;; Peval the producer, then try to inline the consumer into
968 ;; the producer. If that succeeds, peval again. Otherwise
969 ;; reconstruct the let-values, pevaling the consumer.
970 (let ((producer (for-values producer)))
971 (or (match consumer
972 (($ <lambda-case> src req #f #f #f () gensyms body #f)
973 (cond
974 ((inline-values producer src req gensyms body)
975 => for-tail)
976 (else #f)))
977 (_ #f))
978 (make-let-values lv-src producer (for-tail consumer)))))
979 (($ <dynwind> src winder body unwinder)
980 (let ((pre (for-value winder))
981 (body (for-tail body))
982 (post (for-value unwinder)))
983 (cond
984 ((not (constant-expression? pre))
985 (cond
986 ((not (constant-expression? post))
987 (let ((pre-sym (gensym "pre-")) (post-sym (gensym "post-")))
988 (record-new-temporary! 'pre pre-sym 1)
989 (record-new-temporary! 'post post-sym 1)
990 (make-let src '(pre post) (list pre-sym post-sym) (list pre post)
991 (make-dynwind src
992 (make-lexical-ref #f 'pre pre-sym)
993 body
994 (make-lexical-ref #f 'post post-sym)))))
995 (else
996 (let ((pre-sym (gensym "pre-")))
997 (record-new-temporary! 'pre pre-sym 1)
998 (make-let src '(pre) (list pre-sym) (list pre)
999 (make-dynwind src
1000 (make-lexical-ref #f 'pre pre-sym)
1001 body
1002 post))))))
1003 ((not (constant-expression? post))
1004 (let ((post-sym (gensym "post-")))
1005 (record-new-temporary! 'post post-sym 1)
1006 (make-let src '(post) (list post-sym) (list post)
1007 (make-dynwind src
1008 pre
1009 body
1010 (make-lexical-ref #f 'post post-sym)))))
1011 (else
1012 (make-dynwind src pre body post)))))
1013 (($ <dynlet> src fluids vals body)
1014 (make-dynlet src (map for-value fluids) (map for-value vals)
1015 (for-tail body)))
1016 (($ <dynref> src fluid)
1017 (make-dynref src (for-value fluid)))
1018 (($ <dynset> src fluid exp)
1019 (make-dynset src (for-value fluid) (for-value exp)))
1020 (($ <toplevel-ref> src (? effect-free-primitive? name))
1021 (if (local-toplevel? name)
1022 exp
1023 (let ((exp (resolve-primitives! exp cenv)))
1024 (if (primitive-ref? exp)
1025 (for-tail exp)
1026 exp))))
1027 (($ <toplevel-ref>)
1028 ;; todo: open private local bindings.
1029 exp)
1030 (($ <module-ref> src module (? effect-free-primitive? name) #f)
1031 (let ((module (false-if-exception
1032 (resolve-module module #:ensure #f))))
1033 (if (module? module)
1034 (let ((var (module-variable module name)))
1035 (if (eq? var (module-variable the-scm-module name))
1036 (make-primitive-ref src name)
1037 exp))
1038 exp)))
1039 (($ <module-ref>)
1040 exp)
1041 (($ <module-set> src mod name public? exp)
1042 (make-module-set src mod name public? (for-value exp)))
1043 (($ <toplevel-define> src name exp)
1044 (make-toplevel-define src name (for-value exp)))
1045 (($ <toplevel-set> src name exp)
1046 (make-toplevel-set src name (for-value exp)))
1047 (($ <primitive-ref>)
1048 (case ctx
1049 ((effect) (make-void #f))
1050 ((test) (make-const #f #t))
1051 (else exp)))
1052 (($ <conditional> src condition subsequent alternate)
1053 (define (call-with-failure-thunk exp proc)
1054 (match exp
1055 (($ <application> _ _ ()) (proc exp))
1056 (($ <const>) (proc exp))
1057 (($ <void>) (proc exp))
1058 (($ <lexical-ref>) (proc exp))
1059 (_
1060 (let ((t (gensym "failure-")))
1061 (record-new-temporary! 'failure t 2)
1062 (make-let
1063 src (list 'failure) (list t)
1064 (list
1065 (make-lambda
1066 #f '()
1067 (make-lambda-case #f '() #f #f #f '() '() exp #f)))
1068 (proc (make-application #f (make-lexical-ref #f 'failure t)
1069 '())))))))
1070 (define (simplify-conditional c)
1071 (match c
1072 ;; Swap the arms of (if (not FOO) A B), to simplify.
1073 (($ <conditional> src
1074 ($ <application> _ ($ <primitive-ref> _ 'not) (pred))
1075 subsequent alternate)
1076 (simplify-conditional
1077 (make-conditional src pred alternate subsequent)))
1078 ;; Special cases for common tests in the predicates of chains
1079 ;; of if expressions.
1080 (($ <conditional> src
1081 ($ <conditional> src* outer-test inner-test ($ <const> _ #f))
1082 inner-subsequent
1083 alternate)
1084 (let lp ((alternate alternate))
1085 (match alternate
1086 ;; Lift a common repeated test out of a chain of if
1087 ;; expressions.
1088 (($ <conditional> _ (? (cut tree-il=? outer-test <>))
1089 other-subsequent alternate)
1090 (make-conditional
1091 src outer-test
1092 (simplify-conditional
1093 (make-conditional src* inner-test inner-subsequent
1094 other-subsequent))
1095 alternate))
1096 ;; Likewise, but punching through any surrounding
1097 ;; failure continuations.
1098 (($ <let> let-src (name) (sym) ((and thunk ($ <lambda>))) body)
1099 (make-let
1100 let-src (list name) (list sym) (list thunk)
1101 (lp body)))
1102 ;; Otherwise, rotate AND tests to expose a simple
1103 ;; condition in the front. Although this may result in
1104 ;; lexically binding failure thunks, the thunks will be
1105 ;; compiled to labels allocation, so there's no actual
1106 ;; code growth.
1107 (_
1108 (call-with-failure-thunk
1109 alternate
1110 (lambda (failure)
1111 (make-conditional
1112 src outer-test
1113 (simplify-conditional
1114 (make-conditional src* inner-test inner-subsequent failure))
1115 failure)))))))
1116 (_ c)))
1117 (match (for-test condition)
1118 (($ <const> _ val)
1119 (if val
1120 (for-tail subsequent)
1121 (for-tail alternate)))
1122 (c
1123 (simplify-conditional
1124 (make-conditional src c (for-tail subsequent)
1125 (for-tail alternate))))))
1126 (($ <application> src
1127 ($ <primitive-ref> _ '@call-with-values)
1128 (producer
1129 ($ <lambda> _ _
1130 (and consumer
1131 ;; No optional or kwargs.
1132 ($ <lambda-case>
1133 _ req #f rest #f () gensyms body #f)))))
1134 (for-tail (make-let-values src (make-application src producer '())
1135 consumer)))
1136 (($ <application> src ($ <primitive-ref> _ 'values) exps)
1137 (cond
1138 ((null? exps)
1139 (if (eq? ctx 'effect)
1140 (make-void #f)
1141 exp))
1142 (else
1143 (let ((vals (map for-value exps)))
1144 (if (and (case ctx
1145 ((value test effect) #t)
1146 (else (null? (cdr vals))))
1147 (every singly-valued-expression? vals))
1148 (for-tail (make-sequence src (append (cdr vals) (list (car vals)))))
1149 (make-application src (make-primitive-ref #f 'values) vals))))))
1150 (($ <application> src (and apply ($ <primitive-ref> _ (or 'apply '@apply)))
1151 (proc args ... tail))
1152 (let lp ((tail* (find-definition tail 1)) (speculative? #t))
1153 (define (copyable? x)
1154 ;; Inlining a result from find-definition effectively copies it,
1155 ;; relying on the let-pruning to remove its original binding. We
1156 ;; shouldn't copy non-constant expressions.
1157 (or (not speculative?) (constant-expression? x)))
1158 (match tail*
1159 (($ <const> _ (args* ...))
1160 (let ((args* (map (cut make-const #f <>) args*)))
1161 (for-tail (make-application src proc (append args args*)))))
1162 (($ <application> _ ($ <primitive-ref> _ 'cons)
1163 ((and head (? copyable?)) (and tail (? copyable?))))
1164 (for-tail (make-application src apply
1165 (cons proc
1166 (append args (list head tail))))))
1167 (($ <application> _ ($ <primitive-ref> _ 'list)
1168 (and args* ((? copyable?) ...)))
1169 (for-tail (make-application src proc (append args args*))))
1170 (tail*
1171 (if speculative?
1172 (lp (for-value tail) #f)
1173 (let ((args (append (map for-value args) (list tail*))))
1174 (make-application src apply
1175 (cons (for-value proc) args))))))))
1176 (($ <application> src orig-proc orig-args)
1177 ;; todo: augment the global env with specialized functions
1178 (let revisit-proc ((proc (visit orig-proc 'operator)))
1179 (match proc
1180 (($ <primitive-ref> _ (? constructor-primitive? name))
1181 (cond
1182 ((and (memq ctx '(effect test))
1183 (match (cons name orig-args)
1184 ((or ('cons _ _)
1185 ('list . _)
1186 ('vector . _)
1187 ('make-prompt-tag)
1188 ('make-prompt-tag ($ <const> _ (? string?))))
1189 #t)
1190 (_ #f)))
1191 ;; Some expressions can be folded without visiting the
1192 ;; arguments for value.
1193 (let ((res (if (eq? ctx 'effect)
1194 (make-void #f)
1195 (make-const #f #t))))
1196 (for-tail (make-sequence src (append orig-args (list res))))))
1197 (else
1198 (match (cons name (map for-value orig-args))
1199 (('cons head tail)
1200 (match tail
1201 (($ <const> src (? (cut eq? <> '())))
1202 (make-application src (make-primitive-ref #f 'list)
1203 (list head)))
1204 (($ <application> src ($ <primitive-ref> _ 'list) elts)
1205 (make-application src (make-primitive-ref #f 'list)
1206 (cons head elts)))
1207 (_ (make-application src proc (list head tail)))))
1208 ((_ . args)
1209 (make-application src proc args))))))
1210 (($ <primitive-ref> _ (? accessor-primitive? name))
1211 (match (cons name (map for-value orig-args))
1212 ;; FIXME: these for-tail recursions could take place outside
1213 ;; an effort counter.
1214 (('car ($ <application> src ($ <primitive-ref> _ 'cons) (head tail)))
1215 (for-tail (make-sequence src (list tail head))))
1216 (('cdr ($ <application> src ($ <primitive-ref> _ 'cons) (head tail)))
1217 (for-tail (make-sequence src (list head tail))))
1218 (('car ($ <application> src ($ <primitive-ref> _ 'list) (head . tail)))
1219 (for-tail (make-sequence src (append tail (list head)))))
1220 (('cdr ($ <application> src ($ <primitive-ref> _ 'list) (head . tail)))
1221 (for-tail (make-sequence
1222 src
1223 (list head
1224 (make-application
1225 src (make-primitive-ref #f 'list) tail)))))
1226
1227 (('car ($ <const> src (head . tail)))
1228 (for-tail (make-const src head)))
1229 (('cdr ($ <const> src (head . tail)))
1230 (for-tail (make-const src tail)))
1231 (((or 'memq 'memv) k ($ <const> _ (elts ...)))
1232 ;; FIXME: factor
1233 (case ctx
1234 ((effect)
1235 (for-tail
1236 (make-sequence src (list k (make-void #f)))))
1237 ((test)
1238 (cond
1239 ((const? k)
1240 ;; A shortcut. The `else' case would handle it, but
1241 ;; this way is faster.
1242 (let ((member (case name ((memq) memq) ((memv) memv))))
1243 (make-const #f (and (member (const-exp k) elts) #t))))
1244 ((null? elts)
1245 (for-tail
1246 (make-sequence src (list k (make-const #f #f)))))
1247 (else
1248 (let ((t (gensym "t-"))
1249 (eq (if (eq? name 'memq) 'eq? 'eqv?)))
1250 (record-new-temporary! 't t (length elts))
1251 (for-tail
1252 (make-let
1253 src (list 't) (list t) (list k)
1254 (let lp ((elts elts))
1255 (define test
1256 (make-application
1257 #f (make-primitive-ref #f eq)
1258 (list (make-lexical-ref #f 't t)
1259 (make-const #f (car elts)))))
1260 (if (null? (cdr elts))
1261 test
1262 (make-conditional src test
1263 (make-const #f #t)
1264 (lp (cdr elts)))))))))))
1265 (else
1266 (cond
1267 ((const? k)
1268 (let ((member (case name ((memq) memq) ((memv) memv))))
1269 (make-const #f (member (const-exp k) elts))))
1270 ((null? elts)
1271 (for-tail (make-sequence src (list k (make-const #f #f)))))
1272 (else
1273 (make-application src proc (list k (make-const #f elts))))))))
1274 ((_ . args)
1275 (or (fold-constants src name args ctx)
1276 (make-application src proc args)))))
1277 (($ <primitive-ref> _ (? effect-free-primitive? name))
1278 (let ((args (map for-value orig-args)))
1279 (or (fold-constants src name args ctx)
1280 (make-application src proc args))))
1281 (($ <lambda> _ _
1282 ($ <lambda-case> _ req opt rest #f inits gensyms body #f))
1283 ;; Simple case: no keyword arguments.
1284 ;; todo: handle the more complex cases
1285 (let* ((nargs (length orig-args))
1286 (nreq (length req))
1287 (nopt (if opt (length opt) 0))
1288 (key (source-expression proc)))
1289 (define (inlined-application)
1290 (make-let src
1291 (append req
1292 (or opt '())
1293 (if rest (list rest) '()))
1294 gensyms
1295 (if (> nargs (+ nreq nopt))
1296 (append (list-head orig-args (+ nreq nopt))
1297 (list
1298 (make-application
1299 #f
1300 (make-primitive-ref #f 'list)
1301 (drop orig-args (+ nreq nopt)))))
1302 (append orig-args
1303 (drop inits (- nargs nreq))
1304 (if rest
1305 (list (make-const #f '()))
1306 '())))
1307 body))
1308
1309 (cond
1310 ((or (< nargs nreq) (and (not rest) (> nargs (+ nreq nopt))))
1311 ;; An error, or effecting arguments.
1312 (make-application src (for-call orig-proc)
1313 (map for-value orig-args)))
1314 ((or (and=> (find-counter key counter) counter-recursive?)
1315 (lambda? orig-proc))
1316 ;; A recursive call, or a lambda in the operator
1317 ;; position of the source expression. Process again in
1318 ;; tail context.
1319 ;;
1320 ;; In the recursive case, mark intervening counters as
1321 ;; recursive, so we can handle a toplevel counter that
1322 ;; recurses mutually with some other procedure.
1323 ;; Otherwise, the next time we see the other procedure,
1324 ;; the effort limit would be clamped to 100.
1325 ;;
1326 (let ((found (find-counter key counter)))
1327 (if (and found (counter-recursive? found))
1328 (let lp ((counter counter))
1329 (if (not (eq? counter found))
1330 (begin
1331 (set-counter-recursive?! counter #t)
1332 (lp (counter-prev counter)))))))
1333
1334 (log 'inline-recurse key)
1335 (loop (inlined-application) env counter ctx))
1336 (else
1337 ;; An integration at the top-level, the first
1338 ;; recursion of a recursive procedure, or a nested
1339 ;; integration of a procedure that hasn't been seen
1340 ;; yet.
1341 (log 'inline-begin exp)
1342 (let/ec k
1343 (define (abort)
1344 (log 'inline-abort exp)
1345 (k (make-application src (for-call orig-proc)
1346 (map for-value orig-args))))
1347 (define new-counter
1348 (cond
1349 ;; These first two cases will transfer effort
1350 ;; from the current counter into the new
1351 ;; counter.
1352 ((find-counter key counter)
1353 => (lambda (prev)
1354 (make-recursive-counter recursive-effort-limit
1355 operand-size-limit
1356 prev counter)))
1357 (counter
1358 (make-nested-counter abort key counter))
1359 ;; This case opens a new account, effectively
1360 ;; printing money. It should only do so once
1361 ;; for each call site in the source program.
1362 (else
1363 (make-top-counter effort-limit operand-size-limit
1364 abort key))))
1365 (define result
1366 (loop (inlined-application) env new-counter ctx))
1367
1368 (if counter
1369 ;; The nested inlining attempt succeeded.
1370 ;; Deposit the unspent effort and size back
1371 ;; into the current counter.
1372 (transfer! new-counter counter))
1373
1374 (log 'inline-end result exp)
1375 result)))))
1376 (($ <let> _ _ _ vals _)
1377 ;; Attempt to inline `let' in the operator position.
1378 ;;
1379 ;; We have to re-visit the proc in value mode, since the
1380 ;; `let' bindings might have been introduced or renamed,
1381 ;; whereas the lambda (if any) in operator position has not
1382 ;; been renamed.
1383 (if (or (and-map constant-expression? vals)
1384 (and-map constant-expression? orig-args))
1385 ;; The arguments and the let-bound values commute.
1386 (match (for-value orig-proc)
1387 (($ <let> lsrc names syms vals body)
1388 (log 'inline-let orig-proc)
1389 (for-tail
1390 (make-let lsrc names syms vals
1391 (make-application src body orig-args))))
1392 ;; It's possible for a `let' to go away after the
1393 ;; visit due to the fact that visiting a procedure in
1394 ;; value context will prune unused bindings, whereas
1395 ;; visiting in operator mode can't because it doesn't
1396 ;; traverse through lambdas. In that case re-visit
1397 ;; the procedure.
1398 (proc (revisit-proc proc)))
1399 (make-application src (for-call orig-proc)
1400 (map for-value orig-args))))
1401 (_
1402 (make-application src (for-call orig-proc)
1403 (map for-value orig-args))))))
1404 (($ <lambda> src meta body)
1405 (case ctx
1406 ((effect) (make-void #f))
1407 ((test) (make-const #f #t))
1408 ((operator) exp)
1409 (else (record-source-expression!
1410 exp
1411 (make-lambda src meta (for-values body))))))
1412 (($ <lambda-case> src req opt rest kw inits gensyms body alt)
1413 (define (lift-applied-lambda body gensyms)
1414 (and (not opt) rest (not kw)
1415 (match body
1416 (($ <application> _
1417 ($ <primitive-ref> _ '@apply)
1418 (($ <lambda> _ _ lcase)
1419 ($ <lexical-ref> _ _ sym)
1420 ...))
1421 (and (equal? sym gensyms)
1422 (not (lambda-case-alternate lcase))
1423 lcase))
1424 (_ #f))))
1425 (let* ((vars (map lookup-var gensyms))
1426 (new (fresh-gensyms vars))
1427 (env (fold extend-env env gensyms
1428 (make-unbound-operands vars new)))
1429 (new-sym (lambda (old)
1430 (operand-sym (cdr (vhash-assq old env)))))
1431 (body (loop body env counter ctx)))
1432 (or
1433 ;; (lambda args (apply (lambda ...) args)) => (lambda ...)
1434 (lift-applied-lambda body new)
1435 (make-lambda-case src req opt rest
1436 (match kw
1437 ((aok? (kw name old) ...)
1438 (cons aok? (map list kw name (map new-sym old))))
1439 (_ #f))
1440 (map (cut loop <> env counter 'value) inits)
1441 new
1442 body
1443 (and alt (for-tail alt))))))
1444 (($ <sequence> src exps)
1445 (let lp ((exps exps) (effects '()))
1446 (match exps
1447 ((last)
1448 (if (null? effects)
1449 (for-tail last)
1450 (make-sequence
1451 src
1452 (reverse (cons (for-tail last) effects)))))
1453 ((head . rest)
1454 (let ((head (for-effect head)))
1455 (cond
1456 ((sequence? head)
1457 (lp (append (sequence-exps head) rest) effects))
1458 ((void? head)
1459 (lp rest effects))
1460 (else
1461 (lp rest (cons head effects)))))))))
1462 (($ <prompt> src tag body handler)
1463 (define (make-prompt-tag? x)
1464 (match x
1465 (($ <application> _ ($ <primitive-ref> _ 'make-prompt-tag)
1466 (or () ((? constant-expression?))))
1467 #t)
1468 (_ #f)))
1469
1470 (let ((tag (for-value tag))
1471 (body (for-tail body)))
1472 (cond
1473 ((find-definition tag 1)
1474 (lambda (val op)
1475 (make-prompt-tag? val))
1476 => (lambda (val op)
1477 ;; There is no way that an <abort> could know the tag
1478 ;; for this <prompt>, so we can elide the <prompt>
1479 ;; entirely.
1480 (unrecord-operand-uses op 1)
1481 body))
1482 ((find-definition tag 2)
1483 (lambda (val op)
1484 (and (make-prompt-tag? val)
1485 (abort? body)
1486 (tree-il=? (abort-tag body) tag)))
1487 => (lambda (val op)
1488 ;; (let ((t (make-prompt-tag)))
1489 ;; (call-with-prompt t
1490 ;; (lambda () (abort-to-prompt t val ...))
1491 ;; (lambda (k arg ...) e ...)))
1492 ;; => (let-values (((k arg ...) (values values val ...)))
1493 ;; e ...)
1494 (unrecord-operand-uses op 2)
1495 (for-tail
1496 (make-let-values
1497 src
1498 (make-application #f (make-primitive-ref #f 'apply)
1499 `(,(make-primitive-ref #f 'values)
1500 ,(make-primitive-ref #f 'values)
1501 ,@(abort-args body)
1502 ,(abort-tail body)))
1503 (for-value handler)))))
1504 (else
1505 (make-prompt src tag body (for-value handler))))))
1506 (($ <abort> src tag args tail)
1507 (make-abort src (for-value tag) (map for-value args)
1508 (for-value tail))))))