1 ;;; byte-opt.el --- the optimization passes of the emacs-lisp byte compiler
3 ;; Copyright (C) 1991, 1994, 2000-2011 Free Software Foundation, Inc.
5 ;; Author: Jamie Zawinski <jwz@lucid.com>
6 ;; Hallvard Furuseth <hbf@ulrik.uio.no>
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
28 ;; ========================================================================
29 ;; "No matter how hard you try, you can't make a racehorse out of a pig.
30 ;; You can, however, make a faster pig."
32 ;; Or, to put it another way, the Emacs byte compiler is a VW Bug. This code
33 ;; makes it be a VW Bug with fuel injection and a turbocharger... You're
34 ;; still not going to make it go faster than 70 mph, but it might be easier
40 ;; (apply (lambda (x &rest y) ...) 1 (foo))
42 ;; maintain a list of functions known not to access any global variables
43 ;; (actually, give them a 'dynamically-safe property) and then
44 ;; (let ( v1 v2 ... vM vN ) <...dynamically-safe...> ) ==>
45 ;; (let ( v1 v2 ... vM ) vN <...dynamically-safe...> )
46 ;; by recursing on this, we might be able to eliminate the entire let.
47 ;; However certain variables should never have their bindings optimized
48 ;; away, because they affect everything.
49 ;; (put 'debug-on-error 'binding-is-magic t)
50 ;; (put 'debug-on-abort 'binding-is-magic t)
51 ;; (put 'debug-on-next-call 'binding-is-magic t)
52 ;; (put 'inhibit-quit 'binding-is-magic t)
53 ;; (put 'quit-flag 'binding-is-magic t)
54 ;; (put 't 'binding-is-magic t)
55 ;; (put 'nil 'binding-is-magic t)
57 ;; (put 'gc-cons-threshold 'binding-is-magic t)
58 ;; (put 'track-mouse 'binding-is-magic t)
61 ;; Simple defsubsts often produce forms like
62 ;; (let ((v1 (f1)) (v2 (f2)) ...)
64 ;; It would be nice if we could optimize this to
66 ;; but we can't unless FN is dynamically-safe (it might be dynamically
67 ;; referring to the bindings that the lambda arglist established.)
68 ;; One of the uncountable lossages introduced by dynamic scope...
70 ;; Maybe there should be a control-structure that says "turn on
71 ;; fast-and-loose type-assumptive optimizations here." Then when
72 ;; we see a form like (car foo) we can from then on assume that
73 ;; the variable foo is of type cons, and optimize based on that.
74 ;; But, this won't win much because of (you guessed it) dynamic
75 ;; scope. Anything down the stack could change the value.
76 ;; (Another reason it doesn't work is that it is perfectly valid
77 ;; to call car with a null argument.) A better approach might
78 ;; be to allow type-specification of the form
79 ;; (put 'foo 'arg-types '(float (list integer) dynamic))
80 ;; (put 'foo 'result-type 'bool)
81 ;; It should be possible to have these types checked to a certain
84 ;; collapse common subexpressions
86 ;; It would be nice if redundant sequences could be factored out as well,
87 ;; when they are known to have no side-effects:
88 ;; (list (+ a b c) (+ a b c)) --> a b add c add dup list-2
89 ;; but beware of traps like
90 ;; (cons (list x y) (list x y))
92 ;; Tail-recursion elimination is not really possible in Emacs Lisp.
93 ;; Tail-recursion elimination is almost always impossible when all variables
94 ;; have dynamic scope, but given that the "return" byteop requires the
95 ;; binding stack to be empty (rather than emptying it itself), there can be
96 ;; no truly tail-recursive Emacs Lisp functions that take any arguments or
99 ;; Here is an example of an Emacs Lisp function which could safely be
100 ;; byte-compiled tail-recursively:
102 ;; (defun tail-map (fn list)
104 ;; (funcall fn (car list))
105 ;; (tail-map fn (cdr list)))))
107 ;; However, if there was even a single let-binding around the COND,
108 ;; it could not be byte-compiled, because there would be an "unbind"
109 ;; byte-op between the final "call" and "return." Adding a
110 ;; Bunbind_all byteop would fix this.
112 ;; (defun foo (x y z) ... (foo a b c))
113 ;; ... (const foo) (varref a) (varref b) (varref c) (call 3) END: (return)
114 ;; ... (varref a) (varbind x) (varref b) (varbind y) (varref c) (varbind z) (goto 0) END: (unbind-all) (return)
115 ;; ... (varref a) (varset x) (varref b) (varset y) (varref c) (varset z) (goto 0) END: (return)
117 ;; this also can be considered tail recursion:
119 ;; ... (const foo) (varref a) (call 1) (goto X) ... X: (return)
120 ;; could generalize this by doing the optimization
121 ;; (goto X) ... X: (return) --> (return)
123 ;; But this doesn't solve all of the problems: although by doing tail-
124 ;; recursion elimination in this way, the call-stack does not grow, the
125 ;; binding-stack would grow with each recursive step, and would eventually
126 ;; overflow. I don't believe there is any way around this without lexical
129 ;; Wouldn't it be nice if Emacs Lisp had lexical scope.
131 ;; Idea: the form (lexical-scope) in a file means that the file may be
132 ;; compiled lexically. This proclamation is file-local. Then, within
133 ;; that file, "let" would establish lexical bindings, and "let-dynamic"
134 ;; would do things the old way. (Or we could use CL "declare" forms.)
135 ;; We'd have to notice defvars and defconsts, since those variables should
136 ;; always be dynamic, and attempting to do a lexical binding of them
137 ;; should simply do a dynamic binding instead.
138 ;; But! We need to know about variables that were not necessarily defvarred
139 ;; in the file being compiled (doing a boundp check isn't good enough.)
140 ;; Fdefvar() would have to be modified to add something to the plist.
142 ;; A major disadvantage of this scheme is that the interpreter and compiler
143 ;; would have different semantics for files compiled with (dynamic-scope).
144 ;; Since this would be a file-local optimization, there would be no way to
145 ;; modify the interpreter to obey this (unless the loader was hacked
146 ;; in some grody way, but that's a really bad idea.)
148 ;; Other things to consider:
150 ;; ;; Associative math should recognize subcalls to identical function:
151 ;; (disassemble (lambda (x) (+ (+ (foo) 1) (+ (bar) 2))))
152 ;; ;; This should generate the same as (1+ x) and (1- x)
154 ;; (disassemble (lambda (x) (cons (+ x 1) (- x 1))))
155 ;; ;; An awful lot of functions always return a non-nil value. If they're
156 ;; ;; error free also they may act as true-constants.
158 ;; (disassemble (lambda (x) (and (point) (foo))))
160 ;; ;; - all but one arguments to a function are constant
161 ;; ;; - the non-constant argument is an if-expression (cond-expression?)
162 ;; ;; then the outer function can be distributed. If the guarding
163 ;; ;; condition is side-effect-free [assignment-free] then the other
164 ;; ;; arguments may be any expressions. Since, however, the code size
165 ;; ;; can increase this way they should be "simple". Compare:
167 ;; (disassemble (lambda (x) (eq (if (point) 'a 'b) 'c)))
168 ;; (disassemble (lambda (x) (if (point) (eq 'a 'c) (eq 'b 'c))))
170 ;; ;; (car (cons A B)) -> (prog1 A B)
171 ;; (disassemble (lambda (x) (car (cons (foo) 42))))
173 ;; ;; (cdr (cons A B)) -> (progn A B)
174 ;; (disassemble (lambda (x) (cdr (cons 42 (foo)))))
176 ;; ;; (car (list A B ...)) -> (prog1 A B ...)
177 ;; (disassemble (lambda (x) (car (list (foo) 42 (bar)))))
179 ;; ;; (cdr (list A B ...)) -> (progn A (list B ...))
180 ;; (disassemble (lambda (x) (cdr (list 42 (foo) (bar)))))
186 (eval-when-compile (require 'cl))
188 (defun byte-compile-log-lap-1 (format &rest args)
189 ;; Newer byte codes for stack-ref make the slot 0 non-nil again.
190 ;; But the "old disassembler" is *really* ancient by now.
191 ;; (if (aref byte-code-vector 0)
192 ;; (error "The old version of the disassembler is loaded. Reload new-bytecomp as well"))
194 (apply 'format format
196 (mapcar (lambda (arg)
197 (if (not (consp arg))
198 (if (and (symbolp arg)
199 (string-match "^byte-" (symbol-name arg)))
200 (intern (substring (symbol-name arg) 5))
202 (if (integerp (setq c (car arg)))
203 (error "non-symbolic byte-op %s" c))
206 (setq a (cond ((memq c byte-goto-ops)
207 (car (cdr (cdr arg))))
208 ((memq c byte-constref-ops)
211 (setq c (symbol-name c))
212 (if (string-match "^byte-." c)
213 (setq c (intern (substring c 5)))))
214 (if (eq c 'constant) (setq c 'const))
215 (if (and (eq (cdr arg) 0)
216 (not (memq c '(unbind call const))))
218 (format "(%s %s)" c a))))
221 (defmacro byte-compile-log-lap (format-string &rest args)
222 `(and (memq byte-optimize-log '(t byte))
223 (byte-compile-log-lap-1 ,format-string ,@args)))
226 ;;; byte-compile optimizers to support inlining
228 (put 'inline 'byte-optimizer 'byte-optimize-inline-handler)
230 (defun byte-optimize-inline-handler (form)
231 "byte-optimize-handler for the `inline' special-form."
235 (let ((f (car-safe sexp)))
237 (or (cdr (assq f byte-compile-function-environment))
238 (not (or (not (fboundp f))
239 (cdr (assq f byte-compile-macro-environment))
240 (and (consp (setq f (symbol-function f)))
243 (byte-compile-inline-expand sexp)
248 ;; Splice the given lap code into the current instruction stream.
249 ;; If it has any labels in it, you're responsible for making sure there
250 ;; are no collisions, and that byte-compile-tag-number is reasonable
251 ;; after this is spliced in. The provided list is destroyed.
252 (defun byte-inline-lapcode (lap)
253 ;; "Replay" the operations: we used to just do
254 ;; (setq byte-compile-output (nconc (nreverse lap) byte-compile-output))
255 ;; but that fails to update byte-compile-depth, so we had to assume
256 ;; that `lap' ends up adding exactly 1 element to the stack. This
257 ;; happens to be true for byte-code generated by bytecomp.el without
258 ;; lexical-binding, but it's not true in general, and it's not true for
259 ;; code output by bytecomp.el with lexical-binding.
262 ((eq (car op) 'TAG) (byte-compile-out-tag op))
263 ((memq (car op) byte-goto-ops) (byte-compile-goto (car op) (cdr op)))
264 (t (byte-compile-out (car op) (cdr op))))))
266 (defun byte-compile-inline-expand (form)
267 (let* ((name (car form))
268 (fn (or (cdr (assq name byte-compile-function-environment))
269 (and (fboundp name) (symbol-function name)))))
272 (byte-compile-warn "attempt to inline `%s' before it was defined"
276 (when (and (consp fn) (eq (car fn) 'autoload))
278 (setq fn (or (and (fboundp name) (symbol-function name))
279 (cdr (assq name byte-compile-function-environment)))))
280 (if (and (consp fn) (eq (car fn) 'autoload))
281 (error "File `%s' didn't define `%s'" (nth 1 fn) name))
283 ((and (symbolp fn) (not (eq fn t))) ;A function alias.
284 (byte-compile-inline-expand (cons fn (cdr form))))
285 ((and (byte-code-function-p fn)
286 ;; FIXME: This works to inline old-style-byte-codes into
287 ;; old-style-byte-codes, but not mixed cases (not sure
288 ;; about new-style into new-style).
289 (not lexical-binding)
290 (not (and (>= (length fn) 7)
291 (aref fn 6)))) ;6 = COMPILED_PUSH_ARGS
292 ;; (message "Inlining %S byte-code" name)
294 (let ((string (aref fn 1)))
295 ;; Isn't it an error for `string' not to be unibyte?? --stef
296 (if (fboundp 'string-as-unibyte)
297 (setq string (string-as-unibyte string)))
298 ;; `byte-compile-splice-in-already-compiled-code'
299 ;; takes care of inlining the body.
300 (cons `(lambda ,(aref fn 0)
301 (byte-code ,string ,(aref fn 2) ,(aref fn 3)))
303 ((eq (car-safe fn) 'lambda)
304 (macroexpand-all (cons fn (cdr form))
305 byte-compile-macro-environment))
306 (t ;; Give up on inlining.
309 ;; ((lambda ...) ...)
310 (defun byte-compile-unfold-lambda (form &optional name)
311 (or name (setq name "anonymous lambda"))
312 (let ((lambda (car form))
314 (if (byte-code-function-p lambda)
315 (setq lambda (list 'lambda (aref lambda 0)
316 (list 'byte-code (aref lambda 1)
317 (aref lambda 2) (aref lambda 3)))))
318 (let ((arglist (nth 1 lambda))
319 (body (cdr (cdr lambda)))
322 (if (and (stringp (car body)) (cdr body))
323 (setq body (cdr body)))
324 (if (and (consp (car body)) (eq 'interactive (car (car body))))
325 (setq body (cdr body)))
327 (cond ((eq (car arglist) '&optional)
328 ;; ok, I'll let this slide because funcall_lambda() does...
329 ;; (if optionalp (error "multiple &optional keywords in %s" name))
330 (if restp (error "&optional found after &rest in %s" name))
331 (if (null (cdr arglist))
332 (error "nothing after &optional in %s" name))
334 ((eq (car arglist) '&rest)
335 ;; ...but it is by no stretch of the imagination a reasonable
336 ;; thing that funcall_lambda() allows (&rest x y) and
337 ;; (&rest x &optional y) in arglists.
338 (if (null (cdr arglist))
339 (error "nothing after &rest in %s" name))
340 (if (cdr (cdr arglist))
341 (error "multiple vars after &rest in %s" name))
344 (setq bindings (cons (list (car arglist)
345 (and values (cons 'list values)))
348 ((and (not optionalp) (null values))
349 (byte-compile-warn "attempt to open-code `%s' with too few arguments" name)
350 (setq arglist nil values 'too-few))
352 (setq bindings (cons (list (car arglist) (car values))
354 values (cdr values))))
355 (setq arglist (cdr arglist)))
358 (or (eq values 'too-few)
360 "attempt to open-code `%s' with too many arguments" name))
363 ;; The following leads to infinite recursion when loading a
364 ;; file containing `(defsubst f () (f))', and then trying to
365 ;; byte-compile that file.
366 ;(setq body (mapcar 'byte-optimize-form body)))
370 (cons 'let (cons (nreverse bindings) body))
371 (cons 'progn body))))
372 (byte-compile-log " %s\t==>\t%s" form newform)
376 ;;; implementing source-level optimizers
378 (defun byte-optimize-form-code-walker (form for-effect)
380 ;; For normal function calls, We can just mapcar the optimizer the cdr. But
381 ;; we need to have special knowledge of the syntax of the special forms
382 ;; like let and defun (that's why they're special forms :-). (Actually,
383 ;; the important aspect is that they are subrs that don't evaluate all of
386 (let ((fn (car-safe form))
388 (cond ((not (consp form))
389 (if (not (and for-effect
390 (or byte-compile-delete-errors
396 (byte-compile-warn "malformed quote form: `%s'"
397 (prin1-to-string form)))
398 ;; map (quote nil) to nil to simplify optimizer logic.
399 ;; map quoted constants to nil if for-effect (just because).
403 ((or (byte-code-function-p fn)
404 (eq 'lambda (car-safe fn)))
405 (let ((newform (byte-compile-unfold-lambda form)))
406 (if (eq newform form)
407 ;; Some error occurred, avoid infinite recursion
409 (byte-optimize-form-code-walker newform for-effect))))
410 ((memq fn '(let let*))
411 ;; recursively enter the optimizer for the bindings and body
412 ;; of a let or let*. This for depth-firstness: forms that
413 ;; are more deeply nested are optimized first.
416 (mapcar (lambda (binding)
417 (if (symbolp binding)
419 (if (cdr (cdr binding))
420 (byte-compile-warn "malformed let binding: `%s'"
421 (prin1-to-string binding)))
423 (byte-optimize-form (nth 1 binding) nil))))
425 (byte-optimize-body (cdr (cdr form)) for-effect))))
428 (mapcar (lambda (clause)
431 (byte-optimize-form (car clause) nil)
432 (byte-optimize-body (cdr clause) for-effect))
433 (byte-compile-warn "malformed cond form: `%s'"
434 (prin1-to-string clause))
438 ;; as an extra added bonus, this simplifies (progn <x>) --> <x>
441 (setq tmp (byte-optimize-body (cdr form) for-effect))
442 (if (cdr tmp) (cons 'progn tmp) (car tmp)))
443 (byte-optimize-form (nth 1 form) for-effect)))
447 (cons (byte-optimize-form (nth 1 form) for-effect)
448 (byte-optimize-body (cdr (cdr form)) t)))
449 (byte-optimize-form (nth 1 form) for-effect)))
452 (cons (byte-optimize-form (nth 1 form) t)
453 (cons (byte-optimize-form (nth 2 form) for-effect)
454 (byte-optimize-body (cdr (cdr (cdr form))) t)))))
456 ((memq fn '(save-excursion save-restriction save-current-buffer))
457 ;; those subrs which have an implicit progn; it's not quite good
458 ;; enough to treat these like normal function calls.
459 ;; This can turn (save-excursion ...) into (save-excursion) which
460 ;; will be optimized away in the lap-optimize pass.
461 (cons fn (byte-optimize-body (cdr form) for-effect)))
463 ((eq fn 'with-output-to-temp-buffer)
464 ;; this is just like the above, except for the first argument.
467 (byte-optimize-form (nth 1 form) nil)
468 (byte-optimize-body (cdr (cdr form)) for-effect))))
471 (when (< (length form) 3)
472 (byte-compile-warn "too few arguments for `if'"))
474 (cons (byte-optimize-form (nth 1 form) nil)
476 (byte-optimize-form (nth 2 form) for-effect)
477 (byte-optimize-body (nthcdr 3 form) for-effect)))))
479 ((memq fn '(and or)) ; remember, and/or are control structures.
480 ;; take forms off the back until we can't any more.
481 ;; In the future it could conceivably be a problem that the
482 ;; subexpressions of these forms are optimized in the reverse
483 ;; order, but it's ok for now.
485 (let ((backwards (reverse (cdr form))))
486 (while (and backwards
487 (null (setcar backwards
488 (byte-optimize-form (car backwards)
490 (setq backwards (cdr backwards)))
491 (if (and (cdr form) (null backwards))
493 " all subforms of %s called for effect; deleted" form))
495 (cons fn (nreverse (mapcar 'byte-optimize-form backwards)))))
496 (cons fn (mapcar 'byte-optimize-form (cdr form)))))
498 ((eq fn 'interactive)
499 (byte-compile-warn "misplaced interactive spec: `%s'"
500 (prin1-to-string form))
503 ((memq fn '(defun defmacro function condition-case))
504 ;; These forms are compiled as constants or by breaking out
505 ;; all the subexpressions and compiling them separately.
508 ((eq fn 'unwind-protect)
509 ;; the "protected" part of an unwind-protect is compiled (and thus
510 ;; optimized) as a top-level form, so don't do it here. But the
511 ;; non-protected part has the same for-effect status as the
512 ;; unwind-protect itself. (The protected part is always for effect,
513 ;; but that isn't handled properly yet.)
515 (cons (byte-optimize-form (nth 1 form) for-effect)
519 ;; the body of a catch is compiled (and thus optimized) as a
520 ;; top-level form, so don't do it here. The tag is never
521 ;; for-effect. The body should have the same for-effect status
522 ;; as the catch form itself, but that isn't handled properly yet.
524 (cons (byte-optimize-form (nth 1 form) nil)
528 ;; Don't treat the args to `ignore' as being
529 ;; computed for effect. We want to avoid the warnings
530 ;; that might occur if they were treated that way.
531 ;; However, don't actually bother calling `ignore'.
532 `(prog1 nil . ,(mapcar 'byte-optimize-form (cdr form))))
535 (byte-compile-warn "`%s' is a malformed function"
536 (prin1-to-string fn))
539 ((and for-effect (setq tmp (get fn 'side-effect-free))
540 (or byte-compile-delete-errors
542 ;; Detect the expansion of (pop foo).
543 ;; There is no need to compile the call to `car' there.
545 (eq (car-safe (cadr form)) 'prog1)
546 (let ((var (cadr (cadr form)))
547 (last (nth 2 (cadr form))))
549 (null (nthcdr 3 (cadr form)))
550 (eq (car-safe last) 'setq)
552 (eq (car-safe (nth 2 last)) 'cdr)
553 (eq (cadr (nth 2 last)) var))))
555 (byte-compile-warn "value returned from %s is unused"
556 (prin1-to-string form))
558 (byte-compile-log " %s called for effect; deleted" fn)
559 ;; appending a nil here might not be necessary, but it can't hurt.
561 (cons 'progn (append (cdr form) '(nil))) t))
564 ;; Otherwise, no args can be considered to be for-effect,
565 ;; even if the called function is for-effect, because we
566 ;; don't know anything about that function.
567 (let ((args (mapcar #'byte-optimize-form (cdr form))))
568 (if (and (get fn 'pure)
569 (byte-optimize-all-constp args))
570 (list 'quote (apply fn (mapcar #'eval args)))
573 (defun byte-optimize-all-constp (list)
574 "Non-nil if all elements of LIST satisfy `byte-compile-constp'."
576 (while (and list constant)
577 (unless (byte-compile-constp (car list))
579 (setq list (cdr list)))
582 (defun byte-optimize-form (form &optional for-effect)
583 "The source-level pass of the optimizer."
585 ;; First, optimize all sub-forms of this one.
586 (setq form (byte-optimize-form-code-walker form for-effect))
588 ;; after optimizing all subforms, optimize this form until it doesn't
589 ;; optimize any further. This means that some forms will be passed through
590 ;; the optimizer many times, but that's necessary to make the for-effect
591 ;; processing do as much as possible.
594 (if (and (consp form)
597 ;; we don't have any of these yet, but we might.
598 (setq opt (get (car form) 'byte-for-effect-optimizer)))
599 (setq opt (get (car form) 'byte-optimizer)))
600 (not (eq form (setq new (funcall opt form)))))
602 ;; (if (equal form new) (error "bogus optimizer -- %s" opt))
603 (byte-compile-log " %s\t==>\t%s" form new)
604 (setq new (byte-optimize-form new for-effect))
609 (defun byte-optimize-body (forms all-for-effect)
610 ;; optimize the cdr of a progn or implicit progn; all forms is a list of
611 ;; forms, all but the last of which are optimized with the assumption that
612 ;; they are being called for effect. the last is for-effect as well if
613 ;; all-for-effect is true. returns a new list of forms.
618 (setq fe (or all-for-effect (cdr rest)))
619 (setq new (and (car rest) (byte-optimize-form (car rest) fe)))
620 (if (or new (not fe))
621 (setq result (cons new result)))
622 (setq rest (cdr rest)))
626 ;; some source-level optimizers
628 ;; when writing optimizers, be VERY careful that the optimizer returns
629 ;; something not EQ to its argument if and ONLY if it has made a change.
630 ;; This implies that you cannot simply destructively modify the list;
631 ;; you must return something not EQ to it if you make an optimization.
633 ;; It is now safe to optimize code such that it introduces new bindings.
635 (defsubst byte-compile-trueconstp (form)
636 "Return non-nil if FORM always evaluates to a non-nil value."
637 (while (eq (car-safe form) 'progn)
638 (setq form (car (last (cdr form)))))
642 ;; Can't use recursion in a defsubst.
643 ;; (progn (byte-compile-trueconstp (car (last (cdr form)))))
645 ((not (symbolp form)))
649 (defsubst byte-compile-nilconstp (form)
650 "Return non-nil if FORM always evaluates to a nil value."
651 (while (eq (car-safe form) 'progn)
652 (setq form (car (last (cdr form)))))
655 (quote (null (cadr form)))
656 ;; Can't use recursion in a defsubst.
657 ;; (progn (byte-compile-nilconstp (car (last (cdr form)))))
659 ((not (symbolp form)) nil)
662 ;; If the function is being called with constant numeric args,
663 ;; evaluate as much as possible at compile-time. This optimizer
664 ;; assumes that the function is associative, like + or *.
665 (defun byte-optimize-associative-math (form)
670 (if (numberp (car rest))
671 (setq constants (cons (car rest) constants))
672 (setq args (cons (car rest) args)))
673 (setq rest (cdr rest)))
677 (apply (car form) constants)
679 (cons (car form) (nreverse args))
681 (apply (car form) constants))
684 ;; If the function is being called with constant numeric args,
685 ;; evaluate as much as possible at compile-time. This optimizer
686 ;; assumes that the function satisfies
687 ;; (op x1 x2 ... xn) == (op ...(op (op x1 x2) x3) ...xn)
689 (defun byte-optimize-nonassociative-math (form)
690 (if (or (not (numberp (car (cdr form))))
691 (not (numberp (car (cdr (cdr form))))))
693 (let ((constant (car (cdr form)))
694 (rest (cdr (cdr form))))
695 (while (numberp (car rest))
696 (setq constant (funcall (car form) constant (car rest))
699 (cons (car form) (cons constant rest))
702 ;;(defun byte-optimize-associative-two-args-math (form)
703 ;; (setq form (byte-optimize-associative-math form))
705 ;; (byte-optimize-two-args-left form)
708 ;;(defun byte-optimize-nonassociative-two-args-math (form)
709 ;; (setq form (byte-optimize-nonassociative-math form))
711 ;; (byte-optimize-two-args-right form)
714 (defun byte-optimize-approx-equal (x y)
715 (<= (* (abs (- x y)) 100) (abs (+ x y))))
717 ;; Collect all the constants from FORM, after the STARTth arg,
718 ;; and apply FUN to them to make one argument at the end.
719 ;; For functions that can handle floats, that optimization
720 ;; can be incorrect because reordering can cause an overflow
721 ;; that would otherwise be avoided by encountering an arg that is a float.
722 ;; We avoid this problem by (1) not moving float constants and
723 ;; (2) not moving anything if it would cause an overflow.
724 (defun byte-optimize-delay-constants-math (form start fun)
725 ;; Merge all FORM's constants from number START, call FUN on them
726 ;; and put the result at the end.
727 (let ((rest (nthcdr (1- start) form))
729 ;; t means we must check for overflow.
730 (overflow (memq fun '(+ *))))
731 (while (cdr (setq rest (cdr rest)))
732 (if (integerp (car rest))
734 (setq form (copy-sequence form)
735 rest (nthcdr (1- start) form))
736 (while (setq rest (cdr rest))
737 (cond ((integerp (car rest))
738 (setq constants (cons (car rest) constants))
740 ;; If necessary, check now for overflow
741 ;; that might be caused by reordering.
743 ;; We have overflow if the result of doing the arithmetic
744 ;; on floats is not even close to the result
745 ;; of doing it on integers.
746 (not (byte-optimize-approx-equal
747 (apply fun (mapcar 'float constants))
748 (float (apply fun constants)))))
750 (setq form (nconc (delq nil form)
751 (list (apply fun (nreverse constants)))))))))
754 (defsubst byte-compile-butlast (form)
755 (nreverse (cdr (reverse form))))
757 (defun byte-optimize-plus (form)
758 ;; Don't call `byte-optimize-delay-constants-math' (bug#1334).
759 ;;(setq form (byte-optimize-delay-constants-math form 1 '+))
760 (if (memq 0 form) (setq form (delq 0 (copy-sequence form))))
761 ;; For (+ constants...), byte-optimize-predicate does the work.
762 (when (memq nil (mapcar 'numberp (cdr form)))
764 ;; (+ x 1) --> (1+ x) and (+ x -1) --> (1- x).
765 ((and (= (length form) 3)
766 (or (memq (nth 1 form) '(1 -1))
767 (memq (nth 2 form) '(1 -1))))
769 (if (memq (nth 1 form) '(1 -1))
770 (setq integer (nth 1 form) other (nth 2 form))
771 (setq integer (nth 2 form) other (nth 1 form)))
773 (list (if (eq integer 1) '1+ '1-) other))))
774 ;; Here, we could also do
775 ;; (+ x y ... 1) --> (1+ (+ x y ...))
776 ;; (+ x y ... -1) --> (1- (+ x y ...))
777 ;; The resulting bytecode is smaller, but is it faster? -- cyd
779 (byte-optimize-predicate form))
781 (defun byte-optimize-minus (form)
782 ;; Don't call `byte-optimize-delay-constants-math' (bug#1334).
783 ;;(setq form (byte-optimize-delay-constants-math form 2 '+))
785 (when (and (nthcdr 3 form)
786 (memq 0 (cddr form)))
787 (setq form (nconc (list (car form) (cadr form))
788 (delq 0 (copy-sequence (cddr form)))))
789 ;; After the above, we must turn (- x) back into (- x 0)
791 (setq form (nconc form (list 0)))))
792 ;; For (- constants..), byte-optimize-predicate does the work.
793 (when (memq nil (mapcar 'numberp (cdr form)))
795 ;; (- x 1) --> (1- x)
796 ((equal (nthcdr 2 form) '(1))
797 (setq form (list '1- (nth 1 form))))
798 ;; (- x -1) --> (1+ x)
799 ((equal (nthcdr 2 form) '(-1))
800 (setq form (list '1+ (nth 1 form))))
802 ((and (eq (nth 1 form) 0)
804 (setq form (list '- (nth 2 form))))
805 ;; Here, we could also do
806 ;; (- x y ... 1) --> (1- (- x y ...))
807 ;; (- x y ... -1) --> (1+ (- x y ...))
808 ;; The resulting bytecode is smaller, but is it faster? -- cyd
810 (byte-optimize-predicate form))
812 (defun byte-optimize-multiply (form)
813 (setq form (byte-optimize-delay-constants-math form 1 '*))
814 ;; For (* constants..), byte-optimize-predicate does the work.
815 (when (memq nil (mapcar 'numberp (cdr form)))
816 ;; After `byte-optimize-predicate', if there is a INTEGER constant
817 ;; in FORM, it is in the last element.
818 (let ((last (car (reverse (cdr form)))))
820 ;; Would handling (* ... 0) here cause floating point errors?
822 ((eq 1 last) (setq form (byte-compile-butlast form)))
824 (setq form (list '- (if (nthcdr 3 form)
825 (byte-compile-butlast form)
827 (byte-optimize-predicate form))
829 (defun byte-optimize-divide (form)
830 (setq form (byte-optimize-delay-constants-math form 2 '*))
831 ;; After `byte-optimize-predicate', if there is a INTEGER constant
832 ;; in FORM, it is in the last element.
833 (let ((last (car (reverse (cdr (cdr form))))))
835 ;; Runtime error (leave it intact).
838 (memql 0.0 (cddr form))))
839 ;; No constants in expression
840 ((not (numberp last)))
841 ;; For (* constants..), byte-optimize-predicate does the work.
842 ((null (memq nil (mapcar 'numberp (cdr form)))))
843 ;; (/ x y.. 1) --> (/ x y..)
844 ((and (eq last 1) (nthcdr 3 form))
845 (setq form (byte-compile-butlast form)))
846 ;; (/ x -1), (/ x .. -1) --> (- x), (- (/ x ..))
848 (setq form (list '- (if (nthcdr 3 form)
849 (byte-compile-butlast form)
851 (byte-optimize-predicate form))
853 (defun byte-optimize-logmumble (form)
854 (setq form (byte-optimize-delay-constants-math form 1 (car form)))
855 (byte-optimize-predicate
857 (setq form (if (eq (car form) 'logand)
858 (cons 'progn (cdr form))
859 (delq 0 (copy-sequence form)))))
860 ((and (eq (car-safe form) 'logior)
862 (cons 'progn (cdr form)))
866 (defun byte-optimize-binary-predicate (form)
867 (if (byte-compile-constp (nth 1 form))
868 (if (byte-compile-constp (nth 2 form))
870 (list 'quote (eval form))
872 ;; This can enable some lapcode optimizations.
873 (list (car form) (nth 2 form) (nth 1 form)))
876 (defun byte-optimize-predicate (form)
880 (setq ok (byte-compile-constp (car rest))
884 (list 'quote (eval form))
888 (defun byte-optimize-identity (form)
889 (if (and (cdr form) (null (cdr (cdr form))))
891 (byte-compile-warn "identity called with %d arg%s, but requires 1"
893 (if (= 1 (length (cdr form))) "" "s"))
896 (put 'identity 'byte-optimizer 'byte-optimize-identity)
898 (put '+ 'byte-optimizer 'byte-optimize-plus)
899 (put '* 'byte-optimizer 'byte-optimize-multiply)
900 (put '- 'byte-optimizer 'byte-optimize-minus)
901 (put '/ 'byte-optimizer 'byte-optimize-divide)
902 (put 'max 'byte-optimizer 'byte-optimize-associative-math)
903 (put 'min 'byte-optimizer 'byte-optimize-associative-math)
905 (put '= 'byte-optimizer 'byte-optimize-binary-predicate)
906 (put 'eq 'byte-optimizer 'byte-optimize-binary-predicate)
907 (put 'equal 'byte-optimizer 'byte-optimize-binary-predicate)
908 (put 'string= 'byte-optimizer 'byte-optimize-binary-predicate)
909 (put 'string-equal 'byte-optimizer 'byte-optimize-binary-predicate)
911 (put '< 'byte-optimizer 'byte-optimize-predicate)
912 (put '> 'byte-optimizer 'byte-optimize-predicate)
913 (put '<= 'byte-optimizer 'byte-optimize-predicate)
914 (put '>= 'byte-optimizer 'byte-optimize-predicate)
915 (put '1+ 'byte-optimizer 'byte-optimize-predicate)
916 (put '1- 'byte-optimizer 'byte-optimize-predicate)
917 (put 'not 'byte-optimizer 'byte-optimize-predicate)
918 (put 'null 'byte-optimizer 'byte-optimize-predicate)
919 (put 'memq 'byte-optimizer 'byte-optimize-predicate)
920 (put 'consp 'byte-optimizer 'byte-optimize-predicate)
921 (put 'listp 'byte-optimizer 'byte-optimize-predicate)
922 (put 'symbolp 'byte-optimizer 'byte-optimize-predicate)
923 (put 'stringp 'byte-optimizer 'byte-optimize-predicate)
924 (put 'string< 'byte-optimizer 'byte-optimize-predicate)
925 (put 'string-lessp 'byte-optimizer 'byte-optimize-predicate)
927 (put 'logand 'byte-optimizer 'byte-optimize-logmumble)
928 (put 'logior 'byte-optimizer 'byte-optimize-logmumble)
929 (put 'logxor 'byte-optimizer 'byte-optimize-logmumble)
930 (put 'lognot 'byte-optimizer 'byte-optimize-predicate)
932 (put 'car 'byte-optimizer 'byte-optimize-predicate)
933 (put 'cdr 'byte-optimizer 'byte-optimize-predicate)
934 (put 'car-safe 'byte-optimizer 'byte-optimize-predicate)
935 (put 'cdr-safe 'byte-optimizer 'byte-optimize-predicate)
938 ;; I'm not convinced that this is necessary. Doesn't the optimizer loop
939 ;; take care of this? - Jamie
940 ;; I think this may some times be necessary to reduce ie (quote 5) to 5,
941 ;; so arithmetic optimizers recognize the numeric constant. - Hallvard
942 (put 'quote 'byte-optimizer 'byte-optimize-quote)
943 (defun byte-optimize-quote (form)
944 (if (or (consp (nth 1 form))
945 (and (symbolp (nth 1 form))
946 (not (byte-compile-const-symbol-p form))))
950 (defun byte-optimize-zerop (form)
951 (cond ((numberp (nth 1 form))
953 (byte-compile-delete-errors
954 (list '= (nth 1 form) 0))
957 (put 'zerop 'byte-optimizer 'byte-optimize-zerop)
959 (defun byte-optimize-and (form)
960 ;; Simplify if less than 2 args.
961 ;; if there is a literal nil in the args to `and', throw it and following
962 ;; forms away, and surround the `and' with (progn ... nil).
963 (cond ((null (cdr form)))
967 (prog1 (setq form (copy-sequence form))
969 (setq form (cdr form)))
972 ((null (cdr (cdr form)))
974 ((byte-optimize-predicate form))))
976 (defun byte-optimize-or (form)
977 ;; Throw away nil's, and simplify if less than 2 args.
978 ;; If there is a literal non-nil constant in the args to `or', throw away all
981 (setq form (delq nil (copy-sequence form))))
983 (while (cdr (setq rest (cdr rest)))
984 (if (byte-compile-trueconstp (car rest))
985 (setq form (copy-sequence form)
986 rest (setcdr (memq (car rest) form) nil))))
988 (byte-optimize-predicate form)
991 (defun byte-optimize-cond (form)
992 ;; if any clauses have a literal nil as their test, throw them away.
993 ;; if any clause has a literal non-nil constant as its test, throw
994 ;; away all following clauses.
996 ;; This must be first, to reduce (cond (t ...) (nil)) to (progn t ...)
997 (while (setq rest (assq nil (cdr form)))
998 (setq form (delq rest (copy-sequence form))))
999 (if (memq nil (cdr form))
1000 (setq form (delq nil (copy-sequence form))))
1002 (while (setq rest (cdr rest))
1003 (cond ((byte-compile-trueconstp (car-safe (car rest)))
1004 ;; This branch will always be taken: kill the subsequent ones.
1005 (cond ((eq rest (cdr form)) ;First branch of `cond'.
1006 (setq form `(progn ,@(car rest))))
1008 (setq form (copy-sequence form))
1009 (setcdr (memq (car rest) form) nil)))
1011 ((and (consp (car rest))
1012 (byte-compile-nilconstp (caar rest)))
1013 ;; This branch will never be taken: kill its body.
1014 (setcdr (car rest) nil)))))
1016 ;; Turn (cond (( <x> )) ... ) into (or <x> (cond ... ))
1017 (if (eq 'cond (car-safe form))
1018 (let ((clauses (cdr form)))
1019 (if (and (consp (car clauses))
1020 (null (cdr (car clauses))))
1021 (list 'or (car (car clauses))
1023 (cons (car form) (cdr (cdr form)))))
1027 (defun byte-optimize-if (form)
1028 ;; (if (progn <insts> <test>) <rest>) ==> (progn <insts> (if <test> <rest>))
1029 ;; (if <true-constant> <then> <else...>) ==> <then>
1030 ;; (if <false-constant> <then> <else...>) ==> (progn <else...>)
1031 ;; (if <test> nil <else...>) ==> (if (not <test>) (progn <else...>))
1032 ;; (if <test> <then> nil) ==> (if <test> <then>)
1033 (let ((clause (nth 1 form)))
1034 (cond ((and (eq (car-safe clause) 'progn)
1035 ;; `clause' is a proper list.
1036 (null (cdr (last clause))))
1037 (if (null (cddr clause))
1038 ;; A trivial `progn'.
1039 (byte-optimize-if `(if ,(cadr clause) ,@(nthcdr 2 form)))
1040 (nconc (butlast clause)
1043 `(if ,(car (last clause)) ,@(nthcdr 2 form)))))))
1044 ((byte-compile-trueconstp clause)
1045 `(progn ,clause ,(nth 2 form)))
1046 ((byte-compile-nilconstp clause)
1047 `(progn ,clause ,@(nthcdr 3 form)))
1049 (if (equal '(nil) (nthcdr 3 form))
1050 (list 'if clause (nth 2 form))
1052 ((or (nth 3 form) (nthcdr 4 form))
1054 ;; Don't make a double negative;
1055 ;; instead, take away the one that is there.
1056 (if (and (consp clause) (memq (car clause) '(not null))
1057 (= (length clause) 2)) ; (not xxxx) or (not (xxxx))
1061 (cons 'progn (nthcdr 3 form))
1064 (list 'progn clause nil)))))
1066 (defun byte-optimize-while (form)
1067 (when (< (length form) 2)
1068 (byte-compile-warn "too few arguments for `while'"))
1072 (put 'and 'byte-optimizer 'byte-optimize-and)
1073 (put 'or 'byte-optimizer 'byte-optimize-or)
1074 (put 'cond 'byte-optimizer 'byte-optimize-cond)
1075 (put 'if 'byte-optimizer 'byte-optimize-if)
1076 (put 'while 'byte-optimizer 'byte-optimize-while)
1078 ;; byte-compile-negation-optimizer lives in bytecomp.el
1079 (put '/= 'byte-optimizer 'byte-compile-negation-optimizer)
1080 (put 'atom 'byte-optimizer 'byte-compile-negation-optimizer)
1081 (put 'nlistp 'byte-optimizer 'byte-compile-negation-optimizer)
1084 (defun byte-optimize-funcall (form)
1085 ;; (funcall (lambda ...) ...) ==> ((lambda ...) ...)
1086 ;; (funcall foo ...) ==> (foo ...)
1087 (let ((fn (nth 1 form)))
1088 (if (memq (car-safe fn) '(quote function))
1089 (cons (nth 1 fn) (cdr (cdr form)))
1092 (defun byte-optimize-apply (form)
1093 ;; If the last arg is a literal constant, turn this into a funcall.
1094 ;; The funcall optimizer can then transform (funcall 'foo ...) -> (foo ...).
1095 (let ((fn (nth 1 form))
1096 (last (nth (1- (length form)) form))) ; I think this really is fastest
1097 (or (if (or (null last)
1098 (eq (car-safe last) 'quote))
1099 (if (listp (nth 1 last))
1100 (let ((butlast (nreverse (cdr (reverse (cdr (cdr form)))))))
1101 (nconc (list 'funcall fn) butlast
1102 (mapcar (lambda (x) (list 'quote x)) (nth 1 last))))
1104 "last arg to apply can't be a literal atom: `%s'"
1105 (prin1-to-string last))
1109 (put 'funcall 'byte-optimizer 'byte-optimize-funcall)
1110 (put 'apply 'byte-optimizer 'byte-optimize-apply)
1113 (put 'let 'byte-optimizer 'byte-optimize-letX)
1114 (put 'let* 'byte-optimizer 'byte-optimize-letX)
1115 (defun byte-optimize-letX (form)
1116 (cond ((null (nth 1 form))
1118 (cons 'progn (cdr (cdr form))))
1119 ((or (nth 2 form) (nthcdr 3 form))
1122 ((eq (car form) 'let)
1123 (append '(progn) (mapcar 'car-safe (mapcar 'cdr-safe (nth 1 form)))
1126 (let ((binds (reverse (nth 1 form))))
1127 (list 'let* (reverse (cdr binds)) (nth 1 (car binds)) nil)))))
1130 (put 'nth 'byte-optimizer 'byte-optimize-nth)
1131 (defun byte-optimize-nth (form)
1132 (if (= (safe-length form) 3)
1133 (if (memq (nth 1 form) '(0 1))
1134 (list 'car (if (zerop (nth 1 form))
1136 (list 'cdr (nth 2 form))))
1137 (byte-optimize-predicate form))
1140 (put 'nthcdr 'byte-optimizer 'byte-optimize-nthcdr)
1141 (defun byte-optimize-nthcdr (form)
1142 (if (= (safe-length form) 3)
1143 (if (memq (nth 1 form) '(0 1 2))
1144 (let ((count (nth 1 form)))
1145 (setq form (nth 2 form))
1146 (while (>= (setq count (1- count)) 0)
1147 (setq form (list 'cdr form)))
1149 (byte-optimize-predicate form))
1152 ;; Fixme: delete-char -> delete-region (byte-coded)
1153 ;; optimize string-as-unibyte, string-as-multibyte, string-make-unibyte,
1154 ;; string-make-multibyte for constant args.
1156 (put 'featurep 'byte-optimizer 'byte-optimize-featurep)
1157 (defun byte-optimize-featurep (form)
1158 ;; Emacs-21's byte-code doesn't run under XEmacs or SXEmacs anyway, so we
1159 ;; can safely optimize away this test.
1160 (if (member (cdr-safe form) '(((quote xemacs)) ((quote sxemacs))))
1162 (if (member (cdr-safe form) '(((quote emacs))))
1166 (put 'set 'byte-optimizer 'byte-optimize-set)
1167 (defun byte-optimize-set (form)
1168 (let ((var (car-safe (cdr-safe form))))
1170 ((and (eq (car-safe var) 'quote) (consp (cdr var)))
1171 `(setq ,(cadr var) ,@(cddr form)))
1172 ((and (eq (car-safe var) 'make-local-variable)
1173 (eq (car-safe (setq var (car-safe (cdr var)))) 'quote)
1175 `(progn ,(cadr form) (setq ,(cadr var) ,@(cddr form))))
1178 ;; enumerating those functions which need not be called if the returned
1179 ;; value is not used. That is, something like
1180 ;; (progn (list (something-with-side-effects) (yow))
1182 ;; may safely be turned into
1183 ;; (progn (progn (something-with-side-effects) (yow))
1185 ;; Further optimizations will turn (progn (list 1 2 3) 'foo) into 'foo.
1187 ;; Some of these functions have the side effect of allocating memory
1188 ;; and it would be incorrect to replace two calls with one.
1189 ;; But we don't try to do those kinds of optimizations,
1190 ;; so it is safe to list such functions here.
1191 ;; Some of these functions return values that depend on environment
1192 ;; state, so that constant folding them would be wrong,
1193 ;; but we don't do constant folding based on this list.
1195 ;; However, at present the only optimization we normally do
1196 ;; is delete calls that need not occur, and we only do that
1197 ;; with the error-free functions.
1199 ;; I wonder if I missed any :-\)
1200 (let ((side-effect-free-fns
1201 '(% * + - / /= 1+ 1- < <= = > >= abs acos append aref ash asin atan
1203 boundp buffer-file-name buffer-local-variables buffer-modified-p
1204 buffer-substring byte-code-function-p
1205 capitalize car-less-than-car car cdr ceiling char-after char-before
1206 char-equal char-to-string char-width
1207 compare-strings concat coordinates-in-window-p
1208 copy-alist copy-sequence copy-marker cos count-lines
1210 decode-time default-boundp default-value documentation downcase
1211 elt encode-char exp expt encode-time error-message-string
1212 fboundp fceiling featurep ffloor
1213 file-directory-p file-exists-p file-locked-p file-name-absolute-p
1214 file-newer-than-file-p file-readable-p file-symlink-p file-writable-p
1215 float float-time floor format format-time-string frame-visible-p
1217 get gethash get-buffer get-buffer-window getenv get-file-buffer
1219 int-to-string intern-soft
1221 length local-variable-if-set-p local-variable-p log log10 logand
1222 logb logior lognot logxor lsh langinfo
1223 make-list make-string make-symbol
1224 marker-buffer max member memq min mod multibyte-char-to-unibyte
1225 next-window nth nthcdr number-to-string
1226 parse-colon-path plist-get plist-member
1227 prefix-numeric-value previous-window prin1-to-string propertize
1229 radians-to-degrees rassq rassoc read-from-string regexp-quote
1230 region-beginning region-end reverse round
1231 sin sqrt string string< string= string-equal string-lessp string-to-char
1232 string-to-int string-to-number substring sxhash symbol-function
1233 symbol-name symbol-plist symbol-value string-make-unibyte
1234 string-make-multibyte string-as-multibyte string-as-unibyte
1237 unibyte-char-to-multibyte upcase user-full-name
1238 user-login-name user-original-login-name user-variable-p
1240 window-buffer window-dedicated-p window-edges window-height
1241 window-hscroll window-minibuffer-p window-width
1243 (side-effect-and-error-free-fns
1245 bobp bolp bool-vector-p
1246 buffer-end buffer-list buffer-size buffer-string bufferp
1247 car-safe case-table-p cdr-safe char-or-string-p characterp
1248 charsetp commandp cons consp
1249 current-buffer current-global-map current-indentation
1250 current-local-map current-minor-mode-maps current-time
1251 current-time-string current-time-zone
1252 eobp eolp eq equal eventp
1253 floatp following-char framep
1254 get-largest-window get-lru-window
1256 identity ignore integerp integer-or-marker-p interactive-p
1257 invocation-directory invocation-name
1259 line-beginning-position line-end-position list listp
1260 make-marker mark mark-marker markerp max-char
1261 memory-limit minibuffer-window
1263 natnump nlistp not null number-or-marker-p numberp
1264 one-window-p overlayp
1265 point point-marker point-min point-max preceding-char primary-charset
1267 recent-keys recursion-depth
1268 safe-length selected-frame selected-window sequencep
1269 standard-case-table standard-syntax-table stringp subrp symbolp
1270 syntax-table syntax-table-p
1271 this-command-keys this-command-keys-vector this-single-command-keys
1272 this-single-command-raw-keys
1273 user-real-login-name user-real-uid user-uid
1274 vector vectorp visible-frame-list
1275 wholenump window-configuration-p window-live-p windowp)))
1276 (while side-effect-free-fns
1277 (put (car side-effect-free-fns) 'side-effect-free t)
1278 (setq side-effect-free-fns (cdr side-effect-free-fns)))
1279 (while side-effect-and-error-free-fns
1280 (put (car side-effect-and-error-free-fns) 'side-effect-free 'error-free)
1281 (setq side-effect-and-error-free-fns (cdr side-effect-and-error-free-fns)))
1285 ;; pure functions are side-effect free functions whose values depend
1286 ;; only on their arguments. For these functions, calls with constant
1287 ;; arguments can be evaluated at compile time. This may shift run time
1288 ;; errors to compile time.
1291 '(concat symbol-name regexp-opt regexp-quote string-to-syntax)))
1293 (put (car pure-fns) 'pure t)
1294 (setq pure-fns (cdr pure-fns)))
1297 (defun byte-compile-splice-in-already-compiled-code (form)
1298 ;; form is (byte-code "..." [...] n)
1299 (if (not (memq byte-optimize '(t lap)))
1300 (byte-compile-normal-call form)
1301 (byte-inline-lapcode
1302 (byte-decompile-bytecode-1 (nth 1 form) (nth 2 form) t))))
1304 (put 'byte-code 'byte-compile 'byte-compile-splice-in-already-compiled-code)
1307 (defconst byte-constref-ops
1308 '(byte-constant byte-constant2 byte-varref byte-varset byte-varbind))
1310 ;; This function extracts the bitfields from variable-length opcodes.
1311 ;; Originally defined in disass.el (which no longer uses it.)
1313 (defun disassemble-offset ()
1315 ;; fetch and return the offset for the current opcode.
1316 ;; return nil if this opcode has no offset
1317 ;; Used and set dynamically in byte-decompile-bytecode-1.
1318 (defvar bytedecomp-op)
1319 (defvar bytedecomp-ptr)
1320 (defvar bytedecomp-bytes)
1321 (cond ((< bytedecomp-op byte-nth)
1322 (let ((tem (logand bytedecomp-op 7)))
1323 (setq bytedecomp-op (logand bytedecomp-op 248))
1325 ;; Offset in next byte.
1326 (setq bytedecomp-ptr (1+ bytedecomp-ptr))
1327 (aref bytedecomp-bytes bytedecomp-ptr))
1329 ;; Offset in next 2 bytes.
1330 (setq bytedecomp-ptr (1+ bytedecomp-ptr))
1331 (+ (aref bytedecomp-bytes bytedecomp-ptr)
1332 (progn (setq bytedecomp-ptr (1+ bytedecomp-ptr))
1333 (lsh (aref bytedecomp-bytes bytedecomp-ptr) 8))))
1334 (t tem)))) ;offset was in opcode
1335 ((>= bytedecomp-op byte-constant)
1336 (prog1 (- bytedecomp-op byte-constant) ;offset in opcode
1337 (setq bytedecomp-op byte-constant)))
1338 ((or (and (>= bytedecomp-op byte-constant2)
1339 (<= bytedecomp-op byte-goto-if-not-nil-else-pop))
1340 (= bytedecomp-op byte-stack-set2))
1341 ;; Offset in next 2 bytes.
1342 (setq bytedecomp-ptr (1+ bytedecomp-ptr))
1343 (+ (aref bytedecomp-bytes bytedecomp-ptr)
1344 (progn (setq bytedecomp-ptr (1+ bytedecomp-ptr))
1345 (lsh (aref bytedecomp-bytes bytedecomp-ptr) 8))))
1346 ((and (>= bytedecomp-op byte-listN)
1347 (<= bytedecomp-op byte-discardN))
1348 (setq bytedecomp-ptr (1+ bytedecomp-ptr)) ;offset in next byte
1349 (aref bytedecomp-bytes bytedecomp-ptr))))
1352 ;; This de-compiler is used for inline expansion of compiled functions,
1353 ;; and by the disassembler.
1355 ;; This list contains numbers, which are pc values,
1356 ;; before each instruction.
1357 (defun byte-decompile-bytecode (bytes constvec)
1358 "Turn BYTECODE into lapcode, referring to CONSTVEC."
1359 (let ((byte-compile-constants nil)
1360 (byte-compile-variables nil)
1361 (byte-compile-tag-number 0))
1362 (byte-decompile-bytecode-1 bytes constvec)))
1364 ;; As byte-decompile-bytecode, but updates
1365 ;; byte-compile-{constants, variables, tag-number}.
1366 ;; If MAKE-SPLICEABLE is true, then `return' opcodes are replaced
1367 ;; with `goto's destined for the end of the code.
1368 ;; That is for use by the compiler.
1369 ;; If MAKE-SPLICEABLE is nil, we are being called for the disassembler.
1370 ;; In that case, we put a pc value into the list
1371 ;; before each insn (or its label).
1372 (defun byte-decompile-bytecode-1 (bytedecomp-bytes constvec
1373 &optional make-spliceable)
1374 (let ((length (length bytedecomp-bytes))
1375 (bytedecomp-ptr 0) optr tags bytedecomp-op offset
1378 (while (not (= bytedecomp-ptr length))
1380 (setq lap (cons bytedecomp-ptr lap)))
1381 (setq bytedecomp-op (aref bytedecomp-bytes bytedecomp-ptr)
1383 offset (disassemble-offset)) ; this does dynamic-scope magic
1384 (setq bytedecomp-op (aref byte-code-vector bytedecomp-op))
1385 (cond ((memq bytedecomp-op byte-goto-ops)
1388 (cdr (or (assq offset tags)
1391 (byte-compile-make-tag))
1393 ((cond ((eq bytedecomp-op 'byte-constant2)
1394 (setq bytedecomp-op 'byte-constant) t)
1395 ((memq bytedecomp-op byte-constref-ops)))
1396 (setq tmp (if (>= offset (length constvec))
1397 (list 'out-of-range offset)
1398 (aref constvec offset))
1399 offset (if (eq bytedecomp-op 'byte-constant)
1400 (byte-compile-get-constant tmp)
1401 (or (assq tmp byte-compile-variables)
1402 (car (setq byte-compile-variables
1404 byte-compile-variables)))))))
1405 ((and make-spliceable
1406 (eq bytedecomp-op 'byte-return))
1407 (if (= bytedecomp-ptr (1- length))
1408 (setq bytedecomp-op nil)
1409 (setq offset (or endtag (setq endtag (byte-compile-make-tag)))
1410 bytedecomp-op 'byte-goto)))
1411 ((eq bytedecomp-op 'byte-stack-set2)
1412 (setq bytedecomp-op 'byte-stack-set))
1413 ((and (eq bytedecomp-op 'byte-discardN) (>= offset #x80))
1414 ;; The top bit of the operand for byte-discardN is a flag,
1415 ;; saying whether the top-of-stack is preserved. In
1416 ;; lapcode, we represent this by using a different opcode
1417 ;; (with the flag removed from the operand).
1418 (setq bytedecomp-op 'byte-discardN-preserve-tos)
1419 (setq offset (- offset #x80))))
1420 ;; lap = ( [ (pc . (op . arg)) ]* )
1421 (setq lap (cons (cons optr (cons bytedecomp-op (or offset 0)))
1423 (setq bytedecomp-ptr (1+ bytedecomp-ptr)))
1424 ;; take off the dummy nil op that we replaced a trailing "return" with.
1427 (cond ((numberp (car rest)))
1428 ((setq tmp (assq (car (car rest)) tags))
1429 ;; this addr is jumped to
1430 (setcdr rest (cons (cons nil (cdr tmp))
1432 (setq tags (delq tmp tags))
1433 (setq rest (cdr rest))))
1434 (setq rest (cdr rest))))
1435 (if tags (error "optimizer error: missed tags %s" tags))
1436 (if (null (car (cdr (car lap))))
1437 (setq lap (cdr lap)))
1439 (setq lap (cons (cons nil endtag) lap)))
1440 ;; remove addrs, lap = ( [ (op . arg) | (TAG tagno) ]* )
1441 (mapcar (function (lambda (elt)
1448 ;;; peephole optimizer
1450 (defconst byte-tagref-ops (cons 'TAG byte-goto-ops))
1452 (defconst byte-conditional-ops
1453 '(byte-goto-if-nil byte-goto-if-not-nil byte-goto-if-nil-else-pop
1454 byte-goto-if-not-nil-else-pop))
1456 (defconst byte-after-unbind-ops
1457 '(byte-constant byte-dup
1458 byte-symbolp byte-consp byte-stringp byte-listp byte-numberp byte-integerp
1460 byte-cons byte-list1 byte-list2 ; byte-list3 byte-list4
1462 ;; How about other side-effect-free-ops? Is it safe to move an
1463 ;; error invocation (such as from nth) out of an unwind-protect?
1464 ;; No, it is not, because the unwind-protect forms can alter
1465 ;; the inside of the object to which nth would apply.
1466 ;; For the same reason, byte-equal was deleted from this list.
1467 "Byte-codes that can be moved past an unbind.")
1469 (defconst byte-compile-side-effect-and-error-free-ops
1470 '(byte-constant byte-dup byte-symbolp byte-consp byte-stringp byte-listp
1471 byte-integerp byte-numberp byte-eq byte-equal byte-not byte-car-safe
1472 byte-cdr-safe byte-cons byte-list1 byte-list2 byte-point byte-point-max
1473 byte-point-min byte-following-char byte-preceding-char
1474 byte-current-column byte-eolp byte-eobp byte-bolp byte-bobp
1475 byte-current-buffer byte-stack-ref))
1477 (defconst byte-compile-side-effect-free-ops
1479 '(byte-varref byte-nth byte-memq byte-car byte-cdr byte-length byte-aref
1480 byte-symbol-value byte-get byte-concat2 byte-concat3 byte-sub1 byte-add1
1481 byte-eqlsign byte-gtr byte-lss byte-leq byte-geq byte-diff byte-negate
1482 byte-plus byte-max byte-min byte-mult byte-char-after byte-char-syntax
1483 byte-buffer-substring byte-string= byte-string< byte-nthcdr byte-elt
1484 byte-member byte-assq byte-quo byte-rem)
1485 byte-compile-side-effect-and-error-free-ops))
1487 ;; This crock is because of the way DEFVAR_BOOL variables work.
1488 ;; Consider the code
1490 ;; (defun foo (flag)
1491 ;; (let ((old-pop-ups pop-up-windows)
1492 ;; (pop-up-windows flag))
1493 ;; (cond ((not (eq pop-up-windows old-pop-ups))
1494 ;; (setq old-pop-ups pop-up-windows)
1497 ;; Uncompiled, old-pop-ups will always be set to nil or t, even if FLAG is
1498 ;; something else. But if we optimize
1501 ;; varbind pop-up-windows
1502 ;; varref pop-up-windows
1507 ;; varbind pop-up-windows
1510 ;; we break the program, because it will appear that pop-up-windows and
1511 ;; old-pop-ups are not EQ when really they are. So we have to know what
1512 ;; the BOOL variables are, and not perform this optimization on them.
1514 ;; The variable `byte-boolean-vars' is now primitive and updated
1515 ;; automatically by DEFVAR_BOOL.
1517 (defun byte-optimize-lapcode (lap &optional for-effect)
1518 "Simple peephole optimizer. LAP is both modified and returned.
1519 If FOR-EFFECT is non-nil, the return value is assumed to be of no importance."
1523 (keep-going 'first-time)
1526 (side-effect-free (if byte-compile-delete-errors
1527 byte-compile-side-effect-free-ops
1528 byte-compile-side-effect-and-error-free-ops)))
1530 (or (eq keep-going 'first-time)
1531 (byte-compile-log-lap " ---- next pass"))
1535 (setq lap0 (car rest)
1539 ;; You may notice that sequences like "dup varset discard" are
1540 ;; optimized but sequences like "dup varset TAG1: discard" are not.
1541 ;; You may be tempted to change this; resist that temptation.
1543 ;; <side-effect-free> pop --> <deleted>
1545 ;; const-X pop --> <deleted>
1546 ;; varref-X pop --> <deleted>
1547 ;; dup pop --> <deleted>
1549 ((and (eq 'byte-discard (car lap1))
1550 (memq (car lap0) side-effect-free))
1552 (setq tmp (aref byte-stack+-info (symbol-value (car lap0))))
1553 (setq rest (cdr rest))
1555 (byte-compile-log-lap
1556 " %s discard\t-->\t<deleted>" lap0)
1557 (setq lap (delq lap0 (delq lap1 lap))))
1559 (byte-compile-log-lap
1560 " %s discard\t-->\t<deleted> discard" lap0)
1561 (setq lap (delq lap0 lap)))
1563 (byte-compile-log-lap
1564 " %s discard\t-->\tdiscard discard" lap0)
1565 (setcar lap0 'byte-discard)
1567 ((error "Optimizer error: too much on the stack"))))
1569 ;; goto*-X X: --> X:
1571 ((and (memq (car lap0) byte-goto-ops)
1572 (eq (cdr lap0) lap1))
1573 (cond ((eq (car lap0) 'byte-goto)
1574 (setq lap (delq lap0 lap))
1575 (setq tmp "<deleted>"))
1576 ((memq (car lap0) byte-goto-always-pop-ops)
1577 (setcar lap0 (setq tmp 'byte-discard))
1579 ((error "Depth conflict at tag %d" (nth 2 lap0))))
1580 (and (memq byte-optimize-log '(t byte))
1581 (byte-compile-log " (goto %s) %s:\t-->\t%s %s:"
1582 (nth 1 lap1) (nth 1 lap1)
1584 (setq keep-going t))
1586 ;; varset-X varref-X --> dup varset-X
1587 ;; varbind-X varref-X --> dup varbind-X
1588 ;; const/dup varset-X varref-X --> const/dup varset-X const/dup
1589 ;; const/dup varbind-X varref-X --> const/dup varbind-X const/dup
1590 ;; The latter two can enable other optimizations.
1592 ;; For lexical variables, we could do the same
1593 ;; stack-set-X+1 stack-ref-X --> dup stack-set-X+2
1594 ;; but this is a very minor gain, since dup is stack-ref-0,
1595 ;; i.e. it's only better if X>5, and even then it comes
1596 ;; at the cost cost of an extra stack slot. Let's not bother.
1597 ((and (eq 'byte-varref (car lap2))
1598 (eq (cdr lap1) (cdr lap2))
1599 (memq (car lap1) '(byte-varset byte-varbind)))
1600 (if (and (setq tmp (memq (car (cdr lap2)) byte-boolean-vars))
1601 (not (eq (car lap0) 'byte-constant)))
1604 (if (memq (car lap0) '(byte-constant byte-dup))
1606 (setq tmp (if (or (not tmp)
1607 (byte-compile-const-symbol-p
1610 (byte-compile-get-constant t)))
1611 (byte-compile-log-lap " %s %s %s\t-->\t%s %s %s"
1612 lap0 lap1 lap2 lap0 lap1
1613 (cons (car lap0) tmp))
1614 (setcar lap2 (car lap0))
1616 (byte-compile-log-lap " %s %s\t-->\tdup %s" lap1 lap2 lap1)
1617 (setcar lap2 (car lap1))
1618 (setcar lap1 'byte-dup)
1620 ;; The stack depth gets locally increased, so we will
1621 ;; increase maxdepth in case depth = maxdepth here.
1622 ;; This can cause the third argument to byte-code to
1623 ;; be larger than necessary.
1624 (setq add-depth 1))))
1626 ;; dup varset-X discard --> varset-X
1627 ;; dup varbind-X discard --> varbind-X
1628 ;; dup stack-set-X discard --> stack-set-X-1
1629 ;; (the varbind variant can emerge from other optimizations)
1631 ((and (eq 'byte-dup (car lap0))
1632 (eq 'byte-discard (car lap2))
1633 (memq (car lap1) '(byte-varset byte-varbind
1635 (byte-compile-log-lap " dup %s discard\t-->\t%s" lap1 lap1)
1638 (if (eq 'byte-stack-set (car lap1)) (decf (cdr lap1)))
1639 (setq lap (delq lap0 (delq lap2 lap))))
1641 ;; not goto-X-if-nil --> goto-X-if-non-nil
1642 ;; not goto-X-if-non-nil --> goto-X-if-nil
1644 ;; it is wrong to do the same thing for the -else-pop variants.
1646 ((and (eq 'byte-not (car lap0))
1647 (or (eq 'byte-goto-if-nil (car lap1))
1648 (eq 'byte-goto-if-not-nil (car lap1))))
1649 (byte-compile-log-lap " not %s\t-->\t%s"
1652 (if (eq (car lap1) 'byte-goto-if-nil)
1653 'byte-goto-if-not-nil
1656 (setcar lap1 (if (eq (car lap1) 'byte-goto-if-nil)
1657 'byte-goto-if-not-nil
1659 (setq lap (delq lap0 lap))
1660 (setq keep-going t))
1662 ;; goto-X-if-nil goto-Y X: --> goto-Y-if-non-nil X:
1663 ;; goto-X-if-non-nil goto-Y X: --> goto-Y-if-nil X:
1665 ;; it is wrong to do the same thing for the -else-pop variants.
1667 ((and (or (eq 'byte-goto-if-nil (car lap0))
1668 (eq 'byte-goto-if-not-nil (car lap0))) ; gotoX
1669 (eq 'byte-goto (car lap1)) ; gotoY
1670 (eq (cdr lap0) lap2)) ; TAG X
1671 (let ((inverse (if (eq 'byte-goto-if-nil (car lap0))
1672 'byte-goto-if-not-nil 'byte-goto-if-nil)))
1673 (byte-compile-log-lap " %s %s %s:\t-->\t%s %s:"
1675 (cons inverse (cdr lap1)) lap2)
1676 (setq lap (delq lap0 lap))
1677 (setcar lap1 inverse)
1678 (setq keep-going t)))
1680 ;; const goto-if-* --> whatever
1682 ((and (eq 'byte-constant (car lap0))
1683 (memq (car lap1) byte-conditional-ops))
1684 (cond ((if (or (eq (car lap1) 'byte-goto-if-nil)
1685 (eq (car lap1) 'byte-goto-if-nil-else-pop))
1687 (not (car (cdr lap0))))
1688 (byte-compile-log-lap " %s %s\t-->\t<deleted>"
1690 (setq rest (cdr rest)
1691 lap (delq lap0 (delq lap1 lap))))
1693 (byte-compile-log-lap " %s %s\t-->\t%s"
1695 (cons 'byte-goto (cdr lap1)))
1696 (when (memq (car lap1) byte-goto-always-pop-ops)
1697 (setq lap (delq lap0 lap)))
1698 (setcar lap1 'byte-goto)))
1699 (setq keep-going t))
1701 ;; varref-X varref-X --> varref-X dup
1702 ;; varref-X [dup ...] varref-X --> varref-X [dup ...] dup
1703 ;; stackref-X [dup ...] stackref-X+N --> stackref-X [dup ...] dup
1704 ;; We don't optimize the const-X variations on this here,
1705 ;; because that would inhibit some goto optimizations; we
1706 ;; optimize the const-X case after all other optimizations.
1708 ((and (memq (car lap0) '(byte-varref byte-stack-ref))
1710 (setq tmp (cdr rest))
1712 (while (eq (car (car tmp)) 'byte-dup)
1713 (setq tmp2 (1+ tmp2))
1714 (setq tmp (cdr tmp)))
1716 (eq (if (eq 'byte-stack-ref (car lap0))
1717 (+ tmp2 1 (cdr lap0))
1720 (eq (car lap0) (car (car tmp))))
1721 (if (memq byte-optimize-log '(t byte))
1723 (setq tmp2 (cdr rest))
1724 (while (not (eq tmp tmp2))
1725 (setq tmp2 (cdr tmp2)
1726 str (concat str " dup")))
1727 (byte-compile-log-lap " %s%s %s\t-->\t%s%s dup"
1728 lap0 str lap0 lap0 str)))
1730 (setcar (car tmp) 'byte-dup)
1731 (setcdr (car tmp) 0)
1734 ;; TAG1: TAG2: --> TAG1: <deleted>
1735 ;; (and other references to TAG2 are replaced with TAG1)
1737 ((and (eq (car lap0) 'TAG)
1738 (eq (car lap1) 'TAG))
1739 (and (memq byte-optimize-log '(t byte))
1740 (byte-compile-log " adjacent tags %d and %d merged"
1741 (nth 1 lap1) (nth 1 lap0)))
1743 (while (setq tmp2 (rassq lap0 tmp3))
1745 (setq tmp3 (cdr (memq tmp2 tmp3))))
1746 (setq lap (delq lap0 lap)
1749 ;; unused-TAG: --> <deleted>
1751 ((and (eq 'TAG (car lap0))
1752 (not (rassq lap0 lap)))
1753 (and (memq byte-optimize-log '(t byte))
1754 (byte-compile-log " unused tag %d removed" (nth 1 lap0)))
1755 (setq lap (delq lap0 lap)
1758 ;; goto ... --> goto <delete until TAG or end>
1759 ;; return ... --> return <delete until TAG or end>
1761 ((and (memq (car lap0) '(byte-goto byte-return))
1762 (not (memq (car lap1) '(TAG nil))))
1765 (opt-p (memq byte-optimize-log '(t lap)))
1767 (while (and (setq tmp (cdr tmp))
1768 (not (eq 'TAG (car (car tmp)))))
1769 (if opt-p (setq deleted (cons (car tmp) deleted)
1770 str (concat str " %s")
1774 (if (eq 'TAG (car (car tmp)))
1775 (format "%d:" (car (cdr (car tmp))))
1776 (or (car tmp) ""))))
1778 (apply 'byte-compile-log-lap-1
1780 " %s\t-->\t%s <deleted> %s")
1782 (nconc (nreverse deleted)
1783 (list tagstr lap0 tagstr)))
1784 (byte-compile-log-lap
1785 " %s <%d unreachable op%s> %s\t-->\t%s <deleted> %s"
1786 lap0 i (if (= i 1) "" "s")
1787 tagstr lap0 tagstr))))
1789 (setq keep-going t))
1791 ;; <safe-op> unbind --> unbind <safe-op>
1792 ;; (this may enable other optimizations.)
1794 ((and (eq 'byte-unbind (car lap1))
1795 (memq (car lap0) byte-after-unbind-ops))
1796 (byte-compile-log-lap " %s %s\t-->\t%s %s" lap0 lap1 lap1 lap0)
1798 (setcar (cdr rest) lap0)
1799 (setq keep-going t))
1801 ;; varbind-X unbind-N --> discard unbind-(N-1)
1802 ;; save-excursion unbind-N --> unbind-(N-1)
1803 ;; save-restriction unbind-N --> unbind-(N-1)
1805 ((and (eq 'byte-unbind (car lap1))
1806 (memq (car lap0) '(byte-varbind byte-save-excursion
1807 byte-save-restriction))
1809 (if (zerop (setcdr lap1 (1- (cdr lap1))))
1811 (if (eq (car lap0) 'byte-varbind)
1812 (setcar rest (cons 'byte-discard 0))
1813 (setq lap (delq lap0 lap)))
1814 (byte-compile-log-lap " %s %s\t-->\t%s %s"
1815 lap0 (cons (car lap1) (1+ (cdr lap1)))
1816 (if (eq (car lap0) 'byte-varbind)
1819 (if (and (/= 0 (cdr lap1))
1820 (eq (car lap0) 'byte-varbind))
1823 (setq keep-going t))
1825 ;; goto*-X ... X: goto-Y --> goto*-Y
1826 ;; goto-X ... X: return --> return
1828 ((and (memq (car lap0) byte-goto-ops)
1829 (memq (car (setq tmp (nth 1 (memq (cdr lap0) lap))))
1830 '(byte-goto byte-return)))
1831 (cond ((and (not (eq tmp lap0))
1832 (or (eq (car lap0) 'byte-goto)
1833 (eq (car tmp) 'byte-goto)))
1834 (byte-compile-log-lap " %s [%s]\t-->\t%s"
1836 (if (eq (car tmp) 'byte-return)
1837 (setcar lap0 'byte-return))
1838 (setcdr lap0 (cdr tmp))
1839 (setq keep-going t))))
1841 ;; goto-*-else-pop X ... X: goto-if-* --> whatever
1842 ;; goto-*-else-pop X ... X: discard --> whatever
1844 ((and (memq (car lap0) '(byte-goto-if-nil-else-pop
1845 byte-goto-if-not-nil-else-pop))
1846 (memq (car (car (setq tmp (cdr (memq (cdr lap0) lap)))))
1848 (cons 'byte-discard byte-conditional-ops)))
1849 (not (eq lap0 (car tmp))))
1850 (setq tmp2 (car tmp))
1851 (setq tmp3 (assq (car lap0) '((byte-goto-if-nil-else-pop
1853 (byte-goto-if-not-nil-else-pop
1854 byte-goto-if-not-nil))))
1855 (if (memq (car tmp2) tmp3)
1856 (progn (setcar lap0 (car tmp2))
1857 (setcdr lap0 (cdr tmp2))
1858 (byte-compile-log-lap " %s-else-pop [%s]\t-->\t%s"
1859 (car lap0) tmp2 lap0))
1860 ;; Get rid of the -else-pop's and jump one step further.
1861 (or (eq 'TAG (car (nth 1 tmp)))
1862 (setcdr tmp (cons (byte-compile-make-tag)
1864 (byte-compile-log-lap " %s [%s]\t-->\t%s <skip>"
1865 (car lap0) tmp2 (nth 1 tmp3))
1866 (setcar lap0 (nth 1 tmp3))
1867 (setcdr lap0 (nth 1 tmp)))
1868 (setq keep-going t))
1870 ;; const goto-X ... X: goto-if-* --> whatever
1871 ;; const goto-X ... X: discard --> whatever
1873 ((and (eq (car lap0) 'byte-constant)
1874 (eq (car lap1) 'byte-goto)
1875 (memq (car (car (setq tmp (cdr (memq (cdr lap1) lap)))))
1877 (cons 'byte-discard byte-conditional-ops)))
1878 (not (eq lap1 (car tmp))))
1879 (setq tmp2 (car tmp))
1880 (cond ((memq (car tmp2)
1881 (if (null (car (cdr lap0)))
1882 '(byte-goto-if-nil byte-goto-if-nil-else-pop)
1883 '(byte-goto-if-not-nil
1884 byte-goto-if-not-nil-else-pop)))
1885 (byte-compile-log-lap " %s goto [%s]\t-->\t%s %s"
1886 lap0 tmp2 lap0 tmp2)
1887 (setcar lap1 (car tmp2))
1888 (setcdr lap1 (cdr tmp2))
1889 ;; Let next step fix the (const,goto-if*) sequence.
1890 (setq rest (cons nil rest)))
1892 ;; Jump one step further
1893 (byte-compile-log-lap
1894 " %s goto [%s]\t-->\t<deleted> goto <skip>"
1896 (or (eq 'TAG (car (nth 1 tmp)))
1897 (setcdr tmp (cons (byte-compile-make-tag)
1899 (setcdr lap1 (car (cdr tmp)))
1900 (setq lap (delq lap0 lap))))
1901 (setq keep-going t))
1903 ;; X: varref-Y ... varset-Y goto-X -->
1904 ;; X: varref-Y Z: ... dup varset-Y goto-Z
1905 ;; (varset-X goto-BACK, BACK: varref-X --> copy the varref down.)
1906 ;; (This is so usual for while loops that it is worth handling).
1908 ;; Here again, we could do it for stack-ref/stack-set, but
1909 ;; that's replacing a stack-ref-Y with a stack-ref-0, which
1910 ;; is a very minor improvement (if any), at the cost of
1911 ;; more stack use and more byte-code. Let's not do it.
1913 ((and (eq (car lap1) 'byte-varset)
1914 (eq (car lap2) 'byte-goto)
1915 (not (memq (cdr lap2) rest)) ;Backwards jump
1916 (eq (car (car (setq tmp (cdr (memq (cdr lap2) lap)))))
1918 (eq (cdr (car tmp)) (cdr lap1))
1919 (not (memq (car (cdr lap1)) byte-boolean-vars)))
1920 ;;(byte-compile-log-lap " Pulled %s to end of loop" (car tmp))
1921 (let ((newtag (byte-compile-make-tag)))
1922 (byte-compile-log-lap
1923 " %s: %s ... %s %s\t-->\t%s: %s %s: ... %s %s %s"
1924 (nth 1 (cdr lap2)) (car tmp)
1926 (nth 1 (cdr lap2)) (car tmp)
1927 (nth 1 newtag) 'byte-dup lap1
1928 (cons 'byte-goto newtag)
1930 (setcdr rest (cons (cons 'byte-dup 0) (cdr rest)))
1931 (setcdr tmp (cons (setcdr lap2 newtag) (cdr tmp))))
1933 (setq keep-going t))
1935 ;; goto-X Y: ... X: goto-if*-Y --> goto-if-not-*-X+1 Y:
1936 ;; (This can pull the loop test to the end of the loop)
1938 ((and (eq (car lap0) 'byte-goto)
1939 (eq (car lap1) 'TAG)
1941 (cdr (car (setq tmp (cdr (memq (cdr lap0) lap))))))
1942 (memq (car (car tmp))
1943 '(byte-goto byte-goto-if-nil byte-goto-if-not-nil
1944 byte-goto-if-nil-else-pop)))
1945 ;; (byte-compile-log-lap " %s %s, %s %s --> moved conditional"
1946 ;; lap0 lap1 (cdr lap0) (car tmp))
1947 (let ((newtag (byte-compile-make-tag)))
1948 (byte-compile-log-lap
1949 "%s %s: ... %s: %s\t-->\t%s ... %s:"
1950 lap0 (nth 1 lap1) (nth 1 (cdr lap0)) (car tmp)
1951 (cons (cdr (assq (car (car tmp))
1952 '((byte-goto-if-nil . byte-goto-if-not-nil)
1953 (byte-goto-if-not-nil . byte-goto-if-nil)
1954 (byte-goto-if-nil-else-pop .
1955 byte-goto-if-not-nil-else-pop)
1956 (byte-goto-if-not-nil-else-pop .
1957 byte-goto-if-nil-else-pop))))
1962 (setcdr tmp (cons (setcdr lap0 newtag) (cdr tmp)))
1963 (if (eq (car (car tmp)) 'byte-goto-if-nil-else-pop)
1964 ;; We can handle this case but not the -if-not-nil case,
1965 ;; because we won't know which non-nil constant to push.
1966 (setcdr rest (cons (cons 'byte-constant
1967 (byte-compile-get-constant nil))
1969 (setcar lap0 (nth 1 (memq (car (car tmp))
1970 '(byte-goto-if-nil-else-pop
1971 byte-goto-if-not-nil
1973 byte-goto-if-not-nil
1974 byte-goto byte-goto))))
1976 (setq keep-going t))
1978 (setq rest (cdr rest)))
1981 ;; Rebuild byte-compile-constants / byte-compile-variables.
1982 ;; Simple optimizations that would inhibit other optimizations if they
1983 ;; were done in the optimizing loop, and optimizations which there is no
1984 ;; need to do more than once.
1985 (setq byte-compile-constants nil
1986 byte-compile-variables nil)
1988 (byte-compile-log-lap " ---- final pass")
1990 (setq lap0 (car rest)
1992 (if (memq (car lap0) byte-constref-ops)
1993 (if (or (eq (car lap0) 'byte-constant)
1994 (eq (car lap0) 'byte-constant2))
1995 (unless (memq (cdr lap0) byte-compile-constants)
1996 (setq byte-compile-constants (cons (cdr lap0)
1997 byte-compile-constants)))
1998 (unless (memq (cdr lap0) byte-compile-variables)
1999 (setq byte-compile-variables (cons (cdr lap0)
2000 byte-compile-variables)))))
2002 ;; const-C varset-X const-C --> const-C dup varset-X
2003 ;; const-C varbind-X const-C --> const-C dup varbind-X
2005 (and (eq (car lap0) 'byte-constant)
2006 (eq (car (nth 2 rest)) 'byte-constant)
2007 (eq (cdr lap0) (cdr (nth 2 rest)))
2008 (memq (car lap1) '(byte-varbind byte-varset)))
2009 (byte-compile-log-lap " %s %s %s\t-->\t%s dup %s"
2010 lap0 lap1 lap0 lap0 lap1)
2011 (setcar (cdr (cdr rest)) (cons (car lap1) (cdr lap1)))
2012 (setcar (cdr rest) (cons 'byte-dup 0))
2015 ;; const-X [dup/const-X ...] --> const-X [dup ...] dup
2016 ;; varref-X [dup/varref-X ...] --> varref-X [dup ...] dup
2018 ((memq (car lap0) '(byte-constant byte-varref))
2022 (while (eq 'byte-dup (car (car (setq tmp (cdr tmp))))))
2023 (and (eq (cdr lap0) (cdr (car tmp)))
2024 (eq (car lap0) (car (car tmp)))))
2025 (setcar tmp (cons 'byte-dup 0))
2028 (byte-compile-log-lap
2029 " %s [dup/%s]...\t-->\t%s dup..." lap0 lap0 lap0)))
2031 ;; unbind-N unbind-M --> unbind-(N+M)
2033 ((and (eq 'byte-unbind (car lap0))
2034 (eq 'byte-unbind (car lap1)))
2035 (byte-compile-log-lap " %s %s\t-->\t%s" lap0 lap1
2037 (+ (cdr lap0) (cdr lap1))))
2038 (setq lap (delq lap0 lap))
2039 (setcdr lap1 (+ (cdr lap1) (cdr lap0))))
2042 ;; stack-set-M [discard/discardN ...] --> discardN-preserve-tos
2043 ;; stack-set-M [discard/discardN ...] --> discardN
2045 ((and (eq (car lap0) 'byte-stack-set)
2046 (memq (car lap1) '(byte-discard byte-discardN))
2048 ;; See if enough discard operations follow to expose or
2049 ;; destroy the value stored by the stack-set.
2050 (setq tmp (cdr rest))
2051 (setq tmp2 (1- (cdr lap0)))
2053 (while (memq (car (car tmp)) '(byte-discard byte-discardN))
2055 (+ tmp3 (if (eq (car (car tmp)) 'byte-discard)
2058 (setq tmp (cdr tmp)))
2060 ;; Do the optimization.
2061 (setq lap (delq lap0 lap))
2064 ;; The value stored is the new TOS, so pop
2065 ;; one more value (to get rid of the old
2066 ;; value) using the TOS-preserving
2067 ;; discard operator.
2068 'byte-discardN-preserve-tos
2069 ;; Otherwise, the value stored is lost, so just use a
2072 (setcdr lap1 (1+ tmp3))
2073 (setcdr (cdr rest) tmp)
2074 (byte-compile-log-lap " %s [discard/discardN]...\t-->\t%s"
2078 ;; discard/discardN/discardN-preserve-tos-X discard/discardN-Y -->
2081 ((and (memq (car lap0)
2084 byte-discardN-preserve-tos))
2085 (memq (car lap1) '(byte-discard byte-discardN)))
2086 (setq lap (delq lap0 lap))
2087 (byte-compile-log-lap
2088 " %s %s\t-->\t(discardN %s)"
2090 (+ (if (eq (car lap0) 'byte-discard) 1 (cdr lap0))
2091 (if (eq (car lap1) 'byte-discard) 1 (cdr lap1))))
2092 (setcdr lap1 (+ (if (eq (car lap0) 'byte-discard) 1 (cdr lap0))
2093 (if (eq (car lap1) 'byte-discard) 1 (cdr lap1))))
2094 (setcar lap1 'byte-discardN))
2097 ;; discardN-preserve-tos-X discardN-preserve-tos-Y -->
2098 ;; discardN-preserve-tos-(X+Y)
2100 ((and (eq (car lap0) 'byte-discardN-preserve-tos)
2101 (eq (car lap1) 'byte-discardN-preserve-tos))
2102 (setq lap (delq lap0 lap))
2103 (setcdr lap1 (+ (cdr lap0) (cdr lap1)))
2104 (byte-compile-log-lap " %s %s\t-->\t%s" lap0 lap1 (car rest)))
2107 ;; discardN-preserve-tos return --> return
2108 ;; dup return --> return
2109 ;; stack-set-N return --> return ; where N is TOS-1
2111 ((and (eq (car lap1) 'byte-return)
2112 (or (memq (car lap0) '(byte-discardN-preserve-tos byte-dup))
2113 (and (eq (car lap0) 'byte-stack-set)
2115 ;; The byte-code interpreter will pop the stack for us, so
2116 ;; we can just leave stuff on it.
2117 (setq lap (delq lap0 lap))
2118 (byte-compile-log-lap " %s %s\t-->\t%s" lap0 lap1 lap1))
2120 (setq rest (cdr rest)))
2121 (setq byte-compile-maxdepth (+ byte-compile-maxdepth add-depth)))
2127 ;; To avoid "lisp nesting exceeds max-lisp-eval-depth" when this file compiles
2128 ;; itself, compile some of its most used recursive functions (at load time).
2131 (or (byte-code-function-p (symbol-function 'byte-optimize-form))
2132 (assq 'byte-code (symbol-function 'byte-optimize-form))
2133 (let ((byte-optimize nil)
2134 (byte-compile-warnings nil))
2136 (or noninteractive (message "compiling %s..." x))
2138 (or noninteractive (message "compiling %s...done" x)))
2139 '(byte-optimize-form
2141 byte-optimize-predicate
2142 byte-optimize-binary-predicate
2143 ;; Inserted some more than necessary, to speed it up.
2144 byte-optimize-form-code-walker
2145 byte-optimize-lapcode))))
2148 ;;; byte-opt.el ends here