src/codegen-proto.lisp, doc/list-exports.lisp: Export `inst' readers.
[sod] / src / codegen-proto.lisp
CommitLineData
1f1d88f5
MW
1;;; -*-lisp-*-
2;;;
dea4d055 3;;; Code generation protocol
1f1d88f5
MW
4;;;
5;;; (c) 2009 Straylight/Edgeware
6;;;
7
8;;;----- Licensing notice ---------------------------------------------------
9;;;
dea4d055 10;;; This file is part of the Sensble Object Design, an object system for C.
1f1d88f5
MW
11;;;
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.
16;;;
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.
21;;;
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.
25
26(cl:in-package #:sod)
27
28;;;--------------------------------------------------------------------------
29;;; Temporary names.
30
dea4d055
MW
31;; Protocol.
32
33(export 'format-temporary-name)
34(defgeneric format-temporary-name (var stream)
1f1d88f5 35 (:documentation
dea4d055 36 "Write the name of a temporary variable VAR to STREAM."))
1f1d88f5 37
dea4d055
MW
38(export 'var-in-use-p)
39(defgeneric var-in-use-p (var)
40 (:documentation
3109662a 41 "Answer whether VAR is currently being used. See `with-temporary-var'.")
dea4d055
MW
42 (:method (var)
43 "Non-temporary variables are always in use."
1d8cc67a 44 (declare (ignore var))
dea4d055
MW
45 t))
46(defgeneric (setf var-in-use-p) (value var)
47 (:documentation
3109662a 48 "Record whether VAR is currently being used. See `with-temporary-var'."))
1f1d88f5 49
dea4d055 50;; Root class.
1f1d88f5 51
1344e1f9 52(export '(temporary-name temp-tag))
dea4d055
MW
53(defclass temporary-name ()
54 ((tag :initarg :tag :reader temp-tag))
55 (:documentation
56 "Base class for temporary variable and argument names."))
1f1d88f5 57
dea4d055 58;; Important variables.
1f1d88f5
MW
59
60(defparameter *temporary-index* 0
61 "Index for temporary name generation.
62
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
9ec578d9
MW
65 file is always produced from the same input.")
66
67(define-clear-the-decks reset-codegen-index
68 (setf *temporary-index* 0))
1f1d88f5 69
dea4d055 70;; Important temporary names.
1f1d88f5 71
dea4d055 72(export '(*sod-ap* *sod-master-ap*))
1f1d88f5
MW
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"))
2bbe0f1d
MW
77(defparameter *sod-tmp-ap*
78 (make-instance 'temporary-name :tag "sod__tmp_ap"))
1f1d88f5
MW
79
80;;;--------------------------------------------------------------------------
81;;; Instructions.
82
dea4d055
MW
83;; Classes.
84
85(export 'inst)
1f1d88f5
MW
86(defclass inst () ()
87 (:documentation
88 "A base class for instructions.
89
90 An `instruction' is anything which might be useful to string into a code
9ec578d9
MW
91 generator. Both statements and expressions can be represented by trees of
92 instructions. The `definst' macro is a convenient way of defining new
93 instructions.
1f1d88f5
MW
94
95 The only important protocol for instructions is output, which is achieved
3109662a 96 by calling `print-object' with `*print-escape*' nil.
1f1d88f5
MW
97
98 This doesn't really do very much, but it acts as a handy marker for
99 instruction subclasses."))
100
dea4d055 101(export 'inst-metric)
1f1d88f5
MW
102(defgeneric inst-metric (inst)
103 (:documentation
104 "Returns a `metric' describing how complicated INST is.
105
3109662a
MW
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.
1f1d88f5
MW
109
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.")
9ec578d9
MW
113 (:method ((inst t))
114 (declare (ignore inst))
115 1)
116 (:method ((inst null))
1d8cc67a 117 (declare (ignore inst))
9ec578d9
MW
118 1)
119 (:method ((inst list))
120 (reduce #'+ inst :key #'inst-metric)))
1f1d88f5 121
dea4d055
MW
122;; Instruction definition.
123
124(export 'definst)
418752c5 125(defmacro definst (code (streamvar &key export) args &body body)
1f1d88f5
MW
126 "Define an instruction type and describe how to output it.
127
3109662a
MW
128 An `inst' can represent any structured piece of output syntax: a
129 statement, expression or declaration, for example. This macro defines the
130 following things:
1f1d88f5 131
3109662a 132 * A class `CODE-inst' to represent the instruction.
1f1d88f5
MW
133
134 * Instance slots named after the ARGS, with matching keyword initargs,
3109662a 135 and `inst-ARG' readers.
1f1d88f5 136
3109662a 137 * A constructor `make-CODE-inst' which accepts the ARGS (in order, not
1f1d88f5
MW
138 with keywords) as arguments and returns a fresh instance.
139
3109662a 140 * A print method, which prints a diagnostic dump if `*print-escape*' is
1f1d88f5
MW
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
418752c5
MW
143 point.
144
145 If EXPORT is non-nil, then export the `CODE-inst' and `make-CODE-inst'
146 symbols."
1f1d88f5
MW
147
148 (let ((inst-var (gensym "INST"))
149 (class-name (symbolicate code '-inst))
418752c5 150 (constructor-name (symbolicate 'make- code '-inst))
1f1d88f5
MW
151 (keys (mapcar (lambda (arg) (intern (symbol-name arg) :keyword))
152 args)))
153 `(progn
154 (defclass ,class-name (inst)
155 ,(mapcar (lambda (arg key)
156 `(,arg :initarg ,key :reader ,(symbolicate 'inst- arg)))
157 args keys))
418752c5 158 (defun ,constructor-name (,@args)
1f1d88f5
MW
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
165 (if *print-escape*
166 (print-unreadable-object (,inst-var ,streamvar :type t)
167 (format stream "~@<~@{~S ~@_~S~^ ~_~}~:>"
168 ,@(mappend #'list keys args)))
418752c5 169 (progn ,@body))))
34c51b1c
MW
170 ,@(and export `((export '(,class-name ,constructor-name
171 ,@(mapcar (lambda (arg)
172 (symbolicate 'inst- arg))
173 args)))))
418752c5 174 ',code)))
1f1d88f5 175
dea4d055
MW
176;; Important instruction classes.
177
418752c5 178(definst var (stream :export t) (name type init)
dea4d055
MW
179 (pprint-c-type type stream name)
180 (when init
75dbacfc
MW
181 (format stream " = ~A" init))
182 (write-char #\; stream))
418752c5 183(definst set (stream :export t) (var expr)
dea4d055 184 (format stream "~@<~A = ~@_~2I~A;~:>" var expr))
b559689b
MW
185(definst update (stream :export t) (var op expr)
186 (format stream "~@<~A ~A= ~@_~2I~A;~:>" var op expr))
418752c5 187(definst return (stream :export t) (expr)
dea4d055 188 (format stream "return~@[ (~A)~];" expr))
b559689b
MW
189(definst break (stream :export t) ()
190 (format stream "break;"))
191(definst continue (stream :export t) ()
192 (format stream "continue;"))
418752c5 193(definst expr (stream :export t) (expr)
dea4d055 194 (format stream "~A;" expr))
418752c5 195(definst block (stream :export t) (decls body)
75dbacfc 196 (format stream "{~:@_~@< ~2I~@[~{~A~:@_~}~:@_~]~{~A~^~:@_~}~:>~:@_}"
dea4d055 197 decls body))
418752c5 198(definst function (stream :export t) (name type body)
dea4d055
MW
199 (pprint-logical-block (stream nil)
200 (princ "static " stream)
201 (pprint-c-type type stream name)
202 (format stream "~:@_~A~:@_~:@_" body)))
203
204;; Formatting utilities.
205
1f1d88f5 206(defun format-compound-statement* (stream child morep thunk)
3109662a 207 "Underlying function for `format-compound-statement'."
1f1d88f5
MW
208 (cond ((typep child 'block-inst)
209 (funcall thunk stream)
210 (write-char #\space stream)
211 (princ child stream)
212 (when morep (write-char #\space stream)))
213 (t
214 (pprint-logical-block (stream nil)
215 (funcall thunk stream)
216 (write-char #\space stream)
217 (pprint-indent :block 2 stream)
218 (pprint-newline :linear stream)
219 (princ child stream)
220 (pprint-indent :block 0 stream)
221 (case morep
222 (:space
223 (write-char #\space stream)
224 (pprint-newline :linear stream))
dea4d055 225 ((t)
1f1d88f5
MW
226 (pprint-newline :mandatory stream)))))))
227
dea4d055 228(export 'format-compound-statement)
1f1d88f5
MW
229(defmacro format-compound-statement
230 ((stream child &optional morep) &body body)
231 "Format a compound statement to STREAM.
232
233 The introductory material is printed by BODY. The CHILD is formatted
3109662a 234 properly according to whether it's a `block-inst'. If MOREP is true, then
1f1d88f5
MW
235 allow for more stuff following the child."
236 `(format-compound-statement* ,stream ,child ,morep
237 (lambda (,stream) ,@body)))
238
239;;;--------------------------------------------------------------------------
dea4d055 240;;; Code generation.
1f1d88f5 241
dea4d055 242;; Accessors.
1f1d88f5 243
dea4d055
MW
244(export 'codegen-functions)
245(defgeneric codegen-functions (codegen)
1f1d88f5 246 (:documentation
3109662a 247 "Return the list of `function-inst's of completed functions."))
1f1d88f5 248
dea4d055 249(export 'ensure-var)
1f1d88f5
MW
250(defgeneric ensure-var (codegen name type &optional init)
251 (:documentation
252 "Add a variable to CODEGEN's list.
253
3109662a 254 The variable is called NAME (which should be comparable using `equal' and
1f1d88f5 255 print to an identifier) and has the given TYPE. If INIT is present and
3109662a 256 non-nil it is an expression `inst' used to provide the variable with an
dea4d055 257 initial value."))
1f1d88f5 258
dea4d055
MW
259(export '(emit-inst emit-insts))
260(defgeneric emit-inst (codegen inst)
261 (:documentation
262 "Add INST to the end of CODEGEN's list of instructions."))
263(defgeneric emit-insts (codegen insts)
264 (:documentation
265 "Add a list of INSTS to the end of CODEGEN's list of instructions.")
266 (:method (codegen insts)
267 (dolist (inst insts) (emit-inst codegen inst))))
1f1d88f5 268
3f4ac959
MW
269(export '(emit-decl emit-decls))
270(defgeneric emit-decl (codegen inst)
271 (:documentation
272 "Add INST to the end of CODEGEN's list of declarations."))
273(defgeneric emit-decls (codegen insts)
274 (:documentation
275 "Add a list of INSTS to the end of CODEGEN's list of declarations."))
276
dea4d055 277(export 'codegen-push)
1f1d88f5
MW
278(defgeneric codegen-push (codegen)
279 (:documentation
280 "Pushes the current code generation state onto a stack.
281
dea4d055 282 The state consists of the accumulated variables and instructions."))
1f1d88f5 283
dea4d055 284(export 'codegen-pop)
1f1d88f5
MW
285(defgeneric codegen-pop (codegen)
286 (:documentation
287 "Pops a saved state off of the CODEGEN's stack.
288
289 Returns the newly accumulated variables and instructions as lists, as
dea4d055 290 separate values."))
1f1d88f5 291
dea4d055 292(export 'codegen-add-function)
1f1d88f5
MW
293(defgeneric codegen-add-function (codegen function)
294 (:documentation
295 "Adds a function to CODEGEN's list.
296
297 Actually, we're not picky: FUNCTION can be any kind of object that you're
3109662a 298 willing to find in the list returned by `codegen-functions'."))
dea4d055
MW
299
300(export 'temporary-var)
301(defgeneric temporary-var (codegen type)
302 (:documentation
303 "Return the name of a temporary variable.
304
305 The temporary variable will have the given TYPE, and will be marked
306 in-use. You should clear the in-use flag explicitly when you've finished
3109662a
MW
307 with the variable -- or, better, use `with-temporary-var' to do the
308 cleanup automatically."))
1f1d88f5 309
dea4d055 310(export 'codegen-build-function)
1f1d88f5
MW
311(defun codegen-build-function (codegen name type vars insts)
312 "Build a function and add it to CODEGEN's list.
313
314 Returns the function's name."
315 (codegen-add-function codegen
316 (make-function-inst name type
317 (make-block-inst vars insts)))
318 name)
319
dea4d055
MW
320(export 'codegen-pop-block)
321(defgeneric codegen-pop-block (codegen)
322 (:documentation
3109662a 323 "Makes a block (`block-inst') out of the completed code in CODEGEN.")
dea4d055
MW
324 (:method (codegen)
325 (multiple-value-bind (vars insts) (codegen-pop codegen)
326 (make-block-inst vars insts))))
327
328(export 'codegen-pop-function)
1f1d88f5
MW
329(defgeneric codegen-pop-function (codegen name type)
330 (:documentation
331 "Makes a function out of the completed code in CODEGEN.
332
333 The NAME can be any object you like. The TYPE should be a function type
334 object which includes argument names. The return value is the NAME.")
dea4d055 335 (:method (codegen name type)
1f1d88f5
MW
336 (multiple-value-bind (vars insts) (codegen-pop codegen)
337 (codegen-build-function codegen name type vars insts))))
338
dea4d055 339(export 'with-temporary-var)
1f1d88f5
MW
340(defmacro with-temporary-var ((codegen var type) &body body)
341 "Evaluate BODY with VAR bound to a temporary variable name.
342
343 During BODY, VAR will be marked in-use; when BODY ends, VAR will be marked
9ec578d9 344 available for re-use."
1f1d88f5
MW
345 `(let ((,var (temporary-var ,codegen ,type)))
346 (unwind-protect
347 (progn ,@body)
348 (setf (var-in-use-p ,var) nil))))
349
350;;;--------------------------------------------------------------------------
351;;; Code generation idioms.
352
dea4d055 353(export 'deliver-expr)
1f1d88f5
MW
354(defun deliver-expr (codegen target expr)
355 "Emit code to deliver the value of EXPR to the TARGET.
356
357 The TARGET may be one of the following.
358
3109662a 359 * `:void', indicating that the value is to be discarded. The expression
1f1d88f5
MW
360 will still be evaluated.
361
3109662a
MW
362 * `:void-return', indicating that the value is to be discarded (as for
363 `:void') and furthermore a `return' from the current function should
364 be forced after computing the value.
1f1d88f5 365
3109662a
MW
366 * `:return', indicating that the value is to be returned from the
367 current function.
1f1d88f5
MW
368
369 * A variable name, indicating that the value is to be stored in the
370 variable.
371
3109662a
MW
372 In the cases of `:return', `:void' and `:void-return' targets, it is valid
373 for EXPR to be nil; this signifies that no computation needs to be
374 performed. Variable-name targets require an expression."
1f1d88f5
MW
375
376 (case target
377 (:return (emit-inst codegen (make-return-inst expr)))
378 (:void (when expr (emit-inst codegen (make-expr-inst expr))))
379 (:void-return (when expr (emit-inst codegen (make-expr-inst expr)))
380 (emit-inst codegen (make-return-inst nil)))
381 (t (emit-inst codegen (make-set-inst target expr)))))
382
dea4d055 383(export 'convert-stmts)
1f1d88f5 384(defun convert-stmts (codegen target type func)
3109662a 385 "Invoke FUNC to deliver a value to a non-`:return' target.
1f1d88f5 386
3109662a
MW
387 FUNC is a function which accepts a single argument, a non-`:return'
388 target, and generates statements which deliver a value (see
389 `deliver-expr') of the specified TYPE to this target. In general, the
390 generated code will have the form
1f1d88f5
MW
391
392 setup instructions...
3109662a 393 (deliver-expr CODEGEN TARGET (compute value...))
1f1d88f5
MW
394 cleanup instructions...
395
396 where the cleanup instructions are essential to the proper working of the
397 generated program.
398
3109662a
MW
399 The `convert-stmts' function will call FUNC to generate code, and arrange
400 that its value is correctly delivered to TARGET, regardless of what the
401 TARGET is -- i.e., it lifts the restriction to non-`:return' targets. It
402 does this by inventing a new temporary variable."
1f1d88f5
MW
403
404 (case target
405 (:return (with-temporary-var (codegen var type)
406 (funcall func var)
407 (deliver-expr codegen target var)))
408 (:void-return (funcall func :void)
409 (emit-inst codegen (make-return-inst nil)))
410 (t (funcall func target))))
411
412;;;----- That's all, folks --------------------------------------------------