0.8.13.71: CORRECT DOCUMENTATION
[sbcl.git] / doc / manual / compiler.texinfo
1 @node Compiler
2 @comment  node-name,  next,  previous,  up
3 @chapter Compiler
4
5 This chapter will discuss most compiler issues other than efficiency,
6 including compiler error messages, the SBCL compiler's unusual
7 approach to type safety in the presence of type declarations, the
8 effects of various compiler optimization policies, and the way that
9 inlining and open coding may cause optimized code to differ from a
10 naive translation. Efficiency issues are sufficiently varied and
11 separate that they have their own chapter, @ref{Efficiency}.
12
13 @menu
14 * Diagnostic Messages::         
15 * Handling of Types::           
16 * Compiler Policy::             
17 * Compiler Errors::             
18 * Open Coding and Inline Expansion::  
19 @end menu
20
21 @node  Diagnostic Messages
22 @comment  node-name,  next,  previous,  up
23 @section Diagnostic Messages
24 @cindex Messages, Compiler
25 @cindex Compiler messages
26
27 @menu
28 * Controlling Verbosity::       
29 * Diagnostic Severity::         
30 * Understanding Compiler Diagnostics::  
31 @end menu
32
33 @node Controlling Verbosity
34 @comment  node-name,  next,  previous,  up
35 @subsection Controlling Verbosity
36
37 The compiler can be quite verbose in its diagnostic reporting, rather
38 more then some users would prefer -- the amount of noise emitted can
39 be controlled, however.
40
41 To control emission of compiler diagnostics (of any severity other
42 than @code{error}: @pxref{Diagnostic Severity}) use the
43 @code{sb-ext:muffle-conditions} and @code{sb-ext:unmuffle-conditions}
44 declarations, specifying the type of condition that is to be muffled
45 (the muffling is done using an associated @code{muffle-warning} restart).
46
47 Global control:
48 @lisp
49 ;;; Muffle compiler-notes globally
50 (declaim (sb-ext:muffle-conditions sb-ext:compiler-note))
51 @end lisp
52
53 Local control:
54 @lisp
55 ;;; Muffle compiler-notes based on lexical scope
56 (defun foo (x)
57   (declare (optimize speed) (fixnum x)
58            (sb-ext:muffle-conditions sb-ext:compiler-note))
59   (values (* x 5) ; no compiler note from this
60     (locally
61       (declare (sb-ext:unmuffle-conditions sb-ext:compiler-note))
62       ;; this one gives a compiler note
63       (* x -5))))
64 @end lisp
65
66 @deffn {Declaration} sb-ext:muffle-conditions
67 Syntax: type*
68
69 Muffles the diagnostic messages that would be caused by compile-time
70 signals of given types.
71 @end deffn
72
73 @deffn {Declaration} sb-ext:unmuffle-conditions
74 Syntax: type*
75
76 Cancels the effect of a previous @code{sb-ext:muffle-condition}
77 declaration.
78 @end deffn
79
80 @c <!-- FIXME: How much control over error messages is in SBCL?
81 @c      _     How much should be? How much of this documentation should
82 @c      _     we save or adapt? 
83 @c      _ 
84 @c      _ %%\node Error Message Parameterization,  , Read Errors, Interpreting Error Messages
85 @c      _ \subsection{Error Message Parameterization}
86 @c      _ \cpsubindex{error messages}{verbosity}
87 @c      _ \cpsubindex{verbosity}{of error messages}
88 @c      _ 
89 @c      _ There is some control over the verbosity of error messages.  See also
90 @c      _ \varref{undefined-warning-limit}, \code{*efficiency-note-limit*} and
91 @c      _ \varref{efficiency-note-cost-threshold}.
92 @c      _ 
93 @c      _ \begin{defvar}{}{enclosing-source-cutoff}
94 @c      _ 
95 @c      _   This variable specifies the number of enclosing actual source forms
96 @c      _   that are printed in full, rather than in the abbreviated processing
97 @c      _   path format.  Increasing the value from its default of \code{1}
98 @c      _   allows you to see more of the guts of the macroexpanded source,
99 @c      _   which is useful when debugging macros.
100 @c      _ \end{defvar}
101 @c      _ 
102 @c      _ \begin{defvar}{}{error-print-length}
103 @c      _   \defvarx{error-print-level}
104 @c      _ 
105 @c      _   These variables are the print level and print length used in
106 @c      _   printing error messages.  The default values are \code{5} and
107 @c      _   \code{3}.  If null, the global values of \code{*print-level*} and
108 @c      _   \code{*print-length*} are used.
109 @c      _ \end{defvar}
110 @c      _ 
111 @c      _ \begin{defmac}{extensions:}{define-source-context}{%
112 @c      _     \args{\var{name} \var{lambda-list} \mstar{form}}}
113 @c      _ 
114 @c      _   This macro defines how to extract an abbreviated source context from
115 @c      _   the \var{name}d form when it appears in the compiler input.
116 @c      _   \var{lambda-list} is a \code{defmacro} style lambda-list used to
117 @c      _   parse the arguments.  The \var{body} should return a list of
118 @c      _   subforms that can be printed on about one line.  There are
119 @c      _   predefined methods for \code{defstruct}, \code{defmethod}, etc.  If
120 @c      _   no method is defined, then the first two subforms are returned.
121 @c      _   Note that this facility implicitly determines the string name
122 @c      _   associated with anonymous functions.
123 @c      _ \end{defmac}
124 @c      _ 
125 @c      _ -->
126
127
128 @node  Diagnostic Severity
129 @comment  node-name,  next,  previous,  up
130 @subsection Diagnostic Severity
131 @cindex Severity of compiler messages
132 @cindex compiler diagnostic severity
133 @tindex error
134 @tindex warning
135 @tindex style-warning
136 @tindex compiler-note
137 @tindex code-deletion-note
138
139 There are four levels of compiler diagnostic severity: 
140
141 @enumerate 1
142 @item error
143 @item warning
144 @item style warning
145 @item note
146 @end enumerate
147
148 The first three levels correspond to condition classes which are
149 defined in the ANSI standard for Common Lisp and which have special
150 significance to the @code{compile} and @code{compile-file} functions.
151 These levels of compiler error severity occur when the compiler
152 handles conditions of these classes. 
153
154 The fourth level of compiler error severity, @emph{note}, corresponds
155 to the @code{sb-ext:compiler-note}, and is used for problems which are
156 too mild for the standard condition classes, typically hints about how
157 efficiency might be improved. The @code{sb-ext:code-deletion-note}, a
158 subtype of @code{compiler-note}, is signalled when the compiler
159 deletes user-supplied code, usually after proving that the code in
160 question is unreachable.
161
162 Future work for SBCL includes expanding this hierarchy of types to
163 allow more fine-grained control over emission of diagnostic messages.
164
165 @include condition-sb-ext-compiler-note.texinfo
166 @include condition-sb-ext-code-deletion-note.texinfo
167
168
169 @node Understanding Compiler Diagnostics
170 @comment  node-name,  next,  previous,  up
171 @subsection Understanding Compile Diagnostics
172
173 The messages emitted by the compiler contain a lot of detail in a
174 terse format, so they may be confusing at first. The messages will be
175 illustrated using this example program:
176
177 @lisp
178 (defmacro zoq (x)
179   `(roq (ploq (+ ,x 3))))
180
181 (defun foo (y)
182   (declare (symbol y))
183   (zoq y))
184 @end lisp
185
186 The main problem with this program is that it is trying to add
187 @code{3} to a symbol. Note also that the functions @code{roq} and
188 @code{ploq} aren't defined anywhere.
189
190 @menu
191 * The Parts of a Compiler Diagnostic::  
192 * The Original and Actual Source::  
193 * The Processing Path::         
194 @end menu
195
196 @node  The Parts of a Compiler Diagnostic
197 @comment  node-name,  next,  previous,  up
198 @subsubsection The Parts of a Compiler Diagnostic
199
200 When processing this program, the compiler will produce this warning:
201
202 @example
203 ; file: /tmp/foo.lisp
204 ; in: DEFUN FOO
205 ;     (ZOQ Y)
206 ; --> ROQ PLOQ
207 ; ==>
208 ;   (+ Y 3)
209 ;
210 ; caught WARNING:
211 ;   Asserted type NUMBER conflicts with derived type (VALUES SYMBOL &OPTIONAL).
212 @end example
213
214 In this example we see each of the six possible parts of a compiler
215 diagnostic:
216
217 @enumerate
218
219 @item
220 @findex with-compilation-unit
221 @samp{file: /tmp/foo.lisp} This is the name of the file that the
222 compiler read the relevant code from.  The file name is displayed
223 because it may not be immediately obvious when there is an error
224 during compilation of a large system, especially when
225 @code{with-compilation-unit} is used to delay undefined warnings.
226
227 @item
228 @samp{in: DEFUN FOO} This is the definition top level form responsible
229 for the diagnostic. It is obtained by taking the first two elements of
230 the enclosing form whose first element is a symbol beginning with
231 ``@samp{def}''. If there is no such enclosing ``@samp{def}'' form,
232 then the outermost form is used. If there are multiple @samp{def}
233 forms, then they are all printed from the outside in, separated by
234 @samp{=>}'s. In this example, the problem was in the @code{defun} for
235 @code{foo}.
236
237 @item
238 @cindex Original Source
239 @samp{(ZOQ Y)} This is the @dfn{original source} form responsible for
240 the diagnostic. Original source means that the form directly appeared
241 in the original input to the compiler, i.e. in the lambda passed to
242 @code{compile} or in the top level form read from the source file. In
243 this example, the expansion of the @code{zoq} macro was responsible
244 for the message.
245
246 @item
247 @cindex Processing Path
248 @samp{--> ROQ PLOQ} This is the @dfn{processing path} that the
249 compiler used to produce the code that caused the message to be
250 emitted. The processing path is a representation of the evaluated
251 forms enclosing the actual source that the compiler encountered when
252 processing the original source. The path is the first element of each
253 form, or the form itself if the form is not a list. These forms result
254 from the expansion of macros or source-to-source transformation done
255 by the compiler. In this example, the enclosing evaluated forms are
256 the calls to @code{roq} and @code{ploq}. These calls resulted from the
257 expansion of the @code{zoq} macro.
258
259 @item
260 @cindex Actual Source
261 @samp{==> (+ Y 3)} This is the @dfn{actual source} responsible for the
262 diagnostic. If the actual source appears in the explanation, then we
263 print the next enclosing evaluated form, instead of printing the
264 actual source twice. (This is the form that would otherwise have been
265 the last form of the processing path.) In this example, the problem is
266 with the evaluation of the reference to the variable @code{y}.
267
268 @item
269 @samp{caught WARNING: Asserted type NUMBER conflicts with derived type
270 (VALUES SYMBOL &OPTIONAL).}  This is the @dfn{explanation} of the
271 problem. In this example, the problem is that, while the call to
272 @code{+} requires that its arguments are all of type @code{number},
273 the compiler has derived that @code{y} will evaluate to a
274 @code{symbol}.  Note that @samp{(VALUES SYMBOL &OPTIONAL)} expresses
275 that @code{y} evaluates to precisely one value.
276
277 @end enumerate
278
279 Note that each part of the message is distinctively marked:
280
281 @itemize
282
283 @item
284  @samp{file:} and @samp{in:} mark the file and definition,
285 respectively.
286
287 @item
288 The original source is an indented form with no prefix.
289
290 @item
291 Each line of the processing path is prefixed with @samp{-->}
292
293 @item
294 The actual source form is indented like the original source, but is
295 marked by a preceding @samp{==>} line.
296 @comment no it isn't.
297
298 @item
299 The explanation is prefixed with the diagnostic severity, which can be
300 @samp{caught ERROR:}, @samp{caught WARNING:}, @samp{caught
301 STYLE-WARNING:}, or @samp{note:}.
302
303 @end itemize
304
305 Each part of the message is more specific than the preceding one. If
306 consecutive messages are for nearby locations, then the front part of
307 the messages would be the same. In this case, the compiler omits as
308 much of the second message as in common with the first. For example:
309
310 @example
311 ; file: /tmp/foo.lisp
312 ; in: DEFUN FOO
313 ;     (ZOQ Y)
314 ; --> ROQ
315 ; ==>
316 ;   (PLOQ (+ Y 3))
317 ;
318 ; caught STYLE-WARNING:
319 ;   undefined function: PLOQ
320  
321 ; ==>
322 ;   (ROQ (PLOQ (+ Y 3)))
323 ;
324 ; caught STYLE-WARNING:
325 ;   undefined function: ROQ
326 @end example
327 @comment fixing that weird blank line might be good
328
329 In this example, the file, definition and original source are
330 identical for the two messages, so the compiler omits them in the
331 second message. If consecutive messages are entirely identical, then
332 the compiler prints only the first message, followed by: @samp{[Last
333 message occurs @var{repeats} times]} where @var{repeats} is the number
334 of times the message was given.
335
336 If the source was not from a file, then no file line is printed. If
337 the actual source is the same as the original source, then the
338 processing path and actual source will be omitted. If no forms
339 intervene between the original source and the actual source, then the
340 processing path will also be omitted.
341
342
343 @node  The Original and Actual Source
344 @comment  node-name,  next,  previous,  up
345 @subsubsection The Original and Actual Source
346 @cindex Original Source
347 @cindex Actual Source
348
349 The @emph{original source} displayed will almost always be a list. If
350 the actual source for an message is a symbol, the original source will
351 be the immediately enclosing evaluated list form. So even if the
352 offending symbol does appear in the original source, the compiler will
353 print the enclosing list and then print the symbol as the actual
354 source (as though the symbol were introduced by a macro.)
355
356 When the @emph{actual source} is displayed (and is not a symbol), it
357 will always be code that resulted from the expansion of a macro or a
358 source-to-source compiler optimization. This is code that did not
359 appear in the original source program; it was introduced by the
360 compiler.
361
362 Keep in mind that when the compiler displays a source form in an
363 diagnostic message, it always displays the most specific (innermost)
364 responsible form. For example, compiling this function
365
366 @lisp
367 (defun bar (x)
368   (let (a)
369     (declare (fixnum a))
370     (setq a (foo x))
371     a))
372 @end lisp
373
374 gives this error message
375
376 @example
377 ; file: /tmp/foo.lisp
378 ; in: DEFUN BAR
379 ;     (LET (A)
380 ;     (DECLARE (FIXNUM A))
381 ;     (SETQ A (FOO X))
382 ;     A)
383 ;
384 ; caught WARNING:
385 ;   Asserted type FIXNUM conflicts with derived type (VALUES NULL &OPTIONAL).
386 @end example
387
388 This message is not saying ``there is a problem somewhere in this
389 @code{let}'' -- it is saying that there is a problem with the
390 @code{let} itself. In this example, the problem is that @code{a}'s
391 @code{nil} initial value is not a @code{fixnum}.
392
393 @node The Processing Path
394 @comment  node-name,  next,  previous,  up
395 @subsubsection The Processing Path
396 @cindex Processing path
397 @cindex Macroexpansion
398 @cindex Source-to-source transformation
399
400 The processing path is mainly useful for debugging macros, so if you
401 don't write macros, you can probably ignore it. Consider this example:
402
403 @lisp
404 (defun foo (n)
405   (dotimes (i n *undefined*)))
406 @end lisp
407
408 Compiling results in this error message:
409
410 @example
411 ; in: DEFUN FOO
412 ;     (DOTIMES (I N *UNDEFINED*))
413 ; --> DO BLOCK LET TAGBODY RETURN-FROM
414 ; ==>
415 ;   (PROGN *UNDEFINED*)
416 ;
417 ; caught WARNING:
418 ;   undefined variable: *UNDEFINED*
419 @end example
420
421 Note that @code{do} appears in the processing path. This is because
422 @code{dotimes} expands into:
423
424 @lisp
425 (do ((i 0 (1+ i)) (#:g1 n))
426     ((>= i #:g1) *undefined*)
427   (declare (type unsigned-byte i)))
428 @end lisp
429
430 The rest of the processing path results from the expansion of
431 @code{do}:
432
433 @lisp
434 (block nil
435   (let ((i 0) (#:g1 n))
436     (declare (type unsigned-byte i))
437     (tagbody (go #:g3)
438       #:g2    (psetq i (1+ i))
439       #:g3    (unless (>= i #:g1) (go #:g2))
440       (return-from nil (progn *undefined*)))))
441 @end lisp
442
443 In this example, the compiler descended into the @code{block},
444 @code{let}, @code{tagbody} and @code{return-from} to reach the
445 @code{progn} printed as the actual source. This is a place where the
446 ``actual source appears in explanation'' rule was applied. The
447 innermost actual source form was the symbol @code{*undefined*} itself,
448 but that also appeared in the explanation, so the compiler backed out
449 one level.
450
451
452
453
454
455 @node  Handling of Types
456 @comment  node-name,  next,  previous,  up
457 @section Handling of Types
458
459 The most unusual features of the SBCL compiler (which is very
460 similar to the original CMUCL compiler, also known as @dfn{Python})
461 is its unusually sophisticated understanding of the Common Lisp type
462 system and its unusually conservative approach to the implementation
463 of type declarations.
464
465 These two features reward the use of type declarations throughout
466 development, even when high performance is not a concern. Also, as
467 discussed in the chapter on performance (@pxref{Efficiency}), the use
468 of appropriate type declarations can be very important for performance
469 as well.
470
471 @findex satisfies
472 The SBCL compiler also has a greater knowledge of the Common Lisp
473 type system than other compilers. Support is incomplete only for types
474 involving the @code{satisfies} type specifier.
475
476 @c <!-- FIXME: See also sections \ref{advanced-type-stuff}
477 @c      and \ref{type-inference}, once we snarf them from the
478 @c      CMU CL manual. -->
479 @c
480 @c Also see my paper on improving Baker, when I get round to it.
481 @c
482 @c Whose paper?
483
484 @menu
485 * Declarations as Assertions::  
486 * Precise Type Checking::       
487 * Getting Existing Programs to Run::  
488 * Implementation Limitations::  
489 @end menu
490
491 @node Declarations as Assertions
492 @comment  node-name,  next,  previous,  up
493 @subsection Declarations as Assertions
494 @findex safety
495
496 The SBCL compiler treats type declarations differently from most
497 other Lisp compilers. Under default compilation policy the compiler
498 doesn't blindly believe type declarations, but considers them
499 assertions about the program that should be checked: all type
500 declarations that have not been proven to always hold are asserted at
501 runtime.
502
503 @quotation
504 @emph{Remaining bugs in the compiler's handling of types unfortunately
505 provide some exceptions to this rule, see @ref{Implementation
506 Limitations}).}
507 @end quotation
508
509 There are three type checking policies available in SBCL,
510 selectable via @code{optimize} declarations.
511
512 @table @strong
513
514 @c FIXME: This should be properly integrated with general policy
515 @c stuff, once that gets cleaned up.
516
517 @item Full Type Checks
518 All declarations are considered assertions to be checked at runtime,
519 and all type checks are precise.
520
521 Used when @code{(>= safety (max speed space compilation-speed)}. The
522 default compilation policy provides full type checks.
523
524 @item Weak Type Checks
525 Any or all type declarations may be believed without runtime
526 assertions, and assertions that are done may be imprecise.
527
528 Used when @code{(> 0 safety (max speed space compilation-speed)}.
529
530 @item No Type Checks
531 All declarations are believed without assertions. Also disables
532 argument count and array bounds checking.
533
534 Used when @code{(= safety 0)}.
535
536 @end table
537
538 @node  Precise Type Checking
539 @comment  node-name,  next,  previous,  up
540 @subsection Precise Type Checking
541 @cindex Precise type checking
542 @cindex Type checking, precise
543
544 Precise checking means that the check is done as though @code{typep}
545 had been called with the exact type specifier that appeared in the
546 declaration.
547
548 If a variable is declared to be @code{(integer 3 17)} then its value
549 must always be an integer between @code{3} and @code{17}. If multiple
550 type declarations apply to a single variable, then all the
551 declarations must be correct; it is as though all the types were
552 intersected producing a single @code{and} type specifier.
553
554 To gain maximum benefit from the compiler's type checking, you should
555 always declare the types of function arguments and structure slots as
556 precisely as possible. This often involves the use of @code{or},
557 @code{member}, and other list-style type specifiers. 
558
559
560 @node  Getting Existing Programs to Run
561 @comment  node-name,  next,  previous,  up
562 @subsection Getting Existing Programs to Run
563 @cindex Existing programs, to run
564 @cindex Types, portability
565 @cindex Compatibility with other Lisps
566 @c     (should also have an entry in the non-ANSI-isms section)-->
567
568 Since SBCL's compiler does much more comprehensive type checking than
569 most Lisp compilers, SBCL may detect type errors in programs that have
570 been debugged using other compilers. These errors are mostly incorrect
571 declarations, although compile-time type errors can find actual bugs
572 if parts of the program have never been tested.
573
574 Some incorrect declarations can only be detected by run-time type
575 checking. It is very important to initially compile a program with
576 full type checks (high @code{safety} optimization) and then test this
577 safe version. After the checking version has been tested, then you can
578 consider weakening or eliminating type checks.  @emph{This applies
579 even to previously debugged programs,} because the SBCL compiler does
580 much more type inference than other Common Lisp compilers, so an
581 incorrect declaration can do more damage.
582
583 The most common problem is with variables whose constant initial value
584 doesn't match the type declaration. Incorrect constant initial values
585 will always be flagged by a compile-time type error, and they are
586 simple to fix once located. Consider this code fragment:
587
588 @lisp
589 (prog (foo)
590   (declare (fixnum foo))
591   (setq foo ...)
592   ...)
593 @end lisp
594
595 Here @code{foo} is given an initial value of @code{nil}, but is
596 declared to be a @code{fixnum}.  Even if it is never read, the initial
597 value of a variable must match the declared type.  There are two ways
598 to fix this problem. Change the declaration
599
600 @lisp
601 (prog (foo)
602   (declare (type (or fixnum null) foo))
603   (setq foo ...)
604   ...)
605 @end lisp
606
607 or change the initial value
608
609 @lisp
610 (prog ((foo 0))
611   (declare (fixnum foo))
612   (setq foo ...)
613   ...)
614 @end lisp
615
616 It is generally preferable to change to a legal initial value rather
617 than to weaken the declaration, but sometimes it is simpler to weaken
618 the declaration than to try to make an initial value of the
619 appropriate type.
620
621 Another declaration problem occasionally encountered is incorrect
622 declarations on @code{defmacro} arguments. This can happen when a
623 function is converted into a macro. Consider this macro:
624
625 @lisp
626 (defmacro my-1+ (x)
627   (declare (fixnum x))
628   `(the fixnum (1+ ,x)))
629 @end lisp
630
631 Although legal and well-defined Common Lisp code, this meaning of this
632 definition is almost certainly not what the writer intended. For
633 example, this call is illegal:
634
635 @lisp
636 (my-1+ (+ 4 5))
637 @end lisp
638
639 This call is illegal because the argument to the macro is @code{(+ 4
640 5)}, which is a @code{list}, not a @code{fixnum}.  Because of macro
641 semantics, it is hardly ever useful to declare the types of macro
642 arguments.  If you really want to assert something about the type of
643 the result of evaluating a macro argument, then put a @code{the} in
644 the expansion:
645
646 @lisp
647 (defmacro my-1+ (x)
648   `(the fixnum (1+ (the fixnum ,x))))
649 @end lisp
650
651 In this case, it would be stylistically preferable to change this
652 macro back to a function and declare it inline. 
653 @c <!--FIXME: <xref>inline-expansion, once we crib the 
654 @c      relevant text from the CMU CL manual.-->
655
656 Some more subtle problems are caused by incorrect declarations that
657 can't be detected at compile time.  Consider this code:
658   
659 @lisp
660 (do ((pos 0 (position #\a string :start (1+ pos))))
661   ((null pos))
662   (declare (fixnum pos))
663   ...)
664 @end lisp
665
666 Although @code{pos} is almost always a @code{fixnum}, it is @code{nil}
667 at the end of the loop. If this example is compiled with full type
668 checks (the default), then running it will signal a type error at the
669 end of the loop. If compiled without type checks, the program will go
670 into an infinite loop (or perhaps @code{position} will complain
671 because @code{(1+ nil)} isn't a sensible start.) Why? Because if you
672 compile without type checks, the compiler just quietly believes the
673 type declaration. Since the compiler believes that @code{pos} is
674 always a @code{fixnum}, it believes that @code{pos} is never
675 @code{nil}, so @code{(null pos)} is never true, and the loop exit test
676 is optimized away. Such errors are sometimes flagged by unreachable
677 code notes, but it is still important to initially compile and test
678 any system with full type checks, even if the system works fine when
679 compiled using other compilers.
680
681 In this case, the fix is to weaken the type declaration to @code{(or
682 fixnum null)} @footnote{Actually, this declaration is unnecessary in
683 SBCL, since it already knows that @code{position} returns a
684 non-negative @code{fixnum} or @code{nil}.}.
685
686 Note that there is usually little performance penalty for weakening a
687 declaration in this way. Any numeric operations in the body can still
688 assume that the variable is a @code{fixnum}, since @code{nil} is not a
689 legal numeric argument. Another possible fix would be to say:
690
691 @lisp
692 (do ((pos 0 (position #\a string :start (1+ pos))))
693     ((null pos))
694   (let ((pos pos))
695     (declare (fixnum pos))
696     ...))
697 @end lisp
698
699 This would be preferable in some circumstances, since it would allow a
700 non-standard representation to be used for the local @code{pos}
701 variable in the loop body.
702 @c <!-- FIXME: <xref>ND-variables, once we crib the text from the 
703 @c      CMU CL manual. -->
704
705 @node  Implementation Limitations
706 @comment  node-name,  next,  previous,  up
707 @subsection Implementation Limitations
708
709 Ideally, the compiler would consider @emph{all} type declarations to
710 be assertions, so that adding type declarations to a program, no
711 matter how incorrect they might be, would @emph{never} cause undefined
712 behavior. However, the compiler is known to fall short of this goal in
713 two areas:
714
715 @itemize
716
717 @item
718 @emph{Proclaimed} constraints on argument and result types of a
719 function are supposed to be checked by the function. If the function
720 type is proclaimed before function definition, type checks are
721 inserted by the compiler, but the standard allows the reversed order,
722 in which case the compiler will trust the declaration.
723
724 @item
725 The compiler cannot check types of an unknown number of values; if the
726 number of generated values is unknown, but the number of consumed is
727 known, only consumed values are checked.
728
729 For example,
730
731 @lisp
732 (defun foo (x) 
733   (the integer (bar x)))
734 @end lisp
735
736 causes the following compiler diagnostic to be emitted:
737
738 @example
739 ; note: type assertion too complex to check:
740 ;  (VALUES INTEGER &REST T).
741 @end example
742
743 A partial workaround is instead write:
744
745 @lisp
746 (defun foo (x)
747   (the (values integer &optional) (bar x)))
748 @end lisp
749
750 @end itemize
751
752 These are important issues, but are not necessarily easy to fix, so
753 they may, alas, remain in the system for a while.
754
755 @node Compiler Policy
756 @comment  node-name,  next,  previous,  up
757 @section Compiler Policy
758
759 Compiler policy is controlled by the @code{optimize} declaration,
760 supporting all ANSI optimization qualities (@code{debug},
761 @code{safety}, @code{space}, and @code{speed}).@footnote{A deprecated
762 extension @code{sb-ext:inhibit-warnings} is still supported, but
763 liable to go away at any time.}
764
765 For effects of various optimization qualities on type-safety and
766 debuggability see @ref{Declarations as Assertions} and @ref{Debugger
767 Policy Control}.
768
769 Ordinarily, when the @code{speed} quality is high, the compiler emits
770 notes to notify the programmer about its inability to apply various
771 optimizations. 
772
773 Compiler diagnostics (of any severity other than @code{error}:
774 @pxref{Diagnostic Severity}) can be silenced by using the
775 @code{sb-ext:muffle-conditions} declaration, specifying the type of
776 condition that is to be muffled (using an associated
777 @code{muffle-warning} restart). 
778
779 To muffle all compiler notes:
780
781 @lisp
782 (declaim (sb-ext:muffle-conditions sb-ext:compiler-note))
783 @end lisp
784
785 Compiler diagnostics can also be muffled in the lexical scope of a
786 declaration, and also lexically unmuffled by the use of the
787 sb-ext:unmuffle-conditions, for instance:
788
789 @lisp
790 (defun foo (x)
791   (declare (optimize speed) (fixnum x))
792   (declare (sb-ext:muffle-conditions sb-ext:compiler-note))
793   (values (* x 5) ; no compiler note from this
794     (locally
795       (declare (sb-ext:unmuffle-conditions sb-ext:compiler-note))
796       ;; this one gives a compiler note
797       (* x -5))))
798 @end lisp
799
800 The value of @code{space} mostly influences the compiler's decision
801 whether to inline operations, which tend to increase the size of
802 programs. Use the value @code{0} with caution, since it can cause the
803 compiler to inline operations so indiscriminately that the net effect
804 is to slow the program by causing cache misses or even swapping.
805
806 @c <!-- FIXME: old CMU CL compiler policy, should perhaps be adapted
807 @c      _    for SBCL. (Unfortunately, the CMU CL docs are out of sync with the
808 @c      _    CMU CL code, so adapting this requires not only reformatting
809 @c      _    the documentation, but rooting out code rot.)
810 @c      _
811 @c      _<sect2 id="compiler-policy"><title>Compiler Policy</1000
812 @c      _  INDEX {policy}{compiler}
813 @c      _  INDEX compiler policy
814 @c      _
815 @c      _<para>The policy is what tells the compiler <emphasis>how</emphasis> to
816 @c      _compile a program. This is logically (and often textually) distinct
817 @c      _from the program itself. Broad control of policy is provided by the
818 @c      _<parameter>optimize</parameter> declaration; other declarations and variables
819 @c      _control more specific aspects of compilation.
820 @c      _
821 @c      _\begin{comment}
822 @c      _* The Optimize Declaration::
823 @c      _* The Optimize-Interface Declaration::
824 @c      _\end{comment}
825 @c      _
826 @c      _%%\node The Optimize Declaration, The Optimize-Interface Declaration, Compiler Policy, Compiler Policy
827 @c      _\subsection{The Optimize Declaration}
828 @c      _\label{optimize-declaration}
829 @c      _\cindex{optimize declaration}
830 @c      _\cpsubindex{declarations}{\code{optimize}}
831 @c      _
832 @c      _The \code{optimize} declaration recognizes six different
833 @c      _\var{qualities}.  The qualities are conceptually independent aspects
834 @c      _of program performance.  In reality, increasing one quality tends to
835 @c      _have adverse effects on other qualities.  The compiler compares the
836 @c      _relative values of qualities when it needs to make a trade-off; i.e.,
837 @c      _if \code{speed} is greater than \code{safety}, then improve speed at
838 @c      _the cost of safety.
839 @c      _
840 @c      _The default for all qualities (except \code{debug}) is \code{1}.
841 @c      _Whenever qualities are equal, ties are broken according to a broad
842 @c      _idea of what a good default environment is supposed to be.  Generally
843 @c      _this downplays \code{speed}, \code{compile-speed} and \code{space} in
844 @c      _favor of \code{safety} and \code{debug}.  Novice and casual users
845 @c      _should stick to the default policy.  Advanced users often want to
846 @c      _improve speed and memory usage at the cost of safety and
847 @c      _debuggability.
848 @c      _
849 @c      _If the value for a quality is \code{0} or \code{3}, then it may have a
850 @c      _special interpretation.  A value of \code{0} means ``totally
851 @c      _unimportant'', and a \code{3} means ``ultimately important.''  These
852 @c      _extreme optimization values enable ``heroic'' compilation strategies
853 @c      _that are not always desirable and sometimes self-defeating.
854 @c      _Specifying more than one quality as \code{3} is not desirable, since
855 @c      _it doesn't tell the compiler which quality is most important.
856 @c      _
857 @c      _
858 @c      _These are the optimization qualities:
859 @c      _\begin{Lentry}
860 @c      _
861 @c      _\item[\code{speed}] \cindex{speed optimization quality}How fast the
862 @c      _  program should is run.  \code{speed 3} enables some optimizations
863 @c      _  that hurt debuggability.
864 @c      _
865 @c      _\item[\code{compilation-speed}] \cindex{compilation-speed optimization
866 @c      _    quality}How fast the compiler should run.  Note that increasing
867 @c      _  this above \code{safety} weakens type checking.
868 @c      _
869 @c      _\item[\code{space}] \cindex{space optimization quality}How much space
870 @c      _  the compiled code should take up.  Inline expansion is mostly
871 @c      _  inhibited when \code{space} is greater than \code{speed}.  A value
872 @c      _  of \code{0} enables indiscriminate inline expansion.  Wide use of a
873 @c      _  \code{0} value is not recommended, as it may waste so much space
874 @c      _  that run time is slowed.  \xlref{inline-expansion} for a discussion
875 @c      _  of inline expansion.
876 @c      _
877 @c      _\item[\code{debug}] \cindex{debug optimization quality}How debuggable
878 @c      _  the program should be.  The quality is treated differently from the
879 @c      _  other qualities: each value indicates a particular level of debugger
880 @c      _  information; it is not compared with the other qualities.
881 @c      _  \xlref{debugger-policy} for more details.
882 @c      _
883 @c      _\item[\code{safety}] \cindex{safety optimization quality}How much
884 @c      _  error checking should be done.  If \code{speed}, \code{space} or
885 @c      _  \code{compilation-speed} is more important than \code{safety}, then
886 @c      _  type checking is weakened (\pxlref{weakened-type-checks}).  If
887 @c      _  \code{safety} if \code{0}, then no run time error checking is done.
888 @c      _  In addition to suppressing type checks, \code{0} also suppresses
889 @c      _  argument count checking, unbound-symbol checking and array bounds
890 @c      _  checks.
891 @c      _
892 @c      _\item[\code{extensions:inhibit-warnings}] \cindex{inhibit-warnings
893 @c      _    optimization quality}This is a CMU extension that determines how
894 @c      _  little (or how much) diagnostic output should be printed during
895 @c      _  compilation.  This quality is compared to other qualities to
896 @c      _  determine whether to print style notes and warnings concerning those
897 @c      _  qualities.  If \code{speed} is greater than \code{inhibit-warnings},
898 @c      _  then notes about how to improve speed will be printed, etc.  The
899 @c      _  default value is \code{1}, so raising the value for any standard
900 @c      _  quality above its default enables notes for that quality.  If
901 @c      _  \code{inhibit-warnings} is \code{3}, then all notes and most
902 @c      _  non-serious warnings are inhibited.  This is useful with
903 @c      _  \code{declare} to suppress warnings about unavoidable problems.
904 @c      _\end{Lentry}
905 @c      _
906 @c      _%%\node The Optimize-Interface Declaration,  , The Optimize Declaration, Compiler Policy
907 @c      _\subsection{The Optimize-Interface Declaration}
908 @c      _\label{optimize-interface-declaration}
909 @c      _\cindex{optimize-interface declaration}
910 @c      _\cpsubindex{declarations}{\code{optimize-interface}}
911 @c      _
912 @c      _The \code{extensions:optimize-interface} declaration is identical in
913 @c      _syntax to the \code{optimize} declaration, but it specifies the policy
914 @c      _used during compilation of code the compiler automatically generates
915 @c      _to check the number and type of arguments supplied to a function.  It
916 @c      _is useful to specify this policy separately, since even thoroughly
917 @c      _debugged functions are vulnerable to being passed the wrong arguments.
918 @c      _The \code{optimize-interface} declaration can specify that arguments
919 @c      _should be checked even when the general \code{optimize} policy is
920 @c      _unsafe.
921 @c      _
922 @c      _Note that this argument checking is the checking of user-supplied
923 @c      _arguments to any functions defined within the scope of the
924 @c      _declaration, \code{not} the checking of arguments to \llisp{}
925 @c      _primitives that appear in those definitions.
926 @c      _
927 @c      _The idea behind this declaration is that it allows the definition of
928 @c      _functions that appear fully safe to other callers, but that do no
929 @c      _internal error checking.  Of course, it is possible that arguments may
930 @c      _be invalid in ways other than having incorrect type.  Functions
931 @c      _compiled unsafely must still protect themselves against things like
932 @c      _user-supplied array indices that are out of bounds and improper lists.
933 @c      _See also the \kwd{context-declarations} option to
934 @c      _\macref{with-compilation-unit}.
935 @c      _
936 @c      _(end of section on compiler policy)
937 @c      _-->
938
939 @node Compiler Errors
940 @comment  node-name,  next,  previous,  up
941 @section Compiler Errors
942
943 @menu
944 * Type Errors at Compile Time::  
945 * Errors During Macroexpansion::  
946 * Read Errors::                 
947 @end menu
948
949 @node  Type Errors at Compile Time
950 @comment  node-name,  next,  previous,  up
951 @subsection Type Errors at Compile Time
952 @cindex Compile time type errors
953 @cindex Type checking, at compile time
954
955 If the compiler can prove at compile time that some portion of the
956 program cannot be executed without a type error, then it will give a
957 warning at compile time.
958
959 It is possible that the offending code would never actually be
960 executed at run-time due to some higher level consistency constraint
961 unknown to the compiler, so a type warning doesn't always indicate an
962 incorrect program.
963
964 For example, consider this code fragment:
965
966 @lisp
967 (defun raz (foo)
968   (let ((x (case foo
969               (:this 13)
970               (:that 9)
971               (:the-other 42))))
972     (declare (fixnum x))
973     (foo x)))
974 @end lisp
975
976 Compilation produces this warning:
977
978 @example
979 ; in: DEFUN RAZ
980 ;     (CASE FOO (:THIS 13) (:THAT 9) (:THE-OTHER 42))
981 ; --> LET COND IF COND IF COND IF
982 ; ==>
983 ;   (COND)
984 ;
985 ; caught WARNING:
986 ;   This is not a FIXNUM:
987 ;   NIL
988 @end example
989
990 In this case, the warning means that if @code{foo} isn't any of
991 @code{:this}, @code{:that} or @code{:the-other}, then @code{x} will be
992 initialized to @code{nil}, which the @code{fixnum} declaration makes
993 illegal. The warning will go away if @code{ecase} is used instead of
994 @code{case}, or if @code{:the-other} is changed to @code{t}.
995
996 This sort of spurious type warning happens moderately often in the
997 expansion of complex macros and in inline functions. In such cases,
998 there may be dead code that is impossible to correctly execute. The
999 compiler can't always prove this code is dead (could never be
1000 executed), so it compiles the erroneous code (which will always signal
1001 an error if it is executed) and gives a warning.
1002
1003 @node  Errors During Macroexpansion
1004 @comment  node-name,  next,  previous,  up
1005 @subsection Errors During Macroexpansion
1006 @cindex Macroexpansion, errors during
1007
1008 The compiler handles errors that happen during macroexpansion, turning
1009 them into compiler errors. If you want to debug the error (to debug a
1010 macro), you can set @code{*break-on-signals*} to @code{error}. For
1011 example, this definition:
1012
1013 @lisp
1014 (defun foo (e l)
1015   (do ((current l (cdr current))
1016        ((atom current) nil))
1017       (when (eq (car current) e) (return current))))
1018 @end lisp
1019
1020 gives this error:
1021
1022 @example
1023 ; in: DEFUN FOO
1024 ;     (DO ((CURRENT L (CDR CURRENT))
1025 ;        ((ATOM CURRENT) NIL))
1026 ;       (WHEN (EQ (CAR CURRENT) E) (RETURN CURRENT)))
1027 ;
1028 ; caught ERROR:
1029 ;   (in macroexpansion of (DO # #))
1030 ;   (hint: For more precise location, try *BREAK-ON-SIGNALS*.)
1031 ;   DO step variable is not a symbol: (ATOM CURRENT)
1032 @end example
1033
1034
1035 @node  Read Errors
1036 @comment  node-name,  next,  previous,  up
1037 @subsection Read Errors
1038 @cindex Read errors, compiler
1039
1040 SBCL's compiler does not attempt to recover from read errors when
1041 reading a source file, but instead just reports the offending
1042 character position and gives up on the entire source file.
1043
1044 @node  Open Coding and Inline Expansion
1045 @comment  node-name,  next,  previous,  up
1046 @section Open Coding and Inline Expansion
1047 @cindex Open-coding
1048 @cindex inline expansion
1049 @cindex static functions
1050
1051 Since Common Lisp forbids the redefinition of standard functions, the
1052 compiler can have special knowledge of these standard functions
1053 embedded in it. This special knowledge is used in various ways (open
1054 coding, inline expansion, source transformation), but the implications
1055 to the user are basically the same:
1056
1057 @itemize
1058
1059 @item
1060 Attempts to redefine standard functions may be frustrated, since the
1061 function may never be called. Although it is technically illegal to
1062 redefine standard functions, users sometimes want to implicitly
1063 redefine these functions when they are debugging using the
1064 @code{trace} macro.  Special-casing of standard functions can be
1065 inhibited using the @code{notinline} declaration, but even then some
1066 phases of analysis such as type inferencing are applied by the
1067 compiler.
1068
1069 @item
1070 The compiler can have multiple alternate implementations of standard
1071 functions that implement different trade-offs of speed, space and
1072 safety.  This selection is based on the compiler policy, @ref{Compiler
1073 Policy}.
1074
1075 @end itemize
1076
1077 When a function call is @emph{open coded}, inline code whose effect is
1078 equivalent to the function call is substituted for that function
1079 call. When a function call is @emph{closed coded}, it is usually left
1080 as is, although it might be turned into a call to a different function
1081 with different arguments. As an example, if @code{nthcdr} were to be
1082 open coded, then
1083
1084 @lisp
1085 (nthcdr 4 foobar)
1086 @end lisp
1087
1088 might turn into
1089
1090 @lisp
1091 (cdr (cdr (cdr (cdr foobar))))
1092 @end lisp
1093
1094 or even
1095
1096 @lisp
1097 (do ((i 0 (1+ i))
1098   (list foobar (cdr foobar)))
1099   ((= i 4) list))
1100 @end lisp
1101
1102 If @code{nth} is closed coded, then
1103
1104 @lisp
1105 (nth x l)
1106 @end lisp
1107
1108 might stay the same, or turn into something like
1109
1110 @lisp
1111 (car (nthcdr x l))
1112 @end lisp
1113
1114 In general, open coding sacrifices space for speed, but some functions
1115 (such as @code{car}) are so simple that they are always
1116 open-coded. Even when not open-coded, a call to a standard function
1117 may be transformed into a different function call (as in the last
1118 example) or compiled as @emph{static call}. Static function call uses
1119 a more efficient calling convention that forbids redefinition.