byte-opt.el 67.9 KB
Newer Older
Jim Blandy's avatar
Jim Blandy committed
1 2
;;; byte-opt.el --- the optimization passes of the emacs-lisp byte compiler.

Karl Heuer's avatar
Karl Heuer committed
3
;;; Copyright (c) 1991, 1994 Free Software Foundation, Inc.
Jim Blandy's avatar
Jim Blandy committed
4 5 6 7

;; Author: Jamie Zawinski <jwz@lucid.com>
;;	Hallvard Furuseth <hbf@ulrik.uio.no>
;; Keywords: internal
Jim Blandy's avatar
Jim Blandy committed
8 9 10 11 12

;; This file is part of GNU Emacs.

;; GNU Emacs is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
Jim Blandy's avatar
Jim Blandy committed
13
;; the Free Software Foundation; either version 2, or (at your option)
Jim Blandy's avatar
Jim Blandy committed
14 15 16 17 18 19 20 21
;; any later version.

;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
Erik Naggum's avatar
Erik Naggum committed
22 23 24
;; along with GNU Emacs; see the file COPYING.  If not, write to the
;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
;; Boston, MA 02111-1307, USA.
Jim Blandy's avatar
Jim Blandy committed
25

Jim Blandy's avatar
Jim Blandy committed
26 27
;;; Commentary:

Karl Heuer's avatar
Karl Heuer committed
28 29 30 31 32 33 34 35 36
;;; This file has been censored by the Communications Decency Act.
;;; That law was passed under the guise of a ban on pornography, but
;;; it bans far more than that.  This file did not contain pornography,
;;; but it was censored nonetheless.

;;; For information on US government censorship of the Internet, and
;;; what you can do to bring back freedom of the press, see the web
;;; site http://www.vtw.org/

Erik Naggum's avatar
Erik Naggum committed
37 38 39 40 41 42 43 44 45
;; ========================================================================
;; "No matter how hard you try, you can't make a racehorse out of a pig.
;; You can, however, make a faster pig."
;;
;; Or, to put it another way, the emacs byte compiler is a VW Bug.  This code
;; makes it be a VW Bug with fuel injection and a turbocharger...  You're 
;; still not going to make it go faster than 70 mph, but it might be easier
;; to get it there.
;;
Jim Blandy's avatar
Jim Blandy committed
46

Erik Naggum's avatar
Erik Naggum committed
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
;; TO DO:
;;
;; (apply '(lambda (x &rest y) ...) 1 (foo))
;;
;; maintain a list of functions known not to access any global variables
;; (actually, give them a 'dynamically-safe property) and then
;;   (let ( v1 v2 ... vM vN ) <...dynamically-safe...> )  ==>
;;   (let ( v1 v2 ... vM ) vN <...dynamically-safe...> )
;; by recursing on this, we might be able to eliminate the entire let.
;; However certain variables should never have their bindings optimized
;; away, because they affect everything.
;;   (put 'debug-on-error 'binding-is-magic t)
;;   (put 'debug-on-abort 'binding-is-magic t)
;;   (put 'debug-on-next-call 'binding-is-magic t)
;;   (put 'mocklisp-arguments 'binding-is-magic t)
;;   (put 'inhibit-quit 'binding-is-magic t)
;;   (put 'quit-flag 'binding-is-magic t)
;;   (put 't 'binding-is-magic t)
;;   (put 'nil 'binding-is-magic t)
;; possibly also
;;   (put 'gc-cons-threshold 'binding-is-magic t)
;;   (put 'track-mouse 'binding-is-magic t)
;; others?
;;
;; Simple defsubsts often produce forms like
;;    (let ((v1 (f1)) (v2 (f2)) ...)
;;       (FN v1 v2 ...))
;; It would be nice if we could optimize this to 
;;    (FN (f1) (f2) ...)
;; but we can't unless FN is dynamically-safe (it might be dynamically
;; referring to the bindings that the lambda arglist established.)
;; One of the uncountable lossages introduced by dynamic scope...
;;
;; Maybe there should be a control-structure that says "turn on 
;; fast-and-loose type-assumptive optimizations here."  Then when
;; we see a form like (car foo) we can from then on assume that
;; the variable foo is of type cons, and optimize based on that.
;; But, this won't win much because of (you guessed it) dynamic 
;; scope.  Anything down the stack could change the value.
;; (Another reason it doesn't work is that it is perfectly valid
;; to call car with a null argument.)  A better approach might
;; be to allow type-specification of the form
;;   (put 'foo 'arg-types '(float (list integer) dynamic))
;;   (put 'foo 'result-type 'bool)
;; It should be possible to have these types checked to a certain
;; degree.
;;
;; collapse common subexpressions
;;
;; It would be nice if redundant sequences could be factored out as well,
;; when they are known to have no side-effects:
;;   (list (+ a b c) (+ a b c))   -->  a b add c add dup list-2
;; but beware of traps like
;;   (cons (list x y) (list x y))
;;
;; Tail-recursion elimination is not really possible in Emacs Lisp.
;; Tail-recursion elimination is almost always impossible when all variables
;; have dynamic scope, but given that the "return" byteop requires the
;; binding stack to be empty (rather than emptying it itself), there can be
;; no truly tail-recursive Emacs Lisp functions that take any arguments or
;; make any bindings.
;;
;; Here is an example of an Emacs Lisp function which could safely be
;; byte-compiled tail-recursively:
;;
;;  (defun tail-map (fn list)
;;    (cond (list
;;           (funcall fn (car list))
;;           (tail-map fn (cdr list)))))
;;
;; However, if there was even a single let-binding around the COND,
;; it could not be byte-compiled, because there would be an "unbind"
;; byte-op between the final "call" and "return."  Adding a 
;; Bunbind_all byteop would fix this.
;;
;;   (defun foo (x y z) ... (foo a b c))
;;   ... (const foo) (varref a) (varref b) (varref c) (call 3) END: (return)
;;   ... (varref a) (varbind x) (varref b) (varbind y) (varref c) (varbind z) (goto 0) END: (unbind-all) (return)
;;   ... (varref a) (varset x) (varref b) (varset y) (varref c) (varset z) (goto 0) END: (return)
;;
;; this also can be considered tail recursion:
;;
;;   ... (const foo) (varref a) (call 1) (goto X) ... X: (return)
;; could generalize this by doing the optimization
;;   (goto X) ... X: (return)  -->  (return)
;;
;; But this doesn't solve all of the problems: although by doing tail-
;; recursion elimination in this way, the call-stack does not grow, the
;; binding-stack would grow with each recursive step, and would eventually
;; overflow.  I don't believe there is any way around this without lexical
;; scope.
;;
;; Wouldn't it be nice if Emacs Lisp had lexical scope.
;;
;; Idea: the form (lexical-scope) in a file means that the file may be 
;; compiled lexically.  This proclamation is file-local.  Then, within 
;; that file, "let" would establish lexical bindings, and "let-dynamic"
;; would do things the old way.  (Or we could use CL "declare" forms.)
;; We'd have to notice defvars and defconsts, since those variables should
;; always be dynamic, and attempting to do a lexical binding of them
;; should simply do a dynamic binding instead.
;; But!  We need to know about variables that were not necessarily defvarred
;; in the file being compiled (doing a boundp check isn't good enough.)
;; Fdefvar() would have to be modified to add something to the plist.
;;
;; A major disadvantage of this scheme is that the interpreter and compiler 
;; would have different semantics for files compiled with (dynamic-scope).  
;; Since this would be a file-local optimization, there would be no way to
;; modify the interpreter to obey this (unless the loader was hacked 
;; in some grody way, but that's a really bad idea.)
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191

;; Other things to consider:

;;;;; Associative math should recognize subcalls to identical function:
;;;(disassemble (lambda (x) (+ (+ (foo) 1) (+ (bar) 2))))
;;;;; This should generate the same as (1+ x) and (1- x)

;;;(disassemble (lambda (x) (cons (+ x 1) (- x 1))))
;;;;; An awful lot of functions always return a non-nil value.  If they're
;;;;; error free also they may act as true-constants.

;;;(disassemble (lambda (x) (and (point) (foo))))
;;;;; When 
;;;;;   - all but one arguments to a function are constant
;;;;;   - the non-constant argument is an if-expression (cond-expression?)
;;;;; then the outer function can be distributed.  If the guarding
;;;;; condition is side-effect-free [assignment-free] then the other
;;;;; arguments may be any expressions.  Since, however, the code size
;;;;; can increase this way they should be "simple".  Compare:

;;;(disassemble (lambda (x) (eq (if (point) 'a 'b) 'c)))
;;;(disassemble (lambda (x) (if (point) (eq 'a 'c) (eq 'b 'c))))

;;;;; (car (cons A B)) -> (progn B A)
;;;(disassemble (lambda (x) (car (cons (foo) 42))))

;;;;; (cdr (cons A B)) -> (progn A B)
;;;(disassemble (lambda (x) (cdr (cons 42 (foo)))))

;;;;; (car (list A B ...)) -> (progn B ... A)
;;;(disassemble (lambda (x) (car (list (foo) 42 (bar)))))

;;;;; (cdr (list A B ...)) -> (progn A (list B ...))
;;;(disassemble (lambda (x) (cdr (list 42 (foo) (bar)))))

Jim Blandy's avatar
Jim Blandy committed
192

Jim Blandy's avatar
Jim Blandy committed
193
;;; Code:
Jim Blandy's avatar
Jim Blandy committed
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254

(defun byte-compile-log-lap-1 (format &rest args)
  (if (aref byte-code-vector 0)
      (error "The old version of the disassembler is loaded.  Reload new-bytecomp as well."))
  (byte-compile-log-1
   (apply 'format format
     (let (c a)
       (mapcar '(lambda (arg)
		  (if (not (consp arg))
		      (if (and (symbolp arg)
			       (string-match "^byte-" (symbol-name arg)))
			  (intern (substring (symbol-name arg) 5))
			arg)
		    (if (integerp (setq c (car arg)))
			(error "non-symbolic byte-op %s" c))
		    (if (eq c 'TAG)
			(setq c arg)
		      (setq a (cond ((memq c byte-goto-ops)
				     (car (cdr (cdr arg))))
				    ((memq c byte-constref-ops)
				     (car (cdr arg)))
				    (t (cdr arg))))
		      (setq c (symbol-name c))
		      (if (string-match "^byte-." c)
			  (setq c (intern (substring c 5)))))
		    (if (eq c 'constant) (setq c 'const))
		    (if (and (eq (cdr arg) 0)
			     (not (memq c '(unbind call const))))
			c
		      (format "(%s %s)" c a))))
	       args)))))

(defmacro byte-compile-log-lap (format-string &rest args)
  (list 'and
	'(memq byte-optimize-log '(t byte))
	(cons 'byte-compile-log-lap-1
	      (cons format-string args))))


;;; byte-compile optimizers to support inlining

(put 'inline 'byte-optimizer 'byte-optimize-inline-handler)

(defun byte-optimize-inline-handler (form)
  "byte-optimize-handler for the `inline' special-form."
  (cons 'progn
	(mapcar
	 '(lambda (sexp)
	    (let ((fn (car-safe sexp)))
	      (if (and (symbolp fn)
		    (or (cdr (assq fn byte-compile-function-environment))
		      (and (fboundp fn)
			(not (or (cdr (assq fn byte-compile-macro-environment))
				 (and (consp (setq fn (symbol-function fn)))
				      (eq (car fn) 'macro))
				 (subrp fn))))))
		  (byte-compile-inline-expand sexp)
		sexp)))
	 (cdr form))))


255 256 257 258
;; Splice the given lap code into the current instruction stream.
;; If it has any labels in it, you're responsible for making sure there
;; are no collisions, and that byte-compile-tag-number is reasonable
;; after this is spliced in.  The provided list is destroyed.
Jim Blandy's avatar
Jim Blandy committed
259 260 261 262 263 264 265 266 267 268 269 270 271 272
(defun byte-inline-lapcode (lap)
  (setq byte-compile-output (nconc (nreverse lap) byte-compile-output)))


(defun byte-compile-inline-expand (form)
  (let* ((name (car form))
	 (fn (or (cdr (assq name byte-compile-function-environment))
		 (and (fboundp name) (symbol-function name)))))
    (if (null fn)
	(progn
	  (byte-compile-warn "attempt to inline %s before it was defined" name)
	  form)
      ;; else
      (if (and (consp fn) (eq (car fn) 'autoload))
273 274 275 276
	  (progn
	    (load (nth 1 fn))
	    (setq fn (or (cdr (assq name byte-compile-function-environment))
			 (and (fboundp name) (symbol-function name))))))
Jim Blandy's avatar
Jim Blandy committed
277 278 279 280
      (if (and (consp fn) (eq (car fn) 'autoload))
	  (error "file \"%s\" didn't define \"%s\"" (nth 1 fn) name))
      (if (symbolp fn)
	  (byte-compile-inline-expand (cons fn (cdr form)))
281
	(if (byte-code-function-p fn)
282 283 284 285 286
	    (progn
	      (fetch-bytecode fn)
	      (cons (list 'lambda (aref fn 0)
			  (list 'byte-code (aref fn 1) (aref fn 2) (aref fn 3)))
		    (cdr form)))
Jim Blandy's avatar
Jim Blandy committed
287 288 289 290 291 292 293 294 295
	  (if (not (eq (car fn) 'lambda)) (error "%s is not a lambda" name))
	  (cons fn (cdr form)))))))

;;; ((lambda ...) ...)
;;; 
(defun byte-compile-unfold-lambda (form &optional name)
  (or name (setq name "anonymous lambda"))
  (let ((lambda (car form))
	(values (cdr form)))
296
    (if (byte-code-function-p lambda)
Jim Blandy's avatar
Jim Blandy committed
297 298 299
	(setq lambda (list 'lambda (aref lambda 0)
			   (list 'byte-code (aref lambda 1)
				 (aref lambda 2) (aref lambda 3)))))
Jim Blandy's avatar
Jim Blandy committed
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
    (let ((arglist (nth 1 lambda))
	  (body (cdr (cdr lambda)))
	  optionalp restp
	  bindings)
      (if (and (stringp (car body)) (cdr body))
	  (setq body (cdr body)))
      (if (and (consp (car body)) (eq 'interactive (car (car body))))
	  (setq body (cdr body)))
      (while arglist
	(cond ((eq (car arglist) '&optional)
	       ;; ok, I'll let this slide because funcall_lambda() does...
	       ;; (if optionalp (error "multiple &optional keywords in %s" name))
	       (if restp (error "&optional found after &rest in %s" name))
	       (if (null (cdr arglist))
		   (error "nothing after &optional in %s" name))
	       (setq optionalp t))
	      ((eq (car arglist) '&rest)
	       ;; ...but it is by no stretch of the imagination a reasonable
	       ;; thing that funcall_lambda() allows (&rest x y) and
	       ;; (&rest x &optional y) in arglists.
	       (if (null (cdr arglist))
		   (error "nothing after &rest in %s" name))
	       (if (cdr (cdr arglist))
		   (error "multiple vars after &rest in %s" name))
	       (setq restp t))
	      (restp
	       (setq bindings (cons (list (car arglist)
					  (and values (cons 'list values)))
				    bindings)
		     values nil))
	      ((and (not optionalp) (null values))
	       (byte-compile-warn "attempt to open-code %s with too few arguments" name)
	       (setq arglist nil values 'too-few))
	      (t
	       (setq bindings (cons (list (car arglist) (car values))
				    bindings)
		     values (cdr values))))
	(setq arglist (cdr arglist)))
      (if values
	  (progn
	    (or (eq values 'too-few)
		(byte-compile-warn
		 "attempt to open-code %s with too many arguments" name))
	    form)
344
	(setq body (mapcar 'byte-optimize-form body))
Jim Blandy's avatar
Jim Blandy committed
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
	(let ((newform 
	       (if bindings
		   (cons 'let (cons (nreverse bindings) body))
		 (cons 'progn body))))
	  (byte-compile-log "  %s\t==>\t%s" form newform)
	  newform)))))


;;; implementing source-level optimizers

(defun byte-optimize-form-code-walker (form for-effect)
  ;;
  ;; For normal function calls, We can just mapcar the optimizer the cdr.  But
  ;; we need to have special knowledge of the syntax of the special forms
  ;; like let and defun (that's why they're special forms :-).  (Actually,
  ;; the important aspect is that they are subrs that don't evaluate all of
  ;; their args.)
  ;;
  (let ((fn (car-safe form))
	tmp)
    (cond ((not (consp form))
	   (if (not (and for-effect
			 (or byte-compile-delete-errors
			     (not (symbolp form))
			     (eq form t))))
	     form))
	  ((eq fn 'quote)
	   (if (cdr (cdr form))
	       (byte-compile-warn "malformed quote form: %s"
				  (prin1-to-string form)))
	   ;; map (quote nil) to nil to simplify optimizer logic.
	   ;; map quoted constants to nil if for-effect (just because).
	   (and (nth 1 form)
		(not for-effect)
		form))
380
	  ((or (byte-code-function-p fn)
Jim Blandy's avatar
Jim Blandy committed
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
	       (eq 'lambda (car-safe fn)))
	   (byte-compile-unfold-lambda form))
	  ((memq fn '(let let*))
	   ;; recursively enter the optimizer for the bindings and body
	   ;; of a let or let*.  This for depth-firstness: forms that
	   ;; are more deeply nested are optimized first.
	   (cons fn
	     (cons
	      (mapcar '(lambda (binding)
			 (if (symbolp binding)
			     binding
			   (if (cdr (cdr binding))
			       (byte-compile-warn "malformed let binding: %s"
						  (prin1-to-string binding)))
			   (list (car binding)
				 (byte-optimize-form (nth 1 binding) nil))))
		      (nth 1 form))
	      (byte-optimize-body (cdr (cdr form)) for-effect))))
	  ((eq fn 'cond)
	   (cons fn
		 (mapcar '(lambda (clause)
			    (if (consp clause)
				(cons
				 (byte-optimize-form (car clause) nil)
				 (byte-optimize-body (cdr clause) for-effect))
			      (byte-compile-warn "malformed cond form: %s"
						 (prin1-to-string clause))
			      clause))
			 (cdr form))))
	  ((eq fn 'progn)
	   ;; as an extra added bonus, this simplifies (progn <x>) --> <x>
	   (if (cdr (cdr form))
	       (progn
		 (setq tmp (byte-optimize-body (cdr form) for-effect))
		 (if (cdr tmp) (cons 'progn tmp) (car tmp)))
	     (byte-optimize-form (nth 1 form) for-effect)))
	  ((eq fn 'prog1)
	   (if (cdr (cdr form))
	       (cons 'prog1
		     (cons (byte-optimize-form (nth 1 form) for-effect)
			   (byte-optimize-body (cdr (cdr form)) t)))
	     (byte-optimize-form (nth 1 form) for-effect)))
	  ((eq fn 'prog2)
	   (cons 'prog2
	     (cons (byte-optimize-form (nth 1 form) t)
	       (cons (byte-optimize-form (nth 2 form) for-effect)
		     (byte-optimize-body (cdr (cdr (cdr form))) t)))))
	  
429
	  ((memq fn '(save-excursion save-restriction save-current-buffer))
Jim Blandy's avatar
Jim Blandy committed
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
	   ;; those subrs which have an implicit progn; it's not quite good
	   ;; enough to treat these like normal function calls.
	   ;; This can turn (save-excursion ...) into (save-excursion) which
	   ;; will be optimized away in the lap-optimize pass.
	   (cons fn (byte-optimize-body (cdr form) for-effect)))
	  
	  ((eq fn 'with-output-to-temp-buffer)
	   ;; this is just like the above, except for the first argument.
	   (cons fn
	     (cons
	      (byte-optimize-form (nth 1 form) nil)
	      (byte-optimize-body (cdr (cdr form)) for-effect))))
	  
	  ((eq fn 'if)
	   (cons fn
	     (cons (byte-optimize-form (nth 1 form) nil)
	       (cons
		(byte-optimize-form (nth 2 form) for-effect)
		(byte-optimize-body (nthcdr 3 form) for-effect)))))
	  
	  ((memq fn '(and or))  ; remember, and/or are control structures.
	   ;; take forms off the back until we can't any more.
452
	   ;; In the future it could conceivably be a problem that the
Jim Blandy's avatar
Jim Blandy committed
453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585
	   ;; subexpressions of these forms are optimized in the reverse
	   ;; order, but it's ok for now.
	   (if for-effect
	       (let ((backwards (reverse (cdr form))))
		 (while (and backwards
			     (null (setcar backwards
					   (byte-optimize-form (car backwards)
							       for-effect))))
		   (setq backwards (cdr backwards)))
		 (if (and (cdr form) (null backwards))
		     (byte-compile-log
		      "  all subforms of %s called for effect; deleted" form))
		 (and backwards
		      (cons fn (nreverse backwards))))
	     (cons fn (mapcar 'byte-optimize-form (cdr form)))))

	  ((eq fn 'interactive)
	   (byte-compile-warn "misplaced interactive spec: %s"
			      (prin1-to-string form))
	   nil)
	  
	  ((memq fn '(defun defmacro function
		      condition-case save-window-excursion))
	   ;; These forms are compiled as constants or by breaking out
	   ;; all the subexpressions and compiling them separately.
	   form)

	  ((eq fn 'unwind-protect)
	   ;; the "protected" part of an unwind-protect is compiled (and thus
	   ;; optimized) as a top-level form, so don't do it here.  But the
	   ;; non-protected part has the same for-effect status as the
	   ;; unwind-protect itself.  (The protected part is always for effect,
	   ;; but that isn't handled properly yet.)
	   (cons fn
		 (cons (byte-optimize-form (nth 1 form) for-effect)
		       (cdr (cdr form)))))
	   
	  ((eq fn 'catch)
	   ;; the body of a catch is compiled (and thus optimized) as a
	   ;; top-level form, so don't do it here.  The tag is never
	   ;; for-effect.  The body should have the same for-effect status
	   ;; as the catch form itself, but that isn't handled properly yet.
	   (cons fn
		 (cons (byte-optimize-form (nth 1 form) nil)
		       (cdr (cdr form)))))

	  ;; If optimization is on, this is the only place that macros are
	  ;; expanded.  If optimization is off, then macroexpansion happens
	  ;; in byte-compile-form.  Otherwise, the macros are already expanded
	  ;; by the time that is reached.
	  ((not (eq form
		    (setq form (macroexpand form
					    byte-compile-macro-environment))))
	   (byte-optimize-form form for-effect))
	  
	  ((not (symbolp fn))
	   (or (eq 'mocklisp (car-safe fn)) ; ha!
	       (byte-compile-warn "%s is a malformed function"
				  (prin1-to-string fn)))
	   form)

	  ((and for-effect (setq tmp (get fn 'side-effect-free))
		(or byte-compile-delete-errors
		    (eq tmp 'error-free)
		    (progn
		      (byte-compile-warn "%s called for effect"
					 (prin1-to-string form))
		      nil)))
	   (byte-compile-log "  %s called for effect; deleted" fn)
	   ;; appending a nil here might not be necessary, but it can't hurt.
	   (byte-optimize-form
	    (cons 'progn (append (cdr form) '(nil))) t))
	  
	  (t
	   ;; Otherwise, no args can be considered to be for-effect,
	   ;; even if the called function is for-effect, because we
	   ;; don't know anything about that function.
	   (cons fn (mapcar 'byte-optimize-form (cdr form)))))))


(defun byte-optimize-form (form &optional for-effect)
  "The source-level pass of the optimizer."
  ;;
  ;; First, optimize all sub-forms of this one.
  (setq form (byte-optimize-form-code-walker form for-effect))
  ;;
  ;; after optimizing all subforms, optimize this form until it doesn't
  ;; optimize any further.  This means that some forms will be passed through
  ;; the optimizer many times, but that's necessary to make the for-effect
  ;; processing do as much as possible.
  ;;
  (let (opt new)
    (if (and (consp form)
	     (symbolp (car form))
	     (or (and for-effect
		      ;; we don't have any of these yet, but we might.
		      (setq opt (get (car form) 'byte-for-effect-optimizer)))
		 (setq opt (get (car form) 'byte-optimizer)))
	     (not (eq form (setq new (funcall opt form)))))
	(progn
;;	  (if (equal form new) (error "bogus optimizer -- %s" opt))
	  (byte-compile-log "  %s\t==>\t%s" form new)
	  (setq new (byte-optimize-form new for-effect))
	  new)
      form)))


(defun byte-optimize-body (forms all-for-effect)
  ;; optimize the cdr of a progn or implicit progn; all forms is a list of
  ;; forms, all but the last of which are optimized with the assumption that
  ;; they are being called for effect.  the last is for-effect as well if
  ;; all-for-effect is true.  returns a new list of forms.
  (let ((rest forms)
	(result nil)
	fe new)
    (while rest
      (setq fe (or all-for-effect (cdr rest)))
      (setq new (and (car rest) (byte-optimize-form (car rest) fe)))
      (if (or new (not fe))
	  (setq result (cons new result)))
      (setq rest (cdr rest)))
    (nreverse result)))


;;; some source-level optimizers
;;;
;;; when writing optimizers, be VERY careful that the optimizer returns
;;; something not EQ to its argument if and ONLY if it has made a change.
;;; This implies that you cannot simply destructively modify the list;
;;; you must return something not EQ to it if you make an optimization.
;;;
;;; It is now safe to optimize code such that it introduces new bindings.

586
;; I'd like this to be a defsubst, but let's not be self-referential...
Jim Blandy's avatar
Jim Blandy committed
587 588 589 590 591 592
(defmacro byte-compile-trueconstp (form)
  ;; Returns non-nil if FORM is a non-nil constant.
  (` (cond ((consp (, form)) (eq (car (, form)) 'quote))
	   ((not (symbolp (, form))))
	   ((eq (, form) t)))))

593 594 595
;; If the function is being called with constant numeric args,
;; evaluate as much as possible at compile-time.  This optimizer 
;; assumes that the function is associative, like + or *.
Jim Blandy's avatar
Jim Blandy committed
596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614
(defun byte-optimize-associative-math (form)
  (let ((args nil)
	(constants nil)
	(rest (cdr form)))
    (while rest
      (if (numberp (car rest))
	  (setq constants (cons (car rest) constants))
	  (setq args (cons (car rest) args)))
      (setq rest (cdr rest)))
    (if (cdr constants)
	(if args
	    (list (car form)
		  (apply (car form) constants)
		  (if (cdr args)
		      (cons (car form) (nreverse args))
		      (car args)))
	    (apply (car form) constants))
	form)))

615
;; If the function is being called with constant numeric args,
616 617 618 619
;; evaluate as much as possible at compile-time.  This optimizer
;; assumes that the function satisfies
;;   (op x1 x2 ... xn) == (op ...(op (op x1 x2) x3) ...xn)
;; like - and /.
Jim Blandy's avatar
Jim Blandy committed
620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644
(defun byte-optimize-nonassociative-math (form)
  (if (or (not (numberp (car (cdr form))))
	  (not (numberp (car (cdr (cdr form))))))
      form
    (let ((constant (car (cdr form)))
	  (rest (cdr (cdr form))))
      (while (numberp (car rest))
	(setq constant (funcall (car form) constant (car rest))
	      rest (cdr rest)))
      (if rest
	  (cons (car form) (cons constant rest))
	  constant))))

;;(defun byte-optimize-associative-two-args-math (form)
;;  (setq form (byte-optimize-associative-math form))
;;  (if (consp form)
;;      (byte-optimize-two-args-left form)
;;      form))

;;(defun byte-optimize-nonassociative-two-args-math (form)
;;  (setq form (byte-optimize-nonassociative-math form))
;;  (if (consp form)
;;      (byte-optimize-two-args-right form)
;;      form))

645 646 647 648 649 650 651 652 653 654
(defun byte-optimize-approx-equal (x y)
  (< (* (abs (- x y)) 100) (abs (+ x y))))

;; Collect all the constants from FORM, after the STARTth arg,
;; and apply FUN to them to make one argument at the end.
;; For functions that can handle floats, that optimization
;; can be incorrect because reordering can cause an overflow
;; that would otherwise be avoided by encountering an arg that is a float.
;; We avoid this problem by (1) not moving float constants and
;; (2) not moving anything if it would cause an overflow.
Jim Blandy's avatar
Jim Blandy committed
655 656 657
(defun byte-optimize-delay-constants-math (form start fun)
  ;; Merge all FORM's constants from number START, call FUN on them
  ;; and put the result at the end.
658 659 660 661
  (let ((rest (nthcdr (1- start) form))
	(orig form)
	;; t means we must check for overflow.
	(overflow (memq fun '(+ *))))
Jim Blandy's avatar
Jim Blandy committed
662
    (while (cdr (setq rest (cdr rest)))
663
      (if (integerp (car rest))
Jim Blandy's avatar
Jim Blandy committed
664 665 666 667
	  (let (constants)
	    (setq form (copy-sequence form)
		  rest (nthcdr (1- start) form))
	    (while (setq rest (cdr rest))
668
	      (cond ((integerp (car rest))
Jim Blandy's avatar
Jim Blandy committed
669 670
		     (setq constants (cons (car rest) constants))
		     (setcar rest nil))))
671 672 673 674 675 676 677 678 679 680 681 682
	    ;; If necessary, check now for overflow
	    ;; that might be caused by reordering.
	    (if (and overflow
		     ;; We have overflow if the result of doing the arithmetic
		     ;; on floats is not even close to the result
		     ;; of doing it on integers.
		     (not (byte-optimize-approx-equal
			    (apply fun (mapcar 'float constants))
			    (float (apply fun constants)))))
		(setq form orig)
	      (setq form (nconc (delq nil form)
				(list (apply fun (nreverse constants)))))))))
Jim Blandy's avatar
Jim Blandy committed
683 684 685 686 687 688 689 690 691 692
    form))

(defun byte-optimize-plus (form)
  (setq form (byte-optimize-delay-constants-math form 1 '+))
  (if (memq 0 form) (setq form (delq 0 (copy-sequence form))))
  ;;(setq form (byte-optimize-associative-two-args-math form))
  (cond ((null (cdr form))
	 (condition-case ()
	     (eval form)
	   (error form)))
693 694 695 696
;;; It is not safe to delete the function entirely
;;; (actually, it would be safe if we know the sole arg
;;; is not a marker).
;;	((null (cdr (cdr form))) (nth 1 form))
Jim Blandy's avatar
Jim Blandy committed
697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712
	(t form)))

(defun byte-optimize-minus (form)
  ;; Put constants at the end, except the last constant.
  (setq form (byte-optimize-delay-constants-math form 2 '+))
  ;; Now only first and last element can be a number.
  (let ((last (car (reverse (nthcdr 3 form)))))
    (cond ((eq 0 last)
	   ;; (- x y ... 0)  --> (- x y ...)
	   (setq form (copy-sequence form))
	   (setcdr (cdr (cdr form)) (delq 0 (nthcdr 3 form))))
	  ;; If form is (- CONST foo... CONST), merge first and last.
	  ((and (numberp (nth 1 form))
		(numberp last))
	   (setq form (nconc (list '- (- (nth 1 form) last) (nth 2 form))
			     (delq last (copy-sequence (nthcdr 3 form))))))))
713 714 715 716 717
;;; It is not safe to delete the function entirely
;;; (actually, it would be safe if we know the sole arg
;;; is not a marker).
;;;  (if (eq (nth 2 form) 0)
;;;      (nth 1 form)			; (- x 0)  -->  x
Jim Blandy's avatar
Jim Blandy committed
718 719 720 721
    (byte-optimize-predicate
     (if (and (null (cdr (cdr (cdr form))))
	      (eq (nth 1 form) 0))	; (- 0 x)  -->  (- x)
	 (cons (car form) (cdr (cdr form)))
722 723 724
       form))
;;;    )
  )
Jim Blandy's avatar
Jim Blandy committed
725 726 727 728 729

(defun byte-optimize-multiply (form)
  (setq form (byte-optimize-delay-constants-math form 1 '*))
  ;; If there is a constant in FORM, it is now the last element.
  (cond ((null (cdr form)) 1)
730 731 732 733
;;; It is not safe to delete the function entirely
;;; (actually, it would be safe if we know the sole arg
;;; is not a marker or if it appears in other arithmetic).
;;;	((null (cdr (cdr form))) (nth 1 form))
Jim Blandy's avatar
Jim Blandy committed
734
	((let ((last (car (reverse form))))
735
	   (cond ((eq 0 last)  (cons 'progn (cdr form)))
Jim Blandy's avatar
Jim Blandy committed
736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751
		 ((eq 1 last)  (delq 1 (copy-sequence form)))
		 ((eq -1 last) (list '- (delq -1 (copy-sequence form))))
		 ((and (eq 2 last)
		       (memq t (mapcar 'symbolp (cdr form))))
		  (prog1 (setq form (delq 2 (copy-sequence form)))
		    (while (not (symbolp (car (setq form (cdr form))))))
		    (setcar form (list '+ (car form) (car form)))))
		 (form))))))

(defsubst byte-compile-butlast (form)
  (nreverse (cdr (reverse form))))

(defun byte-optimize-divide (form)
  (setq form (byte-optimize-delay-constants-math form 2 '*))
  (let ((last (car (reverse (cdr (cdr form))))))
    (if (numberp last)
752
	(cond ((= (length form) 3)
753 754 755 756 757 758
	       (if (and (numberp (nth 1 form))
			(not (zerop last))
			(condition-case nil
			    (/ (nth 1 form) last)
			  (error nil)))
		   (setq form (list 'progn (/ (nth 1 form) last)))))
759
	      ((= last 1)
Jim Blandy's avatar
Jim Blandy committed
760 761 762 763 764 765
	       (setq form (byte-compile-butlast form)))
	      ((numberp (nth 1 form))
	       (setq form (cons (car form)
				(cons (/ (nth 1 form) last)
				      (byte-compile-butlast (cdr (cdr form)))))
		     last nil))))
766 767 768
    (cond 
;;;	  ((null (cdr (cdr form)))
;;;	   (nth 1 form))
Jim Blandy's avatar
Jim Blandy committed
769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785
	  ((eq (nth 1 form) 0)
	   (append '(progn) (cdr (cdr form)) '(0)))
	  ((eq last -1)
	   (list '- (if (nthcdr 3 form)
			(byte-compile-butlast form)
		      (nth 1 form))))
	  (form))))

(defun byte-optimize-logmumble (form)
  (setq form (byte-optimize-delay-constants-math form 1 (car form)))
  (byte-optimize-predicate
   (cond ((memq 0 form)
	  (setq form (if (eq (car form) 'logand)
			 (cons 'progn (cdr form))
		       (delq 0 (copy-sequence form)))))
	 ((and (eq (car-safe form) 'logior)
	       (memq -1 form))
786
	  (cons 'progn (cdr form)))
Jim Blandy's avatar
Jim Blandy committed
787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865
	 (form))))


(defun byte-optimize-binary-predicate (form)
  (if (byte-compile-constp (nth 1 form))
      (if (byte-compile-constp (nth 2 form))
	  (condition-case ()
	      (list 'quote (eval form))
	    (error form))
	;; This can enable some lapcode optimizations.
	(list (car form) (nth 2 form) (nth 1 form)))
    form))

(defun byte-optimize-predicate (form)
  (let ((ok t)
	(rest (cdr form)))
    (while (and rest ok)
      (setq ok (byte-compile-constp (car rest))
	    rest (cdr rest)))
    (if ok
	(condition-case ()
	    (list 'quote (eval form))
	  (error form))
	form)))

(defun byte-optimize-identity (form)
  (if (and (cdr form) (null (cdr (cdr form))))
      (nth 1 form)
    (byte-compile-warn "identity called with %d arg%s, but requires 1"
		       (length (cdr form))
		       (if (= 1 (length (cdr form))) "" "s"))
    form))

(put 'identity 'byte-optimizer 'byte-optimize-identity)

(put '+   'byte-optimizer 'byte-optimize-plus)
(put '*   'byte-optimizer 'byte-optimize-multiply)
(put '-   'byte-optimizer 'byte-optimize-minus)
(put '/   'byte-optimizer 'byte-optimize-divide)
(put 'max 'byte-optimizer 'byte-optimize-associative-math)
(put 'min 'byte-optimizer 'byte-optimize-associative-math)

(put '=   'byte-optimizer 'byte-optimize-binary-predicate)
(put 'eq  'byte-optimizer 'byte-optimize-binary-predicate)
(put 'eql 'byte-optimizer 'byte-optimize-binary-predicate)
(put 'equal   'byte-optimizer 'byte-optimize-binary-predicate)
(put 'string= 'byte-optimizer 'byte-optimize-binary-predicate)
(put 'string-equal 'byte-optimizer 'byte-optimize-binary-predicate)

(put '<   'byte-optimizer 'byte-optimize-predicate)
(put '>   'byte-optimizer 'byte-optimize-predicate)
(put '<=  'byte-optimizer 'byte-optimize-predicate)
(put '>=  'byte-optimizer 'byte-optimize-predicate)
(put '1+  'byte-optimizer 'byte-optimize-predicate)
(put '1-  'byte-optimizer 'byte-optimize-predicate)
(put 'not 'byte-optimizer 'byte-optimize-predicate)
(put 'null  'byte-optimizer 'byte-optimize-predicate)
(put 'memq  'byte-optimizer 'byte-optimize-predicate)
(put 'consp 'byte-optimizer 'byte-optimize-predicate)
(put 'listp 'byte-optimizer 'byte-optimize-predicate)
(put 'symbolp 'byte-optimizer 'byte-optimize-predicate)
(put 'stringp 'byte-optimizer 'byte-optimize-predicate)
(put 'string< 'byte-optimizer 'byte-optimize-predicate)
(put 'string-lessp 'byte-optimizer 'byte-optimize-predicate)

(put 'logand 'byte-optimizer 'byte-optimize-logmumble)
(put 'logior 'byte-optimizer 'byte-optimize-logmumble)
(put 'logxor 'byte-optimizer 'byte-optimize-logmumble)
(put 'lognot 'byte-optimizer 'byte-optimize-predicate)

(put 'car 'byte-optimizer 'byte-optimize-predicate)
(put 'cdr 'byte-optimizer 'byte-optimize-predicate)
(put 'car-safe 'byte-optimizer 'byte-optimize-predicate)
(put 'cdr-safe 'byte-optimizer 'byte-optimize-predicate)


;; I'm not convinced that this is necessary.  Doesn't the optimizer loop 
;; take care of this? - Jamie
;; I think this may some times be necessary to reduce ie (quote 5) to 5,
866
;; so arithmetic optimizers recognize the numeric constant.  - Hallvard
Jim Blandy's avatar
Jim Blandy committed
867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968
(put 'quote 'byte-optimizer 'byte-optimize-quote)
(defun byte-optimize-quote (form)
  (if (or (consp (nth 1 form))
	  (and (symbolp (nth 1 form))
	       (not (memq (nth 1 form) '(nil t)))))
      form
    (nth 1 form)))

(defun byte-optimize-zerop (form)
  (cond ((numberp (nth 1 form))
	 (eval form))
	(byte-compile-delete-errors
	 (list '= (nth 1 form) 0))
	(form)))

(put 'zerop 'byte-optimizer 'byte-optimize-zerop)

(defun byte-optimize-and (form)
  ;; Simplify if less than 2 args.
  ;; if there is a literal nil in the args to `and', throw it and following
  ;; forms away, and surround the `and' with (progn ... nil).
  (cond ((null (cdr form)))
	((memq nil form)
	 (list 'progn
	       (byte-optimize-and
		(prog1 (setq form (copy-sequence form))
		  (while (nth 1 form)
		    (setq form (cdr form)))
		  (setcdr form nil)))
	       nil))
	((null (cdr (cdr form)))
	 (nth 1 form))
	((byte-optimize-predicate form))))

(defun byte-optimize-or (form)
  ;; Throw away nil's, and simplify if less than 2 args.
  ;; If there is a literal non-nil constant in the args to `or', throw away all
  ;; following forms.
  (if (memq nil form)
      (setq form (delq nil (copy-sequence form))))
  (let ((rest form))
    (while (cdr (setq rest (cdr rest)))
      (if (byte-compile-trueconstp (car rest))
	  (setq form (copy-sequence form)
		rest (setcdr (memq (car rest) form) nil))))
    (if (cdr (cdr form))
	(byte-optimize-predicate form)
      (nth 1 form))))

(defun byte-optimize-cond (form)
  ;; if any clauses have a literal nil as their test, throw them away.
  ;; if any clause has a literal non-nil constant as its test, throw
  ;; away all following clauses.
  (let (rest)
    ;; This must be first, to reduce (cond (t ...) (nil)) to (progn t ...)
    (while (setq rest (assq nil (cdr form)))
      (setq form (delq rest (copy-sequence form))))
    (if (memq nil (cdr form))
	(setq form (delq nil (copy-sequence form))))
    (setq rest form)
    (while (setq rest (cdr rest))
      (cond ((byte-compile-trueconstp (car-safe (car rest)))
	     (cond ((eq rest (cdr form))
		    (setq form
			  (if (cdr (car rest))
			      (if (cdr (cdr (car rest)))
				  (cons 'progn (cdr (car rest)))
				(nth 1 (car rest)))
			    (car (car rest)))))
		   ((cdr rest)
		    (setq form (copy-sequence form))
		    (setcdr (memq (car rest) form) nil)))
	     (setq rest nil)))))
  ;;
  ;; Turn (cond (( <x> )) ... ) into (or <x> (cond ... ))
  (if (eq 'cond (car-safe form))
      (let ((clauses (cdr form)))
	(if (and (consp (car clauses))
		 (null (cdr (car clauses))))
	    (list 'or (car (car clauses))
		  (byte-optimize-cond
		   (cons (car form) (cdr (cdr form)))))
	  form))
    form))

(defun byte-optimize-if (form)
  ;; (if <true-constant> <then> <else...>) ==> <then>
  ;; (if <false-constant> <then> <else...>) ==> (progn <else...>)
  ;; (if <test> nil <else...>) ==> (if (not <test>) (progn <else...>))
  ;; (if <test> <then> nil) ==> (if <test> <then>)
  (let ((clause (nth 1 form)))
    (cond ((byte-compile-trueconstp clause)
	   (nth 2 form))
	  ((null clause)
	   (if (nthcdr 4 form)
	       (cons 'progn (nthcdr 3 form))
	     (nth 3 form)))
	  ((nth 2 form)
	   (if (equal '(nil) (nthcdr 3 form))
	       (list 'if clause (nth 2 form))
	     form))
	  ((or (nth 3 form) (nthcdr 4 form))
969 970 971 972 973 974 975
	   (list 'if
		 ;; Don't make a double negative;
		 ;; instead, take away the one that is there.
		 (if (and (consp clause) (memq (car clause) '(not null))
			  (= (length clause) 2)) ; (not xxxx) or (not (xxxx))
		     (nth 1 clause)
		   (list 'not clause))
Jim Blandy's avatar
Jim Blandy committed
976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
		 (if (nthcdr 4 form)
		     (cons 'progn (nthcdr 3 form))
		   (nth 3 form))))
	  (t
	   (list 'progn clause nil)))))

(defun byte-optimize-while (form)
  (if (nth 1 form)
      form))

(put 'and   'byte-optimizer 'byte-optimize-and)
(put 'or    'byte-optimizer 'byte-optimize-or)
(put 'cond  'byte-optimizer 'byte-optimize-cond)
(put 'if    'byte-optimizer 'byte-optimize-if)
(put 'while 'byte-optimizer 'byte-optimize-while)

;; byte-compile-negation-optimizer lives in bytecomp.el
(put '/= 'byte-optimizer 'byte-compile-negation-optimizer)
(put 'atom 'byte-optimizer 'byte-compile-negation-optimizer)
(put 'nlistp 'byte-optimizer 'byte-compile-negation-optimizer)


(defun byte-optimize-funcall (form)
  ;; (funcall '(lambda ...) ...) ==> ((lambda ...) ...)
  ;; (funcall 'foo ...) ==> (foo ...)
  (let ((fn (nth 1 form)))
    (if (memq (car-safe fn) '(quote function))
	(cons (nth 1 fn) (cdr (cdr form)))
	form)))

(defun byte-optimize-apply (form)
  ;; If the last arg is a literal constant, turn this into a funcall.
  ;; The funcall optimizer can then transform (funcall 'foo ...) -> (foo ...).
  (let ((fn (nth 1 form))
	(last (nth (1- (length form)) form))) ; I think this really is fastest
    (or (if (or (null last)
		(eq (car-safe last) 'quote))
	    (if (listp (nth 1 last))
		(let ((butlast (nreverse (cdr (reverse (cdr (cdr form)))))))
Jim Blandy's avatar
Jim Blandy committed
1015 1016
		  (nconc (list 'funcall fn) butlast
			 (mapcar '(lambda (x) (list 'quote x)) (nth 1 last))))
Jim Blandy's avatar
Jim Blandy committed
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036
	      (byte-compile-warn
	       "last arg to apply can't be a literal atom: %s"
	       (prin1-to-string last))
	      nil))
	form)))

(put 'funcall 'byte-optimizer 'byte-optimize-funcall)
(put 'apply   'byte-optimizer 'byte-optimize-apply)


(put 'let 'byte-optimizer 'byte-optimize-letX)
(put 'let* 'byte-optimizer 'byte-optimize-letX)
(defun byte-optimize-letX (form)
  (cond ((null (nth 1 form))
	 ;; No bindings
	 (cons 'progn (cdr (cdr form))))
	((or (nth 2 form) (nthcdr 3 form))
	 form)
	 ;; The body is nil
	((eq (car form) 'let)
1037 1038
	 (append '(progn) (mapcar 'car-safe (mapcar 'cdr-safe (nth 1 form)))
		 '(nil)))
Jim Blandy's avatar
Jim Blandy committed
1039 1040 1041 1042 1043 1044 1045
	(t
	 (let ((binds (reverse (nth 1 form))))
	   (list 'let* (reverse (cdr binds)) (nth 1 (car binds)) nil)))))


(put 'nth 'byte-optimizer 'byte-optimize-nth)
(defun byte-optimize-nth (form)
1046
  (if (and (= (safe-length form) 3) (memq (nth 1 form) '(0 1)))
Jim Blandy's avatar
Jim Blandy committed
1047 1048 1049 1050 1051 1052 1053
      (list 'car (if (zerop (nth 1 form))
		     (nth 2 form)
		   (list 'cdr (nth 2 form))))
    (byte-optimize-predicate form)))

(put 'nthcdr 'byte-optimizer 'byte-optimize-nthcdr)
(defun byte-optimize-nthcdr (form)
1054 1055 1056
  (if (and (= (safe-length form) 3) (not (memq (nth 1 form) '(0 1 2))))
      (byte-optimize-predicate form)
    (let ((count (nth 1 form)))
Jim Blandy's avatar
Jim Blandy committed
1057
      (setq form (nth 2 form))
1058
      (while (>= (setq count (1- count)) 0)
Jim Blandy's avatar
Jim Blandy committed
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
	(setq form (list 'cdr form)))
      form)))

;;; enumerating those functions which need not be called if the returned 
;;; value is not used.  That is, something like
;;;    (progn (list (something-with-side-effects) (yow))
;;;           (foo))
;;; may safely be turned into
;;;    (progn (progn (something-with-side-effects) (yow))
;;;           (foo))
;;; Further optimizations will turn (progn (list 1 2 3) 'foo) into 'foo.

;;; I wonder if I missed any :-\)
(let ((side-effect-free-fns
1073 1074 1075 1076 1077 1078 1079 1080
       '(% * + - / /= 1+ 1- < <= = > >= abs acos append aref ash asin atan
	 assoc assq
	 boundp buffer-file-name buffer-local-variables buffer-modified-p
	 buffer-substring
	 capitalize car-less-than-car car cdr ceiling concat coordinates-in-window-p
	 copy-marker cos count-lines
	 default-boundp default-value documentation downcase
	 elt exp expt fboundp featurep
Jim Blandy's avatar
Jim Blandy committed
1081 1082
	 file-directory-p file-exists-p file-locked-p file-name-absolute-p
	 file-newer-than-file-p file-readable-p file-symlink-p file-writable-p
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
	 float floor format
	 get get-buffer get-buffer-window getenv get-file-buffer
	 int-to-string
	 length log log10 logand logb logior lognot logxor lsh
	 marker-buffer max member memq min mod
	 next-window nth nthcdr number-to-string
	 parse-colon-path previous-window
	 radians-to-degrees rassq regexp-quote reverse round
	 sin sqrt string< string= string-equal string-lessp string-to-char
	 string-to-int string-to-number substring symbol-plist
	 tan upcase user-variable-p vconcat
	 window-buffer window-dedicated-p window-edges window-height
	 window-hscroll window-minibuffer-p window-width
Jim Blandy's avatar
Jim Blandy committed
1096 1097
	 zerop))
      (side-effect-and-error-free-fns
1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116
       '(arrayp atom
	 bobp bolp buffer-end buffer-list buffer-size buffer-string bufferp
	 car-safe case-table-p cdr-safe char-or-string-p commandp cons consp
	 current-buffer
	 dot dot-marker eobp eolp eq eql equal eventp floatp framep
	 get-largest-window get-lru-window
	 identity ignore integerp integer-or-marker-p interactive-p
	 invocation-directory invocation-name
	 keymapp list listp
	 make-marker mark mark-marker markerp memory-limit minibuffer-window
	 mouse-movement-p
	 natnump nlistp not null number-or-marker-p numberp
	 one-window-p overlayp
	 point point-marker point-min point-max processp
	 selected-window sequencep stringp subrp symbolp syntax-table-p
	 user-full-name user-login-name user-original-login-name
	 user-real-login-name user-real-uid user-uid
	 vector vectorp
	 window-configuration-p window-live-p windowp)))
Jim Blandy's avatar
Jim Blandy committed
1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173
  (while side-effect-free-fns
    (put (car side-effect-free-fns) 'side-effect-free t)
    (setq side-effect-free-fns (cdr side-effect-free-fns)))
  (while side-effect-and-error-free-fns
    (put (car side-effect-and-error-free-fns) 'side-effect-free 'error-free)
    (setq side-effect-and-error-free-fns (cdr side-effect-and-error-free-fns)))
  nil)


(defun byte-compile-splice-in-already-compiled-code (form)
  ;; form is (byte-code "..." [...] n)
  (if (not (memq byte-optimize '(t lap)))
      (byte-compile-normal-call form)
    (byte-inline-lapcode
     (byte-decompile-bytecode-1 (nth 1 form) (nth 2 form) t))
    (setq byte-compile-maxdepth (max (+ byte-compile-depth (nth 3 form))
				     byte-compile-maxdepth))
    (setq byte-compile-depth (1+ byte-compile-depth))))

(put 'byte-code 'byte-compile 'byte-compile-splice-in-already-compiled-code)


(defconst byte-constref-ops
  '(byte-constant byte-constant2 byte-varref byte-varset byte-varbind))

;;; This function extracts the bitfields from variable-length opcodes.
;;; Originally defined in disass.el (which no longer uses it.)

(defun disassemble-offset ()
  "Don't call this!"
  ;; fetch and return the offset for the current opcode.
  ;; return NIL if this opcode has no offset
  ;; OP, PTR and BYTES are used and set dynamically
  (defvar op)
  (defvar ptr)
  (defvar bytes)
  (cond ((< op byte-nth)
	 (let ((tem (logand op 7)))
	   (setq op (logand op 248))
	   (cond ((eq tem 6)
		  (setq ptr (1+ ptr))	;offset in next byte
		  (aref bytes ptr))
		 ((eq tem 7)
		  (setq ptr (1+ ptr))	;offset in next 2 bytes
		  (+ (aref bytes ptr)
		     (progn (setq ptr (1+ ptr))
			    (lsh (aref bytes ptr) 8))))
		 (t tem))))		;offset was in opcode
	((>= op byte-constant)
	 (prog1 (- op byte-constant)	;offset in opcode
	   (setq op byte-constant)))
	((and (>= op byte-constant2)
	      (<= op byte-goto-if-not-nil-else-pop))
	 (setq ptr (1+ ptr))		;offset in next 2 bytes
	 (+ (aref bytes ptr)
	    (progn (setq ptr (1+ ptr))
		   (lsh (aref bytes ptr) 8))))
Jim Blandy's avatar
Jim Blandy committed
1174
	((and (>= op byte-listN)
Jim Blandy's avatar
Jim Blandy committed
1175 1176 1177 1178 1179 1180 1181 1182
	      (<= op byte-insertN))
	 (setq ptr (1+ ptr))		;offset in next byte
	 (aref bytes ptr))))


;;; This de-compiler is used for inline expansion of compiled functions,
;;; and by the disassembler.
;;;
1183 1184
;;; This list contains numbers, which are pc values,
;;; before each instruction.
Jim Blandy's avatar
Jim Blandy committed
1185
(defun byte-decompile-bytecode (bytes constvec)
1186
  "Turns BYTECODE into lapcode, referring to CONSTVEC."
Jim Blandy's avatar
Jim Blandy committed
1187 1188 1189 1190 1191
  (let ((byte-compile-constants nil)
	(byte-compile-variables nil)
	(byte-compile-tag-number 0))
    (byte-decompile-bytecode-1 bytes constvec)))

1192 1193
;; As byte-decompile-bytecode, but updates
;; byte-compile-{constants, variables, tag-number}.
1194
;; If MAKE-SPLICEABLE is true, then `return' opcodes are replaced
1195
;; with `goto's destined for the end of the code.
1196 1197 1198 1199 1200
;; That is for use by the compiler.
;; If MAKE-SPLICEABLE is nil, we are being called for the disassembler.
;; In that case, we put a pc value into the list
;; before each insn (or its label).
(defun byte-decompile-bytecode-1 (bytes constvec &optional make-spliceable)
Jim Blandy's avatar
Jim Blandy committed
1201 1202 1203 1204 1205 1206
  (let ((length (length bytes))
	(ptr 0) optr tag tags op offset
	lap tmp
	endtag
	(retcount 0))
    (while (not (= ptr length))
1207 1208
      (or make-spliceable
	  (setq lap (cons ptr lap)))
Jim Blandy's avatar
Jim Blandy committed
1209 1210 1211 1212
      (setq op (aref bytes ptr)
	    optr ptr
	    offset (disassemble-offset)) ; this does dynamic-scope magic
      (setq op (aref byte-code-vector op))
Jim Blandy's avatar
Jim Blandy committed
1213
      (cond ((memq op byte-goto-ops)
Jim Blandy's avatar
Jim Blandy committed
1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229
	     ;; it's a pc
	     (setq offset
		   (cdr (or (assq offset tags)
			    (car (setq tags
				       (cons (cons offset
						   (byte-compile-make-tag))
					     tags)))))))
	    ((cond ((eq op 'byte-constant2) (setq op 'byte-constant) t)
		   ((memq op byte-constref-ops)))
	     (setq tmp (aref constvec offset)
		   offset (if (eq op 'byte-constant)
			      (byte-compile-get-constant tmp)
			    (or (assq tmp byte-compile-variables)
				(car (setq byte-compile-variables
					   (cons (list tmp)
						 byte-compile-variables)))))))
1230
	    ((and make-spliceable
Jim Blandy's avatar
Jim Blandy committed
1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242
		  (eq op 'byte-return))
	     (if (= ptr (1- length))
		 (setq op nil)
	       (setq offset (or endtag (setq endtag (byte-compile-make-tag)))
		     op 'byte-goto))))
      ;; lap = ( [ (pc . (op . arg)) ]* )
      (setq lap (cons (cons optr (cons op (or offset 0)))
		      lap))
      (setq ptr (1+ ptr)))
    ;; take off the dummy nil op that we replaced a trailing "return" with.
    (let ((rest lap))
      (while rest
1243 1244
	(cond ((numberp (car rest)))
	      ((setq tmp (assq (car (car rest)) tags))
Jim Blandy's avatar
Jim Blandy committed
1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256
	       ;; this addr is jumped to
	       (setcdr rest (cons (cons nil (cdr tmp))
				  (cdr rest)))
	       (setq tags (delq tmp tags))
	       (setq rest (cdr rest))))
	(setq rest (cdr rest))))
    (if tags (error "optimizer error: missed tags %s" tags))
    (if (null (car (cdr (car lap))))
	(setq lap (cdr lap)))
    (if endtag
	(setq lap (cons (cons nil endtag) lap)))
    ;; remove addrs, lap = ( [ (op . arg) | (TAG tagno) ]* )
1257 1258 1259 1260 1261
    (mapcar (function (lambda (elt)
			(if (numberp elt)
			    elt
			  (cdr elt))))
	    (nreverse lap))))
Jim Blandy's avatar
Jim Blandy committed
1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276


;;; peephole optimizer

(defconst byte-tagref-ops (cons 'TAG byte-goto-ops))

(defconst byte-conditional-ops
  '(byte-goto-if-nil byte-goto-if-not-nil byte-goto-if-nil-else-pop
    byte-goto-if-not-nil-else-pop))

(defconst byte-after-unbind-ops
   '(byte-constant byte-dup
     byte-symbolp byte-consp byte-stringp byte-listp byte-numberp byte-integerp
     byte-eq byte-equal byte-not
     byte-cons byte-list1 byte-list2	; byte-list3 byte-list4
1277 1278 1279 1280
     byte-interactive-p)
   ;; How about other side-effect-free-ops?  Is it safe to move an
   ;; error invocation (such as from nth) out of an unwind-protect?
   "Byte-codes that can be moved past an unbind.")
Jim Blandy's avatar
Jim Blandy committed
1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299

(defconst byte-compile-side-effect-and-error-free-ops
  '(byte-constant byte-dup byte-symbolp byte-consp byte-stringp byte-listp
    byte-integerp byte-numberp byte-eq byte-equal byte-not byte-car-safe
    byte-cdr-safe byte-cons byte-list1 byte-list2 byte-point byte-point-max
    byte-point-min byte-following-char byte-preceding-char
    byte-current-column byte-eolp byte-eobp byte-bolp byte-bobp
    byte-current-buffer byte-interactive-p))

(defconst byte-compile-side-effect-free-ops
  (nconc 
   '(byte-varref byte-nth byte-memq byte-car byte-cdr byte-length byte-aref
     byte-symbol-value byte-get byte-concat2 byte-concat3 byte-sub1 byte-add1
     byte-eqlsign byte-gtr byte-lss byte-leq byte-geq byte-diff byte-negate
     byte-plus byte-max byte-min byte-mult byte-char-after byte-char-syntax
     byte-buffer-substring byte-string= byte-string< byte-nthcdr byte-elt
     byte-member byte-assq byte-quo byte-rem)
   byte-compile-side-effect-and-error-free-ops))

Karl Heuer's avatar
Karl Heuer committed
1300
;;; This crock is because of the way DEFVAR_BOOL variables work.
Jim Blandy's avatar
Jim Blandy committed
1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327
;;; Consider the code
;;;
;;;	(defun foo (flag)
;;;	  (let ((old-pop-ups pop-up-windows)
;;;		(pop-up-windows flag))
;;;	    (cond ((not (eq pop-up-windows old-pop-ups))
;;;		   (setq old-pop-ups pop-up-windows)
;;;		   ...))))
;;;
;;; Uncompiled, old-pop-ups will always be set to nil or t, even if FLAG is
;;; something else.  But if we optimize
;;;
;;;	varref flag
;;;	varbind pop-up-windows
;;;	varref pop-up-windows
;;;	not
;;; to
;;;	varref flag
;;;	dup
;;;	varbind pop-up-windows
;;;	not
;;;
;;; we break the program, because it will appear that pop-up-windows and 
;;; old-pop-ups are not EQ when really they are.  So we have to know what
;;; the BOOL variables are, and not perform this optimization on them.
;;;
(defconst byte-boolean-vars
Jim Blandy's avatar
Jim Blandy committed
1328
  '(abbrev-all-caps abbrevs-changed byte-metering-on
1329
    cannot-suspend completion-auto-help completion-ignore-case
Jim Blandy's avatar
Jim Blandy committed
1330
    cursor-in-echo-area debug-on-next-call debug-on-quit
1331 1332 1333 1334 1335 1336 1337 1338
    delete-exited-processes enable-recursive-minibuffers
    highlight-nonselected-windows indent-tabs-mode inhibit-local-menu-bar-menus
    insert-default-directory inverse-video load-force-doc-strings
    load-in-progress menu-prompting minibuffer-auto-raise
    mode-line-inverse-video multiple-frames no-redraw-on-reenter noninteractive
    parse-sexp-ignore-comments pop-up-frames pop-up-windows
    print-escape-newlines system-uses-terminfo truncate-partial-width-windows
    visible-bell vms-stmlf-recfm words-include-escapes)
Jim Blandy's avatar
Jim Blandy committed
1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551
  "DEFVAR_BOOL variables.  Giving these any non-nil value sets them to t.
If this does not enumerate all DEFVAR_BOOL variables, the byte-optimizer
may generate incorrect code.")

(defun byte-optimize-lapcode (lap &optional for-effect)
  "Simple peephole optimizer.  LAP is both modified and returned."
  (let (lap0 off0
	lap1 off1
	lap2 off2
	(keep-going 'first-time)
	(add-depth 0)
	rest tmp tmp2 tmp3
	(side-effect-free (if byte-compile-delete-errors
			      byte-compile-side-effect-free-ops
			    byte-compile-side-effect-and-error-free-ops)))
    (while keep-going
      (or (eq keep-going 'first-time)
	  (byte-compile-log-lap "  ---- next pass"))
      (setq rest lap
	    keep-going nil)
      (while rest
	(setq lap0 (car rest)
	      lap1 (nth 1 rest)
	      lap2 (nth 2 rest))

	;; You may notice that sequences like "dup varset discard" are
	;; optimized but sequences like "dup varset TAG1: discard" are not.
	;; You may be tempted to change this; resist that temptation.
	(cond ;;
	      ;; <side-effect-free> pop -->  <deleted>
	      ;;  ...including:
	      ;; const-X pop   -->  <deleted>
	      ;; varref-X pop  -->  <deleted>
	      ;; dup pop       -->  <deleted>
	      ;;
	      ((and (eq 'byte-discard (car lap1))
		    (memq (car lap0) side-effect-free))
	       (setq keep-going t)
	       (setq tmp (aref byte-stack+-info (symbol-value (car lap0))))
	       (setq rest (cdr rest))
	       (cond ((= tmp 1)
		      (byte-compile-log-lap
 		       "  %s discard\t-->\t<deleted>" lap0)
		      (setq lap (delq lap0 (delq lap1 lap))))
		     ((= tmp 0)
		      (byte-compile-log-lap
		       "  %s discard\t-->\t<deleted> discard" lap0)
		      (setq lap (delq lap0 lap)))
		     ((= tmp -1)
		      (byte-compile-log-lap
		       "  %s discard\t-->\tdiscard discard" lap0)
		      (setcar lap0 'byte-discard)
		      (setcdr lap0 0))
		     ((error "Optimizer error: too much on the stack"))))
	      ;;
	      ;; goto*-X X:  -->  X:
	      ;;
	      ((and (memq (car lap0) byte-goto-ops)
		    (eq (cdr lap0) lap1))
	       (cond ((eq (car lap0) 'byte-goto)
		      (setq lap (delq lap0 lap))
		      (setq tmp "<deleted>"))
		     ((memq (car lap0) byte-goto-always-pop-ops)
		      (setcar lap0 (setq tmp 'byte-discard))
		      (setcdr lap0 0))
		     ((error "Depth conflict at tag %d" (nth 2 lap0))))
	       (and (memq byte-optimize-log '(t byte))
		    (byte-compile-log "  (goto %s) %s:\t-->\t%s %s:"
				      (nth 1 lap1) (nth 1 lap1)
				      tmp (nth 1 lap1)))
	       (setq keep-going t))
	      ;;
	      ;; varset-X varref-X  -->  dup varset-X
	      ;; varbind-X varref-X  -->  dup varbind-X
	      ;; const/dup varset-X varref-X --> const/dup varset-X const/dup
	      ;; const/dup varbind-X varref-X --> const/dup varbind-X const/dup
	      ;; The latter two can enable other optimizations.
	      ;;
	      ((and (eq 'byte-varref (car lap2))
		    (eq (cdr lap1) (cdr lap2))
		    (memq (car lap1) '(byte-varset byte-varbind)))
	       (if (and (setq tmp (memq (car (cdr lap2)) byte-boolean-vars))
			(not (eq (car lap0) 'byte-constant)))
		   nil
		 (setq keep-going t)
		 (if (memq (car lap0) '(byte-constant byte-dup))
		     (progn
		       (setq tmp (if (or (not tmp)
					 (memq (car (cdr lap0)) '(nil t)))
				     (cdr lap0)
				   (byte-compile-get-constant t)))
		       (byte-compile-log-lap "  %s %s %s\t-->\t%s %s %s"
					     lap0 lap1 lap2 lap0 lap1
					     (cons (car lap0) tmp))
		       (setcar lap2 (car lap0))
		       (setcdr lap2 tmp))
		   (byte-compile-log-lap "  %s %s\t-->\tdup %s" lap1 lap2 lap1)
		   (setcar lap2 (car lap1))
		   (setcar lap1 'byte-dup)
		   (setcdr lap1 0)
		   ;; The stack depth gets locally increased, so we will
		   ;; increase maxdepth in case depth = maxdepth here.
		   ;; This can cause the third argument to byte-code to
		   ;; be larger than necessary.
		   (setq add-depth 1))))
	      ;;
	      ;; dup varset-X discard  -->  varset-X
	      ;; dup varbind-X discard  -->  varbind-X
	      ;; (the varbind variant can emerge from other optimizations)
	      ;;
	      ((and (eq 'byte-dup (car lap0))
		    (eq 'byte-discard (car lap2))
		    (memq (car lap1) '(byte-varset byte-varbind)))
	       (byte-compile-log-lap "  dup %s discard\t-->\t%s" lap1 lap1)
	       (setq keep-going t
		     rest (cdr rest))
	       (setq lap (delq lap0 (delq lap2 lap))))
	      ;;
	      ;; not goto-X-if-nil              -->  goto-X-if-non-nil
	      ;; not goto-X-if-non-nil          -->  goto-X-if-nil
	      ;;
	      ;; it is wrong to do the same thing for the -else-pop variants.
	      ;;
	      ((and (eq 'byte-not (car lap0))
		    (or (eq 'byte-goto-if-nil (car lap1))
			(eq 'byte-goto-if-not-nil (car lap1))))
	       (byte-compile-log-lap "  not %s\t-->\t%s"
				     lap1
				     (cons
				      (if (eq (car lap1) 'byte-goto-if-nil)
					  'byte-goto-if-not-nil
					'byte-goto-if-nil)
				      (cdr lap1)))
	       (setcar lap1 (if (eq (car lap1) 'byte-goto-if-nil)
				'byte-goto-if-not-nil
				'byte-goto-if-nil))
	       (setq lap (delq lap0 lap))
	       (setq keep-going t))
	      ;;
	      ;; goto-X-if-nil     goto-Y X:  -->  goto-Y-if-non-nil X:
	      ;; goto-X-if-non-nil goto-Y X:  -->  goto-Y-if-nil     X:
	      ;;
	      ;; it is wrong to do the same thing for the -else-pop variants.
	      ;; 
	      ((and (or (eq 'byte-goto-if-nil (car lap0))
			(eq 'byte-goto-if-not-nil (car lap0)))	; gotoX
		    (eq 'byte-goto (car lap1))			; gotoY
		    (eq (cdr lap0) lap2))			; TAG X
	       (let ((inverse (if (eq 'byte-goto-if-nil (car lap0))
				  'byte-goto-if-not-nil 'byte-goto-if-nil)))
		 (byte-compile-log-lap "  %s %s %s:\t-->\t%s %s:"
				       lap0 lap1 lap2
				       (cons inverse (cdr lap1)) lap2)
		 (setq lap (delq lap0 lap))
		 (setcar lap1 inverse)
		 (setq keep-going t)))
	      ;;
	      ;; const goto-if-* --> whatever
	      ;;
	      ((and (eq 'byte-constant (car lap0))
		    (memq (car lap1) byte-conditional-ops))
	       (cond ((if (or (eq (car lap1) 'byte-goto-if-nil)
			      (eq (car lap1) 'byte-goto-if-nil-else-pop))
			  (car (cdr lap0))
			(not (car (cdr lap0))))
		      (byte-compile-log-lap "  %s %s\t-->\t<deleted>"
					    lap0 lap1)
		      (setq rest (cdr rest)
			    lap (delq lap0 (delq lap1 lap))))
		     (t
		      (if (memq (car lap1) byte-goto-always-pop-ops)
			  (progn
			    (byte-compile-log-lap "  %s %s\t-->\t%s"
			     lap0 lap1 (cons 'byte-goto (cdr lap1)))
			    (setq lap (delq lap0 lap)))
			(byte-compile-log-lap "  %s %s\t-->\t%s" lap0 lap1
			 (cons 'byte-goto (cdr lap1))))
		      (setcar lap1 'byte-goto)))
	       (setq keep-going t))
	      ;;
	      ;; varref-X varref-X  -->  varref-X dup
	      ;; varref-X [dup ...] varref-X  -->  varref-X [dup ...] dup
	      ;; We don't optimize the const-X variations on this here,
	      ;; because that would inhibit some goto optimizations; we
	      ;; optimize the const-X case after all other optimizations.
	      ;;
	      ((and (eq 'byte-varref (car lap0))
		    (progn
		      (setq tmp (cdr rest))
		      (while (eq (car (car tmp)) 'byte-dup)
			(setq tmp (cdr tmp)))
		      t)
		    (eq (cdr lap0) (cdr (car tmp)))
		    (eq 'byte-varref (car (car tmp))))
	       (if (memq byte-optimize-log '(t byte))
		   (let ((str ""))
		     (setq tmp2 (cdr rest))
		     (while (not (eq tmp tmp2))
		       (setq tmp2 (cdr tmp2)
			     str (concat str " dup")))
		     (byte-compile-log-lap "  %s%s %s\t-->\t%s%s dup"
					   lap0 str lap0 lap0 str)))
	       (setq keep-going t)
	       (setcar (car tmp) 'byte-dup)
	       (setcdr (car tmp) 0)
	       (setq rest tmp))
	      ;;
	      ;; TAG1: TAG2: --> TAG1: <deleted>
	      ;; (and other references to TAG2 are replaced with TAG1)
	      ;;
	      ((and (eq (car lap0) 'TAG)
		    (eq (car lap1) 'TAG))
	       (and (memq byte-optimize-log '(t byte))
1552
		    (byte-compile-log "  adjacent tags %d and %d merged"
Jim Blandy's avatar
Jim Blandy committed
1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586
				      (nth 1 lap1) (nth 1 lap0)))
	       (setq tmp3 lap)
	       (while (setq tmp2 (rassq lap0 tmp3))
		 (setcdr tmp2 lap1)
		 (setq tmp3 (cdr (memq tmp2 tmp3))))
	       (setq lap (delq lap0 lap)
		     keep-going t))
	      ;;
	      ;; unused-TAG: --> <deleted>
	      ;;
	      ((and (eq 'TAG (car lap0))
		    (not (rassq lap0 lap)))
	       (and (memq byte-optimize-log '(t byte))
		    (byte-compile-log "  unused tag %d removed" (nth 1 lap0)))
	       (setq lap (delq lap0 lap)
		     keep-going t))
	      ;;
	      ;; goto   ... --> goto   <delete until TAG or end>
	      ;; return ... --> return <delete until TAG or end>
	      ;;
	      ((and (memq (car lap0) '(byte-goto byte-return))
		    (not (memq (car lap1) '(TAG nil))))
	       (setq tmp rest)
	       (let ((i 0)
		     (opt-p (memq byte-optimize-log '(t lap)))
		     str deleted)
		 (while (and (setq tmp (cdr tmp))
			     (not (eq 'TAG (car (car tmp)))))
		   (if opt-p (setq deleted (cons (car tmp) deleted)
				   str (concat str " %s")
				   i (1+ i))))
		 (if opt-p
		     (let ((tagstr 
			    (if (eq 'TAG (car (car tmp)))
1587
				(format "%d:" (car (cdr (car tmp))))
Jim Blandy's avatar
Jim Blandy committed
1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703