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