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