30e8d4af758bfc6fe9d399aee7ff3abb2c5c5c9a
[jscl.git] / experimental / compiler.lisp
1 ;;; compiler.lisp ---
2
3 ;; Copyright (C) 2013 David Vazquez
4
5 ;; JSCL is free software: you can redistribute it and/or
6 ;; modify it under the terms of the GNU General Public License as
7 ;; published by the Free Software Foundation, either version 3 of the
8 ;; License, or (at your option) any later version.
9 ;;
10 ;; JSCL is distributed in the hope that it will be useful, but
11 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
12 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 ;; General Public License for more details.
14 ;;
15 ;; You should have received a copy of the GNU General Public License
16 ;; along with JSCL.  If not, see <http://www.gnu.org/licenses/>.
17
18 (defpackage :jscl
19   (:use :cl))
20
21 (in-package :jscl)
22
23 ;;;; Utilities
24 ;;;;
25 ;;;; Random Common Lisp code useful to use here and there. 
26
27 (defmacro with-gensyms ((&rest vars) &body body)
28   `(let ,(mapcar (lambda (var) `(,var (gensym ,(string var)))) vars)
29      ,@body))
30
31 (defun singlep (x)
32   (and (consp x) (null (cdr x))))
33
34 (defun unlist (x)
35   (assert (singlep x))
36   (first x))
37
38
39 ;;;; Intermediate representation structures
40 ;;;;
41 ;;;; This intermediate representation (IR) is a simplified version of
42 ;;;; the first intermediate representation what you will find if you
43 ;;;; have a look to the source code of SBCL. Some terminology is also
44 ;;;; used, but other is changed, so be careful if you assume you know
45 ;;;; what it is because you know the name.
46 ;;;;
47 ;;;; Computations are represented by `node'.  Nodes are grouped
48 ;;;; sequencially into `basic-block'. It is a plain representation
49 ;;;; rather than a nested one. Computations take data and produce a
50 ;;;; value. Both data transfer are represented by `lvar'.
51
52 (defstruct leaf)
53
54 ;;; A (lexical) variable. Special variables has not a special
55 ;;; representation in the IR. They are handled by the primitive
56 ;;; functions `%symbol-function' and `%symbol-value'.
57 (defstruct (var (:include leaf))
58   ;; The symbol which names this variable in the source code.
59   name)
60
61 ;;; A literal Lisp object. It usually comes from a quoted expression.
62 (defstruct (constant (:include leaf))
63   ;; The object itself.
64   value)
65
66 ;;; A lambda expression. Why do we name it `functional'? Well,
67 ;;; function is reserved by the ANSI, isn't it?
68 (defstruct (functional (:include leaf))
69   ;; The symbol which names this function in the source code or null
70   ;; if we do not know or it is an anonymous function.
71   name
72   arguments
73   return-lvar
74   entry-point)
75
76 ;;; An abstract place where the result of a computation is stored and
77 ;;; it can be referenced from other nodes, so lvars are responsible
78 ;;; for keeping the necessary information of the nested structure of
79 ;;; the code in this plain representation.
80 (defstruct lvar
81   (id (gensym "$")))
82
83 ;;; A base structure for every single computation. Most of the
84 ;;; computations are valued.
85 (defstruct node
86   ;; The next and the prev slots are the next nodes and the previous
87   ;; node in the basic block sequence respectively.
88   next prev
89   ;; Lvar which stands for the result of the computation of this node.
90   lvar)
91
92 ;;; Sentinel nodes in the basic block sequence of nodes.
93 (defstruct (block-entry (:include node)))
94 (defstruct (block-exit (:include node)))
95
96 ;;; A reference to a leaf (variable, constant and functions). The
97 ;;; meaning of this node is leaving the leaf into the lvar of the
98 ;;; node.
99 (defstruct (ref (:include node))
100   leaf)
101
102 ;;; An assignation of the LVAR VALUE into the var VARIABLE.
103 (defstruct (assignment (:include node))
104   variable
105   value)
106
107 ;;; Call the lvar FUNCTION with a list of lvars as ARGUMENTS.
108 (defstruct (call (:include node))
109   function
110   arguments)
111
112 ;;; A conditional branch. If the LVAR is not NIL, then we will jump to
113 ;;; the basic block CONSEQUENT, jumping to ALTERNATIVE otherwise. By
114 ;;; definition, a conditional must appear at the end of a basic block.
115 (defstruct (conditional (:include node))
116   test
117   consequent
118   alternative)
119
120
121 ;;; Blocks are `basic block`. Basic blocks are organized as a control
122 ;;; flow graph with some more information in omponents.
123 (defstruct (basic-block
124              (:conc-name "BLOCK-")
125              (:constructor make-block)
126              (:predicate block-p))
127   (id (gensym "L"))
128   ;; List of successors and predecessors of this basic block.
129   succ pred
130   ;; The sentinel nodes of the sequence.
131   entry exit)
132
133 ;;; Sentinel nodes in the control flow graph of basic blocks.
134 (defstruct (component-entry (:include basic-block)))
135 (defstruct (component-exit (:include basic-block)))
136
137 ;;; Return a fresh empty basic block.
138 (defun make-empty-block ()
139   (let ((entry (make-block-entry))
140         (exit (make-block-exit)))
141     (setf (node-next entry) exit
142           (node-prev exit) entry)
143     (make-block :entry entry :exit exit)))
144
145 ;;; Return T if B is an empty basic block and NIL otherwise.
146 (defun empty-block-p (b)
147   (block-exit-p (node-next (block-entry b))))
148
149 ;;; Iterate across the nodes in a basic block forward.
150 (defmacro do-nodes
151     ((node block &optional result &key include-sentinel-p) &body body)
152   `(do ((,node ,(if include-sentinel-p
153                     `(block-entry ,block)
154                     `(node-next (block-entry ,block))) 
155                (node-next ,node)))
156        (,(if include-sentinel-p
157              `(null ,node)
158              `(block-exit-p ,node))
159         ,result)
160      ,@body))
161
162 ;;; Iterate across the nodes in a basic block backward.
163 (defmacro do-nodes-backward
164     ((node block &optional result &key include-sentinel-p) &body body)
165   `(do ((,node ,(if include-sentinel-p
166                     `(block-exit ,block)
167                     `(node-prev (block-entry ,block))) 
168                (node-prev ,node)))
169        (,(if include-sentinel-p
170              `(null ,node)
171              `(block-entry-p ,node))
172         ,result)
173      ,@body))
174
175 ;;; Link FROM and TO nodes together. FROM and TO must belong to the
176 ;;; same basic block and appear in such order. The nodes between FROM
177 ;;; and TO are discarded.
178 (defun link-nodes (from to)
179   (setf (node-next from) to
180         (node-prev to) from)
181   (values))
182
183
184
185 ;;;; Cursors
186 ;;;;
187 ;;;; A cursor is a point between two nodes in some basic block in the
188 ;;;; IR representation where manipulations can take place, similarly
189 ;;;; to the cursors in text editing.
190 ;;;;
191 ;;;; Cursors cannot point to special component's entry and exit basic
192 ;;;; blocks or after a conditional node. Conveniently, the `cursor'
193 ;;;; function will signal an error if the cursor is not positioned
194 ;;;; correctly, so the rest of the code does not need to check once
195 ;;;; and again.
196
197 (defstruct cursor
198   block next)
199
200 ;;; The current cursor. It is the default cursor for many functions
201 ;;; which work on cursors.
202 (defvar *cursor*)
203
204 ;;; Return the current basic block. It is to say, the basic block
205 ;;; where the current cursor is pointint.
206 (defun current-block ()
207   (cursor-block *cursor*))
208
209 ;;; Create a cursor which points to the basic block BLOCK. If omitted,
210 ;;; then the current block is used.
211 ;;;
212 ;;; The keywords AFTER and BEFORE specify the cursor will point after (or
213 ;;; before) that node respectively. If none is specified, the cursor is
214 ;;; created before the exit node in BLOCK. An error is signaled if both
215 ;;; keywords are specified inconsistently, or if the nodes do not belong
216 ;;; to BLOCK.
217 ;;;
218 ;;; AFTER and BEFORE could also be the special values :ENTRY and :EXIT,
219 ;;; which stand for the entry and exit nodes of the block respectively.
220 (defun cursor (&key (block (current-block))
221                  (before nil before-p)
222                  (after nil after-p))
223   (when (or (component-entry-p block) (component-exit-p block))
224     (error "Invalid cursor on special entry/exit basic block."))
225   ;; Handle special values :ENTRY and :EXIT.
226   (flet ((node-designator (x)
227            (case x
228              (:entry (block-entry block))
229              (:exit  (block-exit block))
230              (t x))))
231     (setq before (node-designator before))
232     (setq after  (node-designator after)))
233   (let* ((next (or before (and after (node-next after)) (block-exit block)))
234          (cursor (make-cursor :block block :next next)))
235     (flet ((out-of-range-cursor ()
236              (error "Out of range cursor."))
237            (ambiguous-cursor ()
238              (error "Ambiguous cursor specified between two non-adjacent nodes.")))
239       (when (conditional-p (node-prev next))
240         (error "Invalid cursor after conditional node."))
241       (when (or (null next) (block-entry-p next))
242         (out-of-range-cursor))
243       (when (and before-p after-p (not (eq after before)))
244         (ambiguous-cursor))
245       (do-nodes-backward (node block (out-of-range-cursor) :include-sentinel-p t)
246         (when (eq next node) (return))))
247     cursor))
248
249 ;;; Accept a cursor specification just as described in `cursor'
250 ;;; describing a position in the IR and modify destructively the
251 ;;; current cursor to point there.
252 (defun set-cursor (&rest cursor-spec)
253   (let ((newcursor (apply #'cursor cursor-spec)))
254     (setf (cursor-block *cursor*) (cursor-block newcursor))
255     (setf (cursor-next *cursor*) (cursor-next newcursor))
256     *cursor*))
257
258 ;;; Insert NODE at cursor.
259 (defun insert-node (node &optional (cursor *cursor*))
260   ;; After if? wrong!
261   (link-nodes (node-prev (cursor-next cursor)) node)
262   (link-nodes node (cursor-next cursor))
263   t)
264
265 ;;; Split the block at CURSOR. The cursor will point to the end of the
266 ;;; first basic block. Return the three basic blocks as multiple
267 ;;; values.
268 (defun split-block (&optional (cursor *cursor*))
269   ;; <aaaaa|zzzzz>  ==>  <aaaaa|>--<zzzzz>
270   (let* ((block (cursor-block cursor))
271          (newexit (make-block-exit))
272          (newentry (make-block-entry))
273          (exit (block-exit block))
274          (newblock (make-block :entry newentry
275                                :exit exit
276                                :pred (list block)
277                                :succ (block-succ block))))
278     (insert-node newexit)
279     (insert-node newentry)
280     (setf (node-next newexit)  nil)
281     (setf (node-prev newentry) nil)
282     (setf (block-exit block) newexit)
283     (setf (block-succ block) (list newblock))
284     (dolist (succ (block-succ newblock))
285       (setf (block-pred succ) (substitute newblock block (block-pred succ))))
286     (set-cursor :block block :before newexit)
287     newblock))
288
289 ;;; Split the block at CURSOR if it is in the middle of it. The cursor
290 ;;; will point to the end of the first basic block. Return the three
291 ;;; basic blocks as multiple values.
292 (defun maybe-split-block (&optional (cursor *cursor*))
293   ;; If we are converting IR into the end of the basic block, it's
294   ;; fine, we don't need to do anything.
295   (unless (block-exit-p (cursor-next cursor))
296     (split-block cursor)))
297
298
299 ;;;; Components
300 ;;;;
301 ;;;; Components are connected pieces of the control flow graph of
302 ;;;; basic blocks with some additional information. Components have
303 ;;;; well-defined entry and exit nodes. It is the toplevel
304 ;;;; organizational entity in the compiler. The IR translation result
305 ;;;; is accumulated into components incrementally.
306 (defstruct (component #-jscl (:print-object print-component))
307   entry
308   exit)
309
310 ;;; Create a new component with an empty basic block, ready to start
311 ;;; conversion to IR. It returns the component and the basic block as
312 ;;; multiple values.
313 (defun make-empty-component ()
314   (let ((entry (make-component-entry))
315         (block (make-empty-block))
316         (exit (make-component-exit)))
317     (setf (block-succ entry)  (list block)
318           (block-pred exit)   (list block)
319           (block-succ block) (list exit)
320           (block-pred block) (list entry))
321     (values (make-component :entry entry :exit exit) block)))
322
323 ;;; Return the list of blocks in COMPONENT, conveniently sorted.
324 (defun component-blocks (component)
325   (let ((seen nil)
326         (output nil))
327     (labels ((compute-rdfo-from (block)
328                (unless (or (component-exit-p block) (find block seen))
329                  (push block seen)
330                  (dolist (successor (block-succ block))
331                    (unless (component-exit-p block)
332                      (compute-rdfo-from successor)))
333                  (push block output))))
334       (compute-rdfo-from (unlist (block-succ (component-entry component))))
335       output)))
336
337 ;;; Iterate across different blocks in COMPONENT.
338 (defmacro do-blocks ((block component &optional result) &body body)
339   `(dolist (,block (component-blocks ,component) ,result)
340      ,@body))
341
342 ;;; A few consistency checks in the IR useful for catching bugs.
343 (defun check-ir-consistency (component)
344   (with-simple-restart (continue "Continue execution")
345     (do-blocks (block component)
346       (dolist (succ (block-succ block))
347         (unless (find block (block-pred succ))
348           (error "The block `~S' does not belong to the predecessors list of the its successor `~S'"
349                  (block-id block)
350                  (block-id succ))))
351       (dolist (pred (block-pred block))
352         (unless (find block (block-succ pred))
353           (error "The block `~S' does not belong to the successors' list of its predecessor `~S'"
354                  (block-id block)
355                  (block-id pred)))))))
356
357
358 ;;;; Lexical environment
359 ;;;;
360 ;;;; It keeps an association between names and the IR entities. It is
361 ;;;; used to guide the translation from the Lisp source code to the
362 ;;;; intermediate representation.
363
364 (defstruct binding
365   name namespace type value)
366
367 (defvar *lexenv*)
368
369 (defun find-binding (name namespace)
370   (find-if (lambda (b)
371              (and (eq (binding-name b) name)
372                   (eq (binding-namespace b) namespace)))
373            *lexenv*))
374
375 (defun push-binding (name namespace value &optional type)
376   (push (make-binding :name name
377                       :namespace namespace
378                       :type type
379                       :value value)
380         *lexenv*))
381
382
383 ;;;; IR Translation
384 ;;;;
385 ;;;; This code covers the translation from Lisp source code to the
386 ;;;; intermediate representation. The main entry point function to do
387 ;;;; that is the `ir-convert' function, which dispatches to IR
388 ;;;; translators. This function ss intended to do the initial
389 ;;;; conversion as well as insert new IR code during optimizations.
390 ;;;;
391 ;;;; The function `ir-complete' will coalesce basic blocks in a
392 ;;;; component to generate proper maximal basic blocks.
393
394 ;;; The current component. We accumulate the results of the IR
395 ;;; conversion in this component.
396 (defvar *component*)
397
398 ;;; A alist of IR translator functions.
399 (defvar *ir-translator* nil)
400
401 ;;; Define a IR translator for NAME. LAMBDA-LIST is used to
402 ;;; destructure the arguments of the form. Calling the local function
403 ;;; `result-lvar' you can get the LVAR where the compilation of the
404 ;;; expression should store the result of the evaluation.
405 ;;;
406 ;;; The cursor is granted to be at the end of a basic block with a
407 ;;; unique successor, and so it should be when the translator returns.
408 (defmacro define-ir-translator (name lambda-list &body body)
409   (check-type name symbol)
410   (let ((fname (intern (format nil "IR-CONVERT-~a" (string name))))
411         (result (gensym))
412         (form (gensym)))
413     `(progn
414        (defun ,fname (,form ,result)
415          (flet ((result-lvar () ,result))
416            (declare (ignorable (function result-lvar)))
417            (destructuring-bind ,lambda-list ,form
418              ,@body)))
419        (push (cons ',name #',fname) *ir-translator*))))
420
421 ;;; Return the unique successor of the current block. If it is not
422 ;;; unique signal an error.
423 (defun next-block ()
424   (unlist (block-succ (current-block))))
425
426 ;;; Set the next block of the current one.
427 (defun (setf next-block) (new-value)
428   (let ((block (current-block)))
429     (dolist (succ (block-succ block))
430       (setf (block-pred succ) (remove block (block-pred succ))))
431     (setf (block-succ block) (list new-value))
432     (push block (block-pred new-value))
433     new-value))
434
435 (defun ir-convert-constant (form result)
436   (let* ((leaf (make-constant :value form)))
437     (insert-node (make-ref :leaf leaf :lvar result))))
438
439 (define-ir-translator quote (form)
440   (ir-convert-constant form (result-lvar)))
441
442 (define-ir-translator setq (variable value)
443   (let ((var (make-var :name variable))
444         (value-lvar (make-lvar)))
445     (ir-convert value value-lvar)
446     (let ((assign (make-assignment :variable var :value value-lvar :lvar (result-lvar))))
447       (insert-node assign))))
448
449 (define-ir-translator progn (&body body)
450   (mapc #'ir-convert (butlast body))
451   (ir-convert (car (last body)) (result-lvar)))
452
453 (define-ir-translator if (test then &optional else)
454   ;; It is the schema of how the basic blocks will look like
455   ;;
456   ;;              / ..then.. \
457   ;;  <aaaaXX> --<            >-- <|> -- <zzzz>
458   ;;              \ ..else.. /
459   ;;
460   ;; Note that is important to leave the cursor in an empty basic
461   ;; block, as zzz could be the exit basic block of the component,
462   ;; which is an invalid position for a cursor.
463   (let ((test-lvar (make-lvar))
464         (then-block (make-empty-block))
465         (else-block (make-empty-block))
466         (join-block (make-empty-block)))
467     (ir-convert test test-lvar)
468     (insert-node (make-conditional :test test-lvar :consequent then-block :alternative else-block))
469     (let* ((block (current-block))
470            (tail-block (next-block)))
471       ;; Link together the different created basic blocks.
472       (setf (block-succ block)      (list else-block then-block)
473             (block-pred else-block) (list block)
474             (block-pred then-block) (list block)
475             (block-succ then-block) (list join-block)
476             (block-succ else-block) (list join-block)
477             (block-pred join-block) (list else-block then-block)
478             (block-succ join-block) (list tail-block)
479             (block-pred tail-block) (substitute join-block block (block-pred tail-block))))
480     ;; Convert he consequent and alternative forms and update cursor.
481     (ir-convert then (result-lvar) (cursor :block then-block))
482     (ir-convert else (result-lvar) (cursor :block else-block))
483     (set-cursor :block join-block)))
484
485 (define-ir-translator block (name &body body)
486   (push-binding name 'block (cons (next-block) (result-lvar)))
487   (ir-convert `(progn ,@body) (result-lvar)))
488
489 (define-ir-translator return-from (name &optional value)
490   (let ((binding
491          (or (find-binding name 'block)
492              (error "Tried to return from unknown block `~S' name" name))))
493     (destructuring-bind (jump-block . lvar)
494         (binding-value binding)
495       (ir-convert value lvar)
496       (setf (next-block) jump-block)
497       ;; This block is really unreachable, even if the following code
498       ;; is labelled in a tagbody, as tagbody will create a new block
499       ;; for each label. However, we have to leave the cursor
500       ;; somewhere to convert new input.
501       (let ((dummy (make-empty-block)))
502         (set-cursor :block dummy)))))
503
504 (define-ir-translator tagbody (&rest statements)
505   (flet ((go-tag-p (x)
506            (or (integerp x) (symbolp x))))
507     (let* ((tags (remove-if-not #'go-tag-p statements))
508            (tag-blocks nil))
509       ;; Create a chain of basic blocks for the tags, recording each
510       ;; block in a alist in TAG-BLOCKS.
511       (let ((*cursor* *cursor*))
512         (dolist (tag tags)
513           (set-cursor :block (split-block))
514           (push-binding tag 'tag (current-block))
515           (if (assoc tag tag-blocks)
516               (error "Duplicated tag `~S' in tagbody." tag)
517               (push (cons tag (current-block)) tag-blocks))))
518       ;; Convert the statements into the correct block.
519       (dolist (stmt statements)
520         (if (go-tag-p stmt)
521             (set-cursor :block (cdr (assoc stmt tag-blocks)))
522             (ir-convert stmt))))))
523
524 (define-ir-translator go (label)
525   (let ((tag-binding
526          (or (find-binding label 'tag)
527              (error "Unable to jump to the label `~S'" label))))
528     (setf (next-block) (binding-value tag-binding))
529     ;; Unreachable block.
530     (let ((dummy (make-empty-block)))
531       (set-cursor :block dummy))))
532
533
534 (defun ir-convert-var (form result)
535   (let* ((leaf (make-var :name form)))
536     (insert-node (make-ref :leaf leaf :lvar result))))
537
538 (defun ir-convert-call (form result)
539   (destructuring-bind (function &rest args) form
540     (let ((func-lvar (make-lvar))
541           (args-lvars nil))
542       (when (symbolp function)
543         (ir-convert `(%symbol-function ,function) func-lvar))
544       (dolist (arg args)
545         (let ((arg-lvar (make-lvar)))
546           (push arg-lvar args-lvars)
547           (ir-convert arg arg-lvar)))
548       (setq args-lvars (reverse args-lvars))
549       (let ((call (make-call :function func-lvar :arguments args-lvars :lvar result)))
550         (insert-node call)))))
551
552 ;;; Convert the Lisp expression FORM into IR before the NEXT node, it
553 ;;; may create new basic blocks into the current component. RESULT is
554 ;;; the lvar representing the result of the computation or null if the
555 ;;; value should be discarded. The IR is inserted at *CURSOR*.
556 (defun ir-convert (form &optional result (*cursor* *cursor*))
557   ;; Rebinding the lexical environment here we make sure that the
558   ;; lexical information introduced by FORM is just available for
559   ;; subforms.
560   (let ((*lexenv* *lexenv*))
561     ;; Possibly create additional blocks in order to make sure the
562     ;; cursor is at end the end of a basic block.
563     (maybe-split-block)
564     (cond
565       ((atom form)
566        (cond
567          ((symbolp form)
568           (ir-convert-var form result))
569          (t
570           (ir-convert-constant form result))))
571       (t
572        (destructuring-bind (op &rest args) form
573          (let ((translator (cdr (assoc op *ir-translator*))))
574            (if translator
575                (funcall translator args result)
576                (ir-convert-call form result))))))
577     (values)))
578
579
580 ;;; Prepare a new component with a current empty block ready to start
581 ;;; IR conversion bound in the current cursor. BODY is evaluated and
582 ;;; the value of the last form is returned.
583 (defmacro with-component-compilation (&body body)
584   (let ((block (gensym)))
585     `(multiple-value-bind (*component* ,block)
586          (make-empty-component)
587        (let ((*cursor* (cursor :block ,block))
588              (*lexenv* nil))
589          ,@body))))
590
591 ;;; Change all the predecessors of BLOCK to precede NEW-BLOCK instead.
592 (defun replace-block (block new-block)
593   (let ((predecessors (block-pred block)))
594     (setf (block-pred new-block) (union (block-pred new-block) predecessors))
595     (dolist (pred predecessors)
596       (setf (block-succ pred) (substitute new-block block (block-succ pred)))
597       (unless (component-entry-p pred)
598         (let ((last-node (node-prev (block-exit pred))))
599           (when (conditional-p last-node)
600             (macrolet ((replacef (place)
601                          `(setf ,place (if (eq block ,place) new-block ,place))))
602               (replacef (conditional-consequent last-node))
603               (replacef (conditional-alternative last-node)))))))))
604
605 (defun delete-empty-block (block)
606   (when (or (component-entry-p block) (component-exit-p block))
607     (error "Cannot delete entry or exit basic blocks."))
608   (unless (empty-block-p block)
609     (error "Block `~S' is not empty!" (block-id block)))
610   (replace-block block (unlist (block-succ block))))
611
612 ;;; Try to coalesce BLOCK with the successor if it is unique and block
613 ;;; is its unique predecessor.
614 (defun maybe-coalesce-block (block)
615   (when (singlep (block-succ block))
616     (let ((succ (first (block-succ block))))
617       (when (and (not (component-exit-p succ)) (singlep (block-pred succ)))
618         (link-nodes (node-prev (block-exit block))
619                     (node-next (block-entry succ)))
620         (setf (block-succ block) (block-succ succ))
621         (dolist (next (block-succ succ))
622           (setf (block-pred next) (substitute block succ (block-pred next))))
623         t))))
624
625 (defun ir-complete (&optional (component *component*))
626   (do-blocks (block component)
627     (maybe-coalesce-block block)
628     (when (empty-block-p block)
629       (delete-empty-block block))))
630
631
632 ;;; IR Debugging
633
634 (defun print-node (node)
635   (when (node-lvar node)
636     (format t "~a = " (lvar-id (node-lvar node))))
637   (cond
638     ((ref-p node)
639      (let ((leaf (ref-leaf node)))
640        (cond
641          ((var-p leaf)
642           (format t "~a" (var-name leaf)))
643          ((constant-p leaf)
644           (format t "'~s" (constant-value leaf)))
645          ((functional-p leaf)
646           (format t "#<function ~a at ~a>"
647                   (functional-name leaf)
648                   (functional-entry-point leaf))))))
649     ((assignment-p node)
650      (format t "set ~a ~a"
651              (var-name (assignment-variable node))
652              (lvar-id (assignment-value node))))
653     ((call-p node)
654      (format t "call ~a" (lvar-id (call-function node)))
655      (dolist (arg (call-arguments node))
656        (format t " ~a" (lvar-id arg))))
657     ((conditional-p node)
658      (format t "if ~a ~a ~a"
659              (lvar-id (conditional-test node))
660              (block-id (conditional-consequent node))
661              (block-id (conditional-alternative node))))
662     (t
663      (error "`print-node' does not support printing ~S as a node." node)))
664   (terpri))
665
666 (defun print-block (block)
667   (flet ((block-name (block)
668            (cond
669              ((and (singlep (block-pred block))
670                    (component-entry-p (unlist (block-pred block))))
671               "ENTRY")
672              ((component-exit-p block)
673               "EXIT")
674              (t (string (block-id block))))))
675     (format t "BLOCK ~a:~%" (block-name block))
676     (do-nodes (node block)
677       (print-node node))
678     (when (singlep (block-succ block))
679       (format t "GO ~a~%" (block-name (first (block-succ block)))))
680     (terpri)))
681
682 (defun print-component (component &optional (stream *standard-output*))
683   (let ((*standard-output* stream))
684     (do-blocks (block component)
685       (print-block block))))
686
687 ;;; Translate FORM into IR and print a textual repreresentation of the
688 ;;; component.
689 (defun describe-ir (form &optional (complete t))
690   (with-component-compilation
691     (ir-convert form (make-lvar :id "$out"))
692     (when complete (ir-complete))
693     (check-ir-consistency *component*)
694     (print-component *component*)))
695
696
697
698
699 ;;; compiler.lisp ends here