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