9a8824fec27687a6e6cc581c42f128e2f7c12c5f
[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 ,(concatenate 'string (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 (defun generic-printer (x stream)
39   (print-unreadable-object (x stream :type t :identity t)))
40
41 ;;; A generic counter mechanism. IDs are used generally for debugging
42 ;;; purposes. You can bind *counter-alist* to NIL to reset the
43 ;;; counters in a dynamic extent.
44 (defvar *counter-alist* nil)
45 (defun generate-id (class)
46   (let ((e (assoc class *counter-alist*)))
47     (if e
48         (incf (cdr e))
49         (prog1 1
50           (push (cons class 1) *counter-alist*)))))
51
52
53 ;;;; Intermediate representation structures
54 ;;;;
55 ;;;; This intermediate representation (IR) is a simplified version of
56 ;;;; the first intermediate representation what you will find if you
57 ;;;; have a look to the source code of SBCL. Some terminology is also
58 ;;;; used, but other is changed, so be careful if you assume you know
59 ;;;; what it is because you know the name.
60 ;;;;
61 ;;;; Computations are represented by `node'.  Nodes are grouped
62 ;;;; sequencially into `basic-block'. It is a plain representation
63 ;;;; rather than a nested one. Computations take data and produce a
64 ;;;; value. Both data transfer are represented by `lvar'.
65
66 (defstruct leaf)
67
68 ;;; A (lexical) variable. Special variables has not a special
69 ;;; representation in the IR. They are handled by the primitive
70 ;;; functions `%symbol-function' and `%symbol-value'.
71 (defstruct (var (:include leaf))
72   ;; The symbol which names this variable in the source code.
73   name)
74
75 ;;; A literal Lisp object. It usually comes from a quoted expression.
76 (defstruct (constant (:include leaf))
77   ;; The object itself.
78   value)
79
80 ;;; A lambda expression. Why do we name it `functional'? Well,
81 ;;; function is reserved by the ANSI, isn't it?
82 (defstruct (functional (:include leaf) (:print-object generic-printer))
83   ;; The symbol which names this function in the source code or null
84   ;; if we do not know or it is an anonymous function.
85   name
86   arguments
87   return-lvar
88   component)
89
90 ;;; An abstract place where the result of a computation is stored and
91 ;;; it can be referenced from other nodes, so lvars are responsible
92 ;;; for keeping the necessary information of the nested structure of
93 ;;; the code in this plain representation.
94 (defstruct lvar
95   (id (generate-id 'lvar)))
96
97 ;;; A base structure for every single computation. Most of the
98 ;;; computations are valued.
99 (defstruct (node (:print-object generic-printer))
100   ;; The next and the prev slots are the next nodes and the previous
101   ;; node in the basic block sequence respectively.
102   next prev
103   ;; Lvar which stands for the result of the computation of this node.
104   lvar)
105
106 ;;; Sentinel nodes in the basic block sequence of nodes.
107 (defstruct (block-entry (:include node)))
108 (defstruct (block-exit (:include node)))
109
110 ;;; A reference to a leaf (variable, constant and functions). The
111 ;;; meaning of this node is leaving the leaf into the lvar of the
112 ;;; node.
113 (defstruct (ref (:include node))
114   leaf)
115
116 ;;; An assignation of the LVAR VALUE into the var VARIABLE.
117 (defstruct (assignment (:include node))
118   variable
119   value)
120
121 ;;; A base node to function calls with a list of lvar as ARGUMENTS.
122 (defstruct (combination (:include node) (:constructor))
123   arguments)
124
125 ;;; A function call to the ordinary Lisp function in the lvar FUNCTION.
126 (defstruct (call (:include combination))
127   function)
128
129 ;;; A function call to the primitive FUNCTION.
130 (defstruct (primitive-call (:include combination))
131   function)
132
133
134 ;;; A conditional branch. If the LVAR is not NIL, then we will jump to
135 ;;; the basic block CONSEQUENT, jumping to ALTERNATIVE otherwise. By
136 ;;; definition, a conditional must appear at the end of a basic block.
137 (defstruct (conditional (:include node))
138   test
139   consequent
140   alternative)
141
142
143 ;;;; Components
144 ;;;;
145 ;;;; Components are connected pieces of the control flow graph of
146 ;;;; basic blocks with some additional information. Components have
147 ;;;; well-defined entry and exit nodes. It is the toplevel
148 ;;;; organizational entity in the compiler. The IR translation result
149 ;;;; is accumulated into components incrementally.
150 (defstruct (component (:print-object generic-printer))
151   (id (generate-id 'component))
152   name
153   entry
154   exit
155   functions
156   blocks)
157
158 ;;; The current component. We accumulate the results of the IR
159 ;;; conversion in this component.
160 (defvar *component*)
161
162 ;;; Create a new component with an empty basic block, ready to start
163 ;;; conversion to IR. It returns the component and the basic block as
164 ;;; multiple values.
165 (defun make-empty-component (&optional name)
166   (let ((*component* (make-component :name name)))
167     (let ((entry (make-component-entry))
168           (block (make-empty-block))
169           (exit (make-component-exit)))
170       (setf (block-succ entry) (list block)
171             (block-pred exit)  (list block)
172             (block-succ block) (list exit)
173             (block-pred block) (list entry)
174             (component-entry *component*) entry
175             (component-exit  *component*) exit)
176       (values *component* block))))
177
178 ;;; Prepare a new component with a current empty block ready to start
179 ;;; IR conversion bound in the current cursor. BODY is evaluated and
180 ;;; the value of the last form is returned.
181 (defmacro with-component-compilation ((&optional name) &body body)
182   (with-gensyms (block)
183     `(multiple-value-bind (*component* ,block)
184          (make-empty-component ,name)
185        (let ((*cursor* (cursor :block ,block)))
186          ,@body))))
187
188 ;;; Call function for each block in component in post-order.
189 (defun map-postorder-blocks (function component)
190   (let ((seen nil))
191     (labels ((compute-from (block)
192                (unless (or (component-exit-p block) (find block seen))
193                  (push block seen)
194                  (dolist (successor (block-succ block))
195                    (unless (component-exit-p block)
196                      (compute-from successor)))
197                  (funcall function block))))
198       (compute-from (unlist (block-succ (component-entry component))))
199       nil)))
200
201 ;;; Iterate across different blocks in COMPONENT.
202 (defmacro do-blocks ((block component &optional result) &body body)
203   `(dolist (,block (or (component-blocks ,component)
204                        (error "Component is not normalized."))
205              ,result)
206      ,@body))
207
208 (defmacro do-blocks-backward ((block component &optional result) &body body)
209   `(dolist (,block (or (reverse (component-blocks ,component))
210                        (error "component is not normalized."))
211              ,result)
212      ,@body))
213
214 ;;; A few consistency checks in the IR useful for catching bugs.
215 (defun check-ir-consistency (&optional (component *component*))
216   (with-simple-restart (continue "Continue execution")
217     (do-blocks (block component)
218       (dolist (succ (block-succ block))
219         (unless (find block (block-pred succ))
220           (error "The block `~S' does not belong to the predecessors list of the its successor `~S'"
221                  (block-id block)
222                  (block-id succ)))
223         (unless (find succ (component-blocks component))
224           (error "Block `~S' is reachable but it is not in the component `~S'" succ component)))
225       (dolist (pred (block-pred block))
226         (unless (find block (block-succ pred))
227           (error "The block `~S' does not belong to the successors' list of its predecessor `~S'"
228                  (block-id block)
229                  (block-id pred)))
230         (unless (find pred (component-blocks component))
231           (error "Block `~S' is reachable but it is not in the component `~S'" pred component))))))
232
233
234 ;;; Blocks are `basic block`. Basic blocks are organized as a control
235 ;;; flow graph with some more information in omponents.
236 (defstruct (basic-block
237              (:conc-name "BLOCK-")
238              (:constructor make-block)
239              (:predicate block-p)
240              (:print-object generic-printer))
241   (id (generate-id 'basic-block))
242   ;; List of successors and predecessors of this basic block.
243   succ pred
244   ;; The sentinel nodes of the sequence.
245   entry exit
246   ;; The component where this block belongs
247   (component *component*)
248   (dominators%))
249
250 ;;; Sentinel nodes in the control flow graph of basic blocks.
251 (defstruct (component-entry (:include basic-block)))
252 (defstruct (component-exit (:include basic-block)))
253
254 ;;; Return a fresh empty basic block.
255 (defun make-empty-block ()
256   (let ((entry (make-block-entry))
257         (exit (make-block-exit)))
258     (setf (node-next entry) exit
259           (node-prev exit) entry)
260     (make-block :entry entry :exit exit)))
261
262 ;;; Return T if B is an empty basic block and NIL otherwise.
263 (defun empty-block-p (b)
264   (block-exit-p (node-next (block-entry b))))
265
266 ;;; Iterate across the nodes in a basic block forward.
267 (defmacro do-nodes
268     ((node block &optional result &key include-sentinel-p) &body body)
269   `(do ((,node ,(if include-sentinel-p
270                     `(block-entry ,block)
271                     `(node-next (block-entry ,block))) 
272                (node-next ,node)))
273        (,(if include-sentinel-p
274              `(null ,node)
275              `(block-exit-p ,node))
276         ,result)
277      ,@body))
278
279 ;;; Iterate across the nodes in a basic block backward.
280 (defmacro do-nodes-backward
281     ((node block &optional result &key include-sentinel-p) &body body)
282   `(do ((,node ,(if include-sentinel-p
283                     `(block-exit ,block)
284                     `(node-prev (block-entry ,block))) 
285                (node-prev ,node)))
286        (,(if include-sentinel-p
287              `(null ,node)
288              `(block-entry-p ,node))
289         ,result)
290      ,@body))
291
292 ;;; Link FROM and TO nodes together. FROM and TO must belong to the
293 ;;; same basic block and appear in such order. The nodes between FROM
294 ;;; and TO are discarded.
295 (defun link-nodes (from to)
296   (setf (node-next from) to
297         (node-prev to) from)
298   (values))
299
300
301
302 ;;;; Cursors
303 ;;;;
304 ;;;; A cursor is a point between two nodes in some basic block in the
305 ;;;; IR representation where manipulations can take place, similarly
306 ;;;; to the cursors in text editing.
307 ;;;;
308 ;;;; Cursors cannot point to special component's entry and exit basic
309 ;;;; blocks or after a conditional node. Conveniently, the `cursor'
310 ;;;; function will signal an error if the cursor is not positioned
311 ;;;; correctly, so the rest of the code does not need to check once
312 ;;;; and again.
313
314 (defstruct cursor
315   block next)
316
317 ;;; The current cursor. It is the default cursor for many functions
318 ;;; which work on cursors.
319 (defvar *cursor*)
320
321 ;;; Return the current basic block. It is to say, the basic block
322 ;;; where the current cursor is pointint.
323 (defun current-block ()
324   (cursor-block *cursor*))
325
326 ;;; Create a cursor which points to the basic block BLOCK. If omitted,
327 ;;; then the current block is used.
328 ;;;
329 ;;; The keywords AFTER and BEFORE specify the cursor will point after (or
330 ;;; before) that node respectively. If none is specified, the cursor is
331 ;;; created before the exit node in BLOCK. An error is signaled if both
332 ;;; keywords are specified inconsistently, or if the nodes do not belong
333 ;;; to BLOCK.
334 ;;;
335 ;;; AFTER and BEFORE could also be the special values :ENTRY and :EXIT,
336 ;;; which stand for the entry and exit nodes of the block respectively.
337 (defun cursor (&key (block (current-block))
338                  (before nil before-p)
339                  (after nil after-p))
340   (when (or (component-entry-p block) (component-exit-p block))
341     (error "Invalid cursor on special entry/exit basic block."))
342   ;; Handle special values :ENTRY and :EXIT.
343   (flet ((node-designator (x)
344            (case x
345              (:entry (block-entry block))
346              (:exit  (block-exit block))
347              (t x))))
348     (setq before (node-designator before))
349     (setq after  (node-designator after)))
350   (let* ((next (or before (and after (node-next after)) (block-exit block)))
351          (cursor (make-cursor :block block :next next)))
352     (flet ((out-of-range-cursor ()
353              (error "Out of range cursor."))
354            (ambiguous-cursor ()
355              (error "Ambiguous cursor specified between two non-adjacent nodes.")))
356       (when (conditional-p (node-prev next))
357         (error "Invalid cursor after conditional node."))
358       (when (or (null next) (block-entry-p next))
359         (out-of-range-cursor))
360       (when (and before-p after-p (not (eq after before)))
361         (ambiguous-cursor))
362       (do-nodes-backward (node block (out-of-range-cursor) :include-sentinel-p t)
363         (when (eq next node) (return))))
364     cursor))
365
366 ;;; Accept a cursor specification just as described in `cursor'
367 ;;; describing a position in the IR and modify destructively the
368 ;;; current cursor to point there.
369 (defun set-cursor (&rest cursor-spec)
370   (let ((newcursor (apply #'cursor cursor-spec)))
371     (setf (cursor-block *cursor*) (cursor-block newcursor))
372     (setf (cursor-next *cursor*) (cursor-next newcursor))
373     *cursor*))
374
375 ;;; Insert NODE at cursor.
376 (defun insert-node (node &optional (cursor *cursor*))
377   (link-nodes (node-prev (cursor-next cursor)) node)
378   (link-nodes node (cursor-next cursor))
379   t)
380
381 ;;; Split the block at CURSOR. The cursor will point to the end of the
382 ;;; first basic block. Return the three basic blocks as multiple
383 ;;; values.
384 (defun split-block (&optional (cursor *cursor*))
385   ;; <aaaaa|zzzzz>  ==>  <aaaaa|>--<zzzzz>
386   (let* ((block (cursor-block cursor))
387          (newexit (make-block-exit))
388          (newentry (make-block-entry))
389          (exit (block-exit block))
390          (newblock (make-block :entry newentry
391                                :exit exit
392                                :pred (list block)
393                                :succ (block-succ block))))
394     (insert-node newexit)
395     (insert-node newentry)
396     (setf (node-next newexit)  nil)
397     (setf (node-prev newentry) nil)
398     (setf (block-exit block) newexit)
399     (setf (block-succ block) (list newblock))
400     (dolist (succ (block-succ newblock))
401       (setf (block-pred succ) (substitute newblock block (block-pred succ))))
402     (set-cursor :block block :before newexit)
403     newblock))
404
405 ;;; Split the block at CURSOR if it is in the middle of it. The cursor
406 ;;; will point to the end of the first basic block. Return the three
407 ;;; basic blocks as multiple values.
408 (defun maybe-split-block (&optional (cursor *cursor*))
409   ;; If we are converting IR into the end of the basic block, it's
410   ;; fine, we don't need to do anything.
411   (unless (block-exit-p (cursor-next cursor))
412     (split-block cursor)))
413
414
415
416 ;;;; Lexical environment
417 ;;;;
418 ;;;; It keeps an association between names and the IR entities. It is
419 ;;;; used to guide the translation from the Lisp source code to the
420 ;;;; intermediate representation.
421
422 (defstruct binding
423   name namespace type value)
424
425 (defvar *lexenv* nil)
426
427 (defun find-binding (name namespace)
428   (find-if (lambda (b)
429              (and (eq (binding-name b) name)
430                   (eq (binding-namespace b) namespace)))
431            *lexenv*))
432
433 (defun push-binding (name namespace value &optional type)
434   (push (make-binding :name name
435                       :namespace namespace
436                       :type type
437                       :value value)
438         *lexenv*))
439
440
441 ;;;; IR Translation
442 ;;;;
443 ;;;; This code covers the translation from Lisp source code to the
444 ;;;; intermediate representation. The main entry point function to do
445 ;;;; that is the `ir-convert' function, which dispatches to IR
446 ;;;; translators. This function ss intended to do the initial
447 ;;;; conversion as well as insert new IR code during optimizations.
448 ;;;;
449 ;;;; The function `ir-normalize' will coalesce basic blocks in a
450 ;;;; component to generate proper maximal basic blocks, as well as
451 ;;;; compute reverse depth first ordering on the blocks.
452
453 ;;; A alist of IR translator functions.
454 (defvar *ir-translator* nil)
455
456 ;;; Define a IR translator for NAME. LAMBDA-LIST is used to
457 ;;; destructure the arguments of the form. Calling the local function
458 ;;; `result-lvar' you can get the LVAR where the compilation of the
459 ;;; expression should store the result of the evaluation.
460 ;;;
461 ;;; The cursor is granted to be at the end of a basic block with a
462 ;;; unique successor, and so it should be when the translator returns.
463 (defmacro define-ir-translator (name lambda-list &body body)
464   (check-type name symbol)
465   (let ((fname (intern (format nil "IR-CONVERT-~a" (string name)))))
466     (with-gensyms (result form)
467       `(progn
468          (defun ,fname (,form ,result)
469            (flet ((result-lvar () ,result))
470              (declare (ignorable (function result-lvar)))
471              (destructuring-bind ,lambda-list ,form
472                ,@body)))
473          (push (cons ',name #',fname) *ir-translator*)))))
474
475 ;;; Return the unique successor of the current block. If it is not
476 ;;; unique signal an error.
477 (defun next-block ()
478   (unlist (block-succ (current-block))))
479
480 ;;; Set the next block of the current one.
481 (defun (setf next-block) (new-value)
482   (let ((block (current-block)))
483     (dolist (succ (block-succ block))
484       (setf (block-pred succ) (remove block (block-pred succ))))
485     (setf (block-succ block) (list new-value))
486     (push block (block-pred new-value))
487     new-value))
488
489 (defun ir-convert-constant (form result)
490   (let* ((leaf (make-constant :value form)))
491     (insert-node (make-ref :leaf leaf :lvar result))))
492
493 (define-ir-translator quote (form)
494   (ir-convert-constant form (result-lvar)))
495
496 (define-ir-translator setq (variable value)
497   (let ((b (find-binding variable 'variable)))
498     (cond
499       (b
500        (let ((var (make-var :name variable))
501              (value-lvar (make-lvar)))
502          (ir-convert value value-lvar)
503          (let ((assign (make-assignment :variable var :value value-lvar :lvar (result-lvar))))
504            (insert-node assign))))
505       (t
506        (ir-convert `(set ',variable ,value) (result-lvar))))))
507
508 (define-ir-translator progn (&body body)
509   (mapc #'ir-convert (butlast body))
510   (ir-convert (car (last body)) (result-lvar)))
511
512 (define-ir-translator if (test then &optional else)
513   ;; It is the schema of how the basic blocks will look like
514   ;;
515   ;;              / ..then.. \
516   ;;  <aaaaXX> --<            >-- <|> -- <zzzz>
517   ;;              \ ..else.. /
518   ;;
519   ;; Note that is important to leave the cursor in an empty basic
520   ;; block, as zzz could be the exit basic block of the component,
521   ;; which is an invalid position for a cursor.
522   (let ((test-lvar (make-lvar))
523         (then-block (make-empty-block))
524         (else-block (make-empty-block))
525         (join-block (make-empty-block)))
526     (ir-convert test test-lvar)
527     (insert-node (make-conditional :test test-lvar :consequent then-block :alternative else-block))
528     (let* ((block (current-block))
529            (tail-block (next-block)))
530       ;; Link together the different created basic blocks.
531       (setf (block-succ block)      (list else-block then-block)
532             (block-pred else-block) (list block)
533             (block-pred then-block) (list block)
534             (block-succ then-block) (list join-block)
535             (block-succ else-block) (list join-block)
536             (block-pred join-block) (list else-block then-block)
537             (block-succ join-block) (list tail-block)
538             (block-pred tail-block) (substitute join-block block (block-pred tail-block))))
539     ;; Convert he consequent and alternative forms and update cursor.
540     (ir-convert then (result-lvar) (cursor :block then-block))
541     (ir-convert else (result-lvar) (cursor :block else-block))
542     (set-cursor :block join-block)))
543
544 (define-ir-translator block (name &body body)
545   (let ((new (split-block)))
546     (push-binding name 'block (cons (next-block) (result-lvar)))
547     (ir-convert `(progn ,@body) (result-lvar))
548     (set-cursor :block new)))
549
550 (define-ir-translator return-from (name &optional value)
551   (let ((binding
552          (or (find-binding name 'block)
553              (error "Tried to return from unknown block `~S' name" name))))
554     (destructuring-bind (jump-block . lvar)
555         (binding-value binding)
556       (ir-convert value lvar)
557       (setf (next-block) jump-block)
558       ;; This block is really unreachable, even if the following code
559       ;; is labelled in a tagbody, as tagbody will create a new block
560       ;; for each label. However, we have to leave the cursor
561       ;; somewhere to convert new input.
562       (let ((dummy (make-empty-block)))
563         (set-cursor :block dummy)))))
564
565 (define-ir-translator tagbody (&rest statements)
566   (flet ((go-tag-p (x)
567            (or (integerp x) (symbolp x))))
568     (let* ((tags (remove-if-not #'go-tag-p statements))
569            (tag-blocks nil))
570       ;; Create a chain of basic blocks for the tags, recording each
571       ;; block in a alist in TAG-BLOCKS.
572       (let ((*cursor* *cursor*))
573         (dolist (tag tags)
574           (setq *cursor* (cursor :block (split-block)))
575           (push-binding tag 'tag (current-block))
576           (if (assoc tag tag-blocks)
577               (error "Duplicated tag `~S' in tagbody." tag)
578               (push (cons tag (current-block)) tag-blocks))))
579       ;; Convert the statements into the correct block.
580       (dolist (stmt statements)
581         (if (go-tag-p stmt)
582             (set-cursor :block (cdr (assoc stmt tag-blocks)))
583             (ir-convert stmt))))))
584
585 (define-ir-translator go (label)
586   (let ((tag-binding
587          (or (find-binding label 'tag)
588              (error "Unable to jump to the label `~S'" label))))
589     (setf (next-block) (binding-value tag-binding))
590     ;; Unreachable block.
591     (let ((dummy (make-empty-block)))
592       (set-cursor :block dummy))))
593
594
595 (defun ir-convert-functoid (result name arguments &rest body)
596   (let ((component)
597         (return-lvar (make-lvar)))
598     (with-component-compilation (name)
599       (ir-convert `(progn ,@body) return-lvar)
600       (ir-normalize)
601       (setq component *component*))
602     (let ((functional
603            (make-functional
604             :name name
605             :arguments arguments
606             :component component
607             :return-lvar return-lvar)))
608       (push functional (component-functions *component*))
609       (insert-node (make-ref :leaf functional :lvar result)))))
610
611 (define-ir-translator function (name)
612   (if (atom name)
613       (ir-convert `(symbol-function ,name) (result-lvar))
614       (ecase (car name)
615         ((lambda named-lambda)
616          (let ((desc (cdr name)))
617            (when (eq 'lambda (car name))
618              (push nil desc))
619            (apply #'ir-convert-functoid (result-lvar) desc)))
620         (setf))))
621
622 (defun ir-convert-var (form result)
623   (let ((binds (find-binding form 'variable)))
624     (if binds
625         (insert-node (make-ref :leaf (binding-value binds) :lvar result))
626         (ir-convert `(symbol-value ',form) result))))
627
628 (defun ir-convert-call (form result)
629   (destructuring-bind (function &rest args) form
630     (let ((func-lvar (make-lvar))
631           (args-lvars nil))
632       ;; Argument list
633       (dolist (arg args)
634         (let ((arg-lvar (make-lvar)))
635           (push arg-lvar args-lvars)
636           (ir-convert arg arg-lvar)))
637       (setq args-lvars (reverse args-lvars))
638       ;; Funcall
639       (if (find-primitive function)
640           (insert-node (make-primitive-call
641                         :function (find-primitive function)
642                         :arguments args-lvars
643                         :lvar result))
644           (progn
645             (ir-convert `(symbol-function ,function) func-lvar)
646             (insert-node (make-call :function func-lvar
647                                     :arguments args-lvars
648                                     :lvar result)))))))
649
650 ;;; Convert the Lisp expression FORM, it may create new basic
651 ;;; blocks. RESULT is the lvar representing the result of the
652 ;;; computation or null if the value should be discarded. The IR is
653 ;;; inserted at *CURSOR*.
654 (defun ir-convert (form &optional result (*cursor* *cursor*))
655   ;; Rebinding the lexical environment here we make sure that the
656   ;; lexical information introduced by FORM is just available for
657   ;; subforms.
658   (let ((*lexenv* *lexenv*))
659     ;; Possibly create additional blocks in order to make sure the
660     ;; cursor is at end the end of a basic block.
661     (maybe-split-block)
662     (cond
663       ((atom form)
664        (cond
665          ((symbolp form)
666           (ir-convert-var form result))
667          (t
668           (ir-convert-constant form result))))
669       (t
670        (destructuring-bind (op &rest args) form
671          (let ((translator (cdr (assoc op *ir-translator*))))
672            (if translator
673                (funcall translator args result)
674                (ir-convert-call form result))))))
675     (values)))
676
677
678 ;;; Change all the predecessors of BLOCK to precede NEW-BLOCK instead.
679 (defun replace-block (block new-block)
680   (let ((predecessors (block-pred block)))
681     (setf (block-pred new-block) (union (block-pred new-block) predecessors))
682     (dolist (pred predecessors)
683       (setf (block-succ pred) (substitute new-block block (block-succ pred)))
684       (unless (component-entry-p pred)
685         (let ((last-node (node-prev (block-exit pred))))
686           (when (conditional-p last-node)
687             (macrolet ((replacef (place)
688                          `(setf ,place (if (eq block ,place) new-block ,place))))
689               (replacef (conditional-consequent last-node))
690               (replacef (conditional-alternative last-node)))))))))
691
692 (defun delete-empty-block (block)
693   (when (or (component-entry-p block) (component-exit-p block))
694     (error "Cannot delete entry or exit basic blocks."))
695   (unless (empty-block-p block)
696     (error "Block `~S' is not empty!" (block-id block)))
697   (replace-block block (unlist (block-succ block))))
698
699 ;;; Try to coalesce BLOCK with the successor if it is unique and block
700 ;;; is its unique predecessor.
701 (defun maybe-coalesce-block (block)
702   (when (singlep (block-succ block))
703     (let ((succ (first (block-succ block))))
704       (when (and (not (component-exit-p succ)) (singlep (block-pred succ)))
705         (link-nodes (node-prev (block-exit block))
706                     (node-next (block-entry succ)))
707         (setf (block-succ block) (block-succ succ))
708         (dolist (next (block-succ succ))
709           (setf (block-pred next) (substitute block succ (block-pred next))))
710         t))))
711
712 ;;; Normalize a component. This function must be called after a batch
713 ;;; of modifications to the flowgraph of the component to make sure it
714 ;;; is a valid input for the possible optimizations and the backend.
715 (defun ir-normalize (&optional (component *component*))
716   (flet ((clean-and-coallesce (block)
717            (maybe-coalesce-block block)
718            (when (empty-block-p block)
719              (delete-empty-block block)))
720          (add-to-list (block)
721            (push block (component-blocks *component*))))
722     (map-postorder-blocks #'clean-and-coallesce component)
723     (map-postorder-blocks #'add-to-list component)
724     (check-ir-consistency)))
725
726
727 ;;; IR Debugging
728
729 (defun format-block-name (block)
730   (cond
731     ((eq block (unlist (block-succ (component-entry (block-component block)))))
732      (format nil "ENTRY-~a" (component-id (block-component block))))
733     ((component-exit-p block)
734      (format nil "EXIT-~a" (component-id (block-component block))))
735     (t
736      (format nil "BLOCK ~a" (block-id block)))))
737
738 (defun print-node (node)
739   (when (node-lvar node)
740     (format t "$~a = " (lvar-id (node-lvar node))))
741   (cond
742     ((ref-p node)
743      (let ((leaf (ref-leaf node)))
744        (cond
745          ((var-p leaf)
746           (format t "~a" (var-name leaf)))
747          ((constant-p leaf)
748           (format t "'~s" (constant-value leaf)))
749          ((functional-p leaf)
750           (format t "#<function ~a>" (functional-name leaf))))))
751     ((assignment-p node)
752      (format t "set ~a $~a"
753              (var-name (assignment-variable node))
754              (lvar-id (assignment-value node))))
755     ((primitive-call-p node)
756      (format t "primitive ~a" (primitive-name (primitive-call-function node)))
757      (dolist (arg (primitive-call-arguments node))
758        (format t " $~a" (lvar-id arg))))
759     ((call-p node)
760      (format t "call $~a" (lvar-id (call-function node)))
761      (dolist (arg (call-arguments node))
762        (format t " $~a" (lvar-id arg))))
763     ((conditional-p node)
764      (format t "if $~a then ~a else ~a~%"
765              (lvar-id (conditional-test node))
766              (format-block-name (conditional-consequent node))
767              (format-block-name (conditional-alternative node))))
768     (t
769      (error "`print-node' does not support printing ~S as a node." node)))
770   (terpri))
771
772 (defun print-block (block)
773   (write-line (format-block-name block))
774   (do-nodes (node block)
775     (print-node node))
776   (when (singlep (block-succ block))
777     (format t "GO ~a~%~%" (format-block-name (unlist (block-succ block))))))
778
779 (defun /print (component &optional (stream *standard-output*))
780   (format t ";;; COMPONENT ~a (~a) ~%~%" (component-name component) (component-id component))
781   (let ((*standard-output* stream))
782     (do-blocks (block component)
783       (print-block block)))
784   (format t ";;; END COMPONENT ~a ~%~%" (component-name component))
785   (let ((*standard-output* stream))
786     (dolist (func (component-functions component))
787       (/print (functional-component func)))))
788
789 ;;; Translate FORM into IR and print a textual repreresentation of the
790 ;;; component.
791 (defun convert-toplevel-and-print (form &optional (normalize t))
792   (let ((*counter-alist* nil))
793     (with-component-compilation ('toplevel)
794       (ir-convert form (make-lvar :id "out"))
795       (when normalize (ir-normalize))
796       (/print *component*)
797       *component*)))
798
799 (defmacro /ir (form)
800   `(convert-toplevel-and-print ',form))
801
802
803
804 ;;;; Dominators
805
806 (defun compute-dominators (component)
807   ;; Initialize the dominators of the entry to the component to be
808   ;; empty and the power set of the set of blocks for proper basic
809   ;; blocks in the component.
810   (let ((n (length (component-blocks component))))
811     ;; The component entry special block has not predecessors in the
812     ;; set of (proper) basic blocks.
813     (setf (block-dominators% (component-entry component))
814           (make-array n :element-type 'bit :initial-element 0))
815     (do-blocks (block component)
816       (setf (block-dominators% block) (make-array n :element-type 'bit :initial-element 1))))
817   ;; Iterate across the blocks in the component removing non domintors
818   ;; until it reaches a fixed point.tpn
819   (do ((i 0 0)
820        (changes t))
821       ((not changes))
822     (setf changes nil)
823     (do-blocks (block component)
824       (format t "Processing ~a~%" (format-block-name block))
825       (let ((new (reduce #'bit-and (mapcar #'block-dominators% (block-pred block)))))
826         (setf (aref new i) 1)
827         (setf changes (or changes (not (equal new (block-dominators% block)))))
828         (setf (block-dominators% block) new)
829         (incf i)))))
830
831
832
833 ;;;; Primitives
834 ;;;;
835 ;;;; Primitive functions are a set of functions provided by the
836 ;;;; compiler. They cannot usually be written in terms of other
837 ;;;; functions. When the compiler tries to compile a function call, it
838 ;;;; looks for a primitive function firstly, and if it is found and
839 ;;;; the declarations allow it, a primitive call is inserted in the
840 ;;;; IR. The back-end of the compiler knows how to compile primitive
841 ;;;; calls.
842 ;;;; 
843
844 (defvar *primitive-function-table* nil)
845
846 (defstruct primitive
847   name)
848
849 (defmacro define-primitive (name args &body body)
850   (declare (ignore args body))
851   `(push (make-primitive :name ',name)
852          *primitive-function-table*))
853
854 (defun find-primitive (name)
855   (find name *primitive-function-table* :key #'primitive-name))
856
857 (define-primitive symbol-function (symbol))
858 (define-primitive symbol-value (symbol))
859 (define-primitive set (symbol value))
860 (define-primitive fset (symbol value))
861
862 (define-primitive + (&rest numbers))
863 (define-primitive - (number &rest other-numbers))
864
865 (define-primitive consp (x))
866 (define-primitive cons (x y))
867 (define-primitive car (x))
868 (define-primitive cdr (x))
869
870
871
872 ;;; compiler.lisp ends here