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