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