3 ;;; Code generation protocol
5 ;;; (c) 2009 Straylight/Edgeware
8 ;;;----- Licensing notice ---------------------------------------------------
10 ;;; This file is part of the Sensble Object Design, an object system for C.
12 ;;; SOD is free software; you can redistribute it and/or modify
13 ;;; it under the terms of the GNU General Public License as published by
14 ;;; the Free Software Foundation; either version 2 of the License, or
15 ;;; (at your option) any later version.
17 ;;; SOD is distributed in the hope that it will be useful,
18 ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;;; GNU General Public License for more details.
22 ;;; You should have received a copy of the GNU General Public License
23 ;;; along with SOD; if not, write to the Free Software Foundation,
24 ;;; Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
28 ;;;--------------------------------------------------------------------------
33 (export 'format-temporary-name)
34 (defgeneric format-temporary-name (var stream)
36 "Write the name of a temporary variable VAR to STREAM."))
38 (export 'var-in-use-p)
39 (defgeneric var-in-use-p (var)
41 "Answer whether VAR is currently being used. See `with-temporary-var'.")
43 "Non-temporary variables are always in use."
44 (declare (ignore var))
46 (defgeneric (setf var-in-use-p) (value var)
48 "Record whether VAR is currently being used. See `with-temporary-var'."))
52 (export '(temporary-name temp-tag))
53 (defclass temporary-name ()
54 ((tag :initarg :tag :reader temp-tag))
56 "Base class for temporary variable and argument names."))
58 ;; Important variables.
60 (defparameter *temporary-index* 0
61 "Index for temporary name generation.
63 This is automatically reset to zero before the output functions are
64 invoked to write a file. This way, we can ensure that the same output
65 file is always produced from the same input.")
67 (define-clear-the-decks reset-codegen-index
68 (setf *temporary-index* 0))
70 ;; Important temporary names.
72 (export '(*sod-ap* *sod-master-ap*))
73 (defparameter *sod-ap*
74 (make-instance 'temporary-name :tag "sod__ap"))
75 (defparameter *sod-master-ap*
76 (make-instance 'temporary-name :tag "sod__master_ap"))
77 (defparameter *sod-tmp-ap*
78 (make-instance 'temporary-name :tag "sod__tmp_ap"))
80 ;;;--------------------------------------------------------------------------
88 "A base class for instructions.
90 An `instruction' is anything which might be useful to string into a code
91 generator. Both statements and expressions can be represented by trees of
92 instructions. The `definst' macro is a convenient way of defining new
95 The only important protocol for instructions is output, which is achieved
96 by calling `print-object' with `*print-escape*' nil.
98 This doesn't really do very much, but it acts as a handy marker for
99 instruction subclasses."))
101 (export 'inst-metric)
102 (defgeneric inst-metric (inst)
104 "Returns a `metric' describing how complicated INST is.
106 The default metric of an inst node is simply 1; `inst' subclasses
107 generated by `definst' (q.v.) have an automatically generated method which
108 returns one plus the sum of the metrics of the node's children.
110 This isn't intended to be a particularly rigorous definition. Its purpose
111 is to allow code generators to make decisions about inlining or calling
112 code fairly simply.")
114 (declare (ignore inst))
116 (:method ((inst null))
117 (declare (ignore inst))
119 (:method ((inst list))
120 (reduce #'+ inst :key #'inst-metric)))
122 ;; Instruction definition.
125 (defmacro definst (code (streamvar &key export) args &body body)
126 "Define an instruction type and describe how to output it.
128 An `inst' can represent any structured piece of output syntax: a
129 statement, expression or declaration, for example. This macro defines the
132 * A class `CODE-inst' to represent the instruction.
134 * Instance slots named after the ARGS, with matching keyword initargs,
135 and `inst-ARG' readers.
137 * A constructor `make-CODE-inst' which accepts the ARGS (in order, not
138 with keywords) as arguments and returns a fresh instance.
140 * A print method, which prints a diagnostic dump if `*print-escape*' is
141 set, or invokes the BODY (with STREAMVAR bound to the output stream)
142 otherwise. The BODY is expected to produce target code at this
145 If EXPORT is non-nil, then export the `CODE-inst' and `make-CODE-inst'
148 (let ((inst-var (gensym "INST"))
149 (class-name (symbolicate code '-inst))
150 (constructor-name (symbolicate 'make- code '-inst))
151 (keys (mapcar (lambda (arg) (intern (symbol-name arg) :keyword))
154 (defclass ,class-name (inst)
155 ,(mapcar (lambda (arg key)
156 `(,arg :initarg ,key :reader ,(symbolicate 'inst- arg)))
158 (defun ,constructor-name (,@args)
159 (make-instance ',class-name ,@(mappend #'list keys args)))
160 (defmethod inst-metric ((,inst-var ,class-name))
161 (with-slots (,@args) ,inst-var
162 (+ 1 ,@(mapcar (lambda (arg) `(inst-metric ,arg)) args))))
163 (defmethod print-object ((,inst-var ,class-name) ,streamvar)
164 (with-slots (,@args) ,inst-var
166 (print-unreadable-object (,inst-var ,streamvar :type t)
167 (format stream "~@<~@{~S ~@_~S~^ ~_~}~:>"
168 ,@(mappend #'list keys args)))
170 ,@(and export `((export '(,class-name ,constructor-name
171 ,@(mapcar (lambda (arg)
172 (symbolicate 'inst- arg))
176 ;; Important instruction classes.
178 ;; HACK: use a gensym for the `expr' and `type' slots to avoid leaking the
179 ;; slot names, since the symbol `expr' is exported from our package and
180 ;; `type' belongs to the `common-lisp' package.
182 (definst var (stream :export t) (name #1=#:type init)
183 (pprint-c-type #1# stream name)
185 (format stream " = ~A" init))
186 (write-char #\; stream))
187 (definst set (stream :export t) (var #1=#:expr)
188 (format stream "~@<~A = ~@_~2I~A;~:>" var #1#))
189 (definst update (stream :export t) (var op #1=#:expr)
190 (format stream "~@<~A ~A= ~@_~2I~A;~:>" var op #1#))
191 (definst return (stream :export t) (#1=#:expr)
192 (format stream "return~@[ (~A)~];" #1#))
193 (definst break (stream :export t) ()
194 (format stream "break;"))
195 (definst continue (stream :export t) ()
196 (format stream "continue;"))
197 (definst expr (stream :export t) (#1=#:expr)
198 (format stream "~A;" #1#))
199 (definst block (stream :export t) (decls body)
200 (format stream "{~:@_~@< ~2I~@[~{~A~:@_~}~:@_~]~{~A~^~:@_~}~:>~:@_}"
202 (definst function (stream :export t) (name #1=#:type body)
203 (pprint-logical-block (stream nil)
204 (princ "static " stream)
205 (pprint-c-type #1# stream name)
206 (format stream "~:@_~A~:@_~:@_" body)))
208 ;; Formatting utilities.
210 (defun format-compound-statement* (stream child morep thunk)
211 "Underlying function for `format-compound-statement'."
212 (cond ((typep child 'block-inst)
213 (funcall thunk stream)
214 (write-char #\space stream)
216 (when morep (write-char #\space stream)))
218 (pprint-logical-block (stream nil)
219 (funcall thunk stream)
220 (write-char #\space stream)
221 (pprint-indent :block 2 stream)
222 (pprint-newline :linear stream)
224 (pprint-indent :block 0 stream)
227 (write-char #\space stream)
228 (pprint-newline :linear stream))
230 (pprint-newline :mandatory stream)))))))
232 (export 'format-compound-statement)
233 (defmacro format-compound-statement
234 ((stream child &optional morep) &body body)
235 "Format a compound statement to STREAM.
237 The introductory material is printed by BODY. The CHILD is formatted
238 properly according to whether it's a `block-inst'. If MOREP is true, then
239 allow for more stuff following the child."
240 `(format-compound-statement* ,stream ,child ,morep
241 (lambda (,stream) ,@body)))
243 ;;;--------------------------------------------------------------------------
248 (export 'codegen-functions)
249 (defgeneric codegen-functions (codegen)
251 "Return the list of `function-inst's of completed functions."))
254 (defgeneric ensure-var (codegen name type &optional init)
256 "Add a variable to CODEGEN's list.
258 The variable is called NAME (which should be comparable using `equal' and
259 print to an identifier) and has the given TYPE. If INIT is present and
260 non-nil it is an expression `inst' used to provide the variable with an
263 (export '(emit-inst emit-insts))
264 (defgeneric emit-inst (codegen inst)
266 "Add INST to the end of CODEGEN's list of instructions."))
267 (defgeneric emit-insts (codegen insts)
269 "Add a list of INSTS to the end of CODEGEN's list of instructions.")
270 (:method (codegen insts)
271 (dolist (inst insts) (emit-inst codegen inst))))
273 (export '(emit-decl emit-decls))
274 (defgeneric emit-decl (codegen inst)
276 "Add INST to the end of CODEGEN's list of declarations."))
277 (defgeneric emit-decls (codegen insts)
279 "Add a list of INSTS to the end of CODEGEN's list of declarations."))
281 (export 'codegen-push)
282 (defgeneric codegen-push (codegen)
284 "Pushes the current code generation state onto a stack.
286 The state consists of the accumulated variables and instructions."))
288 (export 'codegen-pop)
289 (defgeneric codegen-pop (codegen)
291 "Pops a saved state off of the CODEGEN's stack.
293 Returns the newly accumulated variables and instructions as lists, as
296 (export 'codegen-add-function)
297 (defgeneric codegen-add-function (codegen function)
299 "Adds a function to CODEGEN's list.
301 Actually, we're not picky: FUNCTION can be any kind of object that you're
302 willing to find in the list returned by `codegen-functions'."))
304 (export 'temporary-var)
305 (defgeneric temporary-var (codegen type)
307 "Return the name of a temporary variable.
309 The temporary variable will have the given TYPE, and will be marked
310 in-use. You should clear the in-use flag explicitly when you've finished
311 with the variable -- or, better, use `with-temporary-var' to do the
312 cleanup automatically."))
314 (export 'codegen-build-function)
315 (defun codegen-build-function (codegen name type vars insts)
316 "Build a function and add it to CODEGEN's list.
318 Returns the function's name."
319 (codegen-add-function codegen
320 (make-function-inst name type
321 (make-block-inst vars insts)))
324 (export 'codegen-pop-block)
325 (defgeneric codegen-pop-block (codegen)
327 "Makes a block (`block-inst') out of the completed code in CODEGEN.")
329 (multiple-value-bind (vars insts) (codegen-pop codegen)
330 (make-block-inst vars insts))))
332 (export 'codegen-pop-function)
333 (defgeneric codegen-pop-function (codegen name type)
335 "Makes a function out of the completed code in CODEGEN.
337 The NAME can be any object you like. The TYPE should be a function type
338 object which includes argument names. The return value is the NAME.")
339 (:method (codegen name type)
340 (multiple-value-bind (vars insts) (codegen-pop codegen)
341 (codegen-build-function codegen name type vars insts))))
343 (export 'with-temporary-var)
344 (defmacro with-temporary-var ((codegen var type) &body body)
345 "Evaluate BODY with VAR bound to a temporary variable name.
347 During BODY, VAR will be marked in-use; when BODY ends, VAR will be marked
348 available for re-use."
349 `(let ((,var (temporary-var ,codegen ,type)))
352 (setf (var-in-use-p ,var) nil))))
354 ;;;--------------------------------------------------------------------------
355 ;;; Code generation idioms.
357 (export 'deliver-expr)
358 (defun deliver-expr (codegen target expr)
359 "Emit code to deliver the value of EXPR to the TARGET.
361 The TARGET may be one of the following.
363 * `:void', indicating that the value is to be discarded. The expression
364 will still be evaluated.
366 * `:void-return', indicating that the value is to be discarded (as for
367 `:void') and furthermore a `return' from the current function should
368 be forced after computing the value.
370 * `:return', indicating that the value is to be returned from the
373 * A variable name, indicating that the value is to be stored in the
376 In the cases of `:return', `:void' and `:void-return' targets, it is valid
377 for EXPR to be nil; this signifies that no computation needs to be
378 performed. Variable-name targets require an expression."
381 (:return (emit-inst codegen (make-return-inst expr)))
382 (:void (when expr (emit-inst codegen (make-expr-inst expr))))
383 (:void-return (when expr (emit-inst codegen (make-expr-inst expr)))
384 (emit-inst codegen (make-return-inst nil)))
385 (t (emit-inst codegen (make-set-inst target expr)))))
387 (export 'convert-stmts)
388 (defun convert-stmts (codegen target type func)
389 "Invoke FUNC to deliver a value to a non-`:return' target.
391 FUNC is a function which accepts a single argument, a non-`:return'
392 target, and generates statements which deliver a value (see
393 `deliver-expr') of the specified TYPE to this target. In general, the
394 generated code will have the form
396 setup instructions...
397 (deliver-expr CODEGEN TARGET (compute value...))
398 cleanup instructions...
400 where the cleanup instructions are essential to the proper working of the
403 The `convert-stmts' function will call FUNC to generate code, and arrange
404 that its value is correctly delivered to TARGET, regardless of what the
405 TARGET is -- i.e., it lifts the restriction to non-`:return' targets. It
406 does this by inventing a new temporary variable."
409 (:return (with-temporary-var (codegen var type)
411 (deliver-expr codegen target var)))
412 (:void-return (funcall func :void)
413 (emit-inst codegen (make-return-inst nil)))
414 (t (funcall func target))))
416 ;;;----- That's all, folks --------------------------------------------------