]> code.delx.au - gnu-emacs/blob - lisp/emacs-lisp/byte-opt.el
62d1b4577bdbd7a6207d87a0dca59dc1f72053e3
[gnu-emacs] / lisp / emacs-lisp / byte-opt.el
1 ;;; byte-opt.el --- the optimization passes of the emacs-lisp byte compiler
2
3 ;; Copyright (C) 1991, 1994, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
4 ;; 2007, 2008, 2009, 2010, 2011 Free Software Foundation, Inc.
5
6 ;; Author: Jamie Zawinski <jwz@lucid.com>
7 ;; Hallvard Furuseth <hbf@ulrik.uio.no>
8 ;; Maintainer: FSF
9 ;; Keywords: internal
10 ;; Package: emacs
11
12 ;; This file is part of GNU Emacs.
13
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
18
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
23
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26
27 ;;; Commentary:
28
29 ;; ========================================================================
30 ;; "No matter how hard you try, you can't make a racehorse out of a pig.
31 ;; You can, however, make a faster pig."
32 ;;
33 ;; Or, to put it another way, the Emacs byte compiler is a VW Bug. This code
34 ;; makes it be a VW Bug with fuel injection and a turbocharger... You're
35 ;; still not going to make it go faster than 70 mph, but it might be easier
36 ;; to get it there.
37 ;;
38
39 ;; TO DO:
40 ;;
41 ;; (apply (lambda (x &rest y) ...) 1 (foo))
42 ;;
43 ;; maintain a list of functions known not to access any global variables
44 ;; (actually, give them a 'dynamically-safe property) and then
45 ;; (let ( v1 v2 ... vM vN ) <...dynamically-safe...> ) ==>
46 ;; (let ( v1 v2 ... vM ) vN <...dynamically-safe...> )
47 ;; by recursing on this, we might be able to eliminate the entire let.
48 ;; However certain variables should never have their bindings optimized
49 ;; away, because they affect everything.
50 ;; (put 'debug-on-error 'binding-is-magic t)
51 ;; (put 'debug-on-abort 'binding-is-magic t)
52 ;; (put 'debug-on-next-call 'binding-is-magic t)
53 ;; (put 'inhibit-quit 'binding-is-magic t)
54 ;; (put 'quit-flag 'binding-is-magic t)
55 ;; (put 't 'binding-is-magic t)
56 ;; (put 'nil 'binding-is-magic t)
57 ;; possibly also
58 ;; (put 'gc-cons-threshold 'binding-is-magic t)
59 ;; (put 'track-mouse 'binding-is-magic t)
60 ;; others?
61 ;;
62 ;; Simple defsubsts often produce forms like
63 ;; (let ((v1 (f1)) (v2 (f2)) ...)
64 ;; (FN v1 v2 ...))
65 ;; It would be nice if we could optimize this to
66 ;; (FN (f1) (f2) ...)
67 ;; but we can't unless FN is dynamically-safe (it might be dynamically
68 ;; referring to the bindings that the lambda arglist established.)
69 ;; One of the uncountable lossages introduced by dynamic scope...
70 ;;
71 ;; Maybe there should be a control-structure that says "turn on
72 ;; fast-and-loose type-assumptive optimizations here." Then when
73 ;; we see a form like (car foo) we can from then on assume that
74 ;; the variable foo is of type cons, and optimize based on that.
75 ;; But, this won't win much because of (you guessed it) dynamic
76 ;; scope. Anything down the stack could change the value.
77 ;; (Another reason it doesn't work is that it is perfectly valid
78 ;; to call car with a null argument.) A better approach might
79 ;; be to allow type-specification of the form
80 ;; (put 'foo 'arg-types '(float (list integer) dynamic))
81 ;; (put 'foo 'result-type 'bool)
82 ;; It should be possible to have these types checked to a certain
83 ;; degree.
84 ;;
85 ;; collapse common subexpressions
86 ;;
87 ;; It would be nice if redundant sequences could be factored out as well,
88 ;; when they are known to have no side-effects:
89 ;; (list (+ a b c) (+ a b c)) --> a b add c add dup list-2
90 ;; but beware of traps like
91 ;; (cons (list x y) (list x y))
92 ;;
93 ;; Tail-recursion elimination is not really possible in Emacs Lisp.
94 ;; Tail-recursion elimination is almost always impossible when all variables
95 ;; have dynamic scope, but given that the "return" byteop requires the
96 ;; binding stack to be empty (rather than emptying it itself), there can be
97 ;; no truly tail-recursive Emacs Lisp functions that take any arguments or
98 ;; make any bindings.
99 ;;
100 ;; Here is an example of an Emacs Lisp function which could safely be
101 ;; byte-compiled tail-recursively:
102 ;;
103 ;; (defun tail-map (fn list)
104 ;; (cond (list
105 ;; (funcall fn (car list))
106 ;; (tail-map fn (cdr list)))))
107 ;;
108 ;; However, if there was even a single let-binding around the COND,
109 ;; it could not be byte-compiled, because there would be an "unbind"
110 ;; byte-op between the final "call" and "return." Adding a
111 ;; Bunbind_all byteop would fix this.
112 ;;
113 ;; (defun foo (x y z) ... (foo a b c))
114 ;; ... (const foo) (varref a) (varref b) (varref c) (call 3) END: (return)
115 ;; ... (varref a) (varbind x) (varref b) (varbind y) (varref c) (varbind z) (goto 0) END: (unbind-all) (return)
116 ;; ... (varref a) (varset x) (varref b) (varset y) (varref c) (varset z) (goto 0) END: (return)
117 ;;
118 ;; this also can be considered tail recursion:
119 ;;
120 ;; ... (const foo) (varref a) (call 1) (goto X) ... X: (return)
121 ;; could generalize this by doing the optimization
122 ;; (goto X) ... X: (return) --> (return)
123 ;;
124 ;; But this doesn't solve all of the problems: although by doing tail-
125 ;; recursion elimination in this way, the call-stack does not grow, the
126 ;; binding-stack would grow with each recursive step, and would eventually
127 ;; overflow. I don't believe there is any way around this without lexical
128 ;; scope.
129 ;;
130 ;; Wouldn't it be nice if Emacs Lisp had lexical scope.
131 ;;
132 ;; Idea: the form (lexical-scope) in a file means that the file may be
133 ;; compiled lexically. This proclamation is file-local. Then, within
134 ;; that file, "let" would establish lexical bindings, and "let-dynamic"
135 ;; would do things the old way. (Or we could use CL "declare" forms.)
136 ;; We'd have to notice defvars and defconsts, since those variables should
137 ;; always be dynamic, and attempting to do a lexical binding of them
138 ;; should simply do a dynamic binding instead.
139 ;; But! We need to know about variables that were not necessarily defvarred
140 ;; in the file being compiled (doing a boundp check isn't good enough.)
141 ;; Fdefvar() would have to be modified to add something to the plist.
142 ;;
143 ;; A major disadvantage of this scheme is that the interpreter and compiler
144 ;; would have different semantics for files compiled with (dynamic-scope).
145 ;; Since this would be a file-local optimization, there would be no way to
146 ;; modify the interpreter to obey this (unless the loader was hacked
147 ;; in some grody way, but that's a really bad idea.)
148
149 ;; Other things to consider:
150
151 ;; ;; Associative math should recognize subcalls to identical function:
152 ;; (disassemble (lambda (x) (+ (+ (foo) 1) (+ (bar) 2))))
153 ;; ;; This should generate the same as (1+ x) and (1- x)
154
155 ;; (disassemble (lambda (x) (cons (+ x 1) (- x 1))))
156 ;; ;; An awful lot of functions always return a non-nil value. If they're
157 ;; ;; error free also they may act as true-constants.
158
159 ;; (disassemble (lambda (x) (and (point) (foo))))
160 ;; ;; When
161 ;; ;; - all but one arguments to a function are constant
162 ;; ;; - the non-constant argument is an if-expression (cond-expression?)
163 ;; ;; then the outer function can be distributed. If the guarding
164 ;; ;; condition is side-effect-free [assignment-free] then the other
165 ;; ;; arguments may be any expressions. Since, however, the code size
166 ;; ;; can increase this way they should be "simple". Compare:
167
168 ;; (disassemble (lambda (x) (eq (if (point) 'a 'b) 'c)))
169 ;; (disassemble (lambda (x) (if (point) (eq 'a 'c) (eq 'b 'c))))
170
171 ;; ;; (car (cons A B)) -> (prog1 A B)
172 ;; (disassemble (lambda (x) (car (cons (foo) 42))))
173
174 ;; ;; (cdr (cons A B)) -> (progn A B)
175 ;; (disassemble (lambda (x) (cdr (cons 42 (foo)))))
176
177 ;; ;; (car (list A B ...)) -> (prog1 A B ...)
178 ;; (disassemble (lambda (x) (car (list (foo) 42 (bar)))))
179
180 ;; ;; (cdr (list A B ...)) -> (progn A (list B ...))
181 ;; (disassemble (lambda (x) (cdr (list 42 (foo) (bar)))))
182
183
184 ;;; Code:
185
186 (require 'bytecomp)
187 (eval-when-compile (require 'cl))
188
189 (defun byte-compile-log-lap-1 (format &rest args)
190 (if (aref byte-code-vector 0)
191 (error "The old version of the disassembler is loaded. Reload new-bytecomp as well"))
192 (byte-compile-log-1
193 (apply 'format format
194 (let (c a)
195 (mapcar (lambda (arg)
196 (if (not (consp arg))
197 (if (and (symbolp arg)
198 (string-match "^byte-" (symbol-name arg)))
199 (intern (substring (symbol-name arg) 5))
200 arg)
201 (if (integerp (setq c (car arg)))
202 (error "non-symbolic byte-op %s" c))
203 (if (eq c 'TAG)
204 (setq c arg)
205 (setq a (cond ((memq c byte-goto-ops)
206 (car (cdr (cdr arg))))
207 ((memq c byte-constref-ops)
208 (car (cdr arg)))
209 (t (cdr arg))))
210 (setq c (symbol-name c))
211 (if (string-match "^byte-." c)
212 (setq c (intern (substring c 5)))))
213 (if (eq c 'constant) (setq c 'const))
214 (if (and (eq (cdr arg) 0)
215 (not (memq c '(unbind call const))))
216 c
217 (format "(%s %s)" c a))))
218 args)))))
219
220 (defmacro byte-compile-log-lap (format-string &rest args)
221 `(and (memq byte-optimize-log '(t byte))
222 (byte-compile-log-lap-1 ,format-string ,@args)))
223
224 \f
225 ;;; byte-compile optimizers to support inlining
226
227 (put 'inline 'byte-optimizer 'byte-optimize-inline-handler)
228
229 (defun byte-optimize-inline-handler (form)
230 "byte-optimize-handler for the `inline' special-form."
231 (cons 'progn
232 (mapcar
233 (lambda (sexp)
234 (let ((f (car-safe sexp)))
235 (if (and (symbolp f)
236 (or (cdr (assq f byte-compile-function-environment))
237 (not (or (not (fboundp f))
238 (cdr (assq f byte-compile-macro-environment))
239 (and (consp (setq f (symbol-function f)))
240 (eq (car f) 'macro))
241 (subrp f)))))
242 (byte-compile-inline-expand sexp)
243 sexp)))
244 (cdr form))))
245
246
247 ;; Splice the given lap code into the current instruction stream.
248 ;; If it has any labels in it, you're responsible for making sure there
249 ;; are no collisions, and that byte-compile-tag-number is reasonable
250 ;; after this is spliced in. The provided list is destroyed.
251 (defun byte-inline-lapcode (lap)
252 (setq byte-compile-output (nconc (nreverse lap) byte-compile-output)))
253
254 (defun byte-compile-inline-expand (form)
255 (let* ((name (car form))
256 (fn (or (cdr (assq name byte-compile-function-environment))
257 (and (fboundp name) (symbol-function name)))))
258 (if (null fn)
259 (progn
260 (byte-compile-warn "attempt to inline `%s' before it was defined"
261 name)
262 form)
263 ;; else
264 (when (and (consp fn) (eq (car fn) 'autoload))
265 (load (nth 1 fn))
266 (setq fn (or (and (fboundp name) (symbol-function name))
267 (cdr (assq name byte-compile-function-environment)))))
268 (if (and (consp fn) (eq (car fn) 'autoload))
269 (error "File `%s' didn't define `%s'" (nth 1 fn) name))
270 (if (and (symbolp fn) (not (eq fn t)))
271 (byte-compile-inline-expand (cons fn (cdr form)))
272 (if (byte-code-function-p fn)
273 (let (string)
274 (fetch-bytecode fn)
275 (setq string (aref fn 1))
276 ;; Isn't it an error for `string' not to be unibyte?? --stef
277 (if (fboundp 'string-as-unibyte)
278 (setq string (string-as-unibyte string)))
279 ;; `byte-compile-splice-in-already-compiled-code'
280 ;; takes care of inlining the body.
281 (cons `(lambda ,(aref fn 0)
282 (byte-code ,string ,(aref fn 2) ,(aref fn 3)))
283 (cdr form)))
284 (if (eq (car-safe fn) 'lambda)
285 (cons fn (cdr form))
286 ;; Give up on inlining.
287 form))))))
288
289 ;; ((lambda ...) ...)
290 (defun byte-compile-unfold-lambda (form &optional name)
291 (or name (setq name "anonymous lambda"))
292 (let ((lambda (car form))
293 (values (cdr form)))
294 (if (byte-code-function-p lambda)
295 (setq lambda (list 'lambda (aref lambda 0)
296 (list 'byte-code (aref lambda 1)
297 (aref lambda 2) (aref lambda 3)))))
298 (let ((arglist (nth 1 lambda))
299 (body (cdr (cdr lambda)))
300 optionalp restp
301 bindings)
302 (if (and (stringp (car body)) (cdr body))
303 (setq body (cdr body)))
304 (if (and (consp (car body)) (eq 'interactive (car (car body))))
305 (setq body (cdr body)))
306 (while arglist
307 (cond ((eq (car arglist) '&optional)
308 ;; ok, I'll let this slide because funcall_lambda() does...
309 ;; (if optionalp (error "multiple &optional keywords in %s" name))
310 (if restp (error "&optional found after &rest in %s" name))
311 (if (null (cdr arglist))
312 (error "nothing after &optional in %s" name))
313 (setq optionalp t))
314 ((eq (car arglist) '&rest)
315 ;; ...but it is by no stretch of the imagination a reasonable
316 ;; thing that funcall_lambda() allows (&rest x y) and
317 ;; (&rest x &optional y) in arglists.
318 (if (null (cdr arglist))
319 (error "nothing after &rest in %s" name))
320 (if (cdr (cdr arglist))
321 (error "multiple vars after &rest in %s" name))
322 (setq restp t))
323 (restp
324 (setq bindings (cons (list (car arglist)
325 (and values (cons 'list values)))
326 bindings)
327 values nil))
328 ((and (not optionalp) (null values))
329 (byte-compile-warn "attempt to open-code `%s' with too few arguments" name)
330 (setq arglist nil values 'too-few))
331 (t
332 (setq bindings (cons (list (car arglist) (car values))
333 bindings)
334 values (cdr values))))
335 (setq arglist (cdr arglist)))
336 (if values
337 (progn
338 (or (eq values 'too-few)
339 (byte-compile-warn
340 "attempt to open-code `%s' with too many arguments" name))
341 form)
342
343 ;; The following leads to infinite recursion when loading a
344 ;; file containing `(defsubst f () (f))', and then trying to
345 ;; byte-compile that file.
346 ;(setq body (mapcar 'byte-optimize-form body)))
347
348 (let ((newform
349 (if bindings
350 (cons 'let (cons (nreverse bindings) body))
351 (cons 'progn body))))
352 (byte-compile-log " %s\t==>\t%s" form newform)
353 newform)))))
354
355 \f
356 ;;; implementing source-level optimizers
357
358 (defun byte-optimize-form-code-walker (form for-effect)
359 ;;
360 ;; For normal function calls, We can just mapcar the optimizer the cdr. But
361 ;; we need to have special knowledge of the syntax of the special forms
362 ;; like let and defun (that's why they're special forms :-). (Actually,
363 ;; the important aspect is that they are subrs that don't evaluate all of
364 ;; their args.)
365 ;;
366 (let ((fn (car-safe form))
367 tmp)
368 (cond ((not (consp form))
369 (if (not (and for-effect
370 (or byte-compile-delete-errors
371 (not (symbolp form))
372 (eq form t))))
373 form))
374 ((eq fn 'quote)
375 (if (cdr (cdr form))
376 (byte-compile-warn "malformed quote form: `%s'"
377 (prin1-to-string form)))
378 ;; map (quote nil) to nil to simplify optimizer logic.
379 ;; map quoted constants to nil if for-effect (just because).
380 (and (nth 1 form)
381 (not for-effect)
382 form))
383 ((or (byte-code-function-p fn)
384 (eq 'lambda (car-safe fn)))
385 (let ((newform (byte-compile-unfold-lambda form)))
386 (if (eq newform form)
387 ;; Some error occurred, avoid infinite recursion
388 form
389 (byte-optimize-form-code-walker newform for-effect))))
390 ((memq fn '(let let*))
391 ;; recursively enter the optimizer for the bindings and body
392 ;; of a let or let*. This for depth-firstness: forms that
393 ;; are more deeply nested are optimized first.
394 (cons fn
395 (cons
396 (mapcar (lambda (binding)
397 (if (symbolp binding)
398 binding
399 (if (cdr (cdr binding))
400 (byte-compile-warn "malformed let binding: `%s'"
401 (prin1-to-string binding)))
402 (list (car binding)
403 (byte-optimize-form (nth 1 binding) nil))))
404 (nth 1 form))
405 (byte-optimize-body (cdr (cdr form)) for-effect))))
406 ((eq fn 'cond)
407 (cons fn
408 (mapcar (lambda (clause)
409 (if (consp clause)
410 (cons
411 (byte-optimize-form (car clause) nil)
412 (byte-optimize-body (cdr clause) for-effect))
413 (byte-compile-warn "malformed cond form: `%s'"
414 (prin1-to-string clause))
415 clause))
416 (cdr form))))
417 ((eq fn 'progn)
418 ;; as an extra added bonus, this simplifies (progn <x>) --> <x>
419 (if (cdr (cdr form))
420 (progn
421 (setq tmp (byte-optimize-body (cdr form) for-effect))
422 (if (cdr tmp) (cons 'progn tmp) (car tmp)))
423 (byte-optimize-form (nth 1 form) for-effect)))
424 ((eq fn 'prog1)
425 (if (cdr (cdr form))
426 (cons 'prog1
427 (cons (byte-optimize-form (nth 1 form) for-effect)
428 (byte-optimize-body (cdr (cdr form)) t)))
429 (byte-optimize-form (nth 1 form) for-effect)))
430 ((eq fn 'prog2)
431 (cons 'prog2
432 (cons (byte-optimize-form (nth 1 form) t)
433 (cons (byte-optimize-form (nth 2 form) for-effect)
434 (byte-optimize-body (cdr (cdr (cdr form))) t)))))
435
436 ((memq fn '(save-excursion save-restriction save-current-buffer))
437 ;; those subrs which have an implicit progn; it's not quite good
438 ;; enough to treat these like normal function calls.
439 ;; This can turn (save-excursion ...) into (save-excursion) which
440 ;; will be optimized away in the lap-optimize pass.
441 (cons fn (byte-optimize-body (cdr form) for-effect)))
442
443 ((eq fn 'with-output-to-temp-buffer)
444 ;; this is just like the above, except for the first argument.
445 (cons fn
446 (cons
447 (byte-optimize-form (nth 1 form) nil)
448 (byte-optimize-body (cdr (cdr form)) for-effect))))
449
450 ((eq fn 'if)
451 (when (< (length form) 3)
452 (byte-compile-warn "too few arguments for `if'"))
453 (cons fn
454 (cons (byte-optimize-form (nth 1 form) nil)
455 (cons
456 (byte-optimize-form (nth 2 form) for-effect)
457 (byte-optimize-body (nthcdr 3 form) for-effect)))))
458
459 ((memq fn '(and or)) ; remember, and/or are control structures.
460 ;; take forms off the back until we can't any more.
461 ;; In the future it could conceivably be a problem that the
462 ;; subexpressions of these forms are optimized in the reverse
463 ;; order, but it's ok for now.
464 (if for-effect
465 (let ((backwards (reverse (cdr form))))
466 (while (and backwards
467 (null (setcar backwards
468 (byte-optimize-form (car backwards)
469 for-effect))))
470 (setq backwards (cdr backwards)))
471 (if (and (cdr form) (null backwards))
472 (byte-compile-log
473 " all subforms of %s called for effect; deleted" form))
474 (and backwards
475 (cons fn (nreverse (mapcar 'byte-optimize-form backwards)))))
476 (cons fn (mapcar 'byte-optimize-form (cdr form)))))
477
478 ((eq fn 'interactive)
479 (byte-compile-warn "misplaced interactive spec: `%s'"
480 (prin1-to-string form))
481 nil)
482
483 ((memq fn '(defun defmacro function
484 condition-case save-window-excursion))
485 ;; These forms are compiled as constants or by breaking out
486 ;; all the subexpressions and compiling them separately.
487 form)
488
489 ((eq fn 'unwind-protect)
490 ;; the "protected" part of an unwind-protect is compiled (and thus
491 ;; optimized) as a top-level form, so don't do it here. But the
492 ;; non-protected part has the same for-effect status as the
493 ;; unwind-protect itself. (The protected part is always for effect,
494 ;; but that isn't handled properly yet.)
495 (cons fn
496 (cons (byte-optimize-form (nth 1 form) for-effect)
497 (cdr (cdr form)))))
498
499 ((eq fn 'catch)
500 ;; the body of a catch is compiled (and thus optimized) as a
501 ;; top-level form, so don't do it here. The tag is never
502 ;; for-effect. The body should have the same for-effect status
503 ;; as the catch form itself, but that isn't handled properly yet.
504 (cons fn
505 (cons (byte-optimize-form (nth 1 form) nil)
506 (cdr (cdr form)))))
507
508 ((eq fn 'ignore)
509 ;; Don't treat the args to `ignore' as being
510 ;; computed for effect. We want to avoid the warnings
511 ;; that might occur if they were treated that way.
512 ;; However, don't actually bother calling `ignore'.
513 `(prog1 nil . ,(mapcar 'byte-optimize-form (cdr form))))
514
515 ;; If optimization is on, this is the only place that macros are
516 ;; expanded. If optimization is off, then macroexpansion happens
517 ;; in byte-compile-form. Otherwise, the macros are already expanded
518 ;; by the time that is reached.
519 ((not (eq form
520 (setq form (macroexpand form
521 byte-compile-macro-environment))))
522 (byte-optimize-form form for-effect))
523
524 ;; Support compiler macros as in cl.el.
525 ((and (fboundp 'compiler-macroexpand)
526 (symbolp (car-safe form))
527 (get (car-safe form) 'cl-compiler-macro)
528 (not (eq form
529 (with-no-warnings
530 (setq form (compiler-macroexpand form))))))
531 (byte-optimize-form form for-effect))
532
533 ((not (symbolp fn))
534 (byte-compile-warn "`%s' is a malformed function"
535 (prin1-to-string fn))
536 form)
537
538 ((and for-effect (setq tmp (get fn 'side-effect-free))
539 (or byte-compile-delete-errors
540 (eq tmp 'error-free)
541 ;; Detect the expansion of (pop foo).
542 ;; There is no need to compile the call to `car' there.
543 (and (eq fn 'car)
544 (eq (car-safe (cadr form)) 'prog1)
545 (let ((var (cadr (cadr form)))
546 (last (nth 2 (cadr form))))
547 (and (symbolp var)
548 (null (nthcdr 3 (cadr form)))
549 (eq (car-safe last) 'setq)
550 (eq (cadr last) var)
551 (eq (car-safe (nth 2 last)) 'cdr)
552 (eq (cadr (nth 2 last)) var))))
553 (progn
554 (byte-compile-warn "value returned from %s is unused"
555 (prin1-to-string form))
556 nil)))
557 (byte-compile-log " %s called for effect; deleted" fn)
558 ;; appending a nil here might not be necessary, but it can't hurt.
559 (byte-optimize-form
560 (cons 'progn (append (cdr form) '(nil))) t))
561
562 (t
563 ;; Otherwise, no args can be considered to be for-effect,
564 ;; even if the called function is for-effect, because we
565 ;; don't know anything about that function.
566 (let ((args (mapcar #'byte-optimize-form (cdr form))))
567 (if (and (get fn 'pure)
568 (byte-optimize-all-constp args))
569 (list 'quote (apply fn (mapcar #'eval args)))
570 (cons fn args)))))))
571
572 (defun byte-optimize-all-constp (list)
573 "Non-nil if all elements of LIST satisfy `byte-compile-constp'."
574 (let ((constant t))
575 (while (and list constant)
576 (unless (byte-compile-constp (car list))
577 (setq constant nil))
578 (setq list (cdr list)))
579 constant))
580
581 (defun byte-optimize-form (form &optional for-effect)
582 "The source-level pass of the optimizer."
583 ;;
584 ;; First, optimize all sub-forms of this one.
585 (setq form (byte-optimize-form-code-walker form for-effect))
586 ;;
587 ;; after optimizing all subforms, optimize this form until it doesn't
588 ;; optimize any further. This means that some forms will be passed through
589 ;; the optimizer many times, but that's necessary to make the for-effect
590 ;; processing do as much as possible.
591 ;;
592 (let (opt new)
593 (if (and (consp form)
594 (symbolp (car form))
595 (or (and for-effect
596 ;; we don't have any of these yet, but we might.
597 (setq opt (get (car form) 'byte-for-effect-optimizer)))
598 (setq opt (get (car form) 'byte-optimizer)))
599 (not (eq form (setq new (funcall opt form)))))
600 (progn
601 ;; (if (equal form new) (error "bogus optimizer -- %s" opt))
602 (byte-compile-log " %s\t==>\t%s" form new)
603 (setq new (byte-optimize-form new for-effect))
604 new)
605 form)))
606
607
608 (defun byte-optimize-body (forms all-for-effect)
609 ;; optimize the cdr of a progn or implicit progn; all forms is a list of
610 ;; forms, all but the last of which are optimized with the assumption that
611 ;; they are being called for effect. the last is for-effect as well if
612 ;; all-for-effect is true. returns a new list of forms.
613 (let ((rest forms)
614 (result nil)
615 fe new)
616 (while rest
617 (setq fe (or all-for-effect (cdr rest)))
618 (setq new (and (car rest) (byte-optimize-form (car rest) fe)))
619 (if (or new (not fe))
620 (setq result (cons new result)))
621 (setq rest (cdr rest)))
622 (nreverse result)))
623
624 \f
625 ;; some source-level optimizers
626 ;;
627 ;; when writing optimizers, be VERY careful that the optimizer returns
628 ;; something not EQ to its argument if and ONLY if it has made a change.
629 ;; This implies that you cannot simply destructively modify the list;
630 ;; you must return something not EQ to it if you make an optimization.
631 ;;
632 ;; It is now safe to optimize code such that it introduces new bindings.
633
634 (defsubst byte-compile-trueconstp (form)
635 "Return non-nil if FORM always evaluates to a non-nil value."
636 (while (eq (car-safe form) 'progn)
637 (setq form (car (last (cdr form)))))
638 (cond ((consp form)
639 (case (car form)
640 (quote (cadr form))
641 ;; Can't use recursion in a defsubst.
642 ;; (progn (byte-compile-trueconstp (car (last (cdr form)))))
643 ))
644 ((not (symbolp form)))
645 ((eq form t))
646 ((keywordp form))))
647
648 (defsubst byte-compile-nilconstp (form)
649 "Return non-nil if FORM always evaluates to a nil value."
650 (while (eq (car-safe form) 'progn)
651 (setq form (car (last (cdr form)))))
652 (cond ((consp form)
653 (case (car form)
654 (quote (null (cadr form)))
655 ;; Can't use recursion in a defsubst.
656 ;; (progn (byte-compile-nilconstp (car (last (cdr form)))))
657 ))
658 ((not (symbolp form)) nil)
659 ((null form))))
660
661 ;; If the function is being called with constant numeric args,
662 ;; evaluate as much as possible at compile-time. This optimizer
663 ;; assumes that the function is associative, like + or *.
664 (defun byte-optimize-associative-math (form)
665 (let ((args nil)
666 (constants nil)
667 (rest (cdr form)))
668 (while rest
669 (if (numberp (car rest))
670 (setq constants (cons (car rest) constants))
671 (setq args (cons (car rest) args)))
672 (setq rest (cdr rest)))
673 (if (cdr constants)
674 (if args
675 (list (car form)
676 (apply (car form) constants)
677 (if (cdr args)
678 (cons (car form) (nreverse args))
679 (car args)))
680 (apply (car form) constants))
681 form)))
682
683 ;; If the function is being called with constant numeric args,
684 ;; evaluate as much as possible at compile-time. This optimizer
685 ;; assumes that the function satisfies
686 ;; (op x1 x2 ... xn) == (op ...(op (op x1 x2) x3) ...xn)
687 ;; like - and /.
688 (defun byte-optimize-nonassociative-math (form)
689 (if (or (not (numberp (car (cdr form))))
690 (not (numberp (car (cdr (cdr form))))))
691 form
692 (let ((constant (car (cdr form)))
693 (rest (cdr (cdr form))))
694 (while (numberp (car rest))
695 (setq constant (funcall (car form) constant (car rest))
696 rest (cdr rest)))
697 (if rest
698 (cons (car form) (cons constant rest))
699 constant))))
700
701 ;;(defun byte-optimize-associative-two-args-math (form)
702 ;; (setq form (byte-optimize-associative-math form))
703 ;; (if (consp form)
704 ;; (byte-optimize-two-args-left form)
705 ;; form))
706
707 ;;(defun byte-optimize-nonassociative-two-args-math (form)
708 ;; (setq form (byte-optimize-nonassociative-math form))
709 ;; (if (consp form)
710 ;; (byte-optimize-two-args-right form)
711 ;; form))
712
713 (defun byte-optimize-approx-equal (x y)
714 (<= (* (abs (- x y)) 100) (abs (+ x y))))
715
716 ;; Collect all the constants from FORM, after the STARTth arg,
717 ;; and apply FUN to them to make one argument at the end.
718 ;; For functions that can handle floats, that optimization
719 ;; can be incorrect because reordering can cause an overflow
720 ;; that would otherwise be avoided by encountering an arg that is a float.
721 ;; We avoid this problem by (1) not moving float constants and
722 ;; (2) not moving anything if it would cause an overflow.
723 (defun byte-optimize-delay-constants-math (form start fun)
724 ;; Merge all FORM's constants from number START, call FUN on them
725 ;; and put the result at the end.
726 (let ((rest (nthcdr (1- start) form))
727 (orig form)
728 ;; t means we must check for overflow.
729 (overflow (memq fun '(+ *))))
730 (while (cdr (setq rest (cdr rest)))
731 (if (integerp (car rest))
732 (let (constants)
733 (setq form (copy-sequence form)
734 rest (nthcdr (1- start) form))
735 (while (setq rest (cdr rest))
736 (cond ((integerp (car rest))
737 (setq constants (cons (car rest) constants))
738 (setcar rest nil))))
739 ;; If necessary, check now for overflow
740 ;; that might be caused by reordering.
741 (if (and overflow
742 ;; We have overflow if the result of doing the arithmetic
743 ;; on floats is not even close to the result
744 ;; of doing it on integers.
745 (not (byte-optimize-approx-equal
746 (apply fun (mapcar 'float constants))
747 (float (apply fun constants)))))
748 (setq form orig)
749 (setq form (nconc (delq nil form)
750 (list (apply fun (nreverse constants)))))))))
751 form))
752
753 (defsubst byte-compile-butlast (form)
754 (nreverse (cdr (reverse form))))
755
756 (defun byte-optimize-plus (form)
757 ;; Don't call `byte-optimize-delay-constants-math' (bug#1334).
758 ;;(setq form (byte-optimize-delay-constants-math form 1 '+))
759 (if (memq 0 form) (setq form (delq 0 (copy-sequence form))))
760 ;; For (+ constants...), byte-optimize-predicate does the work.
761 (when (memq nil (mapcar 'numberp (cdr form)))
762 (cond
763 ;; (+ x 1) --> (1+ x) and (+ x -1) --> (1- x).
764 ((and (= (length form) 3)
765 (or (memq (nth 1 form) '(1 -1))
766 (memq (nth 2 form) '(1 -1))))
767 (let (integer other)
768 (if (memq (nth 1 form) '(1 -1))
769 (setq integer (nth 1 form) other (nth 2 form))
770 (setq integer (nth 2 form) other (nth 1 form)))
771 (setq form
772 (list (if (eq integer 1) '1+ '1-) other))))
773 ;; Here, we could also do
774 ;; (+ x y ... 1) --> (1+ (+ x y ...))
775 ;; (+ x y ... -1) --> (1- (+ x y ...))
776 ;; The resulting bytecode is smaller, but is it faster? -- cyd
777 ))
778 (byte-optimize-predicate form))
779
780 (defun byte-optimize-minus (form)
781 ;; Don't call `byte-optimize-delay-constants-math' (bug#1334).
782 ;;(setq form (byte-optimize-delay-constants-math form 2 '+))
783 ;; Remove zeros.
784 (when (and (nthcdr 3 form)
785 (memq 0 (cddr form)))
786 (setq form (nconc (list (car form) (cadr form))
787 (delq 0 (copy-sequence (cddr form)))))
788 ;; After the above, we must turn (- x) back into (- x 0)
789 (or (cddr form)
790 (setq form (nconc form (list 0)))))
791 ;; For (- constants..), byte-optimize-predicate does the work.
792 (when (memq nil (mapcar 'numberp (cdr form)))
793 (cond
794 ;; (- x 1) --> (1- x)
795 ((equal (nthcdr 2 form) '(1))
796 (setq form (list '1- (nth 1 form))))
797 ;; (- x -1) --> (1+ x)
798 ((equal (nthcdr 2 form) '(-1))
799 (setq form (list '1+ (nth 1 form))))
800 ;; (- 0 x) --> (- x)
801 ((and (eq (nth 1 form) 0)
802 (= (length form) 3))
803 (setq form (list '- (nth 2 form))))
804 ;; Here, we could also do
805 ;; (- x y ... 1) --> (1- (- x y ...))
806 ;; (- x y ... -1) --> (1+ (- x y ...))
807 ;; The resulting bytecode is smaller, but is it faster? -- cyd
808 ))
809 (byte-optimize-predicate form))
810
811 (defun byte-optimize-multiply (form)
812 (setq form (byte-optimize-delay-constants-math form 1 '*))
813 ;; For (* constants..), byte-optimize-predicate does the work.
814 (when (memq nil (mapcar 'numberp (cdr form)))
815 ;; After `byte-optimize-predicate', if there is a INTEGER constant
816 ;; in FORM, it is in the last element.
817 (let ((last (car (reverse (cdr form)))))
818 (cond
819 ;; Would handling (* ... 0) here cause floating point errors?
820 ;; See bug#1334.
821 ((eq 1 last) (setq form (byte-compile-butlast form)))
822 ((eq -1 last)
823 (setq form (list '- (if (nthcdr 3 form)
824 (byte-compile-butlast form)
825 (nth 1 form))))))))
826 (byte-optimize-predicate form))
827
828 (defun byte-optimize-divide (form)
829 (setq form (byte-optimize-delay-constants-math form 2 '*))
830 ;; After `byte-optimize-predicate', if there is a INTEGER constant
831 ;; in FORM, it is in the last element.
832 (let ((last (car (reverse (cdr (cdr form))))))
833 (cond
834 ;; Runtime error (leave it intact).
835 ((or (null last)
836 (eq last 0)
837 (memql 0.0 (cddr form))))
838 ;; No constants in expression
839 ((not (numberp last)))
840 ;; For (* constants..), byte-optimize-predicate does the work.
841 ((null (memq nil (mapcar 'numberp (cdr form)))))
842 ;; (/ x y.. 1) --> (/ x y..)
843 ((and (eq last 1) (nthcdr 3 form))
844 (setq form (byte-compile-butlast form)))
845 ;; (/ x -1), (/ x .. -1) --> (- x), (- (/ x ..))
846 ((eq last -1)
847 (setq form (list '- (if (nthcdr 3 form)
848 (byte-compile-butlast form)
849 (nth 1 form)))))))
850 (byte-optimize-predicate form))
851
852 (defun byte-optimize-logmumble (form)
853 (setq form (byte-optimize-delay-constants-math form 1 (car form)))
854 (byte-optimize-predicate
855 (cond ((memq 0 form)
856 (setq form (if (eq (car form) 'logand)
857 (cons 'progn (cdr form))
858 (delq 0 (copy-sequence form)))))
859 ((and (eq (car-safe form) 'logior)
860 (memq -1 form))
861 (cons 'progn (cdr form)))
862 (form))))
863
864
865 (defun byte-optimize-binary-predicate (form)
866 (if (byte-compile-constp (nth 1 form))
867 (if (byte-compile-constp (nth 2 form))
868 (condition-case ()
869 (list 'quote (eval form))
870 (error form))
871 ;; This can enable some lapcode optimizations.
872 (list (car form) (nth 2 form) (nth 1 form)))
873 form))
874
875 (defun byte-optimize-predicate (form)
876 (let ((ok t)
877 (rest (cdr form)))
878 (while (and rest ok)
879 (setq ok (byte-compile-constp (car rest))
880 rest (cdr rest)))
881 (if ok
882 (condition-case ()
883 (list 'quote (eval form))
884 (error form))
885 form)))
886
887 (defun byte-optimize-identity (form)
888 (if (and (cdr form) (null (cdr (cdr form))))
889 (nth 1 form)
890 (byte-compile-warn "identity called with %d arg%s, but requires 1"
891 (length (cdr form))
892 (if (= 1 (length (cdr form))) "" "s"))
893 form))
894
895 (put 'identity 'byte-optimizer 'byte-optimize-identity)
896
897 (put '+ 'byte-optimizer 'byte-optimize-plus)
898 (put '* 'byte-optimizer 'byte-optimize-multiply)
899 (put '- 'byte-optimizer 'byte-optimize-minus)
900 (put '/ 'byte-optimizer 'byte-optimize-divide)
901 (put 'max 'byte-optimizer 'byte-optimize-associative-math)
902 (put 'min 'byte-optimizer 'byte-optimize-associative-math)
903
904 (put '= 'byte-optimizer 'byte-optimize-binary-predicate)
905 (put 'eq 'byte-optimizer 'byte-optimize-binary-predicate)
906 (put 'equal 'byte-optimizer 'byte-optimize-binary-predicate)
907 (put 'string= 'byte-optimizer 'byte-optimize-binary-predicate)
908 (put 'string-equal 'byte-optimizer 'byte-optimize-binary-predicate)
909
910 (put '< 'byte-optimizer 'byte-optimize-predicate)
911 (put '> 'byte-optimizer 'byte-optimize-predicate)
912 (put '<= 'byte-optimizer 'byte-optimize-predicate)
913 (put '>= 'byte-optimizer 'byte-optimize-predicate)
914 (put '1+ 'byte-optimizer 'byte-optimize-predicate)
915 (put '1- 'byte-optimizer 'byte-optimize-predicate)
916 (put 'not 'byte-optimizer 'byte-optimize-predicate)
917 (put 'null 'byte-optimizer 'byte-optimize-predicate)
918 (put 'memq 'byte-optimizer 'byte-optimize-predicate)
919 (put 'consp 'byte-optimizer 'byte-optimize-predicate)
920 (put 'listp 'byte-optimizer 'byte-optimize-predicate)
921 (put 'symbolp 'byte-optimizer 'byte-optimize-predicate)
922 (put 'stringp 'byte-optimizer 'byte-optimize-predicate)
923 (put 'string< 'byte-optimizer 'byte-optimize-predicate)
924 (put 'string-lessp 'byte-optimizer 'byte-optimize-predicate)
925
926 (put 'logand 'byte-optimizer 'byte-optimize-logmumble)
927 (put 'logior 'byte-optimizer 'byte-optimize-logmumble)
928 (put 'logxor 'byte-optimizer 'byte-optimize-logmumble)
929 (put 'lognot 'byte-optimizer 'byte-optimize-predicate)
930
931 (put 'car 'byte-optimizer 'byte-optimize-predicate)
932 (put 'cdr 'byte-optimizer 'byte-optimize-predicate)
933 (put 'car-safe 'byte-optimizer 'byte-optimize-predicate)
934 (put 'cdr-safe 'byte-optimizer 'byte-optimize-predicate)
935
936
937 ;; I'm not convinced that this is necessary. Doesn't the optimizer loop
938 ;; take care of this? - Jamie
939 ;; I think this may some times be necessary to reduce ie (quote 5) to 5,
940 ;; so arithmetic optimizers recognize the numeric constant. - Hallvard
941 (put 'quote 'byte-optimizer 'byte-optimize-quote)
942 (defun byte-optimize-quote (form)
943 (if (or (consp (nth 1 form))
944 (and (symbolp (nth 1 form))
945 (not (byte-compile-const-symbol-p form))))
946 form
947 (nth 1 form)))
948
949 (defun byte-optimize-zerop (form)
950 (cond ((numberp (nth 1 form))
951 (eval form))
952 (byte-compile-delete-errors
953 (list '= (nth 1 form) 0))
954 (form)))
955
956 (put 'zerop 'byte-optimizer 'byte-optimize-zerop)
957
958 (defun byte-optimize-and (form)
959 ;; Simplify if less than 2 args.
960 ;; if there is a literal nil in the args to `and', throw it and following
961 ;; forms away, and surround the `and' with (progn ... nil).
962 (cond ((null (cdr form)))
963 ((memq nil form)
964 (list 'progn
965 (byte-optimize-and
966 (prog1 (setq form (copy-sequence form))
967 (while (nth 1 form)
968 (setq form (cdr form)))
969 (setcdr form nil)))
970 nil))
971 ((null (cdr (cdr form)))
972 (nth 1 form))
973 ((byte-optimize-predicate form))))
974
975 (defun byte-optimize-or (form)
976 ;; Throw away nil's, and simplify if less than 2 args.
977 ;; If there is a literal non-nil constant in the args to `or', throw away all
978 ;; following forms.
979 (if (memq nil form)
980 (setq form (delq nil (copy-sequence form))))
981 (let ((rest form))
982 (while (cdr (setq rest (cdr rest)))
983 (if (byte-compile-trueconstp (car rest))
984 (setq form (copy-sequence form)
985 rest (setcdr (memq (car rest) form) nil))))
986 (if (cdr (cdr form))
987 (byte-optimize-predicate form)
988 (nth 1 form))))
989
990 (defun byte-optimize-cond (form)
991 ;; if any clauses have a literal nil as their test, throw them away.
992 ;; if any clause has a literal non-nil constant as its test, throw
993 ;; away all following clauses.
994 (let (rest)
995 ;; This must be first, to reduce (cond (t ...) (nil)) to (progn t ...)
996 (while (setq rest (assq nil (cdr form)))
997 (setq form (delq rest (copy-sequence form))))
998 (if (memq nil (cdr form))
999 (setq form (delq nil (copy-sequence form))))
1000 (setq rest form)
1001 (while (setq rest (cdr rest))
1002 (cond ((byte-compile-trueconstp (car-safe (car rest)))
1003 ;; This branch will always be taken: kill the subsequent ones.
1004 (cond ((eq rest (cdr form)) ;First branch of `cond'.
1005 (setq form `(progn ,@(car rest))))
1006 ((cdr rest)
1007 (setq form (copy-sequence form))
1008 (setcdr (memq (car rest) form) nil)))
1009 (setq rest nil))
1010 ((and (consp (car rest))
1011 (byte-compile-nilconstp (caar rest)))
1012 ;; This branch will never be taken: kill its body.
1013 (setcdr (car rest) nil)))))
1014 ;;
1015 ;; Turn (cond (( <x> )) ... ) into (or <x> (cond ... ))
1016 (if (eq 'cond (car-safe form))
1017 (let ((clauses (cdr form)))
1018 (if (and (consp (car clauses))
1019 (null (cdr (car clauses))))
1020 (list 'or (car (car clauses))
1021 (byte-optimize-cond
1022 (cons (car form) (cdr (cdr form)))))
1023 form))
1024 form))
1025
1026 (defun byte-optimize-if (form)
1027 ;; (if (progn <insts> <test>) <rest>) ==> (progn <insts> (if <test> <rest>))
1028 ;; (if <true-constant> <then> <else...>) ==> <then>
1029 ;; (if <false-constant> <then> <else...>) ==> (progn <else...>)
1030 ;; (if <test> nil <else...>) ==> (if (not <test>) (progn <else...>))
1031 ;; (if <test> <then> nil) ==> (if <test> <then>)
1032 (let ((clause (nth 1 form)))
1033 (cond ((and (eq (car-safe clause) 'progn)
1034 ;; `clause' is a proper list.
1035 (null (cdr (last clause))))
1036 (if (null (cddr clause))
1037 ;; A trivial `progn'.
1038 (byte-optimize-if `(if ,(cadr clause) ,@(nthcdr 2 form)))
1039 (nconc (butlast clause)
1040 (list
1041 (byte-optimize-if
1042 `(if ,(car (last clause)) ,@(nthcdr 2 form)))))))
1043 ((byte-compile-trueconstp clause)
1044 `(progn ,clause ,(nth 2 form)))
1045 ((byte-compile-nilconstp clause)
1046 `(progn ,clause ,@(nthcdr 3 form)))
1047 ((nth 2 form)
1048 (if (equal '(nil) (nthcdr 3 form))
1049 (list 'if clause (nth 2 form))
1050 form))
1051 ((or (nth 3 form) (nthcdr 4 form))
1052 (list 'if
1053 ;; Don't make a double negative;
1054 ;; instead, take away the one that is there.
1055 (if (and (consp clause) (memq (car clause) '(not null))
1056 (= (length clause) 2)) ; (not xxxx) or (not (xxxx))
1057 (nth 1 clause)
1058 (list 'not clause))
1059 (if (nthcdr 4 form)
1060 (cons 'progn (nthcdr 3 form))
1061 (nth 3 form))))
1062 (t
1063 (list 'progn clause nil)))))
1064
1065 (defun byte-optimize-while (form)
1066 (when (< (length form) 2)
1067 (byte-compile-warn "too few arguments for `while'"))
1068 (if (nth 1 form)
1069 form))
1070
1071 (put 'and 'byte-optimizer 'byte-optimize-and)
1072 (put 'or 'byte-optimizer 'byte-optimize-or)
1073 (put 'cond 'byte-optimizer 'byte-optimize-cond)
1074 (put 'if 'byte-optimizer 'byte-optimize-if)
1075 (put 'while 'byte-optimizer 'byte-optimize-while)
1076
1077 ;; byte-compile-negation-optimizer lives in bytecomp.el
1078 (put '/= 'byte-optimizer 'byte-compile-negation-optimizer)
1079 (put 'atom 'byte-optimizer 'byte-compile-negation-optimizer)
1080 (put 'nlistp 'byte-optimizer 'byte-compile-negation-optimizer)
1081
1082
1083 (defun byte-optimize-funcall (form)
1084 ;; (funcall (lambda ...) ...) ==> ((lambda ...) ...)
1085 ;; (funcall foo ...) ==> (foo ...)
1086 (let ((fn (nth 1 form)))
1087 (if (memq (car-safe fn) '(quote function))
1088 (cons (nth 1 fn) (cdr (cdr form)))
1089 form)))
1090
1091 (defun byte-optimize-apply (form)
1092 ;; If the last arg is a literal constant, turn this into a funcall.
1093 ;; The funcall optimizer can then transform (funcall 'foo ...) -> (foo ...).
1094 (let ((fn (nth 1 form))
1095 (last (nth (1- (length form)) form))) ; I think this really is fastest
1096 (or (if (or (null last)
1097 (eq (car-safe last) 'quote))
1098 (if (listp (nth 1 last))
1099 (let ((butlast (nreverse (cdr (reverse (cdr (cdr form)))))))
1100 (nconc (list 'funcall fn) butlast
1101 (mapcar (lambda (x) (list 'quote x)) (nth 1 last))))
1102 (byte-compile-warn
1103 "last arg to apply can't be a literal atom: `%s'"
1104 (prin1-to-string last))
1105 nil))
1106 form)))
1107
1108 (put 'funcall 'byte-optimizer 'byte-optimize-funcall)
1109 (put 'apply 'byte-optimizer 'byte-optimize-apply)
1110
1111
1112 (put 'let 'byte-optimizer 'byte-optimize-letX)
1113 (put 'let* 'byte-optimizer 'byte-optimize-letX)
1114 (defun byte-optimize-letX (form)
1115 (cond ((null (nth 1 form))
1116 ;; No bindings
1117 (cons 'progn (cdr (cdr form))))
1118 ((or (nth 2 form) (nthcdr 3 form))
1119 form)
1120 ;; The body is nil
1121 ((eq (car form) 'let)
1122 (append '(progn) (mapcar 'car-safe (mapcar 'cdr-safe (nth 1 form)))
1123 '(nil)))
1124 (t
1125 (let ((binds (reverse (nth 1 form))))
1126 (list 'let* (reverse (cdr binds)) (nth 1 (car binds)) nil)))))
1127
1128
1129 (put 'nth 'byte-optimizer 'byte-optimize-nth)
1130 (defun byte-optimize-nth (form)
1131 (if (= (safe-length form) 3)
1132 (if (memq (nth 1 form) '(0 1))
1133 (list 'car (if (zerop (nth 1 form))
1134 (nth 2 form)
1135 (list 'cdr (nth 2 form))))
1136 (byte-optimize-predicate form))
1137 form))
1138
1139 (put 'nthcdr 'byte-optimizer 'byte-optimize-nthcdr)
1140 (defun byte-optimize-nthcdr (form)
1141 (if (= (safe-length form) 3)
1142 (if (memq (nth 1 form) '(0 1 2))
1143 (let ((count (nth 1 form)))
1144 (setq form (nth 2 form))
1145 (while (>= (setq count (1- count)) 0)
1146 (setq form (list 'cdr form)))
1147 form)
1148 (byte-optimize-predicate form))
1149 form))
1150
1151 ;; Fixme: delete-char -> delete-region (byte-coded)
1152 ;; optimize string-as-unibyte, string-as-multibyte, string-make-unibyte,
1153 ;; string-make-multibyte for constant args.
1154
1155 (put 'featurep 'byte-optimizer 'byte-optimize-featurep)
1156 (defun byte-optimize-featurep (form)
1157 ;; Emacs-21's byte-code doesn't run under XEmacs or SXEmacs anyway, so we
1158 ;; can safely optimize away this test.
1159 (if (member (cdr-safe form) '(((quote xemacs)) ((quote sxemacs))))
1160 nil
1161 (if (member (cdr-safe form) '(((quote emacs))))
1162 t
1163 form)))
1164
1165 (put 'set 'byte-optimizer 'byte-optimize-set)
1166 (defun byte-optimize-set (form)
1167 (let ((var (car-safe (cdr-safe form))))
1168 (cond
1169 ((and (eq (car-safe var) 'quote) (consp (cdr var)))
1170 `(setq ,(cadr var) ,@(cddr form)))
1171 ((and (eq (car-safe var) 'make-local-variable)
1172 (eq (car-safe (setq var (car-safe (cdr var)))) 'quote)
1173 (consp (cdr var)))
1174 `(progn ,(cadr form) (setq ,(cadr var) ,@(cddr form))))
1175 (t form))))
1176 \f
1177 ;; enumerating those functions which need not be called if the returned
1178 ;; value is not used. That is, something like
1179 ;; (progn (list (something-with-side-effects) (yow))
1180 ;; (foo))
1181 ;; may safely be turned into
1182 ;; (progn (progn (something-with-side-effects) (yow))
1183 ;; (foo))
1184 ;; Further optimizations will turn (progn (list 1 2 3) 'foo) into 'foo.
1185
1186 ;; Some of these functions have the side effect of allocating memory
1187 ;; and it would be incorrect to replace two calls with one.
1188 ;; But we don't try to do those kinds of optimizations,
1189 ;; so it is safe to list such functions here.
1190 ;; Some of these functions return values that depend on environment
1191 ;; state, so that constant folding them would be wrong,
1192 ;; but we don't do constant folding based on this list.
1193
1194 ;; However, at present the only optimization we normally do
1195 ;; is delete calls that need not occur, and we only do that
1196 ;; with the error-free functions.
1197
1198 ;; I wonder if I missed any :-\)
1199 (let ((side-effect-free-fns
1200 '(% * + - / /= 1+ 1- < <= = > >= abs acos append aref ash asin atan
1201 assoc assq
1202 boundp buffer-file-name buffer-local-variables buffer-modified-p
1203 buffer-substring byte-code-function-p
1204 capitalize car-less-than-car car cdr ceiling char-after char-before
1205 char-equal char-to-string char-width
1206 compare-strings concat coordinates-in-window-p
1207 copy-alist copy-sequence copy-marker cos count-lines
1208 decode-char
1209 decode-time default-boundp default-value documentation downcase
1210 elt encode-char exp expt encode-time error-message-string
1211 fboundp fceiling featurep ffloor
1212 file-directory-p file-exists-p file-locked-p file-name-absolute-p
1213 file-newer-than-file-p file-readable-p file-symlink-p file-writable-p
1214 float float-time floor format format-time-string frame-visible-p
1215 fround ftruncate
1216 get gethash get-buffer get-buffer-window getenv get-file-buffer
1217 hash-table-count
1218 int-to-string intern-soft
1219 keymap-parent
1220 length local-variable-if-set-p local-variable-p log log10 logand
1221 logb logior lognot logxor lsh langinfo
1222 make-list make-string make-symbol
1223 marker-buffer max member memq min mod multibyte-char-to-unibyte
1224 next-window nth nthcdr number-to-string
1225 parse-colon-path plist-get plist-member
1226 prefix-numeric-value previous-window prin1-to-string propertize
1227 degrees-to-radians
1228 radians-to-degrees rassq rassoc read-from-string regexp-quote
1229 region-beginning region-end reverse round
1230 sin sqrt string string< string= string-equal string-lessp string-to-char
1231 string-to-int string-to-number substring sxhash symbol-function
1232 symbol-name symbol-plist symbol-value string-make-unibyte
1233 string-make-multibyte string-as-multibyte string-as-unibyte
1234 string-to-multibyte
1235 tan truncate
1236 unibyte-char-to-multibyte upcase user-full-name
1237 user-login-name user-original-login-name user-variable-p
1238 vconcat
1239 window-buffer window-dedicated-p window-edges window-height
1240 window-hscroll window-minibuffer-p window-width
1241 zerop))
1242 (side-effect-and-error-free-fns
1243 '(arrayp atom
1244 bobp bolp bool-vector-p
1245 buffer-end buffer-list buffer-size buffer-string bufferp
1246 car-safe case-table-p cdr-safe char-or-string-p characterp
1247 charsetp commandp cons consp
1248 current-buffer current-global-map current-indentation
1249 current-local-map current-minor-mode-maps current-time
1250 current-time-string current-time-zone
1251 eobp eolp eq equal eventp
1252 floatp following-char framep
1253 get-largest-window get-lru-window
1254 hash-table-p
1255 identity ignore integerp integer-or-marker-p interactive-p
1256 invocation-directory invocation-name
1257 keymapp
1258 line-beginning-position line-end-position list listp
1259 make-marker mark mark-marker markerp max-char
1260 memory-limit minibuffer-window
1261 mouse-movement-p
1262 natnump nlistp not null number-or-marker-p numberp
1263 one-window-p overlayp
1264 point point-marker point-min point-max preceding-char primary-charset
1265 processp
1266 recent-keys recursion-depth
1267 safe-length selected-frame selected-window sequencep
1268 standard-case-table standard-syntax-table stringp subrp symbolp
1269 syntax-table syntax-table-p
1270 this-command-keys this-command-keys-vector this-single-command-keys
1271 this-single-command-raw-keys
1272 user-real-login-name user-real-uid user-uid
1273 vector vectorp visible-frame-list
1274 wholenump window-configuration-p window-live-p windowp)))
1275 (while side-effect-free-fns
1276 (put (car side-effect-free-fns) 'side-effect-free t)
1277 (setq side-effect-free-fns (cdr side-effect-free-fns)))
1278 (while side-effect-and-error-free-fns
1279 (put (car side-effect-and-error-free-fns) 'side-effect-free 'error-free)
1280 (setq side-effect-and-error-free-fns (cdr side-effect-and-error-free-fns)))
1281 nil)
1282
1283 \f
1284 ;; pure functions are side-effect free functions whose values depend
1285 ;; only on their arguments. For these functions, calls with constant
1286 ;; arguments can be evaluated at compile time. This may shift run time
1287 ;; errors to compile time.
1288
1289 (let ((pure-fns
1290 '(concat symbol-name regexp-opt regexp-quote string-to-syntax)))
1291 (while pure-fns
1292 (put (car pure-fns) 'pure t)
1293 (setq pure-fns (cdr pure-fns)))
1294 nil)
1295
1296 (defun byte-compile-splice-in-already-compiled-code (form)
1297 ;; form is (byte-code "..." [...] n)
1298 (if (not (memq byte-optimize '(t lap)))
1299 (byte-compile-normal-call form)
1300 (byte-inline-lapcode
1301 (byte-decompile-bytecode-1 (nth 1 form) (nth 2 form) t))
1302 (setq byte-compile-maxdepth (max (+ byte-compile-depth (nth 3 form))
1303 byte-compile-maxdepth))
1304 (setq byte-compile-depth (1+ byte-compile-depth))))
1305
1306 (put 'byte-code 'byte-compile 'byte-compile-splice-in-already-compiled-code)
1307
1308 \f
1309 (defconst byte-constref-ops
1310 '(byte-constant byte-constant2 byte-varref byte-varset byte-varbind))
1311
1312 ;; This function extracts the bitfields from variable-length opcodes.
1313 ;; Originally defined in disass.el (which no longer uses it.)
1314
1315 (defun disassemble-offset ()
1316 "Don't call this!"
1317 ;; fetch and return the offset for the current opcode.
1318 ;; return nil if this opcode has no offset
1319 ;; Used and set dynamically in byte-decompile-bytecode-1.
1320 (defvar bytedecomp-op)
1321 (defvar bytedecomp-ptr)
1322 (defvar bytedecomp-bytes)
1323 (cond ((< bytedecomp-op byte-nth)
1324 (let ((tem (logand bytedecomp-op 7)))
1325 (setq bytedecomp-op (logand bytedecomp-op 248))
1326 (cond ((eq tem 6)
1327 ;; Offset in next byte.
1328 (setq bytedecomp-ptr (1+ bytedecomp-ptr))
1329 (aref bytedecomp-bytes bytedecomp-ptr))
1330 ((eq tem 7)
1331 ;; Offset in next 2 bytes.
1332 (setq bytedecomp-ptr (1+ bytedecomp-ptr))
1333 (+ (aref bytedecomp-bytes bytedecomp-ptr)
1334 (progn (setq bytedecomp-ptr (1+ bytedecomp-ptr))
1335 (lsh (aref bytedecomp-bytes bytedecomp-ptr) 8))))
1336 (t tem)))) ;offset was in opcode
1337 ((>= bytedecomp-op byte-constant)
1338 (prog1 (- bytedecomp-op byte-constant) ;offset in opcode
1339 (setq bytedecomp-op byte-constant)))
1340 ((and (>= bytedecomp-op byte-constant2)
1341 (<= bytedecomp-op byte-goto-if-not-nil-else-pop))
1342 ;; Offset in next 2 bytes.
1343 (setq bytedecomp-ptr (1+ bytedecomp-ptr))
1344 (+ (aref bytedecomp-bytes bytedecomp-ptr)
1345 (progn (setq bytedecomp-ptr (1+ bytedecomp-ptr))
1346 (lsh (aref bytedecomp-bytes bytedecomp-ptr) 8))))
1347 ((and (>= bytedecomp-op byte-listN)
1348 (<= bytedecomp-op byte-insertN))
1349 (setq bytedecomp-ptr (1+ bytedecomp-ptr)) ;offset in next byte
1350 (aref bytedecomp-bytes bytedecomp-ptr))))
1351
1352
1353 ;; This de-compiler is used for inline expansion of compiled functions,
1354 ;; and by the disassembler.
1355 ;;
1356 ;; This list contains numbers, which are pc values,
1357 ;; before each instruction.
1358 (defun byte-decompile-bytecode (bytes constvec)
1359 "Turn BYTECODE into lapcode, referring to CONSTVEC."
1360 (let ((byte-compile-constants nil)
1361 (byte-compile-variables nil)
1362 (byte-compile-tag-number 0))
1363 (byte-decompile-bytecode-1 bytes constvec)))
1364
1365 ;; As byte-decompile-bytecode, but updates
1366 ;; byte-compile-{constants, variables, tag-number}.
1367 ;; If MAKE-SPLICEABLE is true, then `return' opcodes are replaced
1368 ;; with `goto's destined for the end of the code.
1369 ;; That is for use by the compiler.
1370 ;; If MAKE-SPLICEABLE is nil, we are being called for the disassembler.
1371 ;; In that case, we put a pc value into the list
1372 ;; before each insn (or its label).
1373 (defun byte-decompile-bytecode-1 (bytedecomp-bytes constvec
1374 &optional make-spliceable)
1375 (let ((length (length bytedecomp-bytes))
1376 (bytedecomp-ptr 0) optr tags bytedecomp-op offset
1377 lap tmp
1378 endtag)
1379 (while (not (= bytedecomp-ptr length))
1380 (or make-spliceable
1381 (setq lap (cons bytedecomp-ptr lap)))
1382 (setq bytedecomp-op (aref bytedecomp-bytes bytedecomp-ptr)
1383 optr bytedecomp-ptr
1384 offset (disassemble-offset)) ; this does dynamic-scope magic
1385 (setq bytedecomp-op (aref byte-code-vector bytedecomp-op))
1386 (cond ((memq bytedecomp-op byte-goto-ops)
1387 ;; it's a pc
1388 (setq offset
1389 (cdr (or (assq offset tags)
1390 (car (setq tags
1391 (cons (cons offset
1392 (byte-compile-make-tag))
1393 tags)))))))
1394 ((cond ((eq bytedecomp-op 'byte-constant2)
1395 (setq bytedecomp-op 'byte-constant) t)
1396 ((memq bytedecomp-op byte-constref-ops)))
1397 (setq tmp (if (>= offset (length constvec))
1398 (list 'out-of-range offset)
1399 (aref constvec offset))
1400 offset (if (eq bytedecomp-op 'byte-constant)
1401 (byte-compile-get-constant tmp)
1402 (or (assq tmp byte-compile-variables)
1403 (car (setq byte-compile-variables
1404 (cons (list tmp)
1405 byte-compile-variables)))))))
1406 ((and make-spliceable
1407 (eq bytedecomp-op 'byte-return))
1408 (if (= bytedecomp-ptr (1- length))
1409 (setq bytedecomp-op nil)
1410 (setq offset (or endtag (setq endtag (byte-compile-make-tag)))
1411 bytedecomp-op 'byte-goto))))
1412 ;; lap = ( [ (pc . (op . arg)) ]* )
1413 (setq lap (cons (cons optr (cons bytedecomp-op (or offset 0)))
1414 lap))
1415 (setq bytedecomp-ptr (1+ bytedecomp-ptr)))
1416 ;; take off the dummy nil op that we replaced a trailing "return" with.
1417 (let ((rest lap))
1418 (while rest
1419 (cond ((numberp (car rest)))
1420 ((setq tmp (assq (car (car rest)) tags))
1421 ;; this addr is jumped to
1422 (setcdr rest (cons (cons nil (cdr tmp))
1423 (cdr rest)))
1424 (setq tags (delq tmp tags))
1425 (setq rest (cdr rest))))
1426 (setq rest (cdr rest))))
1427 (if tags (error "optimizer error: missed tags %s" tags))
1428 (if (null (car (cdr (car lap))))
1429 (setq lap (cdr lap)))
1430 (if endtag
1431 (setq lap (cons (cons nil endtag) lap)))
1432 ;; remove addrs, lap = ( [ (op . arg) | (TAG tagno) ]* )
1433 (mapcar (function (lambda (elt)
1434 (if (numberp elt)
1435 elt
1436 (cdr elt))))
1437 (nreverse lap))))
1438
1439 \f
1440 ;;; peephole optimizer
1441
1442 (defconst byte-tagref-ops (cons 'TAG byte-goto-ops))
1443
1444 (defconst byte-conditional-ops
1445 '(byte-goto-if-nil byte-goto-if-not-nil byte-goto-if-nil-else-pop
1446 byte-goto-if-not-nil-else-pop))
1447
1448 (defconst byte-after-unbind-ops
1449 '(byte-constant byte-dup
1450 byte-symbolp byte-consp byte-stringp byte-listp byte-numberp byte-integerp
1451 byte-eq byte-not
1452 byte-cons byte-list1 byte-list2 ; byte-list3 byte-list4
1453 byte-interactive-p)
1454 ;; How about other side-effect-free-ops? Is it safe to move an
1455 ;; error invocation (such as from nth) out of an unwind-protect?
1456 ;; No, it is not, because the unwind-protect forms can alter
1457 ;; the inside of the object to which nth would apply.
1458 ;; For the same reason, byte-equal was deleted from this list.
1459 "Byte-codes that can be moved past an unbind.")
1460
1461 (defconst byte-compile-side-effect-and-error-free-ops
1462 '(byte-constant byte-dup byte-symbolp byte-consp byte-stringp byte-listp
1463 byte-integerp byte-numberp byte-eq byte-equal byte-not byte-car-safe
1464 byte-cdr-safe byte-cons byte-list1 byte-list2 byte-point byte-point-max
1465 byte-point-min byte-following-char byte-preceding-char
1466 byte-current-column byte-eolp byte-eobp byte-bolp byte-bobp
1467 byte-current-buffer byte-interactive-p))
1468
1469 (defconst byte-compile-side-effect-free-ops
1470 (nconc
1471 '(byte-varref byte-nth byte-memq byte-car byte-cdr byte-length byte-aref
1472 byte-symbol-value byte-get byte-concat2 byte-concat3 byte-sub1 byte-add1
1473 byte-eqlsign byte-gtr byte-lss byte-leq byte-geq byte-diff byte-negate
1474 byte-plus byte-max byte-min byte-mult byte-char-after byte-char-syntax
1475 byte-buffer-substring byte-string= byte-string< byte-nthcdr byte-elt
1476 byte-member byte-assq byte-quo byte-rem)
1477 byte-compile-side-effect-and-error-free-ops))
1478
1479 ;; This crock is because of the way DEFVAR_BOOL variables work.
1480 ;; Consider the code
1481 ;;
1482 ;; (defun foo (flag)
1483 ;; (let ((old-pop-ups pop-up-windows)
1484 ;; (pop-up-windows flag))
1485 ;; (cond ((not (eq pop-up-windows old-pop-ups))
1486 ;; (setq old-pop-ups pop-up-windows)
1487 ;; ...))))
1488 ;;
1489 ;; Uncompiled, old-pop-ups will always be set to nil or t, even if FLAG is
1490 ;; something else. But if we optimize
1491 ;;
1492 ;; varref flag
1493 ;; varbind pop-up-windows
1494 ;; varref pop-up-windows
1495 ;; not
1496 ;; to
1497 ;; varref flag
1498 ;; dup
1499 ;; varbind pop-up-windows
1500 ;; not
1501 ;;
1502 ;; we break the program, because it will appear that pop-up-windows and
1503 ;; old-pop-ups are not EQ when really they are. So we have to know what
1504 ;; the BOOL variables are, and not perform this optimization on them.
1505
1506 ;; The variable `byte-boolean-vars' is now primitive and updated
1507 ;; automatically by DEFVAR_BOOL.
1508
1509 (defun byte-optimize-lapcode (lap &optional for-effect)
1510 "Simple peephole optimizer. LAP is both modified and returned.
1511 If FOR-EFFECT is non-nil, the return value is assumed to be of no importance."
1512 (let (lap0
1513 lap1
1514 lap2
1515 (keep-going 'first-time)
1516 (add-depth 0)
1517 rest tmp tmp2 tmp3
1518 (side-effect-free (if byte-compile-delete-errors
1519 byte-compile-side-effect-free-ops
1520 byte-compile-side-effect-and-error-free-ops)))
1521 (while keep-going
1522 (or (eq keep-going 'first-time)
1523 (byte-compile-log-lap " ---- next pass"))
1524 (setq rest lap
1525 keep-going nil)
1526 (while rest
1527 (setq lap0 (car rest)
1528 lap1 (nth 1 rest)
1529 lap2 (nth 2 rest))
1530
1531 ;; You may notice that sequences like "dup varset discard" are
1532 ;; optimized but sequences like "dup varset TAG1: discard" are not.
1533 ;; You may be tempted to change this; resist that temptation.
1534 (cond ;;
1535 ;; <side-effect-free> pop --> <deleted>
1536 ;; ...including:
1537 ;; const-X pop --> <deleted>
1538 ;; varref-X pop --> <deleted>
1539 ;; dup pop --> <deleted>
1540 ;;
1541 ((and (eq 'byte-discard (car lap1))
1542 (memq (car lap0) side-effect-free))
1543 (setq keep-going t)
1544 (setq tmp (aref byte-stack+-info (symbol-value (car lap0))))
1545 (setq rest (cdr rest))
1546 (cond ((= tmp 1)
1547 (byte-compile-log-lap
1548 " %s discard\t-->\t<deleted>" lap0)
1549 (setq lap (delq lap0 (delq lap1 lap))))
1550 ((= tmp 0)
1551 (byte-compile-log-lap
1552 " %s discard\t-->\t<deleted> discard" lap0)
1553 (setq lap (delq lap0 lap)))
1554 ((= tmp -1)
1555 (byte-compile-log-lap
1556 " %s discard\t-->\tdiscard discard" lap0)
1557 (setcar lap0 'byte-discard)
1558 (setcdr lap0 0))
1559 ((error "Optimizer error: too much on the stack"))))
1560 ;;
1561 ;; goto*-X X: --> X:
1562 ;;
1563 ((and (memq (car lap0) byte-goto-ops)
1564 (eq (cdr lap0) lap1))
1565 (cond ((eq (car lap0) 'byte-goto)
1566 (setq lap (delq lap0 lap))
1567 (setq tmp "<deleted>"))
1568 ((memq (car lap0) byte-goto-always-pop-ops)
1569 (setcar lap0 (setq tmp 'byte-discard))
1570 (setcdr lap0 0))
1571 ((error "Depth conflict at tag %d" (nth 2 lap0))))
1572 (and (memq byte-optimize-log '(t byte))
1573 (byte-compile-log " (goto %s) %s:\t-->\t%s %s:"
1574 (nth 1 lap1) (nth 1 lap1)
1575 tmp (nth 1 lap1)))
1576 (setq keep-going t))
1577 ;;
1578 ;; varset-X varref-X --> dup varset-X
1579 ;; varbind-X varref-X --> dup varbind-X
1580 ;; const/dup varset-X varref-X --> const/dup varset-X const/dup
1581 ;; const/dup varbind-X varref-X --> const/dup varbind-X const/dup
1582 ;; The latter two can enable other optimizations.
1583 ;;
1584 ((and (eq 'byte-varref (car lap2))
1585 (eq (cdr lap1) (cdr lap2))
1586 (memq (car lap1) '(byte-varset byte-varbind)))
1587 (if (and (setq tmp (memq (car (cdr lap2)) byte-boolean-vars))
1588 (not (eq (car lap0) 'byte-constant)))
1589 nil
1590 (setq keep-going t)
1591 (if (memq (car lap0) '(byte-constant byte-dup))
1592 (progn
1593 (setq tmp (if (or (not tmp)
1594 (byte-compile-const-symbol-p
1595 (car (cdr lap0))))
1596 (cdr lap0)
1597 (byte-compile-get-constant t)))
1598 (byte-compile-log-lap " %s %s %s\t-->\t%s %s %s"
1599 lap0 lap1 lap2 lap0 lap1
1600 (cons (car lap0) tmp))
1601 (setcar lap2 (car lap0))
1602 (setcdr lap2 tmp))
1603 (byte-compile-log-lap " %s %s\t-->\tdup %s" lap1 lap2 lap1)
1604 (setcar lap2 (car lap1))
1605 (setcar lap1 'byte-dup)
1606 (setcdr lap1 0)
1607 ;; The stack depth gets locally increased, so we will
1608 ;; increase maxdepth in case depth = maxdepth here.
1609 ;; This can cause the third argument to byte-code to
1610 ;; be larger than necessary.
1611 (setq add-depth 1))))
1612 ;;
1613 ;; dup varset-X discard --> varset-X
1614 ;; dup varbind-X discard --> varbind-X
1615 ;; (the varbind variant can emerge from other optimizations)
1616 ;;
1617 ((and (eq 'byte-dup (car lap0))
1618 (eq 'byte-discard (car lap2))
1619 (memq (car lap1) '(byte-varset byte-varbind)))
1620 (byte-compile-log-lap " dup %s discard\t-->\t%s" lap1 lap1)
1621 (setq keep-going t
1622 rest (cdr rest))
1623 (setq lap (delq lap0 (delq lap2 lap))))
1624 ;;
1625 ;; not goto-X-if-nil --> goto-X-if-non-nil
1626 ;; not goto-X-if-non-nil --> goto-X-if-nil
1627 ;;
1628 ;; it is wrong to do the same thing for the -else-pop variants.
1629 ;;
1630 ((and (eq 'byte-not (car lap0))
1631 (or (eq 'byte-goto-if-nil (car lap1))
1632 (eq 'byte-goto-if-not-nil (car lap1))))
1633 (byte-compile-log-lap " not %s\t-->\t%s"
1634 lap1
1635 (cons
1636 (if (eq (car lap1) 'byte-goto-if-nil)
1637 'byte-goto-if-not-nil
1638 'byte-goto-if-nil)
1639 (cdr lap1)))
1640 (setcar lap1 (if (eq (car lap1) 'byte-goto-if-nil)
1641 'byte-goto-if-not-nil
1642 'byte-goto-if-nil))
1643 (setq lap (delq lap0 lap))
1644 (setq keep-going t))
1645 ;;
1646 ;; goto-X-if-nil goto-Y X: --> goto-Y-if-non-nil X:
1647 ;; goto-X-if-non-nil goto-Y X: --> goto-Y-if-nil X:
1648 ;;
1649 ;; it is wrong to do the same thing for the -else-pop variants.
1650 ;;
1651 ((and (or (eq 'byte-goto-if-nil (car lap0))
1652 (eq 'byte-goto-if-not-nil (car lap0))) ; gotoX
1653 (eq 'byte-goto (car lap1)) ; gotoY
1654 (eq (cdr lap0) lap2)) ; TAG X
1655 (let ((inverse (if (eq 'byte-goto-if-nil (car lap0))
1656 'byte-goto-if-not-nil 'byte-goto-if-nil)))
1657 (byte-compile-log-lap " %s %s %s:\t-->\t%s %s:"
1658 lap0 lap1 lap2
1659 (cons inverse (cdr lap1)) lap2)
1660 (setq lap (delq lap0 lap))
1661 (setcar lap1 inverse)
1662 (setq keep-going t)))
1663 ;;
1664 ;; const goto-if-* --> whatever
1665 ;;
1666 ((and (eq 'byte-constant (car lap0))
1667 (memq (car lap1) byte-conditional-ops))
1668 (cond ((if (or (eq (car lap1) 'byte-goto-if-nil)
1669 (eq (car lap1) 'byte-goto-if-nil-else-pop))
1670 (car (cdr lap0))
1671 (not (car (cdr lap0))))
1672 (byte-compile-log-lap " %s %s\t-->\t<deleted>"
1673 lap0 lap1)
1674 (setq rest (cdr rest)
1675 lap (delq lap0 (delq lap1 lap))))
1676 (t
1677 (if (memq (car lap1) byte-goto-always-pop-ops)
1678 (progn
1679 (byte-compile-log-lap " %s %s\t-->\t%s"
1680 lap0 lap1 (cons 'byte-goto (cdr lap1)))
1681 (setq lap (delq lap0 lap)))
1682 (byte-compile-log-lap " %s %s\t-->\t%s" lap0 lap1
1683 (cons 'byte-goto (cdr lap1))))
1684 (setcar lap1 'byte-goto)))
1685 (setq keep-going t))
1686 ;;
1687 ;; varref-X varref-X --> varref-X dup
1688 ;; varref-X [dup ...] varref-X --> varref-X [dup ...] dup
1689 ;; We don't optimize the const-X variations on this here,
1690 ;; because that would inhibit some goto optimizations; we
1691 ;; optimize the const-X case after all other optimizations.
1692 ;;
1693 ((and (eq 'byte-varref (car lap0))
1694 (progn
1695 (setq tmp (cdr rest))
1696 (while (eq (car (car tmp)) 'byte-dup)
1697 (setq tmp (cdr tmp)))
1698 t)
1699 (eq (cdr lap0) (cdr (car tmp)))
1700 (eq 'byte-varref (car (car tmp))))
1701 (if (memq byte-optimize-log '(t byte))
1702 (let ((str ""))
1703 (setq tmp2 (cdr rest))
1704 (while (not (eq tmp tmp2))
1705 (setq tmp2 (cdr tmp2)
1706 str (concat str " dup")))
1707 (byte-compile-log-lap " %s%s %s\t-->\t%s%s dup"
1708 lap0 str lap0 lap0 str)))
1709 (setq keep-going t)
1710 (setcar (car tmp) 'byte-dup)
1711 (setcdr (car tmp) 0)
1712 (setq rest tmp))
1713 ;;
1714 ;; TAG1: TAG2: --> TAG1: <deleted>
1715 ;; (and other references to TAG2 are replaced with TAG1)
1716 ;;
1717 ((and (eq (car lap0) 'TAG)
1718 (eq (car lap1) 'TAG))
1719 (and (memq byte-optimize-log '(t byte))
1720 (byte-compile-log " adjacent tags %d and %d merged"
1721 (nth 1 lap1) (nth 1 lap0)))
1722 (setq tmp3 lap)
1723 (while (setq tmp2 (rassq lap0 tmp3))
1724 (setcdr tmp2 lap1)
1725 (setq tmp3 (cdr (memq tmp2 tmp3))))
1726 (setq lap (delq lap0 lap)
1727 keep-going t))
1728 ;;
1729 ;; unused-TAG: --> <deleted>
1730 ;;
1731 ((and (eq 'TAG (car lap0))
1732 (not (rassq lap0 lap)))
1733 (and (memq byte-optimize-log '(t byte))
1734 (byte-compile-log " unused tag %d removed" (nth 1 lap0)))
1735 (setq lap (delq lap0 lap)
1736 keep-going t))
1737 ;;
1738 ;; goto ... --> goto <delete until TAG or end>
1739 ;; return ... --> return <delete until TAG or end>
1740 ;;
1741 ((and (memq (car lap0) '(byte-goto byte-return))
1742 (not (memq (car lap1) '(TAG nil))))
1743 (setq tmp rest)
1744 (let ((i 0)
1745 (opt-p (memq byte-optimize-log '(t lap)))
1746 str deleted)
1747 (while (and (setq tmp (cdr tmp))
1748 (not (eq 'TAG (car (car tmp)))))
1749 (if opt-p (setq deleted (cons (car tmp) deleted)
1750 str (concat str " %s")
1751 i (1+ i))))
1752 (if opt-p
1753 (let ((tagstr
1754 (if (eq 'TAG (car (car tmp)))
1755 (format "%d:" (car (cdr (car tmp))))
1756 (or (car tmp) ""))))
1757 (if (< i 6)
1758 (apply 'byte-compile-log-lap-1
1759 (concat " %s" str
1760 " %s\t-->\t%s <deleted> %s")
1761 lap0
1762 (nconc (nreverse deleted)
1763 (list tagstr lap0 tagstr)))
1764 (byte-compile-log-lap
1765 " %s <%d unreachable op%s> %s\t-->\t%s <deleted> %s"
1766 lap0 i (if (= i 1) "" "s")
1767 tagstr lap0 tagstr))))
1768 (rplacd rest tmp))
1769 (setq keep-going t))
1770 ;;
1771 ;; <safe-op> unbind --> unbind <safe-op>
1772 ;; (this may enable other optimizations.)
1773 ;;
1774 ((and (eq 'byte-unbind (car lap1))
1775 (memq (car lap0) byte-after-unbind-ops))
1776 (byte-compile-log-lap " %s %s\t-->\t%s %s" lap0 lap1 lap1 lap0)
1777 (setcar rest lap1)
1778 (setcar (cdr rest) lap0)
1779 (setq keep-going t))
1780 ;;
1781 ;; varbind-X unbind-N --> discard unbind-(N-1)
1782 ;; save-excursion unbind-N --> unbind-(N-1)
1783 ;; save-restriction unbind-N --> unbind-(N-1)
1784 ;;
1785 ((and (eq 'byte-unbind (car lap1))
1786 (memq (car lap0) '(byte-varbind byte-save-excursion
1787 byte-save-restriction))
1788 (< 0 (cdr lap1)))
1789 (if (zerop (setcdr lap1 (1- (cdr lap1))))
1790 (delq lap1 rest))
1791 (if (eq (car lap0) 'byte-varbind)
1792 (setcar rest (cons 'byte-discard 0))
1793 (setq lap (delq lap0 lap)))
1794 (byte-compile-log-lap " %s %s\t-->\t%s %s"
1795 lap0 (cons (car lap1) (1+ (cdr lap1)))
1796 (if (eq (car lap0) 'byte-varbind)
1797 (car rest)
1798 (car (cdr rest)))
1799 (if (and (/= 0 (cdr lap1))
1800 (eq (car lap0) 'byte-varbind))
1801 (car (cdr rest))
1802 ""))
1803 (setq keep-going t))
1804 ;;
1805 ;; goto*-X ... X: goto-Y --> goto*-Y
1806 ;; goto-X ... X: return --> return
1807 ;;
1808 ((and (memq (car lap0) byte-goto-ops)
1809 (memq (car (setq tmp (nth 1 (memq (cdr lap0) lap))))
1810 '(byte-goto byte-return)))
1811 (cond ((and (not (eq tmp lap0))
1812 (or (eq (car lap0) 'byte-goto)
1813 (eq (car tmp) 'byte-goto)))
1814 (byte-compile-log-lap " %s [%s]\t-->\t%s"
1815 (car lap0) tmp tmp)
1816 (if (eq (car tmp) 'byte-return)
1817 (setcar lap0 'byte-return))
1818 (setcdr lap0 (cdr tmp))
1819 (setq keep-going t))))
1820 ;;
1821 ;; goto-*-else-pop X ... X: goto-if-* --> whatever
1822 ;; goto-*-else-pop X ... X: discard --> whatever
1823 ;;
1824 ((and (memq (car lap0) '(byte-goto-if-nil-else-pop
1825 byte-goto-if-not-nil-else-pop))
1826 (memq (car (car (setq tmp (cdr (memq (cdr lap0) lap)))))
1827 (eval-when-compile
1828 (cons 'byte-discard byte-conditional-ops)))
1829 (not (eq lap0 (car tmp))))
1830 (setq tmp2 (car tmp))
1831 (setq tmp3 (assq (car lap0) '((byte-goto-if-nil-else-pop
1832 byte-goto-if-nil)
1833 (byte-goto-if-not-nil-else-pop
1834 byte-goto-if-not-nil))))
1835 (if (memq (car tmp2) tmp3)
1836 (progn (setcar lap0 (car tmp2))
1837 (setcdr lap0 (cdr tmp2))
1838 (byte-compile-log-lap " %s-else-pop [%s]\t-->\t%s"
1839 (car lap0) tmp2 lap0))
1840 ;; Get rid of the -else-pop's and jump one step further.
1841 (or (eq 'TAG (car (nth 1 tmp)))
1842 (setcdr tmp (cons (byte-compile-make-tag)
1843 (cdr tmp))))
1844 (byte-compile-log-lap " %s [%s]\t-->\t%s <skip>"
1845 (car lap0) tmp2 (nth 1 tmp3))
1846 (setcar lap0 (nth 1 tmp3))
1847 (setcdr lap0 (nth 1 tmp)))
1848 (setq keep-going t))
1849 ;;
1850 ;; const goto-X ... X: goto-if-* --> whatever
1851 ;; const goto-X ... X: discard --> whatever
1852 ;;
1853 ((and (eq (car lap0) 'byte-constant)
1854 (eq (car lap1) 'byte-goto)
1855 (memq (car (car (setq tmp (cdr (memq (cdr lap1) lap)))))
1856 (eval-when-compile
1857 (cons 'byte-discard byte-conditional-ops)))
1858 (not (eq lap1 (car tmp))))
1859 (setq tmp2 (car tmp))
1860 (cond ((memq (car tmp2)
1861 (if (null (car (cdr lap0)))
1862 '(byte-goto-if-nil byte-goto-if-nil-else-pop)
1863 '(byte-goto-if-not-nil
1864 byte-goto-if-not-nil-else-pop)))
1865 (byte-compile-log-lap " %s goto [%s]\t-->\t%s %s"
1866 lap0 tmp2 lap0 tmp2)
1867 (setcar lap1 (car tmp2))
1868 (setcdr lap1 (cdr tmp2))
1869 ;; Let next step fix the (const,goto-if*) sequence.
1870 (setq rest (cons nil rest)))
1871 (t
1872 ;; Jump one step further
1873 (byte-compile-log-lap
1874 " %s goto [%s]\t-->\t<deleted> goto <skip>"
1875 lap0 tmp2)
1876 (or (eq 'TAG (car (nth 1 tmp)))
1877 (setcdr tmp (cons (byte-compile-make-tag)
1878 (cdr tmp))))
1879 (setcdr lap1 (car (cdr tmp)))
1880 (setq lap (delq lap0 lap))))
1881 (setq keep-going t))
1882 ;;
1883 ;; X: varref-Y ... varset-Y goto-X -->
1884 ;; X: varref-Y Z: ... dup varset-Y goto-Z
1885 ;; (varset-X goto-BACK, BACK: varref-X --> copy the varref down.)
1886 ;; (This is so usual for while loops that it is worth handling).
1887 ;;
1888 ((and (eq (car lap1) 'byte-varset)
1889 (eq (car lap2) 'byte-goto)
1890 (not (memq (cdr lap2) rest)) ;Backwards jump
1891 (eq (car (car (setq tmp (cdr (memq (cdr lap2) lap)))))
1892 'byte-varref)
1893 (eq (cdr (car tmp)) (cdr lap1))
1894 (not (memq (car (cdr lap1)) byte-boolean-vars)))
1895 ;;(byte-compile-log-lap " Pulled %s to end of loop" (car tmp))
1896 (let ((newtag (byte-compile-make-tag)))
1897 (byte-compile-log-lap
1898 " %s: %s ... %s %s\t-->\t%s: %s %s: ... %s %s %s"
1899 (nth 1 (cdr lap2)) (car tmp)
1900 lap1 lap2
1901 (nth 1 (cdr lap2)) (car tmp)
1902 (nth 1 newtag) 'byte-dup lap1
1903 (cons 'byte-goto newtag)
1904 )
1905 (setcdr rest (cons (cons 'byte-dup 0) (cdr rest)))
1906 (setcdr tmp (cons (setcdr lap2 newtag) (cdr tmp))))
1907 (setq add-depth 1)
1908 (setq keep-going t))
1909 ;;
1910 ;; goto-X Y: ... X: goto-if*-Y --> goto-if-not-*-X+1 Y:
1911 ;; (This can pull the loop test to the end of the loop)
1912 ;;
1913 ((and (eq (car lap0) 'byte-goto)
1914 (eq (car lap1) 'TAG)
1915 (eq lap1
1916 (cdr (car (setq tmp (cdr (memq (cdr lap0) lap))))))
1917 (memq (car (car tmp))
1918 '(byte-goto byte-goto-if-nil byte-goto-if-not-nil
1919 byte-goto-if-nil-else-pop)))
1920 ;; (byte-compile-log-lap " %s %s, %s %s --> moved conditional"
1921 ;; lap0 lap1 (cdr lap0) (car tmp))
1922 (let ((newtag (byte-compile-make-tag)))
1923 (byte-compile-log-lap
1924 "%s %s: ... %s: %s\t-->\t%s ... %s:"
1925 lap0 (nth 1 lap1) (nth 1 (cdr lap0)) (car tmp)
1926 (cons (cdr (assq (car (car tmp))
1927 '((byte-goto-if-nil . byte-goto-if-not-nil)
1928 (byte-goto-if-not-nil . byte-goto-if-nil)
1929 (byte-goto-if-nil-else-pop .
1930 byte-goto-if-not-nil-else-pop)
1931 (byte-goto-if-not-nil-else-pop .
1932 byte-goto-if-nil-else-pop))))
1933 newtag)
1934
1935 (nth 1 newtag)
1936 )
1937 (setcdr tmp (cons (setcdr lap0 newtag) (cdr tmp)))
1938 (if (eq (car (car tmp)) 'byte-goto-if-nil-else-pop)
1939 ;; We can handle this case but not the -if-not-nil case,
1940 ;; because we won't know which non-nil constant to push.
1941 (setcdr rest (cons (cons 'byte-constant
1942 (byte-compile-get-constant nil))
1943 (cdr rest))))
1944 (setcar lap0 (nth 1 (memq (car (car tmp))
1945 '(byte-goto-if-nil-else-pop
1946 byte-goto-if-not-nil
1947 byte-goto-if-nil
1948 byte-goto-if-not-nil
1949 byte-goto byte-goto))))
1950 )
1951 (setq keep-going t))
1952 )
1953 (setq rest (cdr rest)))
1954 )
1955 ;; Cleanup stage:
1956 ;; Rebuild byte-compile-constants / byte-compile-variables.
1957 ;; Simple optimizations that would inhibit other optimizations if they
1958 ;; were done in the optimizing loop, and optimizations which there is no
1959 ;; need to do more than once.
1960 (setq byte-compile-constants nil
1961 byte-compile-variables nil)
1962 (setq rest lap)
1963 (while rest
1964 (setq lap0 (car rest)
1965 lap1 (nth 1 rest))
1966 (if (memq (car lap0) byte-constref-ops)
1967 (if (or (eq (car lap0) 'byte-constant)
1968 (eq (car lap0) 'byte-constant2))
1969 (unless (memq (cdr lap0) byte-compile-constants)
1970 (setq byte-compile-constants (cons (cdr lap0)
1971 byte-compile-constants)))
1972 (unless (memq (cdr lap0) byte-compile-variables)
1973 (setq byte-compile-variables (cons (cdr lap0)
1974 byte-compile-variables)))))
1975 (cond (;;
1976 ;; const-C varset-X const-C --> const-C dup varset-X
1977 ;; const-C varbind-X const-C --> const-C dup varbind-X
1978 ;;
1979 (and (eq (car lap0) 'byte-constant)
1980 (eq (car (nth 2 rest)) 'byte-constant)
1981 (eq (cdr lap0) (cdr (nth 2 rest)))
1982 (memq (car lap1) '(byte-varbind byte-varset)))
1983 (byte-compile-log-lap " %s %s %s\t-->\t%s dup %s"
1984 lap0 lap1 lap0 lap0 lap1)
1985 (setcar (cdr (cdr rest)) (cons (car lap1) (cdr lap1)))
1986 (setcar (cdr rest) (cons 'byte-dup 0))
1987 (setq add-depth 1))
1988 ;;
1989 ;; const-X [dup/const-X ...] --> const-X [dup ...] dup
1990 ;; varref-X [dup/varref-X ...] --> varref-X [dup ...] dup
1991 ;;
1992 ((memq (car lap0) '(byte-constant byte-varref))
1993 (setq tmp rest
1994 tmp2 nil)
1995 (while (progn
1996 (while (eq 'byte-dup (car (car (setq tmp (cdr tmp))))))
1997 (and (eq (cdr lap0) (cdr (car tmp)))
1998 (eq (car lap0) (car (car tmp)))))
1999 (setcar tmp (cons 'byte-dup 0))
2000 (setq tmp2 t))
2001 (if tmp2
2002 (byte-compile-log-lap
2003 " %s [dup/%s]...\t-->\t%s dup..." lap0 lap0 lap0)))
2004 ;;
2005 ;; unbind-N unbind-M --> unbind-(N+M)
2006 ;;
2007 ((and (eq 'byte-unbind (car lap0))
2008 (eq 'byte-unbind (car lap1)))
2009 (byte-compile-log-lap " %s %s\t-->\t%s" lap0 lap1
2010 (cons 'byte-unbind
2011 (+ (cdr lap0) (cdr lap1))))
2012 (setq keep-going t)
2013 (setq lap (delq lap0 lap))
2014 (setcdr lap1 (+ (cdr lap1) (cdr lap0))))
2015 )
2016 (setq rest (cdr rest)))
2017 (setq byte-compile-maxdepth (+ byte-compile-maxdepth add-depth)))
2018 lap)
2019
2020 (provide 'byte-opt)
2021
2022 \f
2023 ;; To avoid "lisp nesting exceeds max-lisp-eval-depth" when this file compiles
2024 ;; itself, compile some of its most used recursive functions (at load time).
2025 ;;
2026 (eval-when-compile
2027 (or (byte-code-function-p (symbol-function 'byte-optimize-form))
2028 (assq 'byte-code (symbol-function 'byte-optimize-form))
2029 (let ((byte-optimize nil)
2030 (byte-compile-warnings nil))
2031 (mapc (lambda (x)
2032 (or noninteractive (message "compiling %s..." x))
2033 (byte-compile x)
2034 (or noninteractive (message "compiling %s...done" x)))
2035 '(byte-optimize-form
2036 byte-optimize-body
2037 byte-optimize-predicate
2038 byte-optimize-binary-predicate
2039 ;; Inserted some more than necessary, to speed it up.
2040 byte-optimize-form-code-walker
2041 byte-optimize-lapcode))))
2042 nil)
2043
2044 ;;; byte-opt.el ends here