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

Contents of /src/compiler/macros.lisp

Parent Directory Parent Directory | Revision Log Revision Log


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

  ViewVC Help
Powered by ViewVC 1.1.5