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