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