/[cmucl]/src/compiler/macros.lisp
ViewVC logotype

Contents of /src/compiler/macros.lisp

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.24 - (show annotations)
Thu Jul 11 16:30:02 1991 UTC (22 years, 9 months ago) by ram
Branch: MAIN
Changes since 1.23: +2 -2 lines
Deleted setf bootstrap hack.
1 ;;; -*- Package: C; Log: C.Log -*-
2 ;;;
3 ;;; **********************************************************************
4 ;;; This code was written as part of the CMU Common Lisp project at
5 ;;; Carnegie Mellon University, and has been placed in the public domain.
6 ;;; If you want to use this code or any part of CMU Common Lisp, please contact
7 ;;; Scott Fahlman or slisp-group@cs.cmu.edu.
8 ;;;
9 (ext:file-comment
10 "$Header: /tiger/var/lib/cvsroots/cmucl/src/compiler/macros.lisp,v 1.24 1991/07/11 16:30:02 ram Exp $")
11 ;;;
12 ;;; **********************************************************************
13 ;;;
14 ;;; Random types and macros used in writing the compiler.
15 ;;;
16 ;;; Written by Rob MacLachlan
17 ;;;
18 (in-package 'c)
19
20 (export '(lisp::with-compilation-unit) "LISP")
21
22 (export '(policy symbolicate def-ir1-translator def-source-transform
23 def-primitive-translator deftransform defknown defoptimizer
24 derive-type optimizer ltn-annotate ir2-convert attributes
25 def-boolean-attribute attributes-union attributes-intersection
26 attributes=))
27
28 (proclaim '(special *wild-type* *universal-type* *compiler-error-context*))
29
30 ;;;; Deftypes:
31
32 ;;;
33 ;;; Should be standard:
34 (deftype boolean () '(member t nil))
35
36 ;;;
37 ;;; Inlinep is used to determine how a function is called. The values have
38 ;;; these meanings:
39 ;;; Nil No declaration seen: do whatever you feel like, but don't dump
40 ;;; an inline expansion.
41 ;;;
42 ;;; :Notinline Notinline declaration seen: always do full function call.
43 ;;;
44 ;;; :Inline Inline declaration seen: save expansion, expanding to it if
45 ;;; policy favors.
46 ;;;
47 ;;; :Maybe-Inline
48 ;;; Retain expansion, but only use it opportunistically.
49 ;;;
50 (deftype inlinep () '(member :inline :maybe-inline :notinline nil))
51
52
53 ;;;; The Policy macro:
54
55 (proclaim '(special *lexical-environment*))
56
57 (eval-when (compile load eval)
58 (defconstant policy-parameter-slots
59 '((speed . cookie-speed) (space . cookie-space) (safety . cookie-safety)
60 (cspeed . cookie-cspeed) (brevity . cookie-brevity)
61 (debug . cookie-debug)))
62
63 ;;; Find-Used-Parameters -- Internal
64 ;;;
65 ;;; Find all the policy parameters which are actually mentioned in Stuff,
66 ;;; returning the names in a list. We assume everything is evaluated.
67 ;;;
68 (defun find-used-parameters (stuff)
69 (if (atom stuff)
70 (if (assoc stuff policy-parameter-slots) (list stuff) ())
71 (collect ((res () nunion))
72 (dolist (arg (cdr stuff) (res))
73 (res (find-used-parameters arg))))))
74
75 ); Eval-When (Compile Load Eval)
76
77 ;;; Policy -- Public
78 ;;;
79 ;;; This macro provides some syntactic sugar for querying the settings of
80 ;;; the compiler policy parameters.
81 ;;;
82 (defmacro policy (node &rest conditions)
83 "Policy Node Condition*
84 Test whether some conditions apply to the current compiler policy for Node.
85 Each condition is a predicate form which accesses the policy values by
86 referring to them as the variables SPEED, SPACE, SAFETY, CSPEED, BREVITY and
87 DEBUG. The results of all the conditions are combined with AND and returned
88 as the result.
89
90 Node is a form which is evaluated to obtain the node which the policy is for.
91 If Node is NIL, then we use the current policy as defined by *default-cookie*
92 and *current-cookie*. This option is only well defined during IR1
93 conversion."
94 (let* ((form `(and ,@conditions))
95 (n-cookie (gensym))
96 (binds (mapcar
97 #'(lambda (name)
98 (let ((slot (cdr (assoc name policy-parameter-slots))))
99 `(,name (,slot ,n-cookie))))
100 (find-used-parameters form))))
101 `(let* ((,n-cookie (lexenv-cookie
102 ,(if node
103 `(node-lexenv ,node)
104 '*lexical-environment*)))
105 ,@binds)
106 ,form)))
107
108
109 ;;;; Source-hacking defining forms:
110
111 (eval-when (compile load eval)
112
113 ;;; Symbolicate -- Interface
114 ;;;
115 ;;; Concatenate together the names of some strings and symbols, producing
116 ;;; a symbol in the current package.
117 ;;;
118 (proclaim '(function symbolicate (&rest (or string symbol)) symbol))
119 (defun symbolicate (&rest things)
120 (values (intern (reduce #'(lambda (x y)
121 (concatenate 'string (string x) (string y)))
122 things))))
123
124 ); Eval-When (Compile Load Eval)
125
126 ;;; SPECIAL-FORM-FUNCTION -- Internal
127 ;;;
128 ;;; This function is stored in the SYMBOL-FUNCTION of special form names so
129 ;;; that they are FBOUND.
130 ;;;
131 (defun special-form-function (&rest stuff)
132 (declare (ignore stuff))
133 (error "Can't funcall the SYMBOL-FUNCTION of special forms."))
134
135 ;;; CONVERT-CONDITION-INTO-COMPILER-ERROR -- Internal
136 ;;;
137 ;;; Passed to parse-defmacro when we want compiler errors instead of real
138 ;;; errors.
139 ;;;
140 (proclaim '(inline convert-condition-into-compiler-error))
141 (defun convert-condition-into-compiler-error (datum &rest stuff)
142 (if (stringp datum)
143 (apply #'compiler-error datum stuff)
144 (compiler-error "~A"
145 (if (symbolp datum)
146 (apply #'make-condition datum stuff)
147 datum))))
148
149 ;;; Def-IR1-Translator -- Interface
150 ;;;
151 ;;; Parse defmacro style lambda-list, setting things up so that a compiler
152 ;;; error happens if the syntax is invalid.
153 ;;;
154 (defmacro def-ir1-translator (name (lambda-list start-var cont-var
155 &key (kind :special-form))
156 &body body)
157 "Def-IR1-Translator Name (Lambda-List Start-Var Cont-Var {Key Value}*)
158 [Doc-String] Form*
159 Define a function that converts a Special-Form or other magical thing into
160 IR1. Lambda-List is a defmacro style lambda list. Start-Var and Cont-Var
161 are bound to the start and result continuations for the resulting IR1.
162 This keyword is defined:
163 Kind
164 The function kind to associate with Name (default :special-form)."
165 (let ((fn-name (symbolicate "IR1-CONVERT-" name))
166 (n-form (gensym))
167 (n-env (gensym)))
168 (multiple-value-bind
169 (body decls doc)
170 (lisp::parse-defmacro lambda-list n-form body name "special form"
171 :doc-string-allowed t
172 :environment n-env
173 :error-fun 'convert-condition-into-compiler-error)
174 `(progn
175 (proclaim '(function ,fn-name (continuation continuation t) void))
176 (defun ,fn-name (,start-var ,cont-var ,n-form)
177 (let ((,n-env *lexical-environment*))
178 ,@decls
179 ,body))
180 ,@(when doc
181 `((setf (documentation ',name 'function) ,doc)))
182 (setf (info function ir1-convert ',name) #',fn-name)
183 (setf (info function kind ',name) ,kind)
184 #+new-compiler
185 ,@(when (eq kind :special-form)
186 `((setf (symbol-function ',name) #'special-form-function)))))))
187
188
189 ;;; Def-Source-Transform -- Interface
190 ;;;
191 ;;; Similar to Def-IR1-Translator, except that we pass if the syntax is
192 ;;; invalid.
193 ;;;
194 (defmacro def-source-transform (name lambda-list &body body)
195 "Def-Source-Transform Name Lambda-List Form*
196 Define a macro-like source-to-source transformation for the function Name.
197 A source transform may \"pass\" by returning a non-nil second value. If the
198 transform passes, then the form is converted as a normal function call. If
199 the supplied arguments are not compatible with the specified lambda-list,
200 then the transform automatically passes.
201
202 Source-Transforms may only be defined for functions. Source transformation
203 is not attempted if the function is declared Notinline. Source transforms
204 should not examine their arguments. If it matters how the function is used,
205 then Deftransform should be used to define an IR1 transformation.
206
207 If the desirability of the transformation depends on the current Optimize
208 parameters, then the Policy macro should be used to determine when to pass."
209 (let ((fn-name (symbolicate "SOURCE-TRANSFORM-" name))
210 (n-form (gensym))
211 (n-env (gensym)))
212 (multiple-value-bind
213 (body decls)
214 (lisp::parse-defmacro lambda-list n-form body name "form"
215 :environment n-env
216 :error-fun `(lambda (&rest stuff)
217 (declare (ignore stuff))
218 (return-from ,fn-name
219 (values nil t))))
220 `(progn
221 (defun ,fn-name (,n-form)
222 (let ((,n-env *lexical-environment*))
223 ,@decls
224 ,body))
225 (setf (info function source-transform ',name) #',fn-name)))))
226
227
228 (defmacro def-primitive-translator (name lambda-list &body body)
229 "Def-Primitive-Translator Name Lambda-List Form*
230 Define a function that converts a use of (%PRIMITIVE Name ...) into Lisp
231 code. Lambda-List is a defmacro style lambda list."
232 (let ((fn-name (symbolicate "PRIMITIVE-TRANSLATE-" name))
233 (n-form (gensym))
234 (n-env (gensym)))
235 (multiple-value-bind
236 (body decls)
237 (lisp::parse-defmacro lambda-list n-form body name "%primitive"
238 :environment n-env
239 :error-fun 'convert-condition-into-compiler-error)
240 `(progn
241 (defun ,fn-name (,n-form)
242 (let ((,n-env *lexical-environment*))
243 ,@decls
244 ,body))
245 (setf (gethash ',name *primitive-translators*) ',fn-name)))))
246
247
248 ;;;; Lambda-list parsing utilities:
249 ;;;
250 ;;; IR1 transforms, optimizers and type inferencers need to be able to parse
251 ;;; the IR1 representation of a function call using a standard function
252 ;;; lambda-list.
253
254
255 (eval-when (compile load eval)
256
257 ;;; Parse-Deftransform -- Internal
258 ;;;
259 ;;; Given a deftransform style lambda-list, generate code that parses the
260 ;;; arguments of a combination with respect to that lambda-list. Body is the
261 ;;; the list of forms which are to be evaluated within the bindings. Args is
262 ;;; the variable that holds list of argument continuations. Error-Form is a
263 ;;; form which is evaluated when the syntax of the supplied arguments is
264 ;;; incorrect or a non-constant argument keyword is supplied. Defaults and
265 ;;; other gunk are ignored. The second value is a list of all the arguments
266 ;;; bound. We make the variables IGNORABLE so that we don't have to manually
267 ;;; declare them Ignore if their only purpose is to make the syntax work.
268 ;;;
269 (proclaim '(function parse-deftransform (list list symbol t) list))
270 (defun parse-deftransform (lambda-list body args error-form)
271 (multiple-value-bind (req opt restp rest keyp keys allowp)
272 (parse-lambda-list lambda-list)
273 (let* ((min-args (length req))
274 (max-args (+ min-args (length opt)))
275 (n-keys (gensym)))
276 (collect ((binds)
277 (vars)
278 (pos 0 +)
279 (keywords))
280 (dolist (arg req)
281 (vars arg)
282 (binds `(,arg (nth ,(pos) ,args)))
283 (pos 1))
284
285 (dolist (arg opt)
286 (let ((var (if (atom arg) arg (first arg))))
287 (vars var)
288 (binds `(,var (nth ,(pos) ,args)))
289 (pos 1)))
290
291 (when restp
292 (vars rest)
293 (binds `(,rest (nthcdr ,(pos) ,args))))
294
295 (dolist (spec keys)
296 (if (or (atom spec) (atom (first spec)))
297 (let* ((var (if (atom spec) spec (first spec)))
298 (key (intern (symbol-name var) "KEYWORD")))
299 (vars var)
300 (binds `(,var (find-keyword-continuation ,n-keys ,key)))
301 (keywords key))
302 (let* ((head (first spec))
303 (var (second head))
304 (key (first head)))
305 (vars var)
306 (binds `(,var (find-keyword-continuation ,n-keys ,key)))
307 (keywords key))))
308
309 (let ((n-length (gensym))
310 (limited-legal (not (or restp keyp))))
311 (values
312 `(let ((,n-length (length ,args))
313 ,@(when keyp `((,n-keys (nthcdr ,(pos) ,args)))))
314 (unless (and
315 ,(if limited-legal
316 `(<= ,min-args ,n-length ,max-args)
317 `(<= ,min-args ,n-length))
318 ,@(when keyp
319 (if allowp
320 `((check-keywords-constant ,n-keys))
321 `((check-transform-keys ,n-keys ',(keywords))))))
322 ,error-form)
323 (let ,(binds)
324 ;;; ### Bootstrap hack...
325 #+new-compiler
326 (declare (ignorable ,@(vars)))
327 #-new-compiler
328 (progn ,@(vars))
329 ,@body))
330 (vars)))))))
331
332 ); Eval-When (Compile Load Eval)
333
334
335 ;;;; Utilities used at run-time for parsing keyword args in IR1:
336
337 ;;; Find-Keyword-Continuation -- Internal
338 ;;;
339 ;;; This function is used by the result of Parse-Deftransform to find the
340 ;;; continuation for the value of the keyword argument Key in the list of
341 ;;; continuations Args. It returns the continuation if the keyword is present,
342 ;;; or NIL otherwise. The legality and constantness of the keywords should
343 ;;; already have been checked.
344 ;;;
345 (proclaim '(function find-keyword-continuation (list keyword) (or continuation null)))
346 (defun find-keyword-continuation (args key)
347 (do ((arg args (cddr arg)))
348 ((null arg) nil)
349 (when (eq (continuation-value (first arg)) key)
350 (return (second arg)))))
351
352
353 ;;; Check-Keywords-Constant -- Internal
354 ;;;
355 ;;; This function is used by the result of Parse-Deftransform to verify that
356 ;;; alternating continuations in Args are constant and that there is an even
357 ;;; number of args.
358 ;;;
359 (proclaim '(function check-keywords-constant (list) boolean))
360 (defun check-keywords-constant (args)
361 (do ((arg args (cddr arg)))
362 ((null arg) t)
363 (unless (and (rest arg)
364 (constant-continuation-p (first arg)))
365 (return nil))))
366
367
368 ;;; Check-Transform-Keys -- Internal
369 ;;;
370 ;;; This function is used by the result of Parse-Deftransform to verify that
371 ;;; the list of continuations Args is a well-formed keyword arglist and that
372 ;;; only keywords present in the list Keys are supplied.
373 ;;;
374 (proclaim '(function check-transform-keys (list list) boolean))
375 (defun check-transform-keys (args keys)
376 (and (check-keywords-constant args)
377 (do ((arg args (cddr arg)))
378 ((null arg) t)
379 (unless (member (continuation-value (first arg)) keys)
380 (return nil)))))
381
382
383 ;;;; Deftransform:
384
385 ;;; Deftransform -- Interface
386 ;;;
387 ;;; Parse the lambda-list and generate code to test the policy and
388 ;;; automatically create the result lambda.
389 ;;;
390 (defmacro deftransform (name (lambda-list &optional (arg-types '*) (result-type '*)
391 &key result policy node defun-only
392 eval-name)
393 &body body)
394 "Deftransform Name (Lambda-List [Arg-Types] [Result-Type] {Key Value}*)
395 Declaration* Form*
396 Define an IR1 transformation for Name. An IR1 transformation computes a
397 lambda that replaces the function variable reference for the call. A
398 transform may pass (decide not to transform the call) by calling the Give-Up
399 function. Lambda-List both determines how the current call is parsed and
400 specifies the Lambda-List for the resulting lambda.
401
402 We parse the call and bind each of the lambda-list variables to the
403 continuation which represents the value of the argument. When parsing the
404 call, we ignore the defaults, and always bind the variables for unsupplied
405 arguments to NIL. If a required argument is missing, an unknown keyword is
406 supplied, or an argument keyword is not a constant, then the transform
407 automatically passes. The Declarations apply to the bindings made by
408 Deftransform at transformation time, rather than to the variables of the
409 resulting lambda. Bound-but-not-referenced warnings are suppressed for the
410 lambda-list variables.
411
412 Normally, the body evaluates to a form which becomes the body of an
413 automatically constructed lambda. We make Lambda-List the lambda-list for
414 the lambda, and automatically insert declarations of the argument and result
415 types. If the second value of the body is non-null, then it is a list of
416 declarations which are to be inserted at the head of the lambda. Automatic
417 lambda generation may be inhibited by explicitly returning a lambda from the
418 body.
419
420 The Arg-Types and Result-Type are used to create a function type which the
421 call must satisfy before transformation is attempted. The function type
422 specifier is constructed by wrapping (FUNCTION ...) around these values, so
423 the lack of a restriction may be specified by omitting the argument or
424 supplying *. The argument syntax specified in the Arg-Types need not be the
425 same as that in the Lambda-List, but the transform will never happen if
426 the syntaxes can't be satisfied simultaneously. If there is an existing
427 transform for the same function that has the same type, then it is replaced
428 with the new definition.
429
430 These are the legal keyword options:
431 :Result - A variable which is bound to the result continuation.
432 :Node - A variable which is bound to the combination node for the call.
433 :Policy - A form which is supplied to the Policy macro to determine whether
434 this transformation is appropriate. If the result is false, then
435 the transform automatically passes.
436 :Eval-Name
437 - The name is actually a form to be evaluated. Useful for getting
438 closures that transform similar functions.
439 :Defun-Only
440 - Don't actually instantiate a transform, instead just DEFUN
441 Name with the specified transform definition function. This may
442 be later instantiated with %Deftransform."
443
444 (when (and eval-name defun-only)
445 (error "Can't specify both DEFUN-ONLY and EVAL-NAME."))
446 (let ((n-args (gensym))
447 (n-node (or node (gensym)))
448 (n-decls (gensym))
449 (n-lambda (gensym)))
450 (multiple-value-bind (parsed-form vars)
451 (parse-deftransform
452 lambda-list
453 (if policy
454 `((unless (policy ,n-node ,policy) (give-up))
455 ,@body)
456 body)
457 n-args '(give-up))
458 (let ((stuff
459 `((,n-node)
460 (let* ((,n-args (basic-combination-args ,n-node))
461 ,@(when result
462 `((,result (node-cont ,n-node)))))
463 (multiple-value-bind (,n-lambda ,n-decls)
464 ,parsed-form
465 (if (and (consp ,n-lambda) (eq (car ,n-lambda) 'lambda))
466 ,n-lambda
467 `(lambda ,',lambda-list
468 (declare (ignorable ,@',vars))
469 ,@,n-decls
470 ,,n-lambda)))))))
471 (if defun-only
472 `(defun ,name ,@stuff)
473 `(%deftransform
474 ,(if eval-name name `',name)
475 '(function ,arg-types ,result-type)
476 #'(lambda ,@stuff)))))))
477
478 ;;;; Defknown, Defoptimizer:
479
480 ;;; Defknown -- Interface
481 ;;;
482 ;;; This macro should be the way that all implementation independent
483 ;;; information about functions is made known to the compiler.
484 ;;;
485 (defmacro defknown (name arg-types result-type &optional (attributes '(any))
486 &rest keys)
487 "Defknown Name Arg-Types Result-Type [Attributes] {Key Value}*
488 Declare the function Name to be a known function. We construct a type
489 specifier for the function by wrapping (FUNCTION ...) around the Arg-Types
490 and Result-Type. Attributes is a an unevaluated list of the boolean
491 attributes that the function has. These attributes are meaningful here:
492 call
493 May call functions that are passed as arguments. In order to determine
494 what other effects are present, we must find the effects of all arguments
495 that may be functions.
496
497 unsafe
498 May incorporate arguments in the result or somehow pass them upward.
499
500 unwind
501 May fail to return during correct execution. Errors are O.K.
502
503 any
504 The (default) worst case. Includes all the other bad things, plus any
505 other possible bad thing.
506
507 foldable
508 May be constant-folded. The function has no side effects, but may be
509 affected by side effects on the arguments. e.g. SVREF, MAPC.
510
511 flushable
512 May be eliminated if value is unused. The function has no side effects
513 except possibly CONS. If a function is defined to signal errors, then
514 it is not flushable even if it is movable or foldable.
515
516 movable
517 May be moved with impunity. Has no side effects except possibly CONS,
518 and is affected only by its arguments.
519
520 predicate
521 A true predicate likely to be open-coded. This is a hint to IR1
522 conversion that it should ensure calls always appear as an IF test.
523 Not usually specified to Defknown, since this is implementation
524 dependent, and is usually automatically set by the Define-VOP
525 :Conditional option.
526
527 Name may also be a list of names, in which case the same information is given
528 to all the names. The keywords specify the initial values for various
529 optimizers that the function might have."
530 (when (and (intersection attributes '(any call unwind))
531 (intersection attributes '(movable)))
532 (error "Function cannot have both good and bad attributes: ~S" attributes))
533
534 `(%defknown ',(if (and (consp name)
535 (not (eq (car name) 'setf)))
536 name
537 (list name))
538 '(function ,arg-types ,result-type)
539 (ir1-attributes ,@(if (member 'any attributes)
540 (union '(call unsafe unwind) attributes)
541 attributes))
542 ,@keys))
543
544
545 ;;; Defoptimizer -- Interface
546 ;;;
547 ;;; Create a function which parses combination args according to a
548 ;;; Lambda-List, optionally storing it in a function-info slot.
549 ;;;
550 (defmacro defoptimizer (what (lambda-list &optional (n-node (gensym))
551 &rest vars)
552 &body body)
553 "Defoptimizer (Function Kind) (Lambda-List [Node-Var] Var*)
554 Declaration* Form*
555 Define some Kind of optimizer for the named Function. Function must be a
556 known function. Lambda-List is used to parse the arguments to the
557 combination as in Deftransform. If the argument syntax is invalid or there
558 are non-constant keys, then we simply return NIL.
559
560 The function is DEFUN'ed as Function-Kind-OPTIMIZER. Possible kinds are
561 DERIVE-TYPE, OPTIMIZER, LTN-ANNOTATE and IR2-CONVERT. If a symbol is
562 specified instead of a (Function Kind) list, then we just do a DEFUN with the
563 symbol as its name, and don't do anything with the definition. This is
564 useful for creating optimizers to be passed by name to DEFKNOWN.
565
566 If supplied, Node-Var is bound to the combination node being optimized. If
567 additional Vars are supplied, then they are used as the rest of the optimizer
568 function's lambda-list. LTN-ANNOTATE methods are passed an additional POLICY
569 argument, and IR2-CONVERT methods are passed an additional IR2-BLOCK
570 argument."
571
572 (let ((name (if (symbolp what) what
573 (symbolicate (first what) "-" (second what) "-OPTIMIZER"))))
574
575 (let ((n-args (gensym)))
576 `(progn
577 (defun ,name (,n-node ,@vars)
578 (let ((,n-args (basic-combination-args ,n-node)))
579 ,(parse-deftransform lambda-list body n-args
580 `(return-from ,name nil))))
581 ,@(when (consp what)
582 `((setf (,(symbolicate "FUNCTION-INFO-" (second what))
583 (function-info-or-lose ',(first what)))
584 #',name)))))))
585
586
587 ;;;; IR groveling macros:
588
589 ;;; Do-Blocks, Do-Blocks-Backwards -- Interface
590 ;;;
591 (defmacro do-blocks ((block-var component &optional ends result) &body body)
592 "Do-Blocks (Block-Var Component [Ends] [Result-Form]) {Declaration}* {Form}*
593 Iterate over the blocks in a component, binding Block-Var to each block in
594 turn. The value of Ends determines whether to iterate over dummy head and
595 tail blocks:
596 NIL -- Skip Head and Tail (the default)
597 :Head -- Do head but skip tail
598 :Tail -- Do tail but skip head
599 :Both -- Do both head and tail
600
601 If supplied, Result-Form is the value to return."
602 (unless (member ends '(nil :head :tail :both))
603 (error "Losing Ends value: ~S." ends))
604 (let ((n-component (gensym))
605 (n-tail (gensym)))
606 `(let* ((,n-component ,component)
607 (,n-tail ,(if (member ends '(:both :tail))
608 nil
609 `(component-tail ,n-component))))
610 (do ((,block-var ,(if (member ends '(:both :head))
611 `(component-head ,n-component)
612 `(block-next (component-head ,n-component)))
613 (block-next ,block-var)))
614 ((eq ,block-var ,n-tail) ,result)
615 ,@body))))
616 ;;;
617 (defmacro do-blocks-backwards ((block-var component &optional ends result) &body body)
618 "Do-Blocks-Backwards (Block-Var Component [Ends] [Result-Form]) {Declaration}* {Form}*
619 Like Do-Blocks, only iterate over the blocks in reverse order."
620 (unless (member ends '(nil :head :tail :both))
621 (error "Losing Ends value: ~S." ends))
622 (let ((n-component (gensym))
623 (n-head (gensym)))
624 `(let* ((,n-component ,component)
625 (,n-head ,(if (member ends '(:both :head))
626 nil
627 `(component-head ,n-component))))
628 (do ((,block-var ,(if (member ends '(:both :tail))
629 `(component-tail ,n-component)
630 `(block-prev (component-tail ,n-component)))
631 (block-prev ,block-var)))
632 ((eq ,block-var ,n-head) ,result)
633 ,@body))))
634
635
636 ;;; Do-Uses -- Interface
637 ;;;
638 ;;; Could change it not to replicate the code someday perhaps...
639 ;;;
640 (defmacro do-uses ((node-var continuation &optional result) &body body)
641 "Do-Uses (Node-Var Continuation [Result]) {Declaration}* {Form}*
642 Iterate over the uses of Continuation, binding Node to each one succesively."
643 (once-only ((n-cont continuation))
644 `(ecase (continuation-kind ,n-cont)
645 (:unused)
646 (:inside-block
647 (block nil
648 (let ((,node-var (continuation-use ,n-cont)))
649 ,@body
650 ,result)))
651 ((:block-start :deleted-block-start)
652 (dolist (,node-var (block-start-uses (continuation-block ,n-cont))
653 ,result)
654 ,@body)))))
655
656
657 ;;; Do-Nodes, Do-Nodes-Backwards -- Interface
658 ;;;
659 ;;; In the forward case, we terminate on Last-Cont so that we don't have to
660 ;;; worry about our termination condition being changed when new code is added
661 ;;; during the iteration. In the backward case, we do NODE-PREV before
662 ;;; evaluating the body so that we can keep going when the current node is
663 ;;; deleted.
664 ;;;
665 ;;; When Restart-P is supplied to DO-NODES, we start iterating over again at
666 ;;; the beginning of the block when we run into a continuation whose block
667 ;;; differs from the one we are trying to iterate over, either beacuse the
668 ;;; block was split, or because a node was deleted out from under us (hence its
669 ;;; block is NIL.) If the block start is deleted, we just punt. With
670 ;;; Restart-P, we are also more careful about termination, re-indirecting the
671 ;;; BLOCK-LAST each time.
672 ;;;
673 (defmacro do-nodes ((node-var cont-var block &key restart-p) &body body)
674 "Do-Nodes (Node-Var Cont-Var Block {Key Value}*) {Declaration}* {Form}*
675 Iterate over the nodes in Block, binding Node-Var to the each node and
676 Cont-Var to the node's Cont. The only keyword option is Restart-P, which
677 causes iteration to be restarted when a node is deleted out from under us (if
678 not supplied, this is an error.)"
679 (let ((n-block (gensym))
680 (n-last-cont (gensym)))
681 `(let* ((,n-block ,block)
682 ,@(unless restart-p
683 `((,n-last-cont (node-cont (block-last ,n-block))))))
684 (do* ((,node-var (continuation-next (block-start ,n-block))
685 ,(if restart-p
686 `(cond
687 ((eq (continuation-block ,cont-var) ,n-block)
688 (assert (continuation-next ,cont-var))
689 (continuation-next ,cont-var))
690 (t
691 (let ((start (block-start ,n-block)))
692 (unless (eq (continuation-kind start)
693 :block-start)
694 (return nil))
695 (continuation-next start))))
696 `(continuation-next ,cont-var)))
697 (,cont-var (node-cont ,node-var) (node-cont ,node-var)))
698 (())
699 ,@body
700 (when ,(if restart-p
701 `(eq ,node-var (block-last ,n-block))
702 `(eq ,cont-var ,n-last-cont))
703 (return nil))))))
704 ;;;
705 (defmacro do-nodes-backwards ((node-var cont-var block) &body body)
706 "Do-Nodes-Backwards (Node-Var Cont-Var Block) {Declaration}* {Form}*
707 Like Do-Nodes, only iterates in reverse order."
708 (let ((n-block (gensym))
709 (n-start (gensym))
710 (n-last (gensym))
711 (n-next (gensym)))
712 `(let* ((,n-block ,block)
713 (,n-start (block-start ,n-block))
714 (,n-last (block-last ,n-block)))
715 (do* ((,cont-var (node-cont ,n-last) ,n-next)
716 (,node-var ,n-last (continuation-use ,cont-var))
717 (,n-next (node-prev ,node-var) (node-prev ,node-var)))
718 (())
719 ,@body
720 (when (eq ,n-next ,n-start)
721 (return nil))))))
722
723
724 ;;; With-IR1-Environment -- Interface
725 ;;;
726 ;;; The lexical environment is presumably already null...
727 ;;;
728 (defmacro with-ir1-environment (node &rest forms)
729 "With-IR1-Environment Node Form*
730 Bind the IR1 context variables so that IR1 conversion can be done after the
731 main conversion pass has finished."
732 (let ((n-node (gensym)))
733 `(let* ((,n-node ,node)
734 (*current-component* (block-component (node-block ,n-node)))
735 (*lexical-environment* (node-lexenv ,n-node))
736 (*current-path* (node-source-path ,n-node)))
737 ,@forms)))
738
739
740 ;;; WITH-IR1-NAMESPACE -- Interface
741 ;;;
742 ;;; Bind the hashtables used for keeping track of global variables,
743 ;;; functions, &c.
744 ;;;
745 (defmacro with-ir1-namespace (&body forms)
746 `(let ((*free-variables* (make-hash-table :test #'eq))
747 (*free-functions* (make-hash-table :test #'equal))
748 (*constants* (make-hash-table :test #'equal))
749 (*source-paths* (make-hash-table :test #'eq))
750 (*failed-optimizations* (make-hash-table :test #'eq)))
751 ,@forms))
752
753
754 ;;; LEXENV-FIND -- Interface
755 ;;;
756 (defmacro lexenv-find (name slot &key test)
757 "LEXENV-FIND Name Slot {Key Value}*
758 Look up Name in the lexical environment namespace designated by Slot,
759 returning the <value, T>, or <NIL, NIL> if no entry. The :TEST keyword
760 may be used to determine the name equality predicate."
761 (once-only ((n-res `(assoc ,name (,(symbolicate "LEXENV-" slot)
762 *lexical-environment*)
763 ,@(when test `(:test ,test)))))
764 `(if ,n-res
765 (values (cdr ,n-res) t)
766 (values nil nil))))
767
768
769 ;;;; The Defprinter macro:
770
771 (defvar *defprint-pretty* nil
772 "If true, defprinter print functions print each slot on a separate line.")
773
774
775 ;;; Defprinter-Prin1, Defprinter-Princ -- Internal
776 ;;;
777 ;;; These functions are called by the expansion of the Defprinter
778 ;;; macro to do the actual printing.
779 ;;;
780 (proclaim '(ftype (function (symbol t stream &optional t) void)
781 defprinter-prin1 defprinter-princ))
782 (defun defprinter-prin1 (name value stream &optional indent)
783 (declare (ignore indent))
784 (write-string " " stream)
785 (when *print-pretty*
786 (xp:pprint-newline :linear stream))
787 (princ name stream)
788 (write-string "= " stream)
789 (prin1 value stream))
790 ;;;
791 (defun defprinter-princ (name value stream &optional indent)
792 (declare (ignore indent))
793 (write-string " " stream)
794 (when *print-pretty*
795 (xp:pprint-newline :linear stream))
796 (princ name stream)
797 (write-string "= " stream)
798 (princ value stream))
799
800 (defmacro defprinter (name &rest slots)
801 "Defprinter Name Slot-Desc*
802 Define some kind of reasonable defstruct structure-print function. Name
803 is the name of the structure. We define a function %PRINT-name which
804 prints the slots in the structure in the way described by the Slot-Descs.
805 Each Slot-Desc can be a slot name, indicating that the slot should simply
806 be printed. A Slot-Desc may also be a list of a slot name and other stuff.
807 The other stuff is composed of keywords followed by expressions. The
808 expressions are evaluated with the variable which is the slot name bound
809 to the value of the slot. These keywords are defined:
810
811 :PRIN1 Print the value of the expression instead of the slot value.
812 :PRINC Like :PRIN1, only princ the value
813 :TEST Only print something if the test is true.
814
815 If no printing thing is specified then the slot value is printed as PRIN1.
816
817 The structure being printed is bound to Structure and the stream is bound to
818 Stream."
819
820 (flet ((sref (slot) `(,(symbolicate name "-" slot) structure)))
821 (collect ((prints))
822 (dolist (slot slots)
823 (if (atom slot)
824 (prints `(defprinter-prin1 ',slot ,(sref slot) stream))
825 (let ((sname (first slot))
826 (test t))
827 (collect ((stuff))
828 (do ((option (rest slot) (cddr option)))
829 ((null option)
830 (prints
831 `(let ((,sname ,(sref sname)))
832 (when ,test
833 ,@(or (stuff)
834 `((defprinter-prin1 ',sname ,sname
835 stream)))))))
836 (case (first option)
837 (:prin1
838 (stuff `(defprinter-prin1 ',sname ,(second option)
839 stream)))
840 (:princ
841 (stuff `(defprinter-princ ',sname ,(second option)
842 stream)))
843 (:test (setq test (second option)))
844 (t
845 (error "Losing Defprinter option: ~S."
846 (first option)))))))))
847
848 `(defun ,(symbolicate "%PRINT-" name) (structure stream depth)
849 (flet ((do-prints ()
850 ,@(prints)))
851 (cond (*print-pretty*
852 (xp:pprint-logical-block
853 (stream nil :prefix "#<" :suffix ">")
854 (prin1 ',name stream)
855 (write-char #\space stream)
856 (xp:pprint-indent :current 0 stream)
857 (let ((*print-base* 16)
858 (*print-radix* t))
859 (prin1 (system:%primitive make-fixnum structure)
860 stream))
861 (unless (and *print-level*
862 (<= *print-level* (1+ depth)))
863 (do-prints))))
864 (t
865 (format stream "#<~S ~X"
866 ',name
867 (system:%primitive make-fixnum structure))
868 (let ((*print-level*
869 (if *print-level* (- *print-level* depth 1))))
870 (unless (and *print-level* (<= *print-level* 0))
871 (do-prints)))
872 (format stream ">"))))
873 nil))))
874
875
876 ;;;; Boolean attribute utilities:
877 ;;;
878 ;;; We need to maintain various sets of boolean attributes for known
879 ;;; functions and VOPs. To save space and allow for quick set operations, we
880 ;;; represent them as bits in a fixnum.
881 ;;;
882
883 (deftype attributes () 'fixnum)
884
885 (eval-when (compile load eval)
886 ;;; Compute-Attribute-Mask -- Internal
887 ;;;
888 ;;; Given a list of attribute names and an alist that translates them to
889 ;;; masks, return the OR of the masks.
890 ;;;
891 (defun compute-attribute-mask (names alist)
892 (collect ((res 0 logior))
893 (dolist (name names)
894 (let ((mask (cdr (assoc name alist))))
895 (unless mask
896 (error "Unknown attribute name: ~S." name))
897 (res mask)))
898 (res)))
899
900 ); Eval-When (Compile Load Eval)
901
902 ;;; Def-Boolean-Attribute -- Interface
903 ;;;
904 ;;; Parse the specification and generate some accessor macros.
905 ;;;
906 (defmacro def-boolean-attribute (name &rest attribute-names)
907 "Def-Boolean-Attribute Name Attribute-Name*
908 Define a new class of boolean attributes, with the attributes havin the
909 specified Attribute-Names. Name is the name of the class, which is used to
910 generate some macros to manipulate sets of the attributes:
911
912 NAME-attributep attributes attribute-name*
913 Return true if one of the named attributes is present, false otherwise.
914 When set with SETF, updates the place Attributes setting or clearing the
915 specified attributes.
916
917 NAME-attributes attribute-name*
918 Return a set of the named attributes."
919
920 (let ((const-name (symbolicate name "-ATTRIBUTE-TRANSLATIONS"))
921 (test-name (symbolicate name "-ATTRIBUTEP")))
922 (collect ((alist))
923 (do ((mask 1 (ash mask 1))
924 (names attribute-names (cdr names)))
925 ((null names))
926 (alist (cons (car names) mask)))
927
928 `(progn
929 (eval-when (compile load eval)
930 (defconstant ,const-name ',(alist)))
931
932 (defmacro ,test-name (attributes &rest attribute-names)
933 "Automagically generated boolean attribute test function. See
934 Def-Boolean-Attribute."
935 `(logtest ,(compute-attribute-mask attribute-names ,const-name)
936 (the attributes ,attributes)))
937
938 (define-setf-method ,test-name (place &rest attributes
939 &environment env)
940
941 "Automagically generated boolean attribute setter. See
942 Def-Boolean-Attribute."
943 (multiple-value-bind (temps values stores set get)
944 (get-setf-method place env)
945 (let ((newval (gensym))
946 (n-place (gensym))
947 (mask (compute-attribute-mask attributes ,const-name)))
948 (values `(,@temps ,n-place)
949 `(,@values ,get)
950 `(,newval)
951 `(let ((,(first stores)
952 (if ,newval
953 (logior ,n-place ,mask)
954 (logand ,n-place ,(lognot mask)))))
955 ,set
956 ,newval)
957 `(,',test-name ,n-place ,@attributes)))))
958
959 (defmacro ,(symbolicate name "-ATTRIBUTES") (&rest attribute-names)
960 "Automagically generated boolean attribute creation function. See
961 Def-Boolean-Attribute."
962 (compute-attribute-mask attribute-names ,const-name))))))
963
964
965 ;;; Attributes-Union, Attributes-Intersection, Attributes= -- Interface
966 ;;;
967 ;;; And now for some gratuitous pseudo-abstraction...
968 ;;;
969 (defmacro attributes-union (&rest attributes)
970 "Returns the union of all the sets of boolean attributes which are its
971 arguments."
972 `(the attributes
973 (logior ,@(mapcar #'(lambda (x) `(the attributes ,x)) attributes))))
974 ;;;
975 (defmacro attributes-intersection (&rest attributes)
976 "Returns the intersection of all the sets of boolean attributes which are its
977 arguments."
978 `(the attributes
979 (logand ,@(mapcar #'(lambda (x) `(the attributes ,x)) attributes))))
980 ;;;
981 (proclaim '(inline attributes=))
982 (proclaim '(function attributes= (attributes attributes) boolean))
983 (defun attributes= (attr1 attr2)
984 "Returns true if the attributes present in Attr1 are indentical to those in
985 Attr2."
986 (eql attr1 attr2))
987
988
989 ;;;; The Event statistics/trace utility:
990
991 (eval-when (compile load eval)
992
993 (defstruct event-info
994 ;;
995 ;; The name of this event.
996 (name (required-argument) :type symbol)
997 ;;
998 ;; The string rescribing this event.
999 (description (required-argument) :type string)
1000 ;;
1001 ;; The name of the variable we stash this in.
1002 (var (required-argument) :type symbol)
1003 ;;
1004 ;; The number of times this event has happened.
1005 (count 0 :type fixnum)
1006 ;;
1007 ;; The level of significance of this event.
1008 (level (required-argument) :type unsigned-byte)
1009 ;;
1010 ;; If true, a function that gets called with the node that the event happened
1011 ;; to.
1012 (action nil :type (or function null)))
1013
1014 ;;; A hashtable from event names to event-info structures.
1015 ;;;
1016 (defvar *event-info* (make-hash-table :test #'eq))
1017
1018
1019 ;;; Event-Info-Or-Lose -- Internal
1020 ;;;
1021 ;;; Return the event info for Name or die trying.
1022 ;;;
1023 (proclaim '(function event-info-or-lose (t) event-info))
1024 (defun event-info-or-lose (name)
1025 (let ((res (gethash name *event-info*)))
1026 (unless res
1027 (error "~S is not the name of an event." name))
1028 res))
1029
1030 ); Eval-When (Compile Load Eval)
1031
1032
1033 ;;; Event-Count, Event-Action, Event-Level -- Interface
1034 ;;;
1035 (proclaim '(function event-count (symbol) fixnum))
1036 (defun event-count (name)
1037 "Return the number of times that Event has happened."
1038 (event-info-count (event-info-or-lose name)))
1039 ;;;
1040 (proclaim '(function event-action (symbol) (or function null)))
1041 (defun event-action (name)
1042 "Return the function that is called when Event happens. If this is null,
1043 there is no action. The function is passed the node to which the event
1044 happened, or NIL if there is no relevant node. This may be set with SETF."
1045 (event-info-action (event-info-or-lose name)))
1046 ;;;
1047 (proclaim '(function %set-event-action (symbol (or function null)) (or function null)))
1048 (defun %set-event-action (name new-value)
1049 (setf (event-info-action (event-info-or-lose name))
1050 new-value))
1051 ;;;
1052 (defsetf event-action %set-event-action)
1053 ;;;
1054 (proclaim '(function event-level (symbol) unsigned-byte))
1055 (defun event-level (name)
1056 "Return the non-negative integer which represents the level of significance
1057 of the event Name. This is used to determine whether to print a message when
1058 the event happens. This may be set with SETF."
1059 (event-info-level (event-info-or-lose name)))
1060 ;;;
1061 (proclaim '(function %set-event-level (symbol unsigned-byte) unsigned-byte))
1062 (defun %set-event-level (name new-value)
1063 (setf (event-info-level (event-info-or-lose name))
1064 new-value))
1065 ;;;
1066 (defsetf event-level %set-event-level)
1067
1068
1069 ;;; Defevent -- Interface
1070 ;;;
1071 ;;; Make an event-info structure and stash it in a variable so we can get at
1072 ;;; it quickly.
1073 ;;;
1074 (defmacro defevent (name description &optional (level 0))
1075 "Defevent Name Description
1076 Define a new kind of event. Name is a symbol which names the event and
1077 Description is a string which describes the event. Level (default 0) is the
1078 level of significance associated with this event; it is used to determine
1079 whether to print a Note when the event happens."
1080 (let ((var-name (symbolicate "*" name "-EVENT-INFO*")))
1081 `(eval-when (compile load eval)
1082 (defvar ,var-name
1083 (make-event-info :name ',name :description ',description :var ',var-name
1084 :level ,level))
1085 (setf (gethash ',name *event-info*) ,var-name)
1086 ',name)))
1087
1088 (proclaim '(type unsigned-byte *event-note-threshold*))
1089 (defvar *event-note-threshold* 1
1090 "This variable is a non-negative integer specifying the lowest level of
1091 event that will print a Note when it occurs.")
1092
1093 ;;; Event -- Interface
1094 ;;;
1095 ;;; Increment the counter and do any action. Mumble about the event if
1096 ;;; policy indicates.
1097 ;;;
1098 (defmacro event (name &optional node)
1099 "Event Name Node
1100 Note that the event with the specified Name has happened. Node is evaluated
1101 to determine the node to which the event happened."
1102 `(%event ,(event-info-var (event-info-or-lose name)) ,node))
1103 ;;;
1104 (proclaim '(function %event (event-info (or node null))))
1105 (defun %event (info node)
1106 (incf (event-info-count info))
1107 (when (and (>= (event-info-level info) *event-note-threshold*)
1108 (if node
1109 (policy node (= brevity 0))
1110 (policy nil (= brevity 0))))
1111 (let ((*compiler-error-context* node))
1112 (compiler-note (event-info-description info))))
1113
1114 (let ((action (event-info-action info)))
1115 (when action (funcall action node))))
1116
1117
1118 ;;; Event-Statistics, Clear-Statistics -- Interface
1119 ;;;
1120 (proclaim '(function event-statistics (&optional unsigned-byte stream) void))
1121 (defun event-statistics (&optional (min-count 1) (stream *standard-output*))
1122 "Print a listing of events and their counts, sorted by the count. Events
1123 that happened fewer than Min-Count times will not be printed. Stream is the
1124 stream to write to."
1125 (collect ((info))
1126 (maphash #'(lambda (k v)
1127 (declare (ignore k))
1128 (when (>= (event-info-count v) min-count)
1129 (info v)))
1130 *event-info*)
1131 (dolist (event (sort (info) #'> :key #'event-info-count))
1132 (format stream "~6D: ~A~%" (event-info-count event)
1133 (event-info-description event)))
1134 (values)))
1135 ;;;
1136 (proclaim '(function clear-statistics () void))
1137 (defun clear-statistics ()
1138 (maphash #'(lambda (k v)
1139 (declare (ignore k))
1140 (setf (event-info-count v) 0))
1141 *event-info*)
1142 (values))
1143

  ViewVC Help
Powered by ViewVC 1.1.5