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