3 ;; Copyright (C) 2013 David Vazquez
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.
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.
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/>.
25 ;;;; Random Common Lisp code useful to use here and there.
27 (defmacro with-gensyms ((&rest vars) &body body)
28 `(let ,(mapcar (lambda (var) `(,var (gensym ,(concatenate 'string (string var) "-")))) vars)
32 (and (consp x) (null (cdr x))))
38 (defun generic-printer (x stream)
39 (print-unreadable-object (x stream :type t :identity t)))
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*)))
50 (push (cons class 1) *counter-alist*)))))
53 ;;;; Intermediate representation structures
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.
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'.
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.
75 ;;; A literal Lisp object. It usually comes from a quoted expression.
76 (defstruct (constant (:include leaf))
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.
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.
95 (id (generate-id 'lvar)))
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.
103 ;; Lvar which stands for the result of the computation of this node.
106 ;;; Sentinel nodes in the basic block sequence of nodes.
107 (defstruct (block-entry (:include node)))
108 (defstruct (block-exit (:include node)))
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
113 (defstruct (ref (:include node))
116 ;;; An assignation of the LVAR VALUE into the var VARIABLE.
117 (defstruct (assignment (:include node))
121 ;;; A base node to function calls with a list of lvar as ARGUMENTS.
122 (defstruct (combination (:include node) (:constructor))
125 ;;; A function call to the ordinary Lisp function in the lvar FUNCTION.
126 (defstruct (call (:include combination))
129 ;;; A function call to the primitive FUNCTION.
130 (defstruct (primitive-call (:include combination))
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))
144 ;;; Blocks are `basic block`. Basic blocks are organized as a control
145 ;;; flow graph with some more information in omponents.
146 (defstruct (basic-block
147 (:conc-name "BLOCK-")
148 (:constructor make-block)
150 (:print-object generic-printer))
151 (id (generate-id 'basic-block))
152 ;; List of successors and predecessors of this basic block. They are
153 ;; null only for deleted blocks and component's entry and exit.
155 ;; The sentinel nodes of the sequence.
157 ;; The component where the basic block belongs to.
159 ;; A bit-vector representing the set of dominators. See the function
160 ;; `compute-dominators' to know how to use it properly.
162 ;; Arbitrary data which could be necessary to keep during IR
166 ;;; Sentinel nodes in the control flow graph of basic blocks.
167 (defstruct (component-entry (:include basic-block)))
168 (defstruct (component-exit (:include basic-block)))
170 ;;; Return T if B is an empty basic block and NIL otherwise.
171 (defun empty-block-p (b)
172 (block-exit-p (node-next (block-entry b))))
174 (defun boundary-block-p (block)
175 (or (component-entry-p block)
176 (component-exit-p block)))
178 ;;; Iterate across the nodes in a basic block forward.
180 ((node block &optional result &key include-sentinel-p) &body body)
181 `(do ((,node ,(if include-sentinel-p
182 `(block-entry ,block)
183 `(node-next (block-entry ,block)))
185 (,(if include-sentinel-p
187 `(block-exit-p ,node))
191 ;;; Iterate across the nodes in a basic block backward.
192 (defmacro do-nodes-backward
193 ((node block &optional result &key include-sentinel-p) &body body)
194 `(do ((,node ,(if include-sentinel-p
196 `(node-prev (block-entry ,block)))
198 (,(if include-sentinel-p
200 `(block-entry-p ,node))
204 ;;; Link FROM and TO nodes together. FROM and TO must belong to the
205 ;;; same basic block and appear in such order. The nodes between FROM
206 ;;; and TO are discarded.
207 (defun link-nodes (from to)
208 (setf (node-next from) to
213 ;;; Components are connected pieces of the control flow graph of
214 ;;; basic blocks with some additional information. Components have
215 ;;; well-defined entry and exit nodes. It is the toplevel
216 ;;; organizational entity in the compiler. The IR translation result
217 ;;; is accumulated into components incrementally.
218 (defstruct (component (:print-object generic-printer))
219 (id (generate-id 'component))
224 ;; TODO: Replace with a flags slot for indicate what
225 ;; analysis/transformations have been carried out.
229 ;;; The current component.
232 ;;; Create a new fresh empty basic block in the current component.
233 (defun make-empty-block ()
234 (let ((entry (make-block-entry))
235 (exit (make-block-exit)))
236 (link-nodes entry exit)
237 (let ((block (make-block :entry entry :exit exit :component *component*)))
238 (push block (component-blocks *component*))
241 ;;; Create a new component with an empty basic block, ready to start
242 ;;; conversion to IR. It returns the component and the basic block as
244 (defun make-empty-component (&optional name)
245 (let ((*component* (make-component :name name)))
246 (let ((entry (make-component-entry :component *component*))
247 (exit (make-component-exit :component *component*))
248 (block (make-empty-block)))
249 (setf (block-succ entry) (list block)
250 (block-pred exit) (list block)
251 (block-succ block) (list exit)
252 (block-pred block) (list entry)
253 (component-entry *component*) entry
254 (component-exit *component*) exit)
255 (values *component* block))))
257 ;;; A few consistency checks in the IR useful for catching bugs.
258 (defun check-ir-consistency (&optional (component *component*))
259 (with-simple-restart (continue "Continue execution")
260 (dolist (block (component-blocks component))
261 (dolist (succ (block-succ block))
262 (unless (find block (block-pred succ))
263 (error "The block `~S' does not belong to the predecessors list of the its successor `~S'"
265 (unless (or (boundary-block-p succ) (find succ (component-blocks component)))
266 (error "Block `~S' is reachable from its predecessor `~S' but it is not in the component `~S'"
267 succ block component)))
268 (dolist (pred (block-pred block))
269 (unless (find block (block-succ pred))
270 (error "The block `~S' does not belong to the successors' list of its predecessor `~S'"
272 (unless (or (boundary-block-p pred) (find pred (component-blocks component)))
273 (error "Block `~S' is reachable from its sucessor `~S' but it is not in the component `~S'"
274 pred block component))))))
276 ;;; Prepare a new component with a current empty block ready to start
277 ;;; IR conversion bound in the current cursor. BODY is evaluated and
278 ;;; the value of the last form is returned.
279 (defmacro with-component-compilation ((&optional name) &body body)
280 (with-gensyms (block)
281 `(multiple-value-bind (*component* ,block)
282 (make-empty-component ,name)
283 (let ((*cursor* (cursor :block ,block)))
286 ;;; Call function for each reachable block in component in
287 ;;; post-order. The consequences are unspecified if a block is
288 ;;; FUNCTION modifies a block which has not been processed yet.
289 (defun map-postorder-blocks (function component)
291 (labels ((compute-from (block)
292 (unless (or (component-exit-p block) (find block seen))
294 (dolist (successor (block-succ block))
295 (unless (component-exit-p block)
296 (compute-from successor)))
297 (funcall function block))))
298 (compute-from (unlist (block-succ (component-entry component))))
301 ;;; Change all the predecessors of BLOCK to precede NEW-BLOCK
302 ;;; instead. As consequence, BLOCK becomes unreachable.
303 (defun replace-block (block new-block)
304 (let ((predecessors (block-pred block)))
305 (setf (block-pred block) nil)
306 (dolist (pred predecessors)
307 (pushnew pred (block-pred new-block))
308 (setf (block-succ pred) (substitute new-block block (block-succ pred)))
309 (unless (component-entry-p pred)
310 (let ((last-node (node-prev (block-exit pred))))
311 (when (conditional-p last-node)
312 (macrolet ((replacef (place)
313 `(setf ,place (if (eq block ,place) new-block ,place))))
314 (replacef (conditional-consequent last-node))
315 (replacef (conditional-alternative last-node)))))))))
317 (defun delete-block (block)
318 (when (boundary-block-p block)
319 (error "Cannot delete entry or exit basic blocks."))
320 (unless (singlep (block-succ block))
321 (error "Cannot delete a basic block with multiple successors."))
322 (let ((successor (unlist (block-succ block))))
323 (replace-block block successor)
324 ;; At this point, block is unreachable, however we could have
325 ;; backreferences to it from its successors. Let's get rid of
327 (setf (block-pred successor) (remove block (block-pred successor)))
328 (setf (block-succ block) nil)))
333 ;;;; A cursor is a point between two nodes in some basic block in the
334 ;;;; IR representation where manipulations can take place, similarly
335 ;;;; to the cursors in text editing.
337 ;;;; Cursors cannot point to special component's entry and exit basic
338 ;;;; blocks or after a conditional node. Conveniently, the `cursor'
339 ;;;; function will signal an error if the cursor is not positioned
340 ;;;; correctly, so the rest of the code does not need to check once
346 ;;; The current cursor. It is the default cursor for many functions
347 ;;; which work on cursors.
350 ;;; Return the current basic block. It is to say, the basic block
351 ;;; where the current cursor is pointint.
352 (defun current-block ()
353 (cursor-block *cursor*))
355 ;;; Create a cursor which points to the basic block BLOCK. If omitted,
356 ;;; then the current block is used.
358 ;;; The keywords AFTER and BEFORE specify the cursor will point after (or
359 ;;; before) that node respectively. If none is specified, the cursor is
360 ;;; created before the exit node in BLOCK. An error is signaled if both
361 ;;; keywords are specified inconsistently, or if the nodes do not belong
364 ;;; AFTER and BEFORE could also be the special values :ENTRY and :EXIT,
365 ;;; which stand for the entry and exit nodes of the block respectively.
366 (defun cursor (&key (block (current-block))
367 (before nil before-p)
369 (when (boundary-block-p block)
370 (error "Invalid cursor on special entry/exit basic block."))
371 ;; Handle special values :ENTRY and :EXIT.
372 (flet ((node-designator (x)
374 (:entry (block-entry block))
375 (:exit (block-exit block))
377 (setq before (node-designator before))
378 (setq after (node-designator after)))
379 (let* ((next (or before (and after (node-next after)) (block-exit block)))
380 (cursor (make-cursor :block block :next next)))
381 (flet ((out-of-range-cursor ()
382 (error "Out of range cursor."))
384 (error "Ambiguous cursor specified between two non-adjacent nodes.")))
385 (when (conditional-p (node-prev next))
386 (error "Invalid cursor after conditional node."))
387 (when (or (null next) (block-entry-p next))
388 (out-of-range-cursor))
389 (when (and before-p after-p (not (eq after before)))
391 (do-nodes-backward (node block (out-of-range-cursor) :include-sentinel-p t)
392 (when (eq next node) (return))))
395 ;;; Accept a cursor specification just as described in `cursor'
396 ;;; describing a position in the IR and modify destructively the
397 ;;; current cursor to point there.
398 (defun set-cursor (&rest cursor-spec)
399 (let ((newcursor (apply #'cursor cursor-spec)))
400 (setf (cursor-block *cursor*) (cursor-block newcursor))
401 (setf (cursor-next *cursor*) (cursor-next newcursor))
404 ;;; Insert NODE at cursor.
405 (defun insert-node (node &optional (cursor *cursor*))
406 (link-nodes (node-prev (cursor-next cursor)) node)
407 (link-nodes node (cursor-next cursor))
410 ;;; Split the block at CURSOR. The cursor will point to the end of the
411 ;;; first basic block. Return the three basic blocks as multiple
413 (defun split-block (&optional (cursor *cursor*))
414 ;; <aaaaa|zzzzz> ==> <aaaaa|>--<zzzzz>
415 (let* ((block (cursor-block cursor))
416 (newexit (make-block-exit))
417 (newentry (make-block-entry))
418 (exit (block-exit block))
419 (newblock (make-block :entry newentry
422 :succ (block-succ block)
423 :component *component*)))
424 (insert-node newexit)
425 (insert-node newentry)
426 (setf (node-next newexit) nil)
427 (setf (node-prev newentry) nil)
428 (setf (block-exit block) newexit)
429 (setf (block-succ block) (list newblock))
430 (dolist (succ (block-succ newblock))
431 (setf (block-pred succ) (substitute newblock block (block-pred succ))))
432 (set-cursor :block block :before newexit)
433 (push newblock (component-blocks *component*))
436 ;;; Split the block at CURSOR if it is in the middle of it. The cursor
437 ;;; will point to the end of the first basic block. Return the three
438 ;;; basic blocks as multiple values.
439 (defun maybe-split-block (&optional (cursor *cursor*))
440 ;; If we are converting IR into the end of the basic block, it's
441 ;; fine, we don't need to do anything.
442 (unless (block-exit-p (cursor-next cursor))
443 (split-block cursor)))
446 ;;;; Lexical environment
448 ;;;; It keeps an association between names and the IR entities. It is
449 ;;;; used to guide the translation from the Lisp source code to the
450 ;;;; intermediate representation.
453 name namespace type value)
455 (defvar *lexenv* nil)
457 (defun find-binding (name namespace)
459 (and (eq (binding-name b) name)
460 (eq (binding-namespace b) namespace)))
463 (defun push-binding (name namespace value &optional type)
464 (push (make-binding :name name
473 ;;;; This code covers the translation from Lisp source code to the
474 ;;;; intermediate representation. The main entry point function to do
475 ;;;; that is the `ir-convert' function, which dispatches to IR
476 ;;;; translators. This function ss intended to do the initial
477 ;;;; conversion as well as insert new IR code during optimizations.
479 ;;; A alist of IR translator functions.
480 (defvar *ir-translator* nil)
482 ;;; Define a IR translator for NAME. LAMBDA-LIST is used to
483 ;;; destructure the arguments of the form. Calling the local function
484 ;;; `result-lvar' you can get the LVAR where the compilation of the
485 ;;; expression should store the result of the evaluation.
487 ;;; The cursor is granted to be at the end of a basic block with a
488 ;;; unique successor, and so it should be when the translator returns.
489 (defmacro define-ir-translator (name lambda-list &body body)
490 (check-type name symbol)
491 (let ((fname (intern (format nil "IR-CONVERT-~a" (string name)))))
492 (with-gensyms (result form)
494 (defun ,fname (,form ,result)
495 (flet ((result-lvar () ,result))
496 (declare (ignorable (function result-lvar)))
497 (destructuring-bind ,lambda-list ,form
499 (push (cons ',name #',fname) *ir-translator*)))))
501 ;;; Return the unique successor of the current block. If it is not
502 ;;; unique signal an error.
504 (unlist (block-succ (current-block))))
506 ;;; Set the next block of the current one.
507 (defun (setf next-block) (new-value)
508 (let ((block (current-block)))
509 (dolist (succ (block-succ block))
510 (setf (block-pred succ) (remove block (block-pred succ))))
511 (setf (block-succ block) (list new-value))
512 (push block (block-pred new-value))
515 (defun ir-convert-constant (form result)
516 (let* ((leaf (make-constant :value form)))
517 (insert-node (make-ref :leaf leaf :lvar result))))
519 (define-ir-translator quote (form)
520 (ir-convert-constant form (result-lvar)))
522 (define-ir-translator setq (variable value)
523 (let ((b (find-binding variable 'variable)))
526 (let ((var (make-var :name variable))
527 (value-lvar (make-lvar)))
528 (ir-convert value value-lvar)
529 (let ((assign (make-assignment :variable var :value value-lvar :lvar (result-lvar))))
530 (insert-node assign))))
532 (ir-convert `(set ',variable ,value) (result-lvar))))))
534 (define-ir-translator progn (&body body)
535 (mapc #'ir-convert (butlast body))
536 (ir-convert (car (last body)) (result-lvar)))
538 (define-ir-translator if (test then &optional else)
539 ;; It is the schema of how the basic blocks will look like
542 ;; <aaaaXX> --< >-- <|> -- <zzzz>
545 ;; Note that is important to leave the cursor in an empty basic
546 ;; block, as zzz could be the exit basic block of the component,
547 ;; which is an invalid position for a cursor.
548 (let ((test-lvar (make-lvar))
549 (then-block (make-empty-block))
550 (else-block (make-empty-block))
551 (join-block (make-empty-block)))
552 (ir-convert test test-lvar)
553 (insert-node (make-conditional :test test-lvar :consequent then-block :alternative else-block))
554 (let* ((block (current-block))
555 (tail-block (next-block)))
556 ;; Link together the different created basic blocks.
557 (setf (block-succ block) (list else-block then-block)
558 (block-pred else-block) (list block)
559 (block-pred then-block) (list block)
560 (block-succ then-block) (list join-block)
561 (block-succ else-block) (list join-block)
562 (block-pred join-block) (list else-block then-block)
563 (block-succ join-block) (list tail-block)
564 (block-pred tail-block) (substitute join-block block (block-pred tail-block))))
565 ;; Convert he consequent and alternative forms and update cursor.
566 (ir-convert then (result-lvar) (cursor :block then-block))
567 (ir-convert else (result-lvar) (cursor :block else-block))
568 (set-cursor :block join-block)))
570 (define-ir-translator block (name &body body)
571 (let ((new (split-block)))
572 (push-binding name 'block (cons (next-block) (result-lvar)))
573 (ir-convert `(progn ,@body) (result-lvar))
574 (set-cursor :block new)))
576 (define-ir-translator return-from (name &optional value)
578 (or (find-binding name 'block)
579 (error "Tried to return from unknown block `~S' name" name))))
580 (destructuring-bind (jump-block . lvar)
581 (binding-value binding)
582 (ir-convert value lvar)
583 (setf (next-block) jump-block)
584 ;; This block is really unreachable, even if the following code
585 ;; is labelled in a tagbody, as tagbody will create a new block
586 ;; for each label. However, we have to leave the cursor
587 ;; somewhere to convert new input.
588 (let ((dummy (make-empty-block)))
589 (set-cursor :block dummy)))))
591 (define-ir-translator tagbody (&rest statements)
593 (or (integerp x) (symbolp x))))
594 (let* ((tags (remove-if-not #'go-tag-p statements))
596 ;; Create a chain of basic blocks for the tags, recording each
597 ;; block in a alist in TAG-BLOCKS.
598 (let ((*cursor* *cursor*))
600 (setq *cursor* (cursor :block (split-block)))
601 (push-binding tag 'tag (current-block))
602 (if (assoc tag tag-blocks)
603 (error "Duplicated tag `~S' in tagbody." tag)
604 (push (cons tag (current-block)) tag-blocks))))
605 ;; Convert the statements into the correct block.
606 (dolist (stmt statements)
608 (set-cursor :block (cdr (assoc stmt tag-blocks)))
609 (ir-convert stmt))))))
611 (define-ir-translator go (label)
613 (or (find-binding label 'tag)
614 (error "Unable to jump to the label `~S'" label))))
615 (setf (next-block) (binding-value tag-binding))
616 ;; Unreachable block.
617 (let ((dummy (make-empty-block)))
618 (set-cursor :block dummy))))
621 (defun ir-convert-functoid (result name arguments &rest body)
623 (return-lvar (make-lvar)))
624 (with-component-compilation (name)
625 (ir-convert `(progn ,@body) return-lvar)
627 (setq component *component*))
633 :return-lvar return-lvar)))
634 (push functional (component-functions *component*))
635 (insert-node (make-ref :leaf functional :lvar result)))))
637 (define-ir-translator function (name)
639 (ir-convert `(symbol-function ,name) (result-lvar))
641 ((lambda named-lambda)
642 (let ((desc (cdr name)))
643 (when (eq 'lambda (car name))
645 (apply #'ir-convert-functoid (result-lvar) desc)))
648 (defun ir-convert-var (form result)
649 (let ((binds (find-binding form 'variable)))
651 (insert-node (make-ref :leaf (binding-value binds) :lvar result))
652 (ir-convert `(symbol-value ',form) result))))
654 (defun ir-convert-call (form result)
655 (destructuring-bind (function &rest args) form
656 (let ((func-lvar (make-lvar))
660 (let ((arg-lvar (make-lvar)))
661 (push arg-lvar args-lvars)
662 (ir-convert arg arg-lvar)))
663 (setq args-lvars (reverse args-lvars))
665 (if (find-primitive function)
666 (insert-node (make-primitive-call
667 :function (find-primitive function)
668 :arguments args-lvars
671 (ir-convert `(symbol-function ,function) func-lvar)
672 (insert-node (make-call :function func-lvar
673 :arguments args-lvars
676 ;;; Convert the Lisp expression FORM, it may create new basic
677 ;;; blocks. RESULT is the lvar representing the result of the
678 ;;; computation or null if the value should be discarded. The IR is
679 ;;; inserted at *CURSOR*.
680 (defun ir-convert (form &optional result (*cursor* *cursor*))
681 ;; Rebinding the lexical environment here we make sure that the
682 ;; lexical information introduced by FORM is just available for
684 (let ((*lexenv* *lexenv*))
685 ;; Possibly create additional blocks in order to make sure the
686 ;; cursor is at end the end of a basic block.
692 (ir-convert-var form result))
694 (ir-convert-constant form result))))
696 (destructuring-bind (op &rest args) form
697 (let ((translator (cdr (assoc op *ir-translator*))))
699 (funcall translator args result)
700 (ir-convert-call form result))))))
704 ;;;; IR Normalization
706 ;;;; IR as generated by `ir-convert' or after some transformations is
707 ;;;; not appropiated. Here, we remove unreachable and empty blocks and
708 ;;;; coallesce blocks when it is possible.
710 ;;; Try to coalesce BLOCK with the successor if it is unique and block
711 ;;; is its unique predecessor.
712 (defun maybe-coalesce-block (block)
713 (when (singlep (block-succ block))
714 (let ((succ (first (block-succ block))))
715 (when (and (not (component-exit-p succ)) (singlep (block-pred succ)))
716 (link-nodes (node-prev (block-exit block))
717 (node-next (block-entry succ)))
718 (setf (block-exit block) (block-exit succ))
719 (setf (block-succ block) (block-succ succ))
720 (dolist (next (block-succ succ))
721 (setf (block-pred next) (substitute block succ (block-pred next))))
722 (setf (block-succ succ) nil
723 (block-pred succ) nil)
726 ;;; Normalize a component. This function must be called after a batch
727 ;;; of modifications to the flowgraph of the component to make sure it
728 ;;; is a valid input for the possible optimizations and the backend.
729 (defun ir-normalize (&optional (component *component*))
730 ;; Initialize blocks as unreachables and remove empty basic blocks.
731 (dolist (block (component-blocks component))
732 (setf (block-data block) 'unreachable))
733 ;; Coalesce and mark blocks as reachable.
734 (map-postorder-blocks
736 (maybe-coalesce-block block)
737 (setf (block-data block) 'reachable))
739 (let ((block-list nil))
740 (dolist (block (component-blocks component))
742 ;; If the block is unreachable, but it is predeces a reachable
743 ;; one, then break the link between them. So we discard it
744 ;; from the flowgraph.
745 ((eq (block-data block) 'unreachable)
746 (setf (block-succ block) nil)
747 (dolist (succ (block-succ block))
748 (when (eq (block-data succ) 'reachable)
749 (remove block (block-pred succ)))))
750 ;; Delete empty blocks
751 ((empty-block-p block)
752 (delete-block block))
753 ;; The rest of blocks remain in the component.
755 (push block block-list))))
756 (setf (component-blocks component) block-list))
757 (check-ir-consistency))
762 ;;;; Once IR conversion has been finished. We do some analysis of the
763 ;;;; component to produce information which is useful for both
764 ;;;; optimizations and code generation. Indeed, we provide some
765 ;;;; abstractions to use this information.
767 (defun compute-reverse-post-order (component)
769 (flet ((add-block-to-list (block)
770 (push block output)))
771 (map-postorder-blocks #'add-block-to-list component))
772 (setf (component-reverse-post-order-p component) t)
773 (setf (component-blocks component) output)))
775 ;;; Iterate across blocks in COMPONENT in reverse post order.
776 (defmacro do-blocks-forward ((block component &optional result) &body body)
777 (with-gensyms (g!component)
778 `(let ((,g!component ,component))
779 (dolist (,block (if (component-reverse-post-order-p ,g!component)
780 (component-blocks ,g!component)
781 (error "reverse post order was not computed yet."))
785 ;;; Iterate across blocks in COMPONENT in post order.
786 (defmacro do-blocks-backward ((block component &optional result) &body body)
787 (with-gensyms (g!component)
788 `(let ((,g!component ,component))
789 (dolist (,block (if (component-reverse-post-order-p ,g!component)
790 (reverse (component-blocks ,g!component))
791 (error "reverse post order was not computed yet."))
795 (defun compute-dominators (component)
796 ;; Initialize the dominators of the entry to the component to be
797 ;; empty and the power set of the set of blocks for proper basic
798 ;; blocks in the component.
799 (let ((n (length (component-blocks component))))
800 ;; The component entry special block has not predecessors in the
801 ;; set of (proper) basic blocks.
802 (setf (block-dominators% (component-entry component))
803 (make-array n :element-type 'bit :initial-element 0))
804 (dolist (block (component-blocks component))
805 (setf (block-dominators% block) (make-array n :element-type 'bit :initial-element 1))))
806 ;; Iterate across the blocks in the component removing non domintors
807 ;; until it reaches a fixed point.
809 (iteration 0 (1+ iteration))
813 (do-blocks-forward (block component)
814 (let* ((predecessors (block-pred block)))
815 (bit-and (block-dominators% block) (block-dominators% (first predecessors)) t)
816 (dolist (pred (rest predecessors))
817 (bit-and (block-dominators% block) (block-dominators% pred) t))
818 (setf (aref (block-dominators% block) i) 1)
819 (setf changes (or changes (not (equal (block-dominators% block) (block-dominators% block)))))
825 ;;;; This section provides a function `/print' which write a textual
826 ;;;; representation of a component to the standard output. Also, a
827 ;;;; `/ir' macro is provided, which takes a form, convert it to IR and
828 ;;;; then print the component as above. They are useful commands if
829 ;;;; you are hacking the front-end of the compiler.
832 (defun format-block-name (block)
834 ((eq block (unlist (block-succ (component-entry (block-component block)))))
835 (format nil "ENTRY-~a" (component-id (block-component block))))
836 ((component-exit-p block)
837 (format nil "EXIT-~a" (component-id (block-component block))))
839 (format nil "BLOCK ~a" (block-id block)))))
842 (defun print-node (node)
843 (when (node-lvar node)
844 (format t "$~a = " (lvar-id (node-lvar node))))
847 (let ((leaf (ref-leaf node)))
850 (format t "~a" (var-name leaf)))
852 (format t "'~s" (constant-value leaf)))
854 (format t "#<function ~a>" (functional-name leaf))))))
856 (format t "set ~a $~a"
857 (var-name (assignment-variable node))
858 (lvar-id (assignment-value node))))
859 ((primitive-call-p node)
860 (format t "primitive ~a" (primitive-name (primitive-call-function node)))
861 (dolist (arg (primitive-call-arguments node))
862 (format t " $~a" (lvar-id arg))))
864 (format t "call $~a" (lvar-id (call-function node)))
865 (dolist (arg (call-arguments node))
866 (format t " $~a" (lvar-id arg))))
867 ((conditional-p node)
868 (format t "if $~a then ~a else ~a~%"
869 (lvar-id (conditional-test node))
870 (format-block-name (conditional-consequent node))
871 (format-block-name (conditional-alternative node))))
873 (error "`print-node' does not support printing ~S as a node." node)))
876 (defun print-block (block)
877 (write-line (format-block-name block))
878 (do-nodes (node block)
880 (when (singlep (block-succ block))
881 (format t "GO ~a~%~%" (format-block-name (unlist (block-succ block))))))
883 (defun /print (component &optional (stream *standard-output*))
884 (format t ";;; COMPONENT ~a (~a) ~%~%" (component-name component) (component-id component))
885 (let ((*standard-output* stream))
886 (do-blocks-forward (block component)
887 (print-block block)))
888 (format t ";;; END COMPONENT ~a ~%~%" (component-name component))
889 (let ((*standard-output* stream))
890 (dolist (func (component-functions component))
891 (/print (functional-component func)))))
893 ;;; Translate FORM into IR and print a textual repreresentation of the
895 (defun convert-toplevel-and-print (form)
896 (let ((*counter-alist* nil))
897 (with-component-compilation ('toplevel)
898 (ir-convert form (make-lvar :id "out"))
900 (compute-reverse-post-order *component*)
905 `(convert-toplevel-and-print ',form))
911 ;;;; Primitive functions are a set of functions provided by the
912 ;;;; compiler. They cannot usually be written in terms of other
913 ;;;; functions. When the compiler tries to compile a function call, it
914 ;;;; looks for a primitive function firstly, and if it is found and
915 ;;;; the declarations allow it, a primitive call is inserted in the
916 ;;;; IR. The back-end of the compiler knows how to compile primitive
920 (defvar *primitive-function-table* nil)
925 (defmacro define-primitive (name args &body body)
926 (declare (ignore args body))
927 `(push (make-primitive :name ',name)
928 *primitive-function-table*))
930 (defun find-primitive (name)
931 (find name *primitive-function-table* :key #'primitive-name))
933 (define-primitive symbol-function (symbol))
934 (define-primitive symbol-value (symbol))
935 (define-primitive set (symbol value))
936 (define-primitive fset (symbol value))
938 (define-primitive + (&rest numbers))
939 (define-primitive - (number &rest other-numbers))
941 (define-primitive consp (x))
942 (define-primitive cons (x y))
943 (define-primitive car (x))
944 (define-primitive cdr (x))
947 ;;; compiler.lisp ends here