;;; -*- Mode: Lisp; Package: CCL -*-
;;;
;;; Copyright 1994-2009 Clozure Associates
;;;
;;; Licensed under the Apache License, Version 2.0 (the "License");
;;; you may not use this file except in compliance with the License.
;;; You may obtain a copy of the License at
;;;
;;;     http://www.apache.org/licenses/LICENSE-2.0
;;;
;;; Unless required by applicable law or agreed to in writing, software
;;; distributed under the License is distributed on an "AS IS" BASIS,
;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;;; See the License for the specific language governing permissions and
;;; limitations under the License.



(in-package "CCL")


(defvar *backend-use-linear-scan* nil)
(defvar *force-legacy-backend* nil)

;; :compiler:nx0.lisp - part of the compiler


(defstruct pending-declarations
  vdecls
  fdecls
  mdecls)

; Phony AFUNC "defstruct":
(defun make-afunc (&aux (v (%make-afunc)))
  (setf (afunc-fn-refcount v) 0)
  (setf (afunc-fn-downward-refcount v) 0)
  (setf (afunc-bits v) 0)
  v)

(defvar *compile-code-coverage* nil "True to instrument for code coverage")

(defmethod print-object ((v var) stream)
  (print-unreadable-object (v stream :type t :identity t)
    (format stream "~s" (var-name v))))


(defvar *nx-blocks* nil)
(defvar *nx-tags* nil)
(defvar *nx-parent-function* nil)
(defvar *nx-current-function* nil)
(defvar *nx-lexical-environment* nil)
(defvar *nx-symbol-macros* nil)
(defvar *nx-inner-functions* nil)
(defvar *nx-cur-func-name* nil)
(defvar *nx-current-note* nil)
(defvar *nx-source-note-map* nil) ;; there might be external refs, from macros.
(defvar *nx-form-type* t)
;(defvar *nx-proclaimed-inline* nil)
;(defvar *nx-proclaimed-inline* (make-hash-table :size 400 :test #'eq))
(defvar *nx-proclaimed-ignore* nil)
(defvar *nx-parsing-lambda-decls* nil) ; el grosso.
(defparameter *nx-standard-declaration-handlers* nil)
(defparameter *nx-hoist-declarations* t)
(defparameter *nx-loop-nesting-level* 0)
(defvar *nx-break-on-program-errors* t)

(defvar *nx1-vcells* nil)
(defvar *nx1-fcells* nil)

(defvar *nx1-operators* (make-hash-table :size 300 :test #'eq))

(defvar *nx-lambdalist* (make-symbol "lambdalist"))

  

  
(defmacro make-nx-nil () `(make-acode ,(%nx1-operator nil)))
(defmacro make-nx-t () `(make-acode ,(%nx1-operator t)))


(defmethod print-object ((a acode) stream)
  (print-unreadable-object (a stream :type t)
    (format stream "~a ~s" (string-downcase (acode-operator-name (acode-operator a))) (acode-operands a))))

(defun %nx-null (x)
  (let* ((x (acode-unwrapped-form x)))
    (if (acode-p x)
      (eql (acode-operator x)
           (%nx1-operator nil)))))

(defun %nx-t (x)
  (let* ((x (acode-unwrapped-form x)))
        (if (acode-p x)
          (eql (acode-operator x)
               (%nx1-operator t)))))

(defparameter *nx-current-compiler-policy* (%default-compiler-policy))

(defvar *nx-next-method-var* nil)
(defvar *nx-call-next-method-function* nil)

(defvar *nx-sfname* nil)
(defvar *nx-operators* ())
(defvar *nx-warnings* nil)

(defvar *nx1-compiler-special-forms* nil "Real special forms")

(defmacro without-compiling-code-coverage (&body body)
  "Disable code coverage in the lexical scope of the form"
  `(compiler-let ((*nx-current-code-note* nil))
     ,@body))

(defparameter *nx-never-tail-call*
  '(error cerror break warn type-error file-error
    signal-program-error signal-simple-program-error
    print-call-history
    #-bccl %get-frame-pointer
    #-bccl break-loop)
  "List of functions which never return multiple values and
   should never be tail-called.")

(defvar *cross-compiling* nil "bootstrapping")




(defparameter *nx-operator-result-types-by-name*
  '((%ilognot . fixnum)
    (%ilogxor . fixnum)
    (%ilogand . fixnum)
    (%ilogior . fixnum)
    (char-code . #. `(integer 0 (,char-code-limit)))))

(setq *nx-known-declarations*
  '(special inline notinline type ftype function ignore optimize dynamic-extent ignorable
    ignore-if-unused settable unsettable 
     notspecial global-function-name debugging-function-name resident))

(defun find-optimize-quantity (name env)
  (let ((pair ()))
    (loop
      (when (listp env) (return))
      (when (setq pair (assq name (lexenv.mdecls env)))
        (return (%cdr pair)))
      (setq env (lexenv.parent-env env)))))
    
(defun debug-optimize-quantity (env)
  (or (find-optimize-quantity 'debug env)
      *nx-debug*))

(defun space-optimize-quantity (env)
  (or (find-optimize-quantity 'space env)
      *nx-space*))

(defun safety-optimize-quantity (env)
  (or (find-optimize-quantity 'safety env)
      *nx-safety*))

(defun speed-optimize-quantity (env)
  (or (find-optimize-quantity 'speed env)
      *nx-speed*))

(defun compilation-speed-optimize-quantity (env)
  (or (find-optimize-quantity 'compilation-speed env)
      *nx-cspeed*))

(defvar *nx-ignore-if-unused* ())
(defvar *nx-new-p2decls* ())
(defvar *nx-inlined-self* t)
(defvar *nx-all-vars* nil)
(defvar *nx-bound-vars* nil)
(defvar *nx-punted-vars* nil)
(defvar *nx-inline-expansions* nil)
(defparameter *nx-compile-time-compiler-macros* nil)
(defvar *nx-global-function-name* nil)
(defvar *nx-can-constant-fold* ())
(defvar *nx-synonyms* ())
(defvar *nx-load-time-eval-token* ())

(define-condition compiler-function-overflow (condition) ())

(defun compiler-function-overflow ()
  (signal 'compiler-function-overflow)
  (error "Function size exceeds compiler limitation."))

(defvar *compiler-macros* (make-hash-table :size 100 :test #'eq))

;;; Just who was responsible for the "FUNCALL" nonsense ?
;;; Whoever it is deserves a slow and painful death ...

(defmacro define-compiler-macro  (name arglist &body body &environment env)
  "Define a compiler-macro for NAME."
  (let* ((block-name name)
         (def-name (validate-function-name name)))
    (unless (eq def-name block-name)
      (setq block-name (cadr block-name)))
    (let ((body (parse-macro-1 block-name arglist body env)))
      `(eval-when (:compile-toplevel :load-toplevel :execute)
         (eval-when (:load-toplevel :execute)
           (record-source-file ',name 'compiler-macro))
         (setf (compiler-macro-function ',name)
               (nfunction (compiler-macro-function ,name)  ,body))
         ',name))))

;;; This is silly (as may be the whole idea of actually -using-
;;; compiler-macros).  Compiler-macroexpand-1 will return a second
;;; value of NIL if the value returned by the expansion function is EQ
;;; to the original form.  This differs from the behavior of
;;; macroexpand-1, but users are not encouraged to write macros which
;;; return their &whole args (as the DEFINE-COMPILER-MACRO issue
;;; encourages them to do ...)  Cheer up! Neither of these things have
;;; to exist!
(defun compiler-macroexpand-1 (form &optional env)
  (let ((expander nil)
        (newdef nil))
    (if (and (consp form)
             (symbolp (car form))
             (setq expander (compiler-macro-function (car form) env)))
      (values (setq newdef (funcall *macroexpand-hook* expander form env)) (neq newdef form))
      (values form nil))))

; ... If this exists, it should probably be exported.
(defun compiler-macroexpand (form &optional env)
  (multiple-value-bind (new win) (compiler-macroexpand-1 form env)
    (do* ((won-at-least-once win))
         ((null win) (values new won-at-least-once))
      (multiple-value-setq (new win) (compiler-macroexpand-1 new env)))))




(defun compiler-macro-function (name &optional env)
  "If NAME names a compiler-macro in ENV, return the expansion function, else
   return NIL. Can be set with SETF when ENV is NIL."
  (setq name (validate-function-name name))
  (unless (nx-lexical-finfo name env)
    (or (cdr (assq name *nx-compile-time-compiler-macros*))
        (values (gethash name *compiler-macros*)))))

(defun set-compiler-macro-function (name def)
  (setq name (validate-function-name name))
  (if def
    (setf (gethash name *compiler-macros*) def)
    (remhash name *compiler-macros*))
  def)


;;; Note that all lexical variables bound at this time are live across
;;; a non-tail call by setting a bit in each such var.  This may not
;;; be exactt (for many reasons), but it may help the register allocator:
;;; if a variable is unlikely to be live across a call, there's less 
;;; reason to keep it in a register that's preserved across calls.

(defun nx-note-bound-vars-live-across-call ()
  (dolist (var *nx-bound-vars*)
    (let* ((local-bits (var-local-bits var)))
      (declare (fixnum local-bits))
      (unless (logbitp $vbitspecial (nx-var-bits var))
        (setf (var-local-bits var) (logior (ash 1 $vlocalbitiveacrosscall) local-bits))))))

(defsetf compiler-macro-function set-compiler-macro-function)

(defparameter *nx-add-xref-entry-hook* nil
  "When non-NIL, assumed to be a function of 3 arguments 
which asserts that the specied relation from the current
function to the indicated name is true.")

;; Cross-referencing
(defun nx-record-xref-info (relation name)
  (let* ((axe (fboundp '%add-xref-entry)))
    (when axe
      (funcall axe relation *nx-cur-func-name* name))))



(defun nx-apply-env-hook (hook env &rest args)
  (declare (dynamic-extent args))
  (when (fixnump hook) (setq hook (uvref *nx-current-compiler-policy* hook)))
  (if hook
    (if (functionp hook)
      (apply hook env args)
      t)))

(defun nx-self-calls-inlineable (env)
  (nx-apply-env-hook policy.inline-self-calls env))

(defun nx-allow-register-allocation (env)
  (not (nx-apply-env-hook policy.inhibit-register-allocation env)))

(defun nx-trust-declarations (env)
  (unless (eq (safety-optimize-quantity env) 3)
    (nx-apply-env-hook policy.trust-declarations env)))

(defun nx-open-code-in-line (env)
  (nx-apply-env-hook policy.open-code-inline env))

(defun nx-inline-car-cdr (env)
  (unless (eq (safety-optimize-quantity env) 3)
    (nx-apply-env-hook policy.inhibit-safety-checking env)))

(defun nx-inhibit-safety-checking (env)
  (unless (eq (safety-optimize-quantity env) 3)
    (nx-apply-env-hook policy.inhibit-safety-checking env)))

(defun nx-tailcalls (env)
  (nx-apply-env-hook policy.allow-tail-recursion-elimination env))

(defun nx-allow-transforms (env)
  (nx-apply-env-hook policy.allow-transforms env))

(defun nx-force-boundp-checks (var env)
  (or (eq (safety-optimize-quantity env) 3)
      (nx-apply-env-hook policy.force-boundp-checks var env)))

(defun nx-substititute-constant-value (symbol value env)
  (nx-apply-env-hook policy.allow-constant-substitution symbol value env))

(defun nx-declarations-typecheck (env)
  (nx-apply-env-hook policy.declarations-typecheck env))

(defun nx-strict-structure-typechecking (env)
  (let* ((hook (getf (policy.misc *nx-current-compiler-policy*) :strict-structure-typechecking)))
    (when hook
      (if (functionp hook)
        (funcall hook env)
        t))))

(defun nx-float-safety (env)
  (or (eql (safety-optimize-quantity env) 3)
      (let* ((hook (getf (policy.misc *nx-current-compiler-policy*)
			 :detect-floating-point-exception)))
        (when hook
          (if (functionp hook)
            (funcall hook env)
            t)))))

(defun nx1-default-operator ()
 (or (gethash *nx-sfname* *nx1-operators*)
     (error "Bug - operator not found for  ~S" *nx-sfname*)))

(defun nx-new-temp-var (pending &optional (pname "COMPILER-VAR"))
  (let ((var (nx-new-var pending (make-symbol pname))))
    (nx-set-var-bits var (%ilogior (%ilsl $vbitignoreunused 1)
                                   (%ilsl $vbittemporary 1)
                                   (nx-var-bits var)))
    var))

(defun nx-new-vdecl (pending name class &optional info)
  (push (cons name (cons class info)) (pending-declarations-vdecls pending)))

(defun nx-new-fdecl (pending name class &optional info)
  (push (cons name (cons class info)) (pending-declarations-fdecls pending)))

(defun nx-new-var (pending sym &optional (check t))
  (nx-init-var pending (nx-cons-var (nx-need-var sym check) 0)))
                    
(defun nx-proclaimed-special-p (sym)
  (setq sym (nx-need-sym sym))
  (let* ((defenv (definition-environment *nx-lexical-environment*))
         (specials (if defenv (defenv.specials defenv))))
    (or (assq sym specials)
        (proclaimed-special-p sym))))

(defun nx-proclaimed-parameter-p (sym)
  (setq sym (nx-need-sym sym))
  (or (constantp sym)
      (multiple-value-bind (special-p info) (nx-lex-info sym t)
        (or 
         (and (eq special-p :special) info)
         (let* ((defenv (definition-environment *nx-lexical-environment*)))
           (if defenv 
             (or (%cdr (assq sym (defenv.specials defenv)))
                 (assq sym (defenv.constants defenv)))))))))

(defun nx-process-declarations (pending decls &optional (env *nx-lexical-environment*) &aux s f)
  (dolist (decl decls pending)
    (dolist (spec (%cdr decl))
      (if (memq (setq s (car spec)) *nx-known-declarations*)
        (if (setq f (getf *nx-standard-declaration-handlers* s))
          (funcall f pending spec env))
        ; Any type name is now (ANSI CL) a valid declaration.
        (if (specifier-type-if-known s env)
          (nx-process-type-decl pending spec s (%cdr spec) env)
          (nx-bad-decls spec))))))

; Put all variable decls for the symbol VAR into effect in environment ENV.  Now.
; Returns list of all new vdecls pertaining to VAR.
(defun nx-effect-vdecls (pending var env)
  (let ((vdecls (lexenv.vdecls env))
        (own nil))
    (dolist (decl (pending-declarations-vdecls pending) (setf (lexenv.vdecls env) vdecls))
      (when (eq (car decl) var) 
        (when (eq (cadr decl) 'type)
          (let* ((newtype (cddr decl))
                 (merged-type (nx1-type-intersect var newtype (nx-declared-type var env))))
             (unless (eq merged-type newtype)
              (rplacd (cdr decl) merged-type))))
        (push decl vdecls)
        (push (cdr decl) own)))
    own))




; Guess.
(defun nx-effect-fdecls (pending var env)
  (let ((fdecls (lexenv.fdecls env))
        (own nil))
    (dolist (decl (pending-declarations-fdecls pending) (setf (lexenv.fdecls env) fdecls))
      (when (eq (car decl) var) 
        (push decl fdecls)
        (push (cdr decl) own)))
    own))




(defun nx-acode-form-typep (form type env)
  (acode-form-typep form type  (nx-trust-declarations env)))

(defun acode-form-typep (form type trust-decls)
  (if (acode-p form)
    (let* ((op (acode-operator form))
           (opval-p (or (eq op (%nx1-operator fixnum)) (eq op (%nx1-operator immediate))))
           (optype (acode-form-type form trust-decls)))
      (values
       (if optype 
         (subtypep optype (nx-target-type type))
         (if opval-p (typep (car (acode-operands form)) (nx-target-type type))))))))

(defun nx-acode-form-type (form env)
  (acode-form-type form (nx-trust-declarations env)))

(defparameter *numeric-acode-ops*
  (list (%nx1-operator add2)
        (%nx1-operator sub2)
        (%nx1-operator mul2)
        (%nx1-operator div2)))

(defparameter *acode-operator-types* (make-array (1+ operator-id-mask) :initial-element t)) ; initialized by next-nx-defops


(defparameter *acode-simple-type-inferrers* (make-array (1+ operator-id-mask) :initial-element nil))

(defmacro def-simple-type-infer (name operator-list trust-decls arglist &body body)
  (when (atom operator-list)
    (setq operator-list (list operator-list)))
  (multiple-value-bind (lambda-list whole-var) (normalize-lambda-list arglist t)
    (unless whole-var (setq whole-var (gensym)))
    (multiple-value-bind (body decls)
        (parse-body body nil t)
      (collect ((let-body))
        (dolist (operator operator-list)
          (let-body `(setf (svref *acode-simple-type-inferrers*  (logand operator-id-mask (%nx1-operator ,operator))) fun)))
        (let* ((operands (gensym "OPERANDS")))
          (multiple-value-bind (bindings binding-decls)

              (%destructure-lambda-list lambda-list operands nil nil
                                        :cdr-p nil
                                        :whole-p nil
                                        :use-whole-var t
                                        :default-initial-value nil)
              
            `(let* ((fun (nfunction ,name 
                                    (lambda (,whole-var &optional (,trust-decls t))
                                      (declare (ignorable ,trust-decls))
                                      (block ,name
                                        (let* ((,operands (acode-operands ,whole-var))
                                               ,@(nreverse bindings))
                                          ,@(when binding-decls `((declare ,@binding-decls)))
                                          ,@decls
                                          ,@body))))))
              ,@(let-body))))))))

(defun acode-assert-type (form typespec)
  (setf (acode.asserted-type form)
        (nx-target-type typespec)))

(def-simple-type-infer infer-fixnum fixnum trust-decls (val)
  `(integer ,val ,val))

(def-simple-type-infer infer-immediate immediate trust-decls (val)
  (type-of val))

(def-simple-type-infer infer-progn progn trust-decls (forms)
  (acode-form-type (car (last forms)) trust-decls))

(def-simple-type-infer infer-typed-form typed-form trust-decls (&whole w type form &optional check)
  (declare (ignorable w form))
  (if (or trust-decls check)
    type
    '*))

(def-simple-type-infer infer-let (let let) trust-decls (vars vals body p2decls)
  (declare (ignore vars vals))
  (acode-form-type body (logtest $decl_trustdecls p2decls)))

(def-simple-type-infer infer-ff-call (ff-call eabi-ff-call poweropen-ff-call i386-ff-call) trust-decls (address argspecs argvals resultspec &optional monitor)
  (declare (ignore address argspecs argvals monitor))
  (case resultspec
    (:unsigned-byte '(unsigned-byte 8))
    (:signed-byte '(signed-byte 8))
    (:unsigned-halfword '(unsigned-byte 16))
    (:signed-halfword '(signed-byte 16))
    (:unsigned-fullword '(unsigned-byte 32))
    (:signed-fullword '(signed-byte 32))
    (:unsigned-doubleword '(unsigned-byte 64))
    (:signed-doubleword '(signed-byte 64))
    (:single-float 'single-float)
    (:double-float 'double-float)
    (:address 'macptr)
    (otherwise '*)))


(def-simple-type-infer infer-lambda-bind lambda-bind trust-decls
    (vals req rest keys-p auxen body p2decls)
  (declare (ignore vals req rest keys-p auxen))
  (acode-form-type body (logtest $decl_trustdecls p2decls)))

(def-simple-type-infer infer-if if trust-decls (test true false)
  (declare (ignore test))
  (type-specifier (specifier-type `(or ,(acode-form-type true trust-decls) ,(acode-form-type false trust-decls)))))


;;; If a type declaration applied to a reference, the reference is
;;; likely encapsulate in a TYPED-FORM and we won't reach this code.
;;; The only case that we handle here is that where the variable is
;;; never SETQed and we can tell something about the type of its
;;; initial value.
(def-simple-type-infer infer-lexical-reference lexical-reference trust-decls (var)
  (acode-var-type var trust-decls))


(def-simple-type-infer infer-aref (%aref1 simple-typed-aref2 general-aref2 simple-typed-aref3 general-aref3) trust-decls (array &rest args)
  (declare (ignore args))
  (let* ((atype (acode-form-type array trust-decls))
         (actype (if atype (specifier-type atype))))
    (if (typep actype 'array-ctype)
      (type-specifier (array-ctype-specialized-element-type actype))
      '*)))

(def-simple-type-infer infer-typed-form typed-form trust-decls (type form &optional check)
  (declare (ignore form))
  (if (or trust-decls check)
    type
    '*))

(defun ctype-specifier (thing)
  (when thing (type-specifier thing)))

;;; Accepts a type specifier; returns an integer CTYPE or NIL.
(defun bounded-integer-type-p (typespec)
  (let* ((ctype (specifier-type-if-known(nx-target-type typespec))))
    (and (typep ctype 'numeric-ctype)
         (not (eq :complex (numeric-ctype-complexp ctype)))
         (eq (numeric-ctype-class ctype) 'integer)
         (let* ((low (numeric-ctype-low ctype))
                (high (numeric-ctype-high ctype)))
           (and low (not (eq low '*))
                high (not (eq high '*))
                ctype)))))


(defun acode-form-type (form trust-decls &optional (assert t))
  (declare (ignorable assert))  
  (if (not (acode-p form))
    t
    (or (acode.asserted-type form)
        (acode-assert-type
         form
         (nx-target-type 
          (let* ((op (acode-operator form))
                 (op-id (logand  op operator-id-mask))
                 (type (svref *acode-operator-types* op-id)))
            (declare (fixnum op op-id))
            (if (not (eq type :infer))
              (or type '*)
              (let* ((fn (svref *acode-simple-type-inferrers* op-id)))
                (if fn
                  (let* ((inferred (nx-target-type (funcall fn form trust-decls))))
                    (when (eql (acode-operator form) op-id)
                      (acode-assert-type form inferred))
                    (or inferred '*))
                  t)))))))))


(defun bounded-integer-type-for-addition (type1 type2)
  (let* ((t1 (bounded-integer-type-p type1))
         (t2 (if t1 (bounded-integer-type-p type2))))
    (when t2
      (specifier-type `(integer
                        ,(+ (numeric-ctype-low t1) (numeric-ctype-low t2))
                        ,(+ (numeric-ctype-high t1) (numeric-ctype-high t2)))))))

(defun bounded-integer-type-for-subtraction (type1 type2)
  (let* ((t1 (bounded-integer-type-p type1))
         (t2 (if t1 (bounded-integer-type-p type2))))
    (when t2
      (specifier-type
       `(integer
         ,(- (numeric-ctype-low t1) (numeric-ctype-high t2))
         ,(- (numeric-ctype-high t1) (numeric-ctype-low t2)))))))
         


(defun bounded-integer-type-for-multiplication (type1 type2)
  (let* ((t1 (bounded-integer-type-p type1))
         (t2 (if t1 (bounded-integer-type-p type2))))
    (when t2
      (and (csubtypep t1 (specifier-type '(signed-byte 64)))
           (csubtypep t2 (specifier-type '(signed-byte 64)))
           (let* ((t1low (numeric-ctype-low t1))
                  (t1high (numeric-ctype-high t1))
                  (t2low (numeric-ctype-low t2))
                  (t2high (numeric-ctype-high t2))
                  (p0 (* t1low t2low))
                  (p1 (* t1low t2high))
                  (p2 (* t1high t2low))
                  (p3 (* t1high t2high))
                  (min (min p0 p1 p2 p3))
                  (max (max p0 p1 p2 p3)))
             (specifier-type `(integer
                               ,min
                               ,max)))))))

(defun bounded-integer-type-for-ash (type1 type2)
  (let* ((t1 (bounded-integer-type-p type1))
         (t2 (if t1 (bounded-integer-type-p type2))))
    ;; It's not worth trying to be too precise here if the shift count
    ;; is at all large.
    (when (and t2 (csubtypep t2 (specifier-type '(signed-byte 16))))
      (let* ((vals (ignore-errors
                      (list
                       (ash (numeric-ctype-low t1) (numeric-ctype-low t2))
                       (ash (numeric-ctype-low t1) (numeric-ctype-high t2))
                       (ash (numeric-ctype-high t1) (numeric-ctype-low t2))
                       (ash (numeric-ctype-high t1) (numeric-ctype-high t2))))))
        (when vals
          (specifier-type `(integer
                            ,(apply #'min vals)
                            ,(apply #'max vals))))))))
                        

(defun nx-binop-numeric-contagion (form1 form2 trust-decls)
  (cond ((acode-form-typep form1 'double-float trust-decls)
         (if (acode-form-typep form2 'double-float trust-decls)
           (values form1 form2)
           (let* ((c2 (acode-real-constant-p form2)))
             (if c2
               (values form1 (make-acode (%nx1-operator immediate)
                                         (float c2 0.0d0)))
               (if (acode-form-typep form2 'fixnum trust-decls)
                 (values form1 (make-acode (%nx1-operator %fixnum-to-double)
                                           form2))
                 (values form1 form2))))))
        ((acode-form-typep form2 'double-float trust-decls)
         (let* ((c1 (acode-real-constant-p form1)))
           (if c1
             (values (make-acode (%nx1-operator immediate)
                                 (float c1 0.0d0)) form2)
             (if (acode-form-typep form1 'fixnum trust-decls)
               (values (make-acode (%nx1-operator %fixnum-to-double)
                                   form1) form2)
               (values form1 form2)))))
        ((acode-form-typep form1 'single-float trust-decls)
         (if (acode-form-typep form2 'single-float trust-decls)
           (values form1 form2)
           (let* ((c2 (acode-real-constant-p form2)))
             (if c2
               (values form1 (make-acode (%nx1-operator immediate)
                                         (float c2 0.0f0)))
               (if (acode-form-typep form2 'fixnum trust-decls)
                 (values form1 (make-acode (%nx1-operator %fixnum-to-single)
                                           form2))
                 (values form1 form2))))))
        ((acode-form-typep form2 'single-float trust-decls)
         (let* ((c1 (acode-real-constant-p form1)))
           (if c1
             (values (make-acode (%nx1-operator immediate)
                                 (float c1 0.0f0)) form2)
             (if (acode-form-typep form1 'fixnum trust-decls)
               (values (make-acode (%nx1-operator %fixnum-to-single)
                                   form1) form2)
               (values form1 form2)))))
        (t
         (values form1 form2))))

(defun acode-punted-var-p (var)
  (let ((bits (nx-var-bits var)))
    (and (%ilogbitp $vbitpunted bits)
         (not (%ilogbitp $vbitspecial bits)))))

;; Use acode-unwrapped-form-value to reason about the value of a form at
;; compile time.   To actually generate code, use acode-unwrapped-form.
(defun acode-unwrapped-form-value (form)
  ;; Currently no difference, but if had any operators like with-code-note,
  ;; would unwrap them here.
  (acode-unwrapped-form form))

; Strip off any type info or "punted" lexical references.
; ??? Is it true that the "value" of the punted reference is unwrapped ? ???
(defun acode-unwrapped-form (form) 
  (while (and (acode-p (setq form (nx-untyped-form form)))
           (eq (acode-operator form) (%nx1-operator lexical-reference))
           (acode-punted-var-p (car (acode-operands form))))
    (setq form (var-ea (car (acode-operands form)))))
  form)

(defun acode-fixnum-form-p (x)
  (setq x (acode-unwrapped-form-value x))
  (if (acode-p x)
    (if (eq (acode-operator x) (%nx1-operator fixnum)) 
      (car (acode-operands x)))))

(defun acode-xxx-form-p (x fixnum-supertype)
  (or (acode-fixnum-form-p x)
      (progn
	(setq x (acode-unwrapped-form-value x))
	(if (acode-p x)
	  (if (and (eq (acode-operator x) (%nx1-operator immediate))
		   (typep (car (acode-operands x)) fixnum-supertype))
	    (car (acode-operands x)))))))

(defun acode-integer-form-p (x)
  (acode-xxx-form-p x 'integer))

(defun acode-integer-constant-p (x bits)
  (let ((int (acode-integer-form-p x)))
    (and int
         (or
           (typep int `(signed-byte ,bits))
           (typep int `(unsigned-byte ,bits)))
         int)))

(defun acode-real-constant-p (x)
  (acode-xxx-form-p x 'real))

(defun nx-lookup-target-uvector-subtag (name)
  (or (cdr (assoc name (arch::target-uvector-subtags (backend-target-arch *target-backend*))))
      (nx-error "Type ~s not supported on target ~s"
                name (backend-target-arch-name *target-backend*))))

(defun nx-target-uvector-subtag-name (subtag)
  (or (car (rassoc subtag (arch::target-uvector-subtags (backend-target-arch *target-backend*))))
      (nx-error "Subtag ~s not native on target ~s"
                subtag (backend-target-arch-name *target-backend*))))
(defun nx-error-for-simple-2d-array-type (type-keyword)
  (declare (special arch::error-object-not-simple-array-complex-single-float-2d
                    arch::error-object-not-simple-array-complex-double-float-2d))
  (ecase type-keyword
    (:simple-vector arch::error-object-not-simple-array-t-2d)
    (:simple-string arch::error-object-not-simple-array-char-2d)
    (:bit-vector arch::error-object-not-simple-array-bit-2d)
    (:unsigned-8-bit-vector arch::error-object-not-simple-array-u8-2d)
    (:signed-8-bit-vector arch::error-object-not-simple-array-s8-2d)
    (:unsigned-16-bit-vector arch::error-object-not-simple-array-u16-2d)
    (:signed-16-bit-vector arch::error-object-not-simple-array-s16-2d)
    (:unsigned-32-bit-vector arch::error-object-not-simple-array-u32-2d)
    (:signed-32-bit-vector arch::error-object-not-simple-array-s32-2d)
    (:unsigned-64-bit-vector arch::error-object-not-simple-array-u64-2d)
    (:signed-64-bit-vector arch::error-object-not-simple-array-s64-2d)
    (:double-float-vector arch::error-object-not-simple-array-double-float-2d)
    (:single-float-vector arch::error-object-not-simple-array-single-float-2d)
    (:fixnum-vector arch::error-object-not-simple-array-fixnum-2d)
    (:complex-double-float-vector arch::error-object-not-simple-array-complex-double-float-2d)
    (:complex-single-float-vector arch::error-object-not-simple-array-complex-single-float-2d)))

(defun nx-error-for-simple-3d-array-type (type-keyword)
  ;; Forward refs/bootstrapping:
  (declare (special arch::error-object-not-simple-array-complex-single-float-3d
                    arch::error-object-not-simple-array-complex-double-float-3d))
  (ecase type-keyword
    (:simple-vector arch::error-object-not-simple-array-t-3d)
    (:simple-string arch::error-object-not-simple-array-char-3d)
    (:bit-vector arch::error-object-not-simple-array-bit-3d)
    (:unsigned-8-bit-vector arch::error-object-not-simple-array-u8-3d)
    (:signed-8-bit-vector arch::error-object-not-simple-array-s8-3d)
    (:unsigned-16-bit-vector arch::error-object-not-simple-array-u16-3d)
    (:signed-16-bit-vector arch::error-object-not-simple-array-s16-3d)
    (:unsigned-32-bit-vector arch::error-object-not-simple-array-u32-3d)
    (:signed-32-bit-vector arch::error-object-not-simple-array-s32-3d)
    (:unsigned-64-bit-vector arch::error-object-not-simple-array-u64-3d)
    (:signed-64-bit-vector arch::error-object-not-simple-array-s64-3d)
    (:double-float-vector arch::error-object-not-simple-array-double-float-3d)
    (:single-float-vector arch::error-object-not-simple-array-single-float-3d)
    (:fixnum-vector arch::error-object-not-simple-array-fixnum-3d)
    (:complex-simple-float-vector arch::error-object-not-simple-array-complex-single-float-3d)
    (:complex-double-float-vector arch::error-object-not-simple-array-complex-double-float-3d)))

(defun acode-s16-constant-p (x)
  (setq x (acode-unwrapped-form x))
  (if (acode-p x)
    (let* ((op (acode-operator x)))
      (if (eql op (%nx1-operator fixnum))
        (let* ((val (car (acode-operands x))))
          (if (target-word-size-case
               (32 (typep val '(signed-byte #.(- 16 2))))
               (64 (typep val '(signed-byte #.(- 16 3)))))
            (ash val (target-word-size-case
                      (32 2)
                      (64 3)))))
        (if (eql op (%nx1-operator %unbound-marker))
          (arch::target-unbound-marker-value
           (backend-target-arch *target-backend*))
          (if (eql op (%nx1-operator %slot-unbound-marker))
            (arch::target-slot-unbound-marker-value
             (backend-target-arch *target-backend*))))))))

(defun acode-s32-constant-p (x)
  (setq x (acode-unwrapped-form x))
  (if (acode-p x)
    (let* ((op (acode-operator x)))
      (if (eql op (%nx1-operator fixnum))
        (let* ((val (car (acode-operands x))))
          (if (target-word-size-case
               (32 (typep val '(signed-byte #.(- 32 2))))
               (64 (typep val '(signed-byte #.(- 32 3)))))
            (ash val (target-word-size-case
                      (32 2)
                      (64 3)))))
        (if (eql op (%nx1-operator %unbound-marker))
          (arch::target-unbound-marker-value
           (backend-target-arch *target-backend*))
          (if (eql op (%nx1-operator %slot-unbound-marker))
            (arch::target-slot-unbound-marker-value
             (backend-target-arch *target-backend*))))))))

(defun acode-fixnum-type-p (form trust-decls)
  (or (acode-fixnum-form-p form)
      (and trust-decls
           (acode-p form)
           (eq (acode-operator form) (%nx1-operator typed-form))
           (subtypep (car (acode-operands  form)) 'fixnum))))


(defun nx-acode-fixnum-type-p (form env)
    (acode-fixnum-type-p form (nx-trust-declarations env)))

(defun acode-natural-type-p (form trust-decls)
  (and trust-decls
       (acode-p form)
       (eq (acode-operator form) (%nx1-operator typed-form))
       (subtypep (car (acode-operands form)) *nx-target-natural-type*)))

(defun nx-acode-natural-type-p (form env)
  (acode-natural-type-p form (nx-trust-declarations env)))

;;; Is acode-expression the result of alphatizing (%int-to-ptr <integer>) ?
(defun acode-absolute-ptr-p (acode-expression &optional skip)
  (and (acode-p acode-expression)
       (or skip (prog1 (eq (acode-operator acode-expression) (%nx1-operator %macptrptr%))
                     (setq acode-expression (car (acode-operands acode-expression)))))
          (eq (acode-operator acode-expression) (%nx1-operator %consmacptr%))
          (eq (acode-operator (setq acode-expression (car (acode-operands acode-expression))))
              (%nx1-operator %immediate-int-to-ptr))
          (let* ((op (acode-operator (setq acode-expression (car (acode-operands acode-expression)))))
                 (operands (acode-operands acode-expression)))
            (if (or (eq op (%nx1-operator fixnum))
                    (and (eq op (%nx1-operator immediate))
                         (integerp (car operands))))
              (car operands)))))

(defun specifier-type-if-known (typespec &optional env &key whine values)
  (handler-case (if values (values-specifier-type typespec env) (specifier-type typespec env))
    (parse-unknown-type (c) 
      (when (and whine *compiler-warn-on-undefined-type-references*)
	(nx1-whine (if (keywordp whine) whine :undefined-type) typespec))
      (values nil (parse-unknown-type-specifier c)))
    ;; catch any errors due to destructuring in type-expand
    (program-error (c)
      (when whine
	(nx1-whine :invalid-type typespec c))
      (values nil typespec))))

#+debugging-version
(defun specifier-type-if-known (typespec &optional env &key whine)
  (handler-bind ((parse-unknown-type (lambda (c)
                                       (break "caught unknown-type ~s" c)
				       (when (and whine *compiler-warn-on-undefined-type-references*)
					 (nx1-whine :undefined-type typespec))
                                       (return-from specifier-type-if-known
                                         (values nil (parse-unknown-type-specifier c)))))
		 (program-error (lambda (c)
				  (break "caught program-error ~s" c)
				  (when whine
				    (nx1-whine :invalid-type typespec c))
				  (return-from specifier-type-if-known
				    (values nil typespec)))))
    (specifier-type typespec env)))


(defun nx-check-vdecl-var-ref (decl)
  (let* ((sym (car decl))
         (info (nx-lex-info sym)))
    (when (or (and (not (eq (cadr decl) 'type)) (eq info :symbol-macro))
              (and (null info) (not (or (eq (cadr decl) 'special)
                                        (nx-proclaimed-special-p sym)))))
      (nx1-whine :unknown-declaration-variable (cadr decl) sym))))

(defun nx-check-fdecl-var-ref (decl env &aux (sym (car decl)))
  (unless (eq (cadr decl) 'ftype)
    ;; Complain about forward references, since need a def to use the declaration.
    ;; Perhaps should complain if regular macro, but don't for now.  Compiler macros
    ;; specifically allowed by spec for inline decls
    (unless (or (nx-lexical-finfo sym env)
                (fboundp sym)
                (retrieve-environment-function-info sym env)
                (gethash sym *nx1-alphatizers*)
                (assq sym *nx-compile-time-compiler-macros*)
                (gethash sym *compiler-macros*)
                (eq sym *nx-global-function-name*))
      (nx1-whine :unknown-declaration-function (cadr decl) sym))))


(defun nx-effect-other-decls (pending env)
  (flet ((merge-decls (new old)
                      (dolist (decl new old) (pushnew decl old :test #'eq))))
    (let ((vdecls (pending-declarations-vdecls pending))
          (fdecls (pending-declarations-fdecls pending))
          (mdecls (pending-declarations-mdecls pending)))
      (when vdecls
        (let ((env-vdecls (lexenv.vdecls env)))
          (dolist (decl vdecls (setf (lexenv.vdecls env) env-vdecls))
            (unless (memq decl env-vdecls)
              (nx-check-vdecl-var-ref decl)
              (when (eq (cadr decl) 'type)
                (let* ((var (car decl))
                       (newtype (cddr decl))
                       (merged-type (nx1-type-intersect var newtype (nx-declared-type var env))))
                  (unless (eq merged-type newtype)
                    (rplacd (cdr decl) merged-type))))
              (push decl env-vdecls)))))
      (when fdecls
        (let ((env-fdecls (lexenv.fdecls env)))
          (dolist (decl fdecls (setf (lexenv.fdecls env) env-fdecls))
            (unless (memq decl env-fdecls)
              (nx-check-fdecl-var-ref decl env)
              (push decl env-fdecls)))))
      (when mdecls (setf (lexenv.mdecls env) (merge-decls mdecls (lexenv.mdecls env))))
      (setq *nx-inlined-self* (and (nx-self-calls-inlineable env) 
                                   (let ((name *nx-global-function-name*)) 
                                     (and name (not (nx-declared-notinline-p name env))))))
      (unless (nx-allow-register-allocation env)
        (nx-inhibit-register-allocation))
      (setq *nx-new-p2decls*
            (if (eql (safety-optimize-quantity env) 3)
              (logior $decl_full_safety
                      (if (nx-tailcalls env) $decl_tailcalls 0))
              (%ilogior
                (if (nx-tailcalls env) $decl_tailcalls 0)
                (if (nx-open-code-in-line env) $decl_opencodeinline 0)
                (if (nx-inhibit-safety-checking env) $decl_unsafe 0)
                (if (nx-trust-declarations env) $decl_trustdecls 0)
                (if (nx-float-safety env) $decl_float_safety 0)))))))

#|     
(defun nx-find-misc-decl (declname env)
  (loop
    (unless (and env (eq (uvref env 0) 'lexical-environment)) (return))
    (dolist (mdecl (lexenv.mdecls env))
      (if (atom mdecl)
        (if (eq mdecl declname)
          (return-from nx-find-misc-decl t))
        (if (eq (%car mdecl) declname)
          (return-from nx-find-misc-decl (%cdr mdecl)))))
    (setq env (lexenv.parent-env env))))
|#


(defun nx-bad-decls (decls)
  (nx1-whine :bad-declaration decls))


(defnxdecl special (pending decl env &aux whined)
  (declare (ignore env))
  (dolist (s (%cdr decl))
    (if (symbolp s) 
      (nx-new-vdecl pending s 'special)
      (unless (shiftf whined t) (nx-bad-decls decl)))))

(defnxdecl notspecial (pending decl env &aux whined)
  (declare (ignore env))
  (dolist (s (%cdr decl))
    (if (symbolp s)
      (nx-new-vdecl pending s 'notspecial)
      (unless (shiftf whined t) (nx-bad-decls decl)))))

(defnxdecl dynamic-extent (pending decl env &aux whined)
  (declare (ignore env))
  (dolist (s (%cdr decl))
    (if (symbolp s) 
      (nx-new-vdecl pending s 'dynamic-extent t)
      (if (and (consp s)
               (eq (%car s) 'function)
               (consp (%cdr s))
               (valid-function-name-p (cadr s))
               (setq s (validate-function-name (cadr s))))
        (nx-new-fdecl pending s 'dynamic-extent t)
	(unless (shiftf whined t) (nx-bad-decls decl))))))

(defnxdecl ignorable (pending decl env &aux whined)
  (declare (ignore env))
  (dolist (s (%cdr decl))
    (if (symbolp s) 
      (nx-new-vdecl pending s 'ignorable)
      (if (and (consp s)
               (eq (%car s) 'function)
               (consp (%cdr s))
               (valid-function-name-p (cadr s))
               (setq s (validate-function-name (cadr s))))
        (nx-new-fdecl pending s 'ignorable)
	(unless (shiftf whined t) (nx-bad-decls decl))))))

(defnxdecl ftype (pending decl env &aux whined)
  (destructuring-bind (type &rest fnames) (%cdr decl)
    (let ((ctype (specifier-type-if-known type env :whine :unknown-type-in-declaration)))
      (when ctype
        (if (types-disjoint-p ctype (specifier-type 'function))
          (nx-bad-decls decl)
          (dolist (s fnames)
            (multiple-value-bind (valid nm) (valid-function-name-p s)
            (if valid
              (nx-new-fdecl pending nm 'ftype type)
              (unless (shiftf whined t) (nx-bad-decls decl))))))))))

(defnxdecl settable (pending decl env)
  (nx-settable-decls pending decl env t))

(defnxdecl unsettable (pending decl env)
  (nx-settable-decls pending decl env nil))

(defun nx-settable-decls (pending decl env val &aux whined)
  (declare (ignore env))
  (dolist (s (%cdr decl))
    (if (symbolp s)
      (nx-new-vdecl pending s 'settable val)
      (unless (shiftf whined t) (nx-bad-decls decl)))))

(defnxdecl function (pending decl env)
  (nx-process-type-decl pending decl (car decl) (cdr decl) env))

(defnxdecl type (pending decl env)
  (nx-process-type-decl pending decl (cadr decl) (cddr decl) env))

(defun nx-process-type-decl (pending decl type vars env &aux whined)
  (when (specifier-type-if-known type env :whine :unknown-type-in-declaration)
    (dolist (sym vars)
      (if (symbolp sym)
	(nx-new-vdecl pending sym 'type type)
	(unless (shiftf whined t) (nx-bad-decls decl))))))

(defnxdecl global-function-name (pending decl env)
  (declare (ignore pending))
  (when *nx-parsing-lambda-decls*
    (let ((name (cadr decl)))
      (setq *nx-global-function-name* (setf (afunc-name *nx-current-function*) name))
      (setq *nx-inlined-self* (not (nx-declared-notinline-p name env))))))

(defnxdecl debugging-function-name (pending decl env)
  (declare (ignore pending env))
  (when *nx-parsing-lambda-decls*
    (setf (afunc-name *nx-current-function*) (cadr decl))))


(defnxdecl resident (pending decl env)
  (declare (ignore env pending))
  (declare (ignore decl))
  (nx-decl-set-fbit $fbitresident))


(defun nx-inline-decl (pending decl val &aux valid-name whined)
  (dolist (s (%cdr decl))
    (multiple-value-setq (valid-name s) (valid-function-name-p s))
    (if valid-name
      (progn
        (if (nx-self-call-p s nil t)
          (setq *nx-inlined-self* val))
        (nx-new-fdecl pending s 'inline (if val 'inline 'notinline)))
      (unless (shiftf whined t) (nx-bad-decls decl)))))

(defnxdecl inline (pending decl env)
  (declare (ignore env))
  (nx-inline-decl pending decl t))

(defnxdecl notinline (pending decl env)
  (declare (ignore env))
  (nx-inline-decl pending decl nil))

(defnxdecl ignore (pending decl env &aux whined)
  (declare (ignore env))
  (dolist (s (%cdr decl))
    (if (symbolp s)      
      (nx-new-vdecl pending s 'ignore t)
      (if (and (consp s)
               (eq (%car s) 'function)
               (consp (%cdr s))
               (valid-function-name-p (cadr s))
               (setq s (validate-function-name (cadr s))))
        (nx-new-fdecl pending s 'ignore t)
        (unless (shiftf whined t) (nx-bad-decls decl))))))

(defnxdecl ignore-if-unused (pending decl env &aux whined)
  (declare (ignore env))
  (dolist (s (%cdr decl))
    (if (symbolp s) 
      (nx-new-vdecl pending s 'ignore-if-unused)
      (unless (shiftf whined t) (nx-bad-decls decl)))))

(defun nx-self-call-p (name &optional ignore-lexical (allow *nx-inlined-self*))
  (when (and name (symbolp name))
    (let ((current-afunc *nx-current-function*)
          (target-afunc (unless ignore-lexical (nth-value 1 (nx-lexical-finfo name)))))
      (or (eq current-afunc target-afunc)
          (and allow
               (eq name *nx-global-function-name*)
               (null target-afunc)
               (null (afunc-parent current-afunc)))))))

(defun nx-check-var-usage (var)
  (let* ((sym (var-name var))
         (bits (nx-var-bits var))
         (expansion (var-ea var))
         (setqed (%ilogbitp $vbitsetq bits))
         (reffed (%ilogbitp $vbitreffed bits))
         (closed (%ilogbitp $vbitclosed bits))
         (special (%ilogbitp $vbitspecial bits))
         (ignored (%ilogbitp $vbitignore bits))
         (ignoreunused (%ilogbitp $vbitignoreunused bits)))
    (if special
      (if ignored (nx1-whine :special-ignore sym))
      (if (or reffed closed)
        (progn
          (if ignored (nx1-whine :ignore sym))
          (nx-set-var-bits var (%ilogand (nx-check-downward-vcell var bits) (%ilognot (%ilsl $vbitignore 1)))))
        (progn
          (if (and setqed ignored) (nx1-whine :ignore sym))
          (or ignored ignoreunused 
              (progn (and (consp expansion) (eq (car expansion) :symbol-macro) (setq sym (list :symbol-macro sym))) (nx1-whine :unused sym)))
          (when (eql 0 (logior (nx-var-root-nrefs var) (nx-var-root-nsetqs var)))
            (nx-set-var-bits var (%ilogior (%ilsl $vbitignore 1) bits))))))))

; if an inherited var isn't setqed, it gets no vcell.  If it -is- setqed, but
; all inheritors are downward, the vcell can be stack-consed.  Set a bit so that
; the right thing happens when the var is bound.
; Set the bit for the next-method var even if it is not setqed.
(defun nx-check-downward-vcell (v bits)
  (if (and (%ilogbitp $vbitclosed bits)
           (or (%ilogbitp $vbitsetq bits)
               (eq v *nx-next-method-var*))
           (nx-afuncs-downward-p v (afunc-inner-functions *nx-current-function*)))
    (%ilogior (%ilsl $vbitcloseddownward 1) bits)
    bits))

; afunc is "downward wrt v" if it doesn't inherit v or if all refs to afunc
; are "downward" and no inner function of afunc is not downward with respect to v.
(defun nx-afunc-downward-p (v afunc)
  (or (dolist (i (afunc-inherited-vars afunc) t)
        (when (eq (nx-root-var i) v) (return nil)))
      (if (nx-afuncs-downward-p v (afunc-inner-functions afunc))
        (eq (afunc-fn-refcount afunc)
            (afunc-fn-downward-refcount afunc)))))

(defun nx-afuncs-downward-p (v afuncs)
  (dolist (afunc afuncs t)
    (unless (nx-afunc-downward-p v afunc) (return nil))))

(defun nx1-punt-bindings (vars initforms)
  (dolist (v vars)
    (nx1-punt-var v (pop initforms))))

;;; at the beginning of a binding construct, note which lexical
;;; variables are bound to other variables and the number of setqs
;;; done so far on the initform.  After executing the body, if neither
;;; variable has been closed over, the new variable hasn't been
;;; setq'ed, and the old guy wasn't setq'ed in the body, the binding
;;; can be punted.

(defun nx1-note-var-binding (var initform)
  (let* ((init (nx-untyped-form initform))
         (bits (nx-var-bits var)))
    (when (%ilogbitp $vbitspecial bits) (nx-record-xref-info :binds (var-name var)))
    (when (and (not (%ilogbitp $vbitspecial bits))
               (acode-p init))
      (setf (var-initform var) initform)
      (let* ((op (acode-operator init)))
        (if (eq op (%nx1-operator lexical-reference))
          (let* ((target (car (acode-operands init)))
                 (setq-count (nx-var-root-nsetqs target)))
            (cons var (cons setq-count target)))
          (if (and (%ilogbitp $vbitdynamicextent bits)
                   (or (eq op (%nx1-operator closed-function))
                       (eq op (%nx1-operator simple-function))))
            (let* ((afunc (car (acode-operands init))))
              (setf (afunc-fn-downward-refcount afunc
)
                    (afunc-fn-refcount afunc)
                    (afunc-bits afunc) (logior (ash 1 $fbitdownward) (ash 1 $fbitbounddownward)
                                               (the fixnum (afunc-bits afunc))))
              nil)))))))


;;; Process entries involving variables bound to other variables at
;;; the end of a binding construct.  Each entry is of the form
;;; (source-var setq-count . target-var), where setq-count is the
;;; assignment count of TARGET-VAR at the time that the binding's
;;; initform was evaluated (not, in the case of LET, at the time that
;;; the bindinw was established.).  If the target isn't closed-over
;;; and SETQed (somewhere), and wasn't setqed in the body (e.g.,
;;; still has the same assignment-count as it had when the initform
;;; was executed), then we can "punt" the source (and replace references
;;; to it with references to the target.)
;;; It obviously makes no sense to do this if the source is SPECIAL;
;;; in some cases (LET), we create the source variable and add it to
;;; this alist before it's known whether or not the source variable
;;; is SPECIAL. so we have to ignore that case here.
(defun nx1-check-var-bindings (alist)
  (dolist (pair alist)
    (let* ((var (car pair))
           (target (cddr pair))
           (vbits (nx-var-bits var))
           (target-bits (nx-var-bits target)))
      (unless (or
               ;; var can't be special, setq'ed or closed; target can't be
               ;; setq'ed AND closed.
               (neq (%ilogand vbits (%ilogior (%ilsl $vbitsetq 1)
                                              (%ilsl $vbitclosed 1)
                                              (%ilsl $vbitspecial 1))) 0)
               (eq (%ilogior (%ilsl $vbitsetq 1) (%ilsl $vbitclosed 1)) 
                   (%ilogand
                     (%ilogior (%ilsl $vbitsetq 1) (%ilsl $vbitclosed 1))
                     target-bits))               
               (neq (nx-var-root-nsetqs target) (cadr pair)))
             (push (cons var target) *nx-punted-vars*)))))

;;; Someone might be able to come up with a case where (perhaps through
;;; use of (DECLAIM (IGNORE ...))) it might make some sense to bind
;;; the same variable more than once in a parallel binding construct.
;;; Even if that's done intentionally, there's probably some value
;;; in warning about it (and it's hard to guess whether it's done
;;; intentionally.
;;; Something like (LET* ((X 1) (X (1+ X))) ...) is well-defined (even
;;; if it's a bit unaesthetic.
;;; We error if there are duplicate required args in a lambda list,
;;; but let things like (LAMBDA (A &OPTIONAL A) ...) slide.  (Those
;;; cases generally generate an unused-variable warning, so we don't

(defun nx1-check-duplicate-bindings (syms context)
  (do* ()
       ((null syms))
    (let* ((sym (pop syms)))
      (when (member sym syms :test #'eq)
        (nx1-whine :duplicate-binding (maybe-setf-name sym) context)))))
              

(defun nx1-punt-var (var initform)
  (let* ((bits (nx-var-bits var))
         (mask (%ilogior (%ilsl $vbitsetq 1) (ash -1 $vbitspecial) (%ilsl $vbitclosed 1)))
         (nrefs (nx-var-root-nrefs var))
         (val (nx-untyped-form initform))
         (op (if (acode-p val) (acode-operator val))))
    (when (%izerop (%ilogand mask bits))
      (if
        (or 
         (nx-t val)
         (nx-null val)
         (and (eql nrefs 1) (not (logbitp $vbitdynamicextent bits)) ( acode-absolute-ptr-p val t))
         (eq op (%nx1-operator fixnum))
         (eq op (%nx1-operator immediate)))
        (progn
          (nx-set-var-bits var (%ilogior (%ilsl $vbitpuntable 1) bits)))))
    (when (and (%ilogbitp $vbitdynamicextent bits)
               (or (eq op (%nx1-operator closed-function))
                   (eq op (%nx1-operator simple-function))))
      (let* ((afunc (car (acode-operands val))))
        (setf (afunc-bits afunc) (%ilogior (%ilsl $fbitbounddownward 1) (afunc-bits afunc))
              (afunc-fn-downward-refcount afunc) 1))) 
    nil))
            
(defnxdecl optimize (pending specs env)
  (declare (ignore env))
  (let* ((q nil)
         (v nil)
         (mdecls (pending-declarations-mdecls pending)))
    (dolist (spec (%cdr specs) (setf (pending-declarations-mdecls pending) mdecls))
      (if (atom spec)
        (setq q spec v 3)
        (setq q (%car spec) v (cadr spec)))
      (if (and (fixnump v) (<= 0 v 3))
        (if  (memq q '(speed space compilation-speed safety debug))
          (push (cons q v) mdecls)
          (if (or (eq q 'stack-access)
                  (eq q :stack-access))
            (when (and *nx-parsing-lambda-decls* (not *force-legacy-backend*)) (target-arch-case (:x8664 (setq *backend-use-linear-scan* (not (eql v 0))))))
            (nx-bad-decls spec)))))))

(defun %proclaim-optimize (specs &aux q v)
  (dolist (spec specs)
    (if (atom spec)
      (setq q spec v 3)
      (setq q (%car spec) v (cadr spec)))
    (or (and (fixnump v)
             (<= 0 v 3)
             (case q
               (speed (setq *nx-speed* v))
               (space (setq *nx-space* v))
               (compilation-speed (setq *nx-cspeed* v))
               (safety (setq *nx-safety* v))
               (debug (setq *nx-debug* v))
               ((stack-access :stack-access) (progn (target-arch-case (:x8664 (setq *backend-use-linear-scan* (not (eql v 0))))) v ))))
        (bad-proclaim-spec `(optimize ,spec)))))

(defun nx-lexical-finfo (sym &optional (env *nx-lexical-environment*))
  (let* ((info nil)
         (barrier-crossed nil))
    (if env
      (loop
        (when (eq 'barrier (lexenv.variables env))
          (setq barrier-crossed t))
        (when (setq info (%cdr (assq sym (lexenv.functions env))))
          (return (values info (if (and (eq (car info) 'function)
                                        (consp (%cdr info)))
                                 (progn
                                   (when barrier-crossed
                                     (nx-error "Illegal reference to lexically-defined function ~S." sym))
                                   (%cadr info))))))
        (if (listp (setq env (lexenv.parent-env env)))
          (return (values nil nil))))
      (values nil nil))))

(defun nx-inline-expansion (sym &optional (env *nx-lexical-environment*) global-only)
  (let* ((lambda-form nil)
         (containing-env nil)
         (token nil))
    (if (and (nx-declared-inline-p sym env)
             (not (gethash sym *nx1-alphatizers*))
             (not *nx-current-code-note*))
      (multiple-value-bind (info afunc) (unless global-only (nx-lexical-finfo sym env))
        (if info (setq token afunc 
                       containing-env (afunc-environment afunc)
                       lambda-form (afunc-lambdaform afunc)))
        (setq info (cdr (retrieve-environment-function-info sym env)))
        (if (def-info.lambda info)
          (setq lambda-form (%def-info.lambda info)
                token sym
                containing-env (new-lexical-environment (%def-info.environment info)))
          (unless info
            (if (cdr (setq info (assq sym *nx-globally-inline*)))
              (setq lambda-form (%cdr info)
                    token sym
                    containing-env (new-lexical-environment (new-definition-environment nil))))))))
    (values lambda-form (nx-closed-environment env containing-env) token)))

(defun nx-closed-environment (current-env target)
  (when target
    (let* ((intervening-functions nil))
      (do* ((env current-env (lexenv.parent-env env)))
           ((or (eq env target) (null env) (istruct-typep env 'definition-environment)))
        (let* ((fn (lexenv.lambda env)))
          (when fn (push fn intervening-functions))))
      (let* ((result target))
        (dolist (fn intervening-functions result)
          (setf (lexenv.lambda (setq result (new-lexical-environment result))) fn))))))


(defun nx-reconcile-inherited-vars (more)
  (let ((last nil)) ; Bop 'til ya drop.
    (loop
      (setq last more more nil)
      (dolist (callee last)
        (dolist (caller (afunc-callers callee))
          (unless (or (eq caller callee)
                      (eq caller (afunc-parent callee)))
            (dolist (v (afunc-inherited-vars callee))
              (let ((root-v (nx-root-var v)))
                (unless (dolist (caller-v (afunc-inherited-vars caller))
                          (when (eq root-v (nx-root-var caller-v))
                            (return t)))
                  ; caller must inherit root-v in order to call callee without using closure.
                  ; can't just bind afunc & call nx-lex-info here, 'cause caller may have
                  ; already shadowed another var with same name.  So:
                  ; 1) find the ancestor of callee which bound v; this afunc is also an ancestor
                  ;    of caller
                  ; 2) ensure that each afunc on the inheritance path from caller to this common
                  ;    ancestor inherits root-v.
                  (let ((ancestor (afunc-parent callee))
                        (inheritors (list caller)))
                    (until (eq (setq v (var-bits v)) root-v)
                      (setq ancestor (afunc-parent ancestor)))
                    (do* ((p (afunc-parent caller) (afunc-parent p)))
                         ((eq p ancestor))
                      (push p inheritors))
                    (dolist (f inheritors)
                      (setq v (nx-cons-var (var-name v) v))
                      (unless (dolist (i (afunc-inherited-vars f))
                                (when (eq root-v (nx-root-var i))
                                  (return (setq v i))))
                        (pushnew f more)
                        (push v (afunc-inherited-vars f))
                        ; change shared structure of all refs in acode with one swell foop.
                        (nx1-afunc-ref f))))))))))    
      (unless more (return)))))

(defun nx-inherit-var (var binder current)
  (if (eq binder current)
    (progn
      (nx-set-var-bits var (%ilogior2 (%ilsl $vbitclosed 1) (nx-var-bits var)))
      var)
    (let ((sym (var-name var)))
      (or (dolist (already (afunc-inherited-vars current))
            (when (eq sym (var-name already)) (return already)))
          (progn
            (setq var (nx-cons-var sym (nx-inherit-var var binder (afunc-parent current))))
            (push var (afunc-inherited-vars current))
            var)))))

(defun nx-lex-info (sym &optional current-only)
  (let* ((current-function *nx-current-function*)
         (catch nil)
         (barrier-crossed nil))
    (multiple-value-bind 
      (info afunc)
      (do* ((env *nx-lexical-environment* (lexenv.parent-env env))
            (continue env (and env (not (istruct-typep env 'definition-environment))))
            (binder current-function (or (if continue (lexenv.lambda env)) binder)))
           ((or (not continue) (and (neq binder current-function) current-only)) 
            (values nil nil))
        (let ((vars (lexenv.variables env)))
          (if (eq vars 'catch) 
            (setq catch t)
            (if (eq vars 'barrier)
              (setq barrier-crossed t)
              (let ((v (dolist (var vars)
                         (when (eq (var-name var) sym) (return var)))))
                (when v (return (values v binder)))
                (dolist (decl (lexenv.vdecls env))
                  (when (and (eq (car decl) sym)
                             (eq (cadr decl) 'special))
                    (return-from nx-lex-info (values :special nil nil)))))))))
      (if info
        (if (var-expansion info)
          (values :symbol-macro (cdr (var-expansion info)) info)
          (if (%ilogbitp $vbitspecial (nx-var-bits info))
            (values :special info nil)
            (if barrier-crossed
              (nx-error "Illegal reference to lexically defined variable ~S." sym)
              (if (eq afunc current-function)
                (values info nil catch)
                (values (nx-inherit-var info afunc current-function) t catch)))))
        (values nil nil nil)))))


(defun nx-block-info (blockname)
  (do* ((toplevel t nil)
        (afunc *nx-current-function*(afunc-parent afunc)))
       ((null afunc) (values nil nil))
    (let* ((info (assq blockname (if toplevel *nx-blocks* (afunc-blocks afunc)))))
      (if info
        (return-from nx-block-info (values info (not toplevel)))))))


(defun nx-tag-info (tagname &optional (afunc *nx-current-function*) &aux
                            tags
                            parent
                            index
                            counter
                            (toplevel (eq afunc *nx-current-function*))
                            taginfo)
  (when afunc
    (setq
     tags (if toplevel *nx-tags* (afunc-tags afunc))
     taginfo (assoc tagname tags)
     parent (afunc-parent afunc))
    (if taginfo
      (values taginfo nil)
      (when (and parent (setq taginfo (nx-tag-info tagname parent)))
        (unless (setq index (cadr taginfo))
          (setq counter (caddr taginfo))
          (%rplaca counter (%i+ (%car counter) 1))
          (setq index (%car counter))
          (%rplaca (%cdr taginfo) index))
        (values taginfo index)))))

(defun nx1-transitively-punt-bindings (pairs) 
  (dolist (pair (nreverse pairs))
    (let* ((var         (%car pair))
           (boundto     (%cdr pair))
           (varbits     (nx-var-bits var))
           (boundtobits (nx-var-bits boundto)))
      (declare (fixnum varbits boundtobits))
      (unless (eq (%ilogior
                   (%ilsl $vbitsetq 1)
                   (%ilsl $vbitclosed 1))
                  (%ilogand
                   (%ilogior
                    (%ilsl $vbitsetq 1)
                    (%ilsl $vbitclosed 1))
                   boundtobits))
        ;; Can't happen -
        (unless (%izerop (%ilogand (%ilogior
                                    (%ilsl $vbitsetq 1) 
                                    (ash -1 $vbitspecial)
                                    (%ilsl $vbitclosed 1)) varbits))
          (error "Bug-o-rama - \"punted\" var had bogus bits. ~
Or something. Right? ~s ~s" var varbits))
        (let* ((varcount     (nx-var-root-nrefs var))
               (boundtocount (nx-var-root-nrefs boundto)))
          (nx-set-var-bits var (%ilogior
                                (%ilsl $vbitpuntable 1)
                                varbits))
          (setf (var-refs boundto) (+ (var-refs var) (var-refs boundto))
                (var-refs var) 0)
          (nx-set-var-root-nrefs boundto
                                 (+ (1- boundtocount) varcount)))))))

;;; Home-baked handler-case replacement.  About 10 times as fast as full handler-case.
;;;(LET ((S 0)) (DOTIMES (I 1000000) (INCF S))) took 45,678 microseconds
;;;(LET ((S 0)) (DOTIMES (I 1000000) (BLOCK X (ERROR (CATCH 'X (RETURN-FROM X (INCF S))))))) took 57,485
;;;(LET ((S 0)) (DOTIMES (I 1000000) (HANDLER-CASE (INCF S) (ERROR (C) C)))) took 168,947
(defmacro with-program-error-handler (handler &body body)
  (let ((tag (gensym)))
    `(block ,tag
       (,handler (catch 'program-error-handler (return-from ,tag (progn ,@body)))))))

(defun runtime-program-error-form (c)
  `(signal-program-error "Invalid program: ~a" ,(princ-to-string c)))

(defun nx1-compile-lambda (name lambda-form &optional
                                 (p (make-afunc))
                                 q
                                 parent-env
                                 (policy *default-compiler-policy*)
                                 load-time-eval-token)

  (if q
     (setf (afunc-parent p) q))

  ;; In the case of a method function, the name will get reset at load time to the
  ;; method object.  However, during compilation, we want any inner functions to use
  ;; the fully qualified method name, so store that.
  (when (method-lambda-p lambda-form)
    (setq name (or *nx-method-warning-name* name)))

  (setf (afunc-name p)
        (let ((parent-name (and (afunc-parent p) (afunc-name (afunc-parent p)))))
          (if parent-name
            (if (and (consp parent-name) (eq (%car parent-name) :internal))
              (if name
                `(:internal ,name ,@(cdr parent-name))
                parent-name)
              (if name
                `(:internal ,name ,parent-name)
                `(:internal ,parent-name)))
            name)))

  (unless (lambda-expression-p lambda-form)
    (nx-error "~S is not a valid lambda expression." lambda-form))

  (let* ((*nx-current-function* p)
         (*nx-parent-function* q)
         (*nx-current-note* (or *nx-current-note* (nx-source-note lambda-form)))
         (*nx-lexical-environment* (new-lexical-environment parent-env))
         (*nx-load-time-eval-token* load-time-eval-token)
         (*nx-all-vars* nil)
         (*nx-bound-vars* nil)
         (*nx-punted-vars* nil)
         (*nx-current-compiler-policy* policy)
         (*nx-blocks* nil)
         (*nx-tags* nil)
         (*nx-loop-nesting-level* 0)
         (*nx-inner-functions* nil)
         (*nx-global-function-name* nil)
         (*nx-warnings* nil)
         (*nx1-fcells* nil)
         (*nx1-vcells* nil)
         (*nx-inline-expansions* nil)
         (*nx-parsing-lambda-decls* nil)
         (*nx-next-method-var* (if q *nx-next-method-var*))
         (*nx-call-next-method-function* (if q *nx-call-next-method-function*))
         (*nx-cur-func-name* name))
    (if (%non-empty-environment-p *nx-lexical-environment*)
      (setf (afunc-bits p) (logior (ash 1 $fbitnonnullenv) (the fixnum (afunc-bits p)))))

    (setf (afunc-lambdaform p) lambda-form)

    (when *nx-current-note*
      (setf (afunc-lfun-info p)
            (list* '%function-source-note *nx-current-note* (afunc-lfun-info p))))

    (with-program-error-handler
	(lambda (c)
	  (setf (afunc-acode p) (nx1-lambda '(&rest args) `(args ,(runtime-program-error-form c)) nil)))
      (handler-bind ((warning (lambda (c)
                                (nx1-whine :program-error c)
                                (muffle-warning c)))
                     (program-error (lambda (c)
                                      (when *nx-break-on-program-errors*
                                        (cerror "continue compilation ignoring this form" c))
                                      (when (typep c 'compile-time-program-error)
                                        (setq c (make-condition 'simple-program-error
                                                                :format-control (simple-condition-format-control c)
                                                                :format-arguments (simple-condition-format-arguments c))))
                                      (unless *nx-break-on-program-errors*
                                        (nx1-whine :program-error c))
                                      (throw 'program-error-handler c))))
	(multiple-value-bind (body decls)
	    (with-program-error-handler (lambda (c) (runtime-program-error-form c))
	      (parse-body (%cddr lambda-form) *nx-lexical-environment* t))
          (setf (afunc-acode p) (nx1-lambda (%cadr lambda-form) body decls)))))
    (rewrite-acode-form (afunc-acode p))
    (nx1-transitively-punt-bindings *nx-punted-vars*)
    (setf (afunc-blocks p) *nx-blocks*)
    (setf (afunc-tags p) *nx-tags*)
    (setf (afunc-inner-functions p) *nx-inner-functions*)
    (setf (afunc-all-vars p) *nx-all-vars*)
    (setf (afunc-vcells p) *nx1-vcells*)
    (setf (afunc-fcells p) *nx1-fcells*)
    (when *nx-current-code-note*
      (when (null q) ;; toplevel functions only
        (nx-record-code-coverage-acode p)))
    (let* ((warnings (merge-compiler-warnings *nx-warnings*))
	   (name *nx-cur-func-name*))        
      (dolist (inner *nx-inner-functions*)
	(dolist (w (afunc-warnings inner))
	  (push name (compiler-warning-function-name w))
	  (push w warnings)))
      (setf (afunc-warnings p) warnings))
    p))

(defun method-lambda-p (form)
  (and (consp form)
       (consp (setq form (%cdr form)))
       (consp (car form))
       (eq (caar form) '&method)))


(defun nx1-lambda (ll body decls &aux (l ll) methvar)
  (let* ((old-env *nx-lexical-environment*)
         (*nx-bound-vars* *nx-bound-vars*))
    (with-nx-declarations (pending)
      (let* ((*nx-parsing-lambda-decls* t))
        (nx-process-declarations pending decls))
      (when (eq (car l) '&lap)
        (let ((bits nil))
          (unless (and (eq (length (%cdr l)) 1) (fixnump (setq bits (%cadr l))))
            (unless (setq bits (encode-lambda-list (%cdr l)))
              (nx-error "invalid lambda-list  - ~s" l)))
          (return-from nx1-lambda
                       (make-acode
                        (%nx1-operator lambda-list)
                        (list (cons '&lap bits))
                        nil
                        nil
                        nil
                        nil
                        (nx1-env-body :value body old-env)
                        *nx-new-p2decls*))))
      (when (eq (car l) '&method)
        (setf (afunc-bits *nx-current-function*)
              (%ilogior (%ilsl $fbitmethodp 1)
                        (afunc-bits *nx-current-function*)))
        (setq *nx-inlined-self* nil)
        (setq *nx-next-method-var* (setq methvar (let ((var (nx-new-var
							     pending
							     (%cadr ll))))
                                                   (nx-set-var-bits var (%ilogior 
                                                                          (%ilsl $vbitignoreunused 1) 
                                                                          ;(%ilsl $vbitnoreg 1) 
                                                                          (nx-var-bits var)))
                                                   var)))
                                                   
        (setq ll (%cddr ll)))
      (multiple-value-bind (req opt rest keys auxen lexpr)
                           (nx-parse-simple-lambda-list pending ll)
        (nx-effect-other-decls pending *nx-lexical-environment*)
        (setq body (nx1-env-body :return body old-env))
        (nx1-punt-bindings (%car auxen) (%cdr auxen))
        (when methvar
          (push methvar req)
          (unless (eq 0 (%ilogand (%ilogior (%ilsl $vbitreffed 1)
                                            (%ilsl $vbitclosed 1)
                                            (%ilsl $vbitsetq 1))
                                  (nx-var-bits methvar)))
            (setf (afunc-bits *nx-current-function*)
                  (%ilogior 
                   (%ilsl $fbitnextmethp 1)
                   (afunc-bits *nx-current-function*)))))
        (let ((acode (make-acode
                      (%nx1-operator lambda-list) 
                      req
                      opt 
                      (if lexpr (list rest) rest)
                      keys
                      auxen
                      body
                      *nx-new-p2decls*)))
          (when *nx-current-code-note*
            (setf (acode-note acode) *nx-current-code-note*))
          acode)))))

(defun nx-ensure-supplied-p (always pending vals spvars)
  (when (or always
            (dolist (v spvars) (when v (return t)))
            (dolist (v vals) (unless (nx-null v) (return t))))
    (do*  ((spvars spvars (cdr spvars)))
          ((null spvars))
      (unless (car spvars)
        (setf (car spvars) (nx-new-temp-var pending)))))
  spvars)
              
    
           
(defun nx-parse-simple-lambda-list (pending ll &aux
					      req
					      opt
					      rest
					      keys
					      lexpr
					      sym)
  (multiple-value-bind (ok reqsyms opttail resttail keytail auxtail)
                       (verify-lambda-list ll)
    (unless ok (nx-error "Bad lambda list : ~S" ll))
    (dolist (var reqsyms)
      (push (nx-new-var pending var t) req))
    (when (eq (pop opttail) '&optional)
      (let* (optvars optinits optsuppliedp)
        (until (eq opttail resttail) 
          (setq sym (pop opttail))
          (let* ((var sym)
                 (initform nil)
                 (spvar nil))
            (when (consp var)
              (setq sym (pop var) initform (pop var) spvar (%car var)))
            (push (nx1-typed-var-initform pending sym initform) optinits)
            (push (nx-new-var pending sym t) optvars)
            (push (if spvar (nx-new-var pending spvar t)) optsuppliedp)))
        (if optvars
          (setq opt (list (nreverse optvars) (setq optinits (nreverse optinits)) (nx-ensure-supplied-p nil pending optinits (nreverse optsuppliedp))))
          (nx1-whine :lambda ll))))
    (let ((temp (pop resttail)))
      (when (or (eq temp '&rest)
                (setq lexpr (eq temp '&lexpr)))
        (setq rest (nx-new-var pending (%car resttail) t))))
    (when (eq (%car keytail) '&key) 
      (setq keytail (%cdr keytail))
      (let* ((keysyms ())
             (keykeys ())
             (keyinits ())
             (keysupp ())
             (kallowother (not (null (memq '&allow-other-keys ll))))
             (kvar ())
             (kkey ())
             (kinit ())
             (ksupp))
        (until (eq keytail auxtail)
          (unless (eq (setq sym (pop keytail)) '&allow-other-keys)      
            (setq kinit (make-nx-nil) ksupp nil)
            (if (atom sym)
              (setq kvar sym kkey (make-keyword sym))
              (progn
                (if (consp (%car sym))
                  (setq kkey (%caar sym) kvar (%cadar sym))
                  (progn
                    (setq kvar (%car sym))
                    (setq kkey (make-keyword kvar))))
                (setq kinit (nx1-typed-var-initform pending kvar (%cadr sym)))
                (setq ksupp (%caddr sym))))
            (push (nx-new-var pending kvar t) keysyms)
            (push kkey keykeys)
            (push kinit keyinits)
            (push (if ksupp (nx-new-var pending ksupp t)) keysupp)))
        (setq 
         keys
         (list
          kallowother
          (nreverse keysyms)
          (nx-ensure-supplied-p  t pending nil (nreverse keysupp))
          (nreverse keyinits)
          (apply #'vector (nreverse keykeys))))))
    (let (auxvals auxvars)
      (dolist (pair (%cdr auxtail))
        (let* ((auxvar (nx-pair-name pair))
               (auxval (nx1-typed-var-initform pending auxvar (nx-pair-initform pair))))
          (push auxval auxvals)
          (push (nx-new-var pending auxvar t) auxvars)))
      (values
       (nreverse req) 
       opt 
       rest
       keys
       (list (nreverse auxvars) (nreverse auxvals))
       lexpr))))



(defun nx1-immediate (context form)
  (declare (ignorable context))
  (cond ((eq form t) (make-acode (%nx1-operator t)))
          ((null form) (make-acode (%nx1-operator nil)))
          ((nx1-target-fixnump form)
           (make-acode (%nx1-operator fixnum) form))
          (t (make-acode (%nx1-operator immediate) form))))

;;; Note that "simple lexical refs" may not be; that's the whole problem ...
(defun nx1-symbol (context form &optional (env *nx-lexical-environment*))
  (let* ((type (nx-declared-type form))
         (form
          (multiple-value-bind (info inherited-p more)
                               (nx-lex-info form)
            (if (and info (neq info :special))
              (if (eq info :symbol-macro)
                (progn
                  (nx-set-var-bits more (%ilogior (%ilsl $vbitreffed 1) (nx-var-bits more)))
                  (if (eq type t)
                    (nx1-form context inherited-p)
                    (nx1-form context `(the ,(prog1 type (setq type t)) ,inherited-p))))
                (progn
                  (when (not inherited-p)
                    (nx-set-var-bits info (%ilogior2 (%ilsl $vbitreffed 1) (nx-var-bits info))))
                  (when context
                    (nx-adjust-ref-count info))
                  (nx-make-lexical-reference info)))
              (make-acode
	       (if (nx1-check-special-ref form info)
		   (progn
		     (nx-record-xref-info :references form)
		     (if (nx-global-p form env)
			 (%nx1-operator global-ref)
		         (if (and (not (nx-force-boundp-checks form env))
				  (or (nx-proclaimed-parameter-p form)
				  (assq form *nx-compile-time-types*)
				  (assq form *nx-proclaimed-types*)
				  (nx-open-code-in-line env)))
			     (%nx1-operator bound-special-ref)
			     (%nx1-operator special-ref))))
		   (%nx1-operator free-reference))
               (nx1-note-vcell-ref form))))))
    (if (eq type t)
	form
      (make-acode (%nx1-operator typed-form) type form))))

(defun nx1-combination (context form env)
  (destructuring-bind (sym &rest args) form
    (if (symbolp sym)
      (let* ((*nx-sfname* sym)
             (special (gethash sym *nx1-alphatizers*))
             (def (fboundp sym)))
        (if (and special
                 (not (nx-lexical-finfo sym env))
                 (or (special-operator-p sym)
                     (not (nx-declared-notinline-p sym env)))
                 (or (not (functionp def))
                     (null (nx1-check-call-args def (cdr form) nil))))
          (funcall special context form env) ; pass environment arg ...
          (progn            
            (nx1-typed-call context sym args))))
      (if (lambda-expression-p sym)
        (nx1-lambda-bind context (%cadr sym) args (%cddr sym))
	(nx-error "In the form ~S, ~S is not a symbol or lambda expression." form sym)))))

(defun nx1-transformed-form (context form env)
  (let* ((*nx-current-note* (or (nx-source-note form) *nx-current-note*))
         (*nx-current-code-note*  (and *nx-current-code-note*
                                       (or (nx-ensure-code-note form *nx-current-code-note*)
                                           (compiler-bug "No source note for ~s" form))))
         (acode (if (consp form)
                  (nx1-combination context form env)
                  (let* ((symbolp (non-nil-symbol-p form))
                         (constant-value (unless symbolp form))
                         (constant-symbol-p nil))
                    (if symbolp 
                      (multiple-value-setq (constant-value constant-symbol-p) 
                        (nx-transform-defined-constant form env)))
                    (if (and symbolp (not constant-symbol-p))
                      (nx1-symbol context form env)
                      (nx1-immediate context (nx-unquote constant-value)))))))
    (unless (acode-note acode) ;; leave it with most specific note
      (cond (*nx-current-code-note*
             (setf (acode-note acode) *nx-current-code-note*))
            (*record-pc-mapping*
             (setf (acode-note acode) (nx-source-note form)))))
    acode))

(defun nx1-typed-form (context original env)
  (with-program-error-handler
      (lambda (c)
        (let ((replacement (runtime-program-error-form c)))
          (nx-note-source-transformation original replacement)
          (nx1-transformed-form context (nx-transform replacement env) env)))
    (multiple-value-bind (form changed source) (nx-transform original env)
      (declare (ignore changed))
      ;; Bind this for cases where the transformed form is an atom, so it doesn't remember the source it came from.
      (let ((*nx-current-note* (or source *nx-current-note*)))
	(nx1-transformed-form context form env)))))

(defun nx1-form (context form &optional (*nx-lexical-environment* *nx-lexical-environment*))
  #-bootstrapped
  (unless (member context '(nil :return :value))
    (break "bad context ~s" context))
  (let* ((*nx-form-type* (if (and (consp form) (eq (car form) 'the))
                           (nx-target-type (cadr form))
                           t)))
    (nx1-typed-form context form *nx-lexical-environment*)))

(defun nx1-typed-var-initform (pending sym form &optional (env *nx-lexical-environment*))
  (let* ((type t)
         (*nx-form-type* (if (nx-trust-declarations env)
                           (dolist (decl (pending-declarations-vdecls pending) type)
                             (when (and (eq (car decl) sym) (eq (cadr decl) 'type))
                               (setq type (nx1-type-intersect sym (nx-target-type type) (cddr decl)))))
                           t)))
    (nx1-typed-form :value form env)))





(defun nx1-target-fixnump (form)
  (when (typep form 'integer)
    (let* ((target (backend-target-arch *target-backend*)))
      (and
       (>= form (arch::target-most-negative-fixnum target))
       (<= form (arch::target-most-positive-fixnum target))))))




(defun nx2-constant-form-value (form)
  (setq form (nx-untyped-form form))
  (and (or (nx-null form)
           (nx-t form)
           (and (acode-p form)
                (or (eq (acode-operator form) (%nx1-operator immediate))
                    (eq (acode-operator form) (%nx1-operator fixnum))
                    (eq (acode-operator form) (%nx1-operator simple-function)))))
       form))

(defun nx-natural-constant-p (form)
  (setq form (nx-untyped-form form))
  (if (consp form)
    (let* ((val (if (or (eq (acode-operator form) (%nx1-operator fixnum))
			(eq (acode-operator form) (%nx1-operator immediate)))
		  (car (acode-operands form)))))
      (and (typep val *nx-target-natural-type*) val))))

(defun nx-u32-constant-p (form)
  (setq form (nx-untyped-form form))
  (if (consp form)
    (let* ((val (if (or (eq (acode-operator form) (%nx1-operator fixnum))
			(eq (acode-operator form) (%nx1-operator immediate)))
		  (car (acode-operands form)))))
      (and (typep val '(unsigned-byte 32)) val))))

(defun nx-u31-constant-p (form)
  (setq form (nx-untyped-form form))
  (if (consp form)
    (let* ((val (if (or (eq (acode-operator form) (%nx1-operator fixnum))
			(eq (acode-operator form) (%nx1-operator immediate)))
		  (car (acode-operands form)))))
      (and (typep val '(unsigned-byte 31)) val))))


;;; Reference-count vcell, fcell refs.
(defun nx1-note-vcell-ref (sym)
  (let* ((there (assq sym *nx1-vcells*))
         (count (expt 4 *nx-loop-nesting-level*)))
    (if there
      (%rplacd there (%i+ (%cdr there) count))
      (push (cons sym count) *nx1-vcells*)))
  sym)

(defun nx1-note-fcell-ref (sym)
  (let* ((there (assq sym *nx1-fcells*))
         (count (expt 4 *nx-loop-nesting-level*)))
    (if there
      (%rplacd there (%i+ (%cdr there) count))
      (push (cons sym count) *nx1-fcells*))
    sym))



(defun nx1-check-special-ref (form auxinfo)
  (or (eq auxinfo :special) 
      (nx-proclaimed-special-p form)
      (let ((defenv (definition-environment *nx-lexical-environment*)))
        (unless (and defenv (eq (car (defenv.type defenv)) :execute) (boundp form))
          (nx1-whine :special form))
        nil)))



(defun nx1-whine (about &rest forms)
  ;; Don't turn STYLE-WARNINGs generated during compilation into
  ;; vanilla COMPILER-WARNINGs.
  (let* ((c (if (and (eq about :program-error)
                     (typep (car forms) 'style-warning))
              (let* ((c (car forms)))
                (with-slots (source-note function-name) c
                  (setq source-note *nx-current-note*
                        function-name (list *nx-cur-func-name*))
                  c))
              (make-condition (or (cdr (assq about *compiler-whining-conditions*))
                                  'compiler-warning)
                              :function-name (list *nx-cur-func-name*)
                              :source-note *nx-current-note*
                              :warning-type about
                              :args (or forms (list nil))))))

    (push c *nx-warnings*)))

(defun p2-whine (afunc about &rest forms)
  (let* ((warning (make-condition (or (cdr (assq about *compiler-whining-conditions*)) 'compiler-warning)
                                  :function-name (list (afunc-name afunc))
                                  :warning-type about
                                  :args (or forms (list nil)))))
    (push warning (afunc-warnings afunc))
    (do* ((p (afunc-parent afunc) (afunc-parent p)))
         ((null p) warning)
      (let* ((pname (afunc-name p)))
        (push pname (compiler-warning-function-name warning))
        (push warning (afunc-warnings p))))))

(defun nx1-type-intersect (form type1 type2 &optional (env *nx-lexical-environment*))
  (let* ((ctype1 (if (typep type1 'ctype) type1 (values-specifier-type type1 env)))
         (ctype2 (if (typep type2 'ctype) type2 (values-specifier-type type2 env)))
         (intersection (if (or (values-ctype-p ctype1) (values-ctype-p ctype2))
                         (values-type-intersection ctype1 ctype2)
                         (type-intersection ctype1 ctype2))))
    (when (eq intersection *empty-type*)
      (let ((type1 (if (typep type1 'ctype)
                     (type-specifier type1)
                     type1))
            (type2 (if (typep type2 'ctype)
                     (type-specifier type2)
                     type2)))
        (nx1-whine :type-conflict form type1 type2)))
    (type-specifier intersection)))

(defun nx-declared-notinline-p (sym env)
  (setq sym (maybe-setf-function-name sym))
  (loop
    (when (listp env)
      (return (and (symbolp sym)
                   (proclaimed-notinline-p sym))))
    (dolist (decl (lexenv.fdecls env))
      (when (and (eq (car decl) sym)
                 (eq (cadr decl) 'inline))
         (return-from nx-declared-notinline-p (eq (cddr decl) 'notinline))))
    (when (assq sym (lexenv.functions env))
      (return nil))
    (setq env (lexenv.parent-env env))))



;;; If "sym" is an expression (not a symbol which names a function),
;;; the caller has already alphatized it.
(defun nx1-call (context sym args &optional spread-p global-only inhibit-inline)
  (nx1-verify-length args 0 nil)
  (when (and (acode-p sym) (eq (acode-operator sym) (%nx1-operator immediate)))
    (multiple-value-bind (valid name) (valid-function-name-p (car (acode-operands sym)))
      (when valid
	(setq global-only t sym name))))
  (let ((args-in-regs (if spread-p 1 (backend-num-arg-regs *target-backend*))))
    (if (nx-self-call-p sym global-only)
      ;; Should check for downward functions here as well.
      (multiple-value-bind (deftype reason)
                           (nx1-check-call-args *nx-current-function* args spread-p)
        (when deftype
          (nx1-whine deftype sym reason args spread-p))
        (if (eq context :return)
          ;; Could check policy, note things that interfere with
          ;; tail call, and try to better estimate whether or not
          ;; this will be a real tail call.
          (setf (afunc-bits *nx-current-function*)
                (logior (ash 1 $fbittailcallsself) (afunc-bits *nx-current-function*)))
          (nx-note-bound-vars-live-across-call))
        (make-acode (%nx1-operator self-call) (nx1-arglist args args-in-regs) spread-p))
      (multiple-value-bind (lambda-form containing-env token) (nx-inline-expansion sym *nx-lexical-environment* global-only)
        (or (and (not inhibit-inline)
		 (nx1-expand-inline-call context lambda-form containing-env token args spread-p *nx-lexical-environment*))
            (multiple-value-bind (info afunc) (if (and  (symbolp sym) (not global-only)) (nx-lexical-finfo sym))
              (when (eq 'macro (car info))
                (nx-error "Can't call macro function ~s" sym))
	      (nx-record-xref-info :direct-calls sym)
              (if (and afunc (%ilogbitp $fbitruntimedef (afunc-bits afunc)))
                (let ((sym (var-name (afunc-lfun afunc))))
                  (nx1-form
                   context
                   (if spread-p
                     `(,(if (eql spread-p 0) 'applyv 'apply) ,sym ,args)
                     `(funcall ,sym ,@args))))
                (let* ((val (nx1-call-form context sym afunc args spread-p)))
                    (when afunc
                      (let ((callers (afunc-callers afunc))
                            (self *nx-current-function*))
                        (unless (or (eq self afunc) (memq self callers))
                          (setf (afunc-callers afunc) (cons self callers)))))
                    (if (and (null afunc) (memq sym *nx-never-tail-call*))
                      (make-acode (%nx1-operator values) (list val))
                      val)))))))))


(defun nx1-treat-as-call (context args)
  (nx1-typed-call context (car args) (%cdr args)))

(defun nx1-typed-call (context fn args &optional spread-p)
  (let ((global-only nil)
	(errors-p nil)
	(result-type t))
    (when (and (acode-p fn) (eq (acode-operator fn) (%nx1-operator immediate)))
      (multiple-value-bind (valid name) (valid-function-name-p (car (acode-operands fn)))
	(when valid
	  (setq fn name global-only t))))
    (when (non-nil-symbol-p fn)
      (multiple-value-setq (errors-p args result-type)
	(nx1-check-typed-call fn args spread-p global-only)))
    (setq result-type (nx1-type-intersect fn *nx-form-type* result-type))
    (let ((form (nx1-call context fn args spread-p global-only errors-p)))
      (if (eq result-type t)
	form
	(make-acode (%nx1-operator typed-form) result-type form)))))

(defvar *format-arg-functions* '((format . 1) (format-to-string . 1) (error . 0) (warn . 0)
				 (y-or-n-p . 0) (yes-or-no-p . 0)
				 (signal-simple-program-error . 0)
				 (signal-simple-condition . 1)
				 (signal-reader-error . 1)
				 (%method-combination-error . 0)
				 (%invalid-method-error . 1)
				 (nx-compile-time-error . 0)
				 (nx-error . 0)
				 (compiler-bug . 0)))

(defun nx1-find-call-def (sym &optional (env *nx-lexical-environment*) (global-only nil))
  (and (or (and (not global-only) (nth-value 1 (nx-lexical-finfo sym)))
	   (retrieve-environment-function-info sym env)
	   (let ((def (fboundp sym)))
	     (and (functionp def) def)))))

(defun nx1-check-typed-call (sym args &optional spread-p global-only)
  (let ((env *nx-lexical-environment*)
	(result-type t)
	(typed-args args)
	(errors-p nil)
	(ftype nil)
	(def nil))
    (setq ftype (find-ftype-decl sym env args spread-p))
    (setq def (nx1-find-call-def sym env global-only))
    (when ftype
      (multiple-value-setq (typed-args result-type errors-p)
	(nx1-analyze-ftyped-call ftype sym args spread-p env)))
    (when (and def (not errors-p))
      (multiple-value-bind (deftype reason) (nx1-check-call-args def args spread-p)
	(when deftype
	  (nx1-whine deftype sym reason args spread-p)
	  (setq errors-p t))))
    (unless (or def ftype (eq sym *nx-global-function-name*))
      (nx1-whine :undefined-function sym args spread-p)
      (setq errors-p t))
    (unless errors-p
      (let* ((format-args (and (not spread-p)
			       (not (typep def 'afunc))
			       (let* ((n (cdr (assq sym *format-arg-functions*))))
				 (and n (nthcdr n typed-args)))))
	     (control (pop format-args)))
	(when (and (consp control)
		   (eq (%car control) 'the)
		   (consp (%cdr control))
		   (consp (%cddr control)))
	  (setq control (%caddr control)))
	(when (stringp (setq control (nx-transform control env)))
	  (when (nx1-check-format-call control format-args env)
	    (setq errors-p t)))))

    (values errors-p typed-args result-type)))

(defun known-ftype-for-call (sym args spread-p env)
  ;; Find ftype based on actual arguments.
  ;; This should be more general, but for now just pick off some special cases..
  (when (and args (or (not spread-p) (cdr args)))
    (cond ((or (eq sym 'aref) (eq sym 'uvref))
           (let* ((atype (nx-form-type (car args) env))
                  (a-ctype (specifier-type atype)))
             (when (array-ctype-p a-ctype)
               ;; No point declaring the type of an arg whose type we already know
               `(function (t &rest integer) ,(type-specifier (array-ctype-specialized-element-type
                                                                  a-ctype))))))
          ((eq sym 'error)
           (let ((condition (car args)))
             (cond ((nx-form-typep condition 'condition env)
                    '(function (t) *))
                   ((nx-form-typep condition 'symbol env)
                    ;; TODO: might be able to figure out actual initargs...
                    `(function (t &key &allow-other-keys) *))
                   (t nil))))
          ((eq sym 'cerror)
           (when (and (cdr args) (or (not spread-p) (cddr args)))
             (let ((condition (cadr args)))
               (cond ((nx-form-typep condition 'condition env)
                      `(function (string t &rest t) *))
                     ((nx-form-typep condition 'symbol env)
                      `(function (string t &key &allow-other-keys) *))
                     (t `(function (string t &rest t) *))))))
          (t nil))))

(defun find-ftype-decl (sym &optional (env *nx-lexical-environment*) (args :unknown) spread-p)
  (setq sym (maybe-setf-function-name sym))
  (loop
    for lexenv = env then (lexenv.parent-env lexenv) until (listp lexenv)
    do (dolist (fdecl (lexenv.fdecls lexenv))
         (when (and (eq (car fdecl) sym)
                    (eq (car (%cdr fdecl)) 'ftype))
           (return-from find-ftype-decl (%cddr fdecl))))
    do (when (and (istruct-typep lexenv 'lexical-environment)
                  (assq sym (lexenv.functions lexenv)))
         (return-from find-ftype-decl nil)))
  (or (proclaimed-ftype sym)
      (and (listp args)
           (known-ftype-for-call sym args spread-p env))))

(defun nx1-analyze-ftyped-call (ftype sym arglist spread-p env)
  (let ((ctype (if (typep ftype 'ctype) ftype (specifier-type ftype)))
	(result-type t)
	(errors-p nil))
    (unless (or (null ctype) (not (function-ctype-p ctype)))
      (unless (function-ctype-wild-args ctype)
	(let ((req (args-ctype-required ctype))
	      (opt (args-ctype-optional ctype))
	      (rest (args-ctype-rest ctype))
	      (keyp (args-ctype-keyp ctype))
	      (aokp (or spread-p (args-ctype-allowp ctype)))
	      (keys (args-ctype-keywords ctype))
	      (typed-arglist nil)
	      (key-type nil)
	      (bad-keys nil)
	      (nargs (if spread-p (1- (length arglist)) (length arglist))))
	  (flet ((collect-type (arg type)
		   (push (if (and type
                                  (neq type *universal-type*)
                                  (neq type *wild-type*)
                                  (setq type (type-specifier type))
                                  ;; Don't record unknown types, just causes spurious warnings.
                                  (specifier-type-if-known type env :values t))
                             `(the ,type ,arg)
                             arg)
                         typed-arglist))
                 (key-name (x) (key-info-name x))
		 (whine (&rest reason)
		   (nx1-whine :ftype-mismatch sym reason arglist spread-p)
		   (setq errors-p t)))
	    (declare (dynamic-extent #'collect-type #'whine))
	    (loop for arg in arglist as i below nargs
		  do (cond
		       (req (collect-type arg (pop req)))
		       (opt (collect-type arg (pop opt)))
		       (rest (collect-type arg rest))
		       (key-type (collect-type arg (shiftf key-type nil)))
		       (keyp (if (nx-form-constant-p arg env)
			       (let* ((key (nx-form-constant-value arg env))
				      (ki (find key keys :key #'key-name)))
				 (when (eq key :allow-other-keys) (setq aokp t))
				 (if ki
				   (setq key-type (key-info-type ki))
				   (unless aokp (push key bad-keys))))
			       (setq aokp t))
			     (collect-type arg nil)
			     (unless key-type (setq key-type *universal-type*)))
		       (t (return (whine :toomany
					 nargs
					 (+ (length (args-ctype-required ctype))
					    (length (args-ctype-optional ctype)))))))
		  finally (cond (spread-p (collect-type arg nil))
				(req (whine :toofew
					    nargs
					    (length (args-ctype-required ctype))))
				(key-type (whine :odd-keywords 
						 (nthcdr
						  (+ (length (args-ctype-required ctype))
						     (length (args-ctype-optional ctype)))
						  arglist)))
				(bad-keys (whine :unknown-keyword
						 (if (cdr bad-keys)
						   (nreverse bad-keys)
						   (car bad-keys))
						 (map 'list #'key-name keys)))))
	    (unless errors-p
	      (setq arglist (nreverse typed-arglist))))))
      (setq result-type (type-specifier (single-value-type (function-ctype-returns ctype)))))
    (values arglist (nx-target-type result-type) errors-p)))



(defun innermost-lfun-bits-keyvect (def)
  (let* ((inner-def (closure-function (find-unencapsulated-definition def)))
         (bits (lfun-bits inner-def))
         (keys (lfun-keyvect inner-def)))
    (declare (fixnum bits))
    #+no
    (when (and (eq (ash 1 $lfbits-gfn-bit)
                   (logand bits (logior (ash 1 $lfbits-gfn-bit)
                                        (ash 1 $lfbits-method-bit))))
               (logbitp $lfbits-keys-bit bits))
      (setq bits (logior (ash 1 $lfbits-aok-bit) bits)
            keys nil))
    (values bits keys)))

(defun def-info-bits-keyvect (info)
  (let ((bits (def-info.lfbits info)))
    (when (and (eq (def-info.function-type info) 'defgeneric)
               (logbitp $lfbits-keys-bit bits)
               (not (logbitp $lfbits-aok-bit bits))
	       #-BOOTSTRAPPED (fboundp 'def-info-method.keyvect)
               (loop for m in (def-info.methods info)
                     thereis (null (def-info-method.keyvect m))))
      ;; Some method has &aok, don't bother checking keywords.
      (setq bits (logior bits (ash 1 $lfbits-aok-bit))))
    (values bits (def-info.keyvect info))))


(defun nx1-check-call-args (def arglist spread-p)
  (multiple-value-bind (bits keyvect)
      (etypecase def
        (function (innermost-lfun-bits-keyvect def))
        (afunc (let ((lambda-form (afunc-lambdaform def)))
                 (and (lambda-expression-p lambda-form)
                      (encode-lambda-list (cadr lambda-form) t))))
        (cons (def-info-bits-keyvect (cdr def))))
    (when bits
      (multiple-value-bind (reason defer-p)
          (or (nx1-check-call-bits bits arglist spread-p) ;; never deferred
              (nx1-check-call-keywords def bits keyvect arglist spread-p))
        (when reason
          #-BOOTSTRAPPED (unless (find-class 'undefined-keyword-reference nil)
                           (return-from nx1-check-call-args nil))
          (values (if defer-p
                    :deferred-mismatch
                    (typecase def
                      (function :global-mismatch)
                      (afunc :lexical-mismatch)
                      (t :environment-mismatch)))
                  reason))))))

(defun nx1-check-call-bits (bits arglist spread-p)
  (let* ((nargs (length arglist))
         (minargs (if spread-p (1- nargs) nargs))
         (required (ldb $lfbits-numreq bits))
         (max (if (logtest (logior (ash 1 $lfbits-rest-bit) (ash 1 $lfbits-restv-bit) (ash 1 $lfbits-keys-bit)) bits)
                nil
                (+ required (ldb $lfbits-numopt bits)))))
    ;; If the (apparent) number of args in the call doesn't
    ;; match the definition, complain.  If "spread-p" is true,
    ;; we can only be sure of the case when more than the
    ;; required number of args have been supplied.
    (or (and (not spread-p)
             (< minargs required)
             `(:toofew ,minargs ,required))
        (and max
             (> minargs max)
             `(:toomany ,nargs ,max)))))

(defun nx1-check-call-keywords (def bits keyvect args spread-p &aux (env *nx-lexical-environment*))
  ;; Ok, if generic function, bits and keyvect are for the generic function itself.
  ;; Still, since all congruent, can check whether have variable numargs
  (unless (and (logbitp $lfbits-keys-bit bits)
               (not spread-p)) ; last argform may contain :allow-other-keys
    (return-from nx1-check-call-keywords nil))
  (let* ((bad-keys nil)
         (key-args (nthcdr (+ (ldb $lfbits-numreq bits) (ldb $lfbits-numopt bits)) args))
         (generic-p (or (generic-function-p def)
                        (and (consp def)
                             (eq (def-info.function-type (cdr def)) 'defgeneric)))))
    (when (oddp (length key-args))
      (return-from nx1-check-call-keywords (list :odd-keywords key-args)))
    (when (logbitp $lfbits-aok-bit bits)
      (return-from nx1-check-call-keywords nil))
    (loop for key-form in key-args by #'cddr
          do (unless (nx-form-constant-p key-form env) ;; could be :aok
               (return-from nx1-check-call-keywords nil))
          do (let ((key (nx-form-constant-value key-form env)))
               (when (eq key :allow-other-keys)
                 (return-from nx1-check-call-keywords nil))
               (unless (or (find key keyvect)
                          (and generic-p (nx1-valid-gf-keyword-p def key)))
                 (push key bad-keys))))
    (when bad-keys
      (if generic-p
        (values (list :unknown-gf-keywords bad-keys) t)
        (list :unknown-keyword (if (cdr bad-keys) (nreverse bad-keys) (%car bad-keys)) keyvect)))))

(defun nx1-valid-gf-keyword-p (def key)
  ;; Can assume has $lfbits-keys-bit and not $lfbits-aok-bit
  (if (consp def)
    (let ((definfo (cdr def)))
      (assert (eq (def-info.function-type definfo) 'defgeneric))
      (loop for m in (def-info.methods definfo)
            as keyvect = (def-info-method.keyvect m)
            thereis (or (null keyvect) (find key keyvect))))
    (let ((gf (find-unencapsulated-definition def)))
      (or (find key (%defgeneric-keys gf))
          (loop for m in (%gf-methods gf)
                thereis (let* ((func (%inner-method-function m))
                               (mbits (lfun-bits func)))
                          (or (and (logbitp $lfbits-aok-bit mbits)
                                   ;; If no &rest, then either don't use the keyword in which case
                                   ;; it's good to warn; or it's used via next-method, we'll approve
                                   ;; it when we get to that method.
                                   (logbitp $lfbits-rest-bit mbits))
                              (find key (lfun-keyvect func)))))))))

;;; we can save some space by going through subprims to call "builtin"
;;; functions for us.
(defun nx1-builtin-function-offset (name)
   (arch::builtin-function-name-offset name))

(defun nx1-call-form (context global-name afunc arglist spread-p  &optional (env *nx-lexical-environment*))
  (unless (eq context :return)
    (nx-note-bound-vars-live-across-call))
  (if afunc
    (make-acode (%nx1-operator lexical-function-call) afunc (nx1-arglist arglist (if spread-p 1 (backend-num-arg-regs *target-backend*))) spread-p)
    (let* ((builtin (unless (or spread-p
                                (eql 3 (safety-optimize-quantity env)))
                      (nx1-builtin-function-offset global-name))))
      (if (and builtin
               (let* ((bits (lfun-bits (fboundp global-name))))
                 (and bits (eql (logand $lfbits-args-mask bits)
                                (dpb (length arglist)
                                     $lfbits-numreq
                                     0)))))
        (make-acode (%nx1-operator builtin-call) 
                    (make-acode (%nx1-operator fixnum) builtin)
                    (nx1-arglist arglist))
        (make-acode (%nx1-operator call)
                     (if (symbolp global-name)
                       (nx1-immediate context (if context (nx1-note-fcell-ref global-name) global-name))
                       global-name)
                     (nx1-arglist arglist (if spread-p 1 (backend-num-arg-regs *target-backend*)))
                     spread-p)))))
  


(defun nx1-expand-inline-call (context lambda-form env token args spread-p old-env)
  (if (and (or (null spread-p) (eq (length args) 1)))
    (if (and token (not (memq token *nx-inline-expansions*)))
      (with-program-error-handler (lambda (c) (declare (ignore c)) nil)
	(let* ((*nx-inline-expansions* (cons token *nx-inline-expansions*))
	       (lambda-list (cadr lambda-form))
	       (body (cddr lambda-form))
	       (new-env (new-lexical-environment env)))
	  (setf (lexenv.mdecls new-env)
                `((speed . ,(speed-optimize-quantity old-env))
		  (space . ,(space-optimize-quantity old-env))
		  (safety . ,(space-optimize-quantity old-env))
		  (compilation-speed . ,(compilation-speed-optimize-quantity old-env))
		  (debug . ,(debug-optimize-quantity old-env))))
	  (if spread-p
	    (nx1-destructure context lambda-list (car args) nil nil body new-env)
	    (nx1-lambda-bind context lambda-list args body new-env)))))))
             
; note that regforms are reversed: arg_z is always in the car
(defun nx1-arglist (args &optional (nregargs (backend-num-arg-regs *target-backend*)))
  (declare (fixnum nregargs))
  (let* ((stkforms nil)
         (regforms nil)
         (nstkargs (%i- (length args) nregargs)))
    (declare (fixnum nstkargs))
      (list
       (dotimes (i nstkargs (nreverse stkforms))
         (declare (fixnum i))
         (push (nx1-form :value (%car args)) stkforms)
         (setq args (%cdr args)))
       (dolist (arg args regforms)
         (push (nx1-form :value arg) regforms)))))

(defun nx1-formlist (context args)
  (let* ((a nil))
    (dolist (arg args)
      (push (nx1-form (if context :value) arg) a))
    (nreverse a)))

(defun nx1-verify-length (forms min max &aux (len (list-length forms)))
 (if (or (null len)
         (%i> min len)
         (and max (%i> len max)))
     (nx-error "Wrong number of args in form ~S." (cons *nx-sfname* forms))
     len))

(defun nx-unquote (form)
  (if (nx-quoted-form-p form)
    (%cadr form)
    form))

(defun nx-quoted-form-p (form &aux (f form))
 (and (consp form)
      (eq (pop form) 'quote)
      (or
       (and (consp form)
            (not (%cdr form)))
       (nx-error "Illegally quoted form ~S." f))))

(defun nx-form-constant-p (form env)
  (declare (ignore env))
  (or (quoted-form-p form)
      (self-evaluating-p form)))

(defun nx-form-constant-value (form env)
  (declare (ignore env))
  (declare (type (satisfies nx-form-constant-p) form))
  (if (consp form) (%cadr form) form))

; Returns two values: expansion & win
; win is true if expansion is not EQ to form.
; This is a bootstrapping version.
; The real one is in "ccl:compiler;optimizers.lisp".
(unless (fboundp 'maybe-optimize-slot-accessor-form)

(defun maybe-optimize-slot-accessor-form (form environment)
  (declare (ignore environment))
  (values form nil))

)

(defun nx-source-note (form &aux (source-notes *nx-source-note-map*))
  (when source-notes
    (when (or (consp form) (vectorp form) (pathnamep form))
      (let ((note (gethash form source-notes)))
        (unless (listp note) note)))))


(defun nx-transform (form &optional (environment *nx-lexical-environment*) (source-note-map *nx-source-note-map*))
  (macrolet ((form-changed (form)
               `(progn
                  (unless source (setq source (gethash ,form source-note-map)))
                  (setq changed t))))
    (prog (sym transforms lexdefs changed enabled macro-function compiler-macro (source t))
       (when source-note-map
         (setq source (gethash form source-note-map)))
       (go START)
     LOOP
       (form-changed form)
       (when (and (consp form) 
                  (or (eq (%car form) 'the)
                      (and sym (eq (%car form) sym))))
         (go DONE))
     START
       (when (non-nil-symbol-p form)
         (multiple-value-bind (newform win) (nx-transform-symbol form environment)
           (unless win (go DONE))
           (setq form newform)
           (go LOOP)))
       (when (atom form) (go DONE))
       (unless (symbolp (setq sym (%car form)))
         (go DONE))
       #+no
       (when (eq sym 'the)
         (destructuring-bind (typespec thing) (cdr form)
           (if (constantp thing)
             (progn
               (setq form thing)
               (go LOOP))
             (multiple-value-bind (newform win) (nx-transform thing environment source-note-map)
               (when win
                 (form-changed newform)
                 (if (and (self-evaluating-p newform)
                          (typep newform typespec))
                   (setq form newform)
                   (setq form `(the ,typespec ,newform)))
                 (go DONE))))))
       (when (nx-quoted-form-p form)
         (when (self-evaluating-p (%cadr form))
           (setq form (%cadr form)))
         (go DONE))
       (when (setq lexdefs (nx-lexical-finfo sym environment))
         (if (eq 'function (%car lexdefs))
           (go DONE)))
       (setq transforms (setq compiler-macro (compiler-macro-function sym environment))
             macro-function (macro-function sym environment)
             enabled (nx-allow-transforms environment))
       (unless macro-function
         (let* ((win nil))
           (when (and enabled (functionp (fboundp sym)))
             (multiple-value-setq (form win) (nx-transform-arglist form environment source-note-map))
             (when win
               (form-changed form)))))
       (when (and enabled
                  (not (nx-declared-notinline-p sym environment)))
         (multiple-value-bind (value folded) (nx-constant-fold form environment)
           (when folded
             (setq form value)
             (form-changed form)
             (unless (and (consp form) (eq (car form) sym)) (go START))))
         (when compiler-macro
           (multiple-value-bind (newform win) (compiler-macroexpand-1 form environment)
             (when win
               (when (and (consp newform) (eq (car newform) sym) (functionp (fboundp sym)))
                 (setq sym nil))
               (setq form newform)
               (go LOOP))))
         (multiple-value-bind (newform win) (maybe-optimize-slot-accessor-form form environment)
           (when win
             (setq sym nil)
             (setq form newform)
             (go START)))
         (unless macro-function
           (when (and (eql (length (%cdr form)) 1)
                      (setq transforms (structref-info sym environment)))
             (setq form (defstruct-ref-transform transforms (%cdr form) environment))
             (form-changed form)
             (go START))
           (when (setq transforms (assq sym *nx-synonyms*))
             (setq form (cons (%cdr transforms) (setq sym (%cdr form))))
             (go LOOP))))
       (when (and macro-function
                  (or lexdefs
                      (not (and (gethash sym *nx1-alphatizers*) (not (nx-declared-notinline-p sym environment))))))
         (nx-record-xref-info :macro-calls (function-name macro-function))
         (setq form (macroexpand-1 form environment))
         (form-changed form)
         (go START))
     DONE
       (if (eq source t)
	 (setq source nil)
	 (let ((this (nx-source-note form)))
	   (if this
	     (setq source this)
	     (when source
	       (unless (and (consp form)
			    (eq (%car form) 'the)
			    (eq source (gethash (caddr form) source-note-map)))
		 (when (or (consp form) (vectorp form) (pathnamep form))
		   (unless (or (eq form (%unbound-marker))
			       (eq form (%slot-unbound-marker)))
		     (setf (gethash form source-note-map) source))))))))
       ;; Return source for symbols, even though don't record it in hash table.
       (return (values form changed source)))))


; Transform all of the arguments to the function call form.
; If any of them won, return a new call form (with the same operator as the original), else return the original
; call form unchanged.
(defun nx-transform-arglist (callform env source-note-map)
  (let* ((any-wins nil)
         (transformed-call (cons (car callform) nil))
         (ptr transformed-call)
         (win nil))
    (declare (type cons ptr))
    (dolist (form (cdr callform) (if any-wins (values (copy-list transformed-call) t) (values callform nil)))
      (multiple-value-setq (form win) (nx-transform form env source-note-map))
      (rplacd ptr (setq ptr (cons form nil)))
      (if win (setq any-wins t)))))

;This is needed by (at least) SETF.
(defun nxenv-local-function-p (name macro-env)
  (multiple-value-bind (type local-p) (function-information name macro-env)
    (and local-p (eq :function type))))

           
;;; This guy has to return multiple values.  The arguments have
;;; already been transformed; if they're all constant (or quoted), try
;;; to evaluate the expression at compile-time.
(defun nx-constant-fold (original-call &optional (environment *nx-lexical-environment*) &aux 
                                       (fn (car original-call)) form mv foldable foldfn)
  (flet ((quotify (x) (if (self-evaluating-p x) x (list 'quote x))))
    (if (and (nx-allow-transforms environment)
             (let* ((bits (if (symbolp fn) (%symbol-bits fn) 0)))
               (declare (fixnum bits))
               (if (setq foldable (logbitp $sym_fbit_constant_fold bits))
                 (if (logbitp $sym_fbit_fold_subforms bits)
                   (setq foldfn 'fold-constant-subforms))
                 (setq foldable (assq fn *nx-can-constant-fold*)
                       foldfn (cdr foldable)))
               foldable))
      (if foldfn
        (funcall foldfn original-call environment)
        (progn
          (let ((args nil))
            (dolist (arg (cdr original-call) (setq args (nreverse args)))
              (if (quoted-form-p arg)
                (setq arg (%cadr arg))
                (unless (self-evaluating-p arg) (return-from nx-constant-fold (values original-call nil))))
              (push arg args))
            (if (nx1-check-call-args (fboundp fn) args nil)
              (return-from nx-constant-fold (values original-call nil))
              (setq form (multiple-value-list 
                             (handler-case (apply fn args)
                               (error (condition)
                                      (warn "Error: \"~A\" ~&signalled during compile-time evaluation of ~S ."
                                            condition original-call)
                                      (return-from nx-constant-fold
                                        (values `(locally (declare (notinline ,fn))
                                                  ,original-call)
                                                t))))))))
          (if form
            (if (null (%cdr form))
              (setq form (%car form))
              (setq mv (setq form (cons 'values (mapcar #'quotify form))))))
          (values (if mv form (quotify form)) T)))
      (values original-call nil))))

(defun nx-transform-symbol (sym &optional (env *nx-lexical-environment*))
; Gak.  Can't call NX-LEX-INFO without establishing *nx-lexical-environment*.
; NX-LEX-INFO should take env arg!.
  (let* ((*nx-lexical-environment* env))
    (multiple-value-bind (expansion win) (macroexpand-1 sym env)
      (if win
        (let ((type (nx-declared-type sym))
              (var (nth-value 2 (nx-lex-info sym))))
          (unless (eq t type) (setq expansion `(the ,type ,expansion)))
          (if var (nx-set-var-bits var (%ilogior (%ilsl $vbitreffed 1) (nx-var-bits var)))))
        (progn
          (multiple-value-setq (expansion win)
            (nx-transform-defined-constant sym env))
          (if win (setq win (neq sym expansion)))))
      (values expansion win))))

; if sym has a substitutable constant value in env (or globally), return
; (values <value> t), else (values nil nil)
(defun nx-transform-defined-constant (sym env)
  (let* ((defenv (definition-environment env))
         (val (if defenv (assq sym (defenv.constants defenv))))
         (constant-value-p val))
    (if val
      (setq val (%cdr val))
      (if (constant-symbol-p sym)
        (setq constant-value-p t val (%sym-global-value sym))))
    (if (and (neq val (%unbound-marker-8))
             constant-value-p 
             (nx-substititute-constant-value sym val env))
      (values (if (self-evaluating-p val) val (list 'quote val)) t)
      (values nil nil))))


(defun nx-root-var (var)
  (do* ((var var bits)
        (bits (var-bits var) (var-bits var)))
       ((typep bits 'fixnum) var)))

(defun nx-var-bits (var)
  (do* ((var var bits)
        (bits (var-bits var) (var-bits var)))
       ((fixnump bits) bits)))

(defun nx-set-var-bits (var newbits)
  (do* ((var var bits)
        (bits (var-bits var) (var-bits var)))
       ((fixnump bits) (setf (var-bits var) newbits))))

(defun nx-var-root-nrefs (var)
  (do* ((var var bits)
        (bits (var-bits var) (var-bits var)))
       ((fixnump bits) (var-root-nrefs var))))


(defun nx-set-var-root-nrefs (var new)
  (do* ((var var bits)
        (bits (var-bits var) (var-bits var)))
       ((fixnump bits) (setf (var-root-nrefs var) new))))

(defun nx-var-root-nsetqs (var)
  (do* ((var var bits)
        (bits (var-bits var) (var-bits var)))
       ((fixnump bits) (var-root-nsetqs var))))

(defun nx-set-var-root-nsetqs (var new)
  (do* ((var var bits)
        (bits (var-bits var) (var-bits var)))
       ((fixnump bits) (setf (var-root-nsetqs var) new))))

(defun nx-make-lexical-reference (var)
  (let* ((ref (make-acode (%nx1-operator lexical-reference) var)))
    (push ref (var-ref-forms var))
    ref))

(defun nx-adjust-ref-count (var)
  (let* ((bits (nx-var-bits var))
         (temp-p (%ilogbitp $vbittemporary bits))
         (by (if temp-p 1 (expt  4 *nx-loop-nesting-level*)))
         (new (+ (var-refs var) by)))
    (setf (var-refs var) new)
    (nx-set-var-root-nrefs var (+ (nx-var-root-nrefs var) 1))
    new))

;;; Treat (VALUES x . y) as X if it appears in a THE form
(defun nx-form-type (form &optional (env *nx-lexical-environment*))
  (if (nx-form-constant-p form env)
    ;(type-of (nx-form-constant-value form env))
    `(member ,(nx-form-constant-value form env))
    (if (and (consp form)	   ; Kinda bogus now, but require-type
	     (eq (%car form) 'require-type) ; should be special some day
	     (nx-form-constant-p (caddr form) env))
      (nx-form-constant-value (%caddr form) env)
      (if (nx-trust-declarations env)
	(if (symbolp form)
	  (nx-target-type (nx-declared-type form env))
	  (if (consp form)
	    (if (eq (%car form) 'the)
	      (destructuring-bind (typespec val) (%cdr form)
		(declare (ignore val))
		(nx-target-type (type-specifier (single-value-type (values-specifier-type typespec)))))
	      (if (eq (%car form) 'setq)
		(let* ((args (%cdr form))
		       (n (length args)))
		  (if (and (evenp n)
			   (> n 0)
			   (setq args (nthcdr (- n 2) args))
			   (non-nil-symbol-p (car args)))
		    (nx1-type-intersect (%car args)
					(nx-declared-type (%car args) env)
					(nx-form-type (%cadr args) env)
					env)
		    t))
		  (or (nx-declared-result-type (%car form) env (%cdr form))
		      t)))
	    t))
	t))))


(defparameter *numeric-ops* '(+ -  / * +-2 --2 *-2 /-2))

(defparameter *logical-ops* '(logxor-2 logior-2 logand-2  lognot logxor))

(defun numeric-type-p (type &optional not-complex)
  (or (memq type '(fixnum integer double-float single-float float))
      (let ((ctype (specifier-type type)))
        (and (numeric-ctype-p ctype)
             (or (not not-complex)
                 (neq (numeric-ctype-complexp ctype) :complex))))))



(defun nx-form-typep (arg type &optional (env *nx-lexical-environment*))
  (setq type (nx-target-type (type-expand type)))
  (if (nx-form-constant-p arg env)
    (typep (nx-form-constant-value arg env) type env)
    (subtypep (nx-form-type arg env) type env)))

(defun nx-binary-fixnum-op-p (form1 form2 env &optional ignore-result-type)
  (setq form1 (nx-transform form1 env)
        form2 (nx-transform form2 env))
  (and
   (nx-form-typep form1 *nx-target-fixnum-type* env)
   (nx-form-typep form2 *nx-target-fixnum-type* env)
   (or ignore-result-type
        (and (nx-trust-declarations env)
             (subtypep *nx-form-type* *nx-target-fixnum-type*)))))


(defun nx-binary-natural-op-p (form1 form2 env &optional (ignore-result-type t))
  (and
   (nx-form-typep form1 *nx-target-natural-type* env)
   (nx-form-typep form2 *nx-target-natural-type* env)
   (or ignore-result-type
       (and (nx-trust-declarations env)
            (subtypep *nx-form-type* *nx-target-natural-type*)))))




(defun nx-global-p (sym &optional (env *nx-lexical-environment*))
  (or 
   (logbitp $sym_vbit_global (the fixnum (%symbol-bits sym)))
   (let* ((defenv (definition-environment env)))
     (if defenv 
       (eq :global (%cdr (assq sym (defenv.specials defenv))))))))
  
(defun nx-need-var (sym &optional (check-bindable t))
  (if (and (nx-need-sym sym)
           (not (constantp sym))
           (let* ((defenv (definition-environment *nx-lexical-environment*)))
             (or (null defenv)
                 (not (assq sym (defenv.constants defenv)))))) ; check compile-time-constants, too
    (if (and check-bindable (nx-global-p sym))
      (nx-error "~S is declared static and can not be bound" sym)
      sym)
    (nx-error "Can't bind or assign to constant ~S." sym)))

(defun nx-need-sym (sym)
  (if (symbolp sym)
    sym
    (nx-error "~S is not a symbol." sym)))

(defun nx-need-function-name (name)
  (multiple-value-bind (valid nm) (valid-function-name-p name)
    (if valid nm (nx-error "Invalid function name ~S" name))))

(defun nx-pair-name (form)
  (nx-need-sym (if (consp form) (%car form) form)))

(defun nx-pair-initform (form)
  (if (atom form)
    nil
    (if (and (listp (%cdr form)) (null (%cddr form)))
      (%cadr form)
      (nx-error "Bad initialization form: ~S." form))))

; some callers might assume that this guy errors out if it can't conjure up
; a fixnum.  I certainly did ...
(defun nx-get-fixnum (form &aux (trans (nx-transform form *nx-lexical-environment*)))
 (if (fixnump trans)
  trans
  form))
 
(defun nx1-func-name (gizmo)
  (and (consp gizmo)
       (eq (%car gizmo) 'function)
       (consp (%cdr gizmo))
       (null (%cddr gizmo))
       (if (lambda-expression-p (%cadr gizmo))
	 (%cadr gizmo)
	 (nth-value 1 (valid-function-name-p (%cadr gizmo))))))

; distinguish between program errors & incidental ones.
(defun nx-error (format-string &rest args)
  (error (make-condition 'compile-time-program-error 
                :context (nx-error-context)
                :format-control format-string
                :format-arguments args)))

(defun nx-compile-time-error (format-string &rest args)
  (error (make-condition 'compile-time-program-error 
                :context (nx-error-context)
                :format-control format-string
                :format-arguments args)))

; Should return information about file being compiled, nested functions, etc. ...
(defun nx-error-context ()
  (or *nx-cur-func-name* "an anonymous function"))

(defparameter *warn-if-function-result-ignored*
  '(sort stable-sort delete delete-if delete-if-not remf nreverse
    nunion nset-intersection)
  "Names of functions whose result(s) should ordinarily be used, because of their side-effects or lack of them.")
