Faster iteration through a variable's constraints during constraint propagation
[sbcl.git] / src / compiler / constraint.lisp
1 ;;;; This file implements the constraint propagation phase of the
2 ;;;; compiler, which uses global flow analysis to obtain dynamic type
3 ;;;; information.
4
5 ;;;; This software is part of the SBCL system. See the README file for
6 ;;;; more information.
7 ;;;;
8 ;;;; This software is derived from the CMU CL system, which was
9 ;;;; written at Carnegie Mellon University and released into the
10 ;;;; public domain. The software is in the public domain and is
11 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
12 ;;;; files for more information.
13
14 ;;; TODO:
15 ;;;
16 ;;; -- documentation
17 ;;;
18 ;;; -- MV-BIND, :ASSIGNMENT
19 ;;;
20 ;;; Note: The functions in this file that accept constraint sets are
21 ;;; actually receiving the constraint sets associated with nodes,
22 ;;; blocks, and lambda-vars.  It might be make CP easier to understand
23 ;;; and work on if these functions traded in nodes, blocks, and
24 ;;; lambda-vars directly.
25
26 ;;; Problems:
27 ;;;
28 ;;; -- Constraint propagation badly interacts with bottom-up type
29 ;;; inference. Consider
30 ;;;
31 ;;; (defun foo (n &aux (i 42))
32 ;;;   (declare (optimize speed))
33 ;;;   (declare (fixnum n)
34 ;;;            #+nil (type (integer 0) i))
35 ;;;   (tagbody
36 ;;;      (setq i 0)
37 ;;;    :loop
38 ;;;      (when (>= i n) (go :exit))
39 ;;;      (setq i (1+ i))
40 ;;;      (go :loop)
41 ;;;    :exit))
42 ;;;
43 ;;; In this case CP cannot even infer that I is of class INTEGER.
44 ;;;
45 ;;; -- In the above example if we place the check after SETQ, CP will
46 ;;; fail to infer (< I FIXNUM): it does not understand that this
47 ;;; constraint follows from (TYPEP I (INTEGER 0 0)).
48
49 (in-package "SB!C")
50
51 ;;; *CONSTRAINT-UNIVERSE* gets bound in IR1-PHASES to a fresh,
52 ;;; zero-length, non-zero-total-size vector-with-fill-pointer.
53 (declaim (type (and vector (not simple-vector)) *constraint-universe*))
54 (defvar *constraint-universe*)
55
56 (deftype constraint-y () '(or ctype lvar lambda-var constant))
57
58 (defstruct (constraint
59             (:include sset-element)
60             (:constructor make-constraint (number kind x y not-p))
61             (:copier nil))
62   ;; the kind of constraint we have:
63   ;;
64   ;; TYPEP
65   ;;     X is a LAMBDA-VAR and Y is a CTYPE. The value of X is
66   ;;     constrained to be of type Y.
67   ;;
68   ;; > or <
69   ;;     X is a lambda-var and Y is a CTYPE. The relation holds
70   ;;     between X and some object of type Y.
71   ;;
72   ;; EQL
73   ;;     X is a LAMBDA-VAR and Y is a LVAR, a LAMBDA-VAR or a CONSTANT.
74   ;;     The relation is asserted to hold.
75   (kind nil :type (member typep < > eql))
76   ;; The operands to the relation.
77   (x nil :type lambda-var)
78   (y nil :type constraint-y)
79   ;; If true, negates the sense of the constraint, so the relation
80   ;; does *not* hold.
81   (not-p nil :type boolean))
82 \f
83 ;;; Historically, CMUCL and SBCL have used a sparse set implementation
84 ;;; for which most operations are O(n) (see sset.lisp), but at the
85 ;;; cost of at least a full word of pointer for each constraint set
86 ;;; element.  Using bit-vectors instead of pointer structures saves a
87 ;;; lot of space and thus GC time (particularly on 64-bit machines),
88 ;;; and saves time on copy, union, intersection, and difference
89 ;;; operations; but makes iteration slower.  Circa September 2008,
90 ;;; switching to bit-vectors gave a modest (5-10%) improvement in real
91 ;;; compile time for most Lisp systems, and as much as 20-30% for some
92 ;;; particularly CP-dependent systems.
93
94 ;;; It's bad to leave commented code in files, but if some clever
95 ;;; person comes along and makes SSETs better than bit-vectors as sets
96 ;;; for constraint propagation, or if bit-vectors on some XC host
97 ;;; really lose compared to SSETs, here's the conset API as a wrapper
98 ;;; around SSETs:
99 #+nil
100 (progn
101   (deftype conset () 'sset)
102   (declaim (ftype (sfunction (conset) boolean) conset-empty))
103   (declaim (ftype (sfunction (conset) conset) copy-conset))
104   (declaim (ftype (sfunction (constraint conset) boolean) conset-member))
105   (declaim (ftype (sfunction (constraint conset) boolean) conset-adjoin))
106   (declaim (ftype (sfunction (conset conset) boolean) conset=))
107   (declaim (ftype (sfunction (conset conset) (values)) conset-union))
108   (declaim (ftype (sfunction (conset conset) (values)) conset-intersection))
109   (declaim (ftype (sfunction (conset conset) (values)) conset-difference))
110   (defun make-conset () (make-sset))
111   (defmacro do-conset-elements ((constraint conset &optional result) &body body)
112     `(do-sset-elements (,constraint ,conset ,result) ,@body))
113   (defmacro do-conset-intersection
114       ((constraint conset1 conset2 &optional result) &body body)
115     `(do-conset-elements (,constraint ,conset1 ,result)
116        (when (conset-member ,constraint ,conset2)
117          ,@body)))
118   (defun conset-empty (conset) (sset-empty conset))
119   (defun copy-conset (conset) (copy-sset conset))
120   (defun conset-member (constraint conset) (sset-member constraint conset))
121   (defun conset-adjoin (constraint conset) (sset-adjoin constraint conset))
122   (defun conset= (conset1 conset2) (sset= conset1 conset2))
123   ;; Note: CP doesn't ever care whether union, intersection, and
124   ;; difference change the first set.  (This is an important degree of
125   ;; freedom, since some ways of implementing sets lose a great deal
126   ;; when these operations are required to track changes.)
127   (defun conset-union (conset1 conset2)
128     (sset-union conset1 conset2) (values))
129   (defun conset-intersection (conset1 conset2)
130     (sset-intersection conset1 conset2) (values))
131   (defun conset-difference (conset1 conset2)
132     (sset-difference conset1 conset2) (values)))
133
134 (locally
135     ;; This is performance critical for the compiler, and benefits
136     ;; from the following declarations.  Probably you'll want to
137     ;; disable these declarations when debugging consets.
138     (declare #-sb-xc-host (optimize (speed 3) (safety 0) (space 0)))
139   (declaim (inline %constraint-number))
140   (defun %constraint-number (constraint)
141     (sset-element-number constraint))
142   (defstruct (conset
143               (:constructor make-conset ())
144               (:copier %copy-conset))
145     (vector (make-array
146              ;; FIXME: make POWER-OF-TWO-CEILING available earlier?
147              (ash 1 (integer-length (1- (length *constraint-universe*))))
148              :element-type 'bit :initial-element 0)
149             :type simple-bit-vector)
150     ;; Bit-vectors win over lightweight hashes for copy, union,
151     ;; intersection, difference, but lose for iteration if you iterate
152     ;; over the whole vector.  Tracking extrema helps a bit.
153     (min 0 :type fixnum)
154     (max 0 :type fixnum))
155
156   (defmacro do-conset-elements ((constraint conset &optional result) &body body)
157     (with-unique-names (vector index start end
158                                #-sb-xc-host ignore
159                                #-sb-xc-host constraint-universe-end)
160       (let* ((constraint-universe #+sb-xc-host '*constraint-universe*
161                                   #-sb-xc-host (sb!xc:gensym "UNIVERSE"))
162              (with-array-data
163                 #+sb-xc-host '(progn)
164                 #-sb-xc-host `(with-array-data
165                                   ((,constraint-universe *constraint-universe*)
166                                    (,ignore 0) (,constraint-universe-end nil)
167                                    :check-fill-pointer t)
168                                 (declare (ignore ,ignore))
169                                 (aver (<= ,end ,constraint-universe-end)))))
170         `(let* ((,vector (conset-vector ,conset))
171                (,start (conset-min ,conset))
172                (,end (min (conset-max ,conset) (length ,vector))))
173           (,@with-array-data
174             (do ((,index ,start (1+ ,index))) ((>= ,index ,end) ,result)
175               (when (plusp (sbit ,vector ,index))
176                 (let ((,constraint (elt ,constraint-universe ,index)))
177                   ,@body))))))))
178
179   ;; Oddly, iterating just between the maximum of the two sets' minima
180   ;; and the minimum of the sets' maxima slowed down CP.
181   (defmacro do-conset-intersection
182       ((constraint conset1 conset2 &optional result) &body body)
183     `(do-conset-elements (,constraint ,conset1 ,result)
184        (when (conset-member ,constraint ,conset2)
185          ,@body)))
186
187   (defun conset-empty (conset)
188     (or (= (conset-min conset) (conset-max conset))
189         ;; TODO: I bet FIND on bit-vectors can be optimized, if it
190         ;; isn't.
191         (not (find 1 (conset-vector conset)
192                    :start (conset-min conset)
193                    ;; By inspection, supplying :END here breaks the
194                    ;; build with a "full call to
195                    ;; DATA-VECTOR-REF-WITH-OFFSET" in the
196                    ;; cross-compiler.  If that should change, add
197                    ;; :end (conset-max conset)
198                    ))))
199
200   (defun copy-conset (conset)
201     (let ((ret (%copy-conset conset)))
202       (setf (conset-vector ret) (copy-seq (conset-vector conset)))
203       ret))
204
205   (defun %conset-grow (conset new-size)
206     (declare (type index new-size))
207     (setf (conset-vector conset)
208           (replace (the simple-bit-vector
209                      (make-array
210                       (ash 1 (integer-length (1- new-size)))
211                       :element-type 'bit
212                       :initial-element 0))
213                    (the simple-bit-vector
214                      (conset-vector conset)))))
215
216   (declaim (inline conset-grow))
217   (defun conset-grow (conset new-size)
218     (declare (type index new-size))
219     (when (< (length (conset-vector conset)) new-size)
220       (%conset-grow conset new-size))
221     (values))
222
223   (defun conset-member (constraint conset)
224     (let ((number (%constraint-number constraint))
225           (vector (conset-vector conset)))
226       (when (< number (length vector))
227         (plusp (sbit vector number)))))
228
229   (defun conset-adjoin (constraint conset)
230     (prog1
231       (not (conset-member constraint conset))
232       (let ((number (%constraint-number constraint)))
233         (conset-grow conset (1+ number))
234         (setf (sbit (conset-vector conset) number) 1)
235         (setf (conset-min conset) (min number (conset-min conset)))
236         (when (>= number (conset-max conset))
237           (setf (conset-max conset) (1+ number))))))
238
239   (defun conset= (conset1 conset2)
240     (let* ((vector1 (conset-vector conset1))
241            (vector2 (conset-vector conset2))
242            (length1 (length vector1))
243            (length2 (length vector2)))
244       (if (= length1 length2)
245           ;; When the lengths are the same, we can rely on EQUAL being
246           ;; nicely optimized on bit-vectors.
247           (equal vector1 vector2)
248           (multiple-value-bind (shorter longer)
249               (if (< length1 length2)
250                   (values vector1 vector2)
251                   (values vector2 vector1))
252             ;; FIXME: make MISMATCH fast on bit-vectors.
253             (dotimes (index (length shorter))
254               (when (/= (sbit vector1 index) (sbit vector2 index))
255                 (return-from conset= nil)))
256             (if (find 1 longer :start (length shorter))
257                 nil
258                 t)))))
259
260   (macrolet
261       ((defconsetop (name bit-op)
262            `(defun ,name (conset-1 conset-2)
263               (declare (optimize (speed 3) (safety 0)))
264               (let* ((size-1 (length (conset-vector conset-1)))
265                      (size-2 (length (conset-vector conset-2)))
266                      (new-size (max size-1 size-2)))
267                 (conset-grow conset-1 new-size)
268                 (conset-grow conset-2 new-size))
269               (let ((vector1 (conset-vector conset-1))
270                     (vector2 (conset-vector conset-2)))
271                 (declare (simple-bit-vector vector1 vector2))
272                 (setf (conset-vector conset-1) (,bit-op vector1 vector2 t))
273                 ;; Update the extrema.
274                 ,(ecase name
275                    ((conset-union)
276                     `(setf (conset-min conset-1)
277                            (min (conset-min conset-1)
278                                 (conset-min conset-2))
279                            (conset-max conset-1)
280                            (max (conset-max conset-1)
281                                 (conset-max conset-2))))
282                    ((conset-intersection)
283                     `(let ((start (max (conset-min conset-1)
284                                        (conset-min conset-2)))
285                            (end (min (conset-max conset-1)
286                                      (conset-max conset-2))))
287                        (setf (conset-min conset-1)
288                              (if (> start end)
289                                  0
290                                  (or (position 1 (conset-vector conset-1)
291                                                :start start :end end)
292                                      0))
293                              (conset-max conset-1)
294                              (if (> start end)
295                                  0
296                                  (let ((position
297                                         (position
298                                          1 (conset-vector conset-1)
299                                          :start start :end end :from-end t)))
300                                    (if position
301                                        (1+ position)
302                                        0))))))
303                    ((conset-difference)
304                     `(setf (conset-min conset-1)
305                            (or (position 1 (conset-vector conset-1)
306                                          :start (conset-min conset-1)
307                                          :end (conset-max conset-1))
308                                0)
309                            (conset-max conset-1)
310                            (let ((position
311                                   (position
312                                    1 (conset-vector conset-1)
313                                    :start (conset-min conset-1)
314                                    :end (conset-max conset-1)
315                                    :from-end t)))
316                              (if position
317                                  (1+ position)
318                                  0))))))
319               (values))))
320     (defconsetop conset-union bit-ior)
321     (defconsetop conset-intersection bit-and)
322     (defconsetop conset-difference bit-andc2)))
323 \f
324 ;;; Constraints are hash-consed. Unfortunately, types aren't, so we have
325 ;;; to over-approximate and then linear search through the potential hits.
326 ;;; LVARs can only be found in EQL (not-p = NIL) constraints, while constant
327 ;;; and lambda-vars can only be found in EQL constraints.
328
329 (defun find-constraint (kind x y not-p)
330   (declare (type lambda-var x) (type constraint-y y) (type boolean not-p))
331   (etypecase y
332     (ctype
333        (awhen (lambda-var-ctype-constraints x)
334          (dolist (con (gethash (sb!kernel::type-class-info y) it) nil)
335            (when (and (eq (constraint-kind con) kind)
336                       (eq (constraint-not-p con) not-p)
337                       (type= (constraint-y con) y))
338              (return-from find-constraint con)))
339          nil))
340     (lvar
341        (awhen (lambda-var-eq-constraints x)
342          (gethash y it)))
343     ((or constant lambda-var)
344        (awhen (lambda-var-eq-constraints x)
345          (let ((cache (gethash y it)))
346            (declare (type list cache))
347            (if not-p (cdr cache) (car cache)))))))
348
349 ;;; The most common operations on consets are iterating through the constraints
350 ;;; that are related to a certain variable in a given conset.  Storing the
351 ;;; constraints related to each variable in vectors allows us to easily iterate
352 ;;; through the intersection of such constraints and the constraints in a conset.
353 ;;;
354 ;;; EQL-var constraints assert that two lambda-vars are EQL.
355 ;;; Private constraints assert that a lambda-var is EQL or not EQL to a constant.
356 ;;; Inheritable constraints are constraints that may be propagated to EQL
357 ;;; lambda-vars (along with EQL-var constraints).
358 ;;;
359 ;;; Lambda-var -- lvar EQL constraints only serve one purpose: remember whether
360 ;;; an lvar is (only) written to by a ref to that lambda-var, and aren't ever
361 ;;; propagated.
362
363 (defun register-constraint (x con y)
364   (declare (type lambda-var x) (type constraint con) (type constraint-y y))
365   (conset-adjoin con (lambda-var-constraints x))
366   (macrolet ((ensuref (place default)
367                `(or ,place (setf ,place ,default)))
368              (ensure-hash (place)
369                `(ensuref ,place (make-hash-table)))
370              (ensure-vec (place)
371                `(ensuref ,place (make-array 8 :adjustable t :fill-pointer 0))))
372     (etypecase y
373       (ctype
374        (let ((index (ensure-hash (lambda-var-ctype-constraints x)))
375              (vec   (ensure-vec  (lambda-var-inheritable-constraints x))))
376          (push con (gethash (sb!kernel::type-class-info y) index))
377          (vector-push-extend con vec)))
378       (lvar
379        (let ((index (ensure-hash (lambda-var-eq-constraints x))))
380          (setf (gethash y index) con)))
381       ((or constant lambda-var)
382        (let* ((index (ensure-hash (lambda-var-eq-constraints x)))
383               (cons  (ensuref (gethash y index) (list nil))))
384          (if (constraint-not-p con)
385              (setf (cdr cons) con)
386              (setf (car cons) con)))
387        (typecase y
388          (constant
389           (let ((vec (ensure-vec (lambda-var-private-constraints x))))
390             (vector-push-extend con vec)))
391          (lambda-var
392           (let ((vec (if (constraint-not-p con)
393                          (ensure-vec (lambda-var-inheritable-constraints x))
394                          (ensure-vec (lambda-var-eql-var-constraints x)))))
395             (vector-push-extend con vec)))))))
396   nil)
397
398 ;;; Return a constraint for the specified arguments. We only create a
399 ;;; new constraint if there isn't already an equivalent old one,
400 ;;; guaranteeing that all equivalent constraints are EQ. This
401 ;;; shouldn't be called on LAMBDA-VARs with no CONSTRAINTS set.
402 (defun find-or-create-constraint (kind x y not-p)
403   (declare (type lambda-var x) (type constraint-y y) (type boolean not-p))
404   (or (find-constraint kind x y not-p)
405       (let ((new (make-constraint (length *constraint-universe*)
406                                   kind x y not-p)))
407         (vector-push-extend new *constraint-universe*
408                             (1+ (length *constraint-universe*)))
409         (register-constraint x new y)
410         (when (lambda-var-p y)
411           (register-constraint y new x))
412         new)))
413
414 ;;; If REF is to a LAMBDA-VAR with CONSTRAINTs (i.e. we can do flow
415 ;;; analysis on it), then return the LAMBDA-VAR, otherwise NIL.
416 #!-sb-fluid (declaim (inline ok-ref-lambda-var))
417 (defun ok-ref-lambda-var (ref)
418   (declare (type ref ref))
419   (let ((leaf (ref-leaf ref)))
420     (when (and (lambda-var-p leaf)
421                (lambda-var-constraints leaf))
422       leaf)))
423
424 ;;; See if LVAR's single USE is a REF to a LAMBDA-VAR and they are EQL
425 ;;; according to CONSTRAINTS. Return LAMBDA-VAR if so.
426 (defun ok-lvar-lambda-var (lvar constraints)
427   (declare (type lvar lvar))
428   (let ((use (lvar-uses lvar)))
429     (cond ((ref-p use)
430            (let ((lambda-var (ok-ref-lambda-var use)))
431              (when lambda-var
432                (let ((constraint (find-constraint 'eql lambda-var lvar nil)))
433                  (when (and constraint (conset-member constraint constraints))
434                    lambda-var)))))
435           ((cast-p use)
436            (ok-lvar-lambda-var (cast-value use) constraints)))))
437
438 (defmacro do-conset-constraints-intersection ((symbol (conset constraints) &optional result)
439                                              &body body)
440   (let ((min (gensym "MIN"))
441         (max (gensym "MAX")))
442     (once-only ((conset conset)
443                 (constraints constraints))
444       `(flet ((body (,symbol)
445                 (declare (type constraint ,symbol))
446                 ,@body))
447          (when ,constraints
448            (let ((,min (conset-min ,conset))
449                  (,max (conset-max ,conset)))
450              (map nil (lambda (constraint)
451                         (declare (type constraint constraint))
452                         (let ((number (constraint-number constraint)))
453                           (when (and (<= ,min number)
454                                      (< number ,max)
455                                      (conset-member constraint ,conset))
456                             (body constraint))))
457                   ,constraints)))
458          ,result))))
459
460 (defmacro do-eql-vars ((symbol (var constraints) &optional result) &body body)
461   (once-only ((var         var)
462               (constraints constraints))
463     `(flet ((body-fun (,symbol)
464               ,@body))
465        (body-fun ,var)
466        (do-conset-constraints-intersection
467            (con (,constraints (lambda-var-eql-var-constraints ,var)) ,result)
468          (let ((x (constraint-x con))
469                (y (constraint-y con)))
470            (body-fun (if (eq ,var x) y x)))))))
471
472 (defmacro do-inheritable-constraints ((symbol (conset variable) &optional result)
473                                       &body body)
474   (once-only ((conset   conset)
475               (variable variable))
476     `(block nil
477        (flet ((body-fun (,symbol)
478                 ,@body))
479          (do-conset-constraints-intersection
480              (con (,conset (lambda-var-inheritable-constraints ,variable)))
481            (body-fun con))
482          (do-conset-constraints-intersection
483              (con (,conset (lambda-var-eql-var-constraints ,variable)) ,result)
484            (body-fun con))))))
485
486 (defmacro do-propagatable-constraints ((symbol (conset variable) &optional result)
487                                        &body body)
488   (once-only ((conset conset)
489               (variable variable))
490     `(block nil
491        (flet ((body-fun (,symbol)
492                 ,@body))
493          (do-conset-constraints-intersection
494              (con (,conset (lambda-var-private-constraints ,variable)))
495            (body-fun con))
496          (do-conset-constraints-intersection
497              (con (,conset (lambda-var-eql-var-constraints ,variable)))
498            (body-fun con))
499          (do-conset-constraints-intersection
500              (con (,conset (lambda-var-inheritable-constraints ,variable)) ,result)
501            (body-fun con))))))
502 ;;;; Searching constraints
503
504 ;;; Add the indicated test constraint to BLOCK. We don't add the
505 ;;; constraint if the block has multiple predecessors, since it only
506 ;;; holds on this particular path.
507 (defun add-test-constraint (fun x y not-p constraints target)
508   (cond ((and (eq 'eql fun) (lambda-var-p y) (not not-p))
509          (add-eql-var-var-constraint x y constraints target))
510         (t
511          (do-eql-vars (x (x constraints))
512            (let ((con (find-or-create-constraint fun x y not-p)))
513              (conset-adjoin con target)))))
514   (values))
515
516 ;;; Add complementary constraints to the consequent and alternative
517 ;;; blocks of IF. We do nothing if X is NIL.
518 (defun add-complement-constraints (fun x y not-p constraints
519                                    consequent-constraints
520                                    alternative-constraints)
521   (when x
522     (add-test-constraint fun x y not-p constraints
523                          consequent-constraints)
524     (add-test-constraint fun x y (not not-p) constraints
525                          alternative-constraints))
526   (values))
527
528 ;;; Add test constraints to the consequent and alternative blocks of
529 ;;; the test represented by USE.
530 (defun add-test-constraints (use if constraints)
531   (declare (type node use) (type cif if))
532   ;; Note: Even if we do (IF test exp exp) => (PROGN test exp)
533   ;; optimization, the *MAX-OPTIMIZE-ITERATIONS* cutoff means that we
534   ;; can't guarantee that the optimization will be done, so we still
535   ;; need to avoid barfing on this case.
536   (unless (eq (if-consequent if) (if-alternative if))
537     (let ((consequent-constraints (make-conset))
538           (alternative-constraints (make-conset)))
539       (macrolet ((add (fun x y not-p)
540                    `(add-complement-constraints ,fun ,x ,y ,not-p
541                                                 constraints
542                                                 consequent-constraints
543                                                 alternative-constraints)))
544         (typecase use
545           (ref
546            (add 'typep (ok-lvar-lambda-var (ref-lvar use) constraints)
547                 (specifier-type 'null) t))
548           (combination
549            (unless (eq (combination-kind use)
550                        :error)
551              (let ((name (lvar-fun-name
552                           (basic-combination-fun use)))
553                    (args (basic-combination-args use)))
554                (case name
555                  ((%typep %instance-typep)
556                   (let ((type (second args)))
557                     (when (constant-lvar-p type)
558                       (let ((val (lvar-value type)))
559                         (add 'typep
560                              (ok-lvar-lambda-var (first args) constraints)
561                              (if (ctype-p val)
562                                  val
563                                  (let ((*compiler-error-context* use))
564                                    (specifier-type val)))
565                              nil)))))
566                  ((eq eql)
567                   (let* ((arg1 (first args))
568                          (var1 (ok-lvar-lambda-var arg1 constraints))
569                          (arg2 (second args))
570                          (var2 (ok-lvar-lambda-var arg2 constraints)))
571                     ;; The code below assumes that the constant is the
572                     ;; second argument in case of variable to constant
573                     ;; comparision which is sometimes true (see source
574                     ;; transformations for EQ, EQL and CHAR=). Fixing
575                     ;; that would result in more constant substitutions
576                     ;; which is not a universally good thing, thus the
577                     ;; unnatural asymmetry of the tests.
578                     (cond ((not var1)
579                            (when var2
580                              (add-test-constraint 'typep var2 (lvar-type arg1)
581                                                   nil constraints
582                                                   consequent-constraints)))
583                           (var2
584                            (add 'eql var1 var2 nil))
585                           ((constant-lvar-p arg2)
586                            (add 'eql var1
587                                 (let ((use (principal-lvar-use arg2)))
588                                   (if (ref-p use)
589                                       (ref-leaf use)
590                                       (find-constant (lvar-value arg2))))
591                                 nil))
592                           (t
593                            (add-test-constraint 'typep var1 (lvar-type arg2)
594                                                 nil constraints
595                                                 consequent-constraints)))))
596                  ((< >)
597                   (let* ((arg1 (first args))
598                          (var1 (ok-lvar-lambda-var arg1 constraints))
599                          (arg2 (second args))
600                          (var2 (ok-lvar-lambda-var arg2 constraints)))
601                     (when var1
602                       (add name var1 (lvar-type arg2) nil))
603                     (when var2
604                       (add (if (eq name '<) '> '<) var2 (lvar-type arg1) nil))))
605                  (t
606                   (let ((ptype (gethash name *backend-predicate-types*)))
607                     (when ptype
608                       (add 'typep (ok-lvar-lambda-var (first args) constraints)
609                            ptype nil))))))))))
610       (values consequent-constraints alternative-constraints))))
611
612 ;;;; Applying constraints
613
614 ;;; Return true if X is an integer NUMERIC-TYPE.
615 (defun integer-type-p (x)
616   (declare (type ctype x))
617   (and (numeric-type-p x)
618        (eq (numeric-type-class x) 'integer)
619        (eq (numeric-type-complexp x) :real)))
620
621 ;;; Given that an inequality holds on values of type X and Y, return a
622 ;;; new type for X. If GREATER is true, then X was greater than Y,
623 ;;; otherwise less. If OR-EQUAL is true, then the inequality was
624 ;;; inclusive, i.e. >=.
625 ;;;
626 ;;; If GREATER (or not), then we max (or min) in Y's lower (or upper)
627 ;;; bound into X and return that result. If not OR-EQUAL, we can go
628 ;;; one greater (less) than Y's bound.
629 (defun constrain-integer-type (x y greater or-equal)
630   (declare (type numeric-type x y))
631   (flet ((exclude (x)
632            (cond ((not x) nil)
633                  (or-equal x)
634                  (greater (1+ x))
635                  (t (1- x))))
636          (bound (x)
637            (if greater (numeric-type-low x) (numeric-type-high x))))
638     (let* ((x-bound (bound x))
639            (y-bound (exclude (bound y)))
640            (new-bound (cond ((not x-bound) y-bound)
641                             ((not y-bound) x-bound)
642                             (greater (max x-bound y-bound))
643                             (t (min x-bound y-bound)))))
644       (if greater
645           (modified-numeric-type x :low new-bound)
646           (modified-numeric-type x :high new-bound)))))
647
648 ;;; Return true if X is a float NUMERIC-TYPE.
649 (defun float-type-p (x)
650   (declare (type ctype x))
651   (and (numeric-type-p x)
652        (eq (numeric-type-class x) 'float)
653        (eq (numeric-type-complexp x) :real)))
654
655 ;;; Exactly the same as CONSTRAIN-INTEGER-TYPE, but for float numbers.
656 (defun constrain-float-type (x y greater or-equal)
657   (declare (type numeric-type x y))
658   (declare (ignorable x y greater or-equal)) ; for CROSS-FLOAT-INFINITY-KLUDGE
659
660   (aver (eql (numeric-type-class x) 'float))
661   (aver (eql (numeric-type-class y) 'float))
662   #+sb-xc-host                    ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
663   x
664   #-sb-xc-host                    ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
665   (labels ((exclude (x)
666              (cond ((not x) nil)
667                    (or-equal x)
668                    (t
669                     (if (consp x)
670                         x
671                         (list x)))))
672            (bound (x)
673              (if greater (numeric-type-low x) (numeric-type-high x)))
674            (tighter-p (x ref)
675              (cond ((null x) nil)
676                    ((null ref) t)
677                    ((and or-equal
678                          (= (type-bound-number x) (type-bound-number ref)))
679                     ;; X is tighter if REF is not an open bound and X is
680                     (and (not (consp ref)) (consp x)))
681                    (greater
682                     (< (type-bound-number ref) (type-bound-number x)))
683                    (t
684                     (> (type-bound-number ref) (type-bound-number x))))))
685     (let* ((x-bound (bound x))
686            (y-bound (exclude (bound y)))
687            (new-bound (cond ((not x-bound)
688                              y-bound)
689                             ((not y-bound)
690                              x-bound)
691                             ((tighter-p y-bound x-bound)
692                              y-bound)
693                             (t
694                              x-bound))))
695       (if greater
696           (modified-numeric-type x :low new-bound)
697           (modified-numeric-type x :high new-bound)))))
698
699 ;;; Return true if LEAF is "visible" from NODE.
700 (defun leaf-visible-from-node-p (leaf node)
701   (cond
702    ((lambda-var-p leaf)
703     ;; A LAMBDA-VAR is visible iif it is homed in a CLAMBDA that is an
704     ;; ancestor for NODE.
705     (let ((leaf-lambda (lambda-var-home leaf)))
706       (loop for lambda = (node-home-lambda node)
707             then (lambda-parent lambda)
708             while lambda
709             when (eq lambda leaf-lambda)
710             return t)))
711    ;; FIXME: Check on FUNCTIONALs (CLAMBDAs and OPTIONAL-DISPATCHes),
712    ;; not just LAMBDA-VARs.
713    (t
714     ;; Assume everything else is globally visible.
715     t)))
716
717 ;;; Given the set of CONSTRAINTS for a variable and the current set of
718 ;;; restrictions from flow analysis IN, set the type for REF
719 ;;; accordingly.
720 (defun constrain-ref-type (ref in)
721   (declare (type ref ref) (type conset in))
722   ;; KLUDGE: The NOT-SET and NOT-FPZ here are so that we don't need to
723   ;; cons up endless union types when propagating large number of EQL
724   ;; constraints -- eg. from large CASE forms -- instead we just
725   ;; directly accumulate one XSET, and a set of fp zeroes, which we at
726   ;; the end turn into a MEMBER-TYPE.
727   ;;
728   ;; Since massive symbol cases are an especially atrocious pattern
729   ;; and the (NOT (MEMBER ...ton of symbols...)) will never turn into
730   ;; a more useful type, don't propagate their negation except for NIL
731   ;; unless SPEED > COMPILATION-SPEED.
732   (let ((res (single-value-type (node-derived-type ref)))
733         (constrain-symbols (policy ref (> speed compilation-speed)))
734         (not-set (alloc-xset))
735         (not-fpz nil)
736         (not-res *empty-type*)
737         (leaf (ref-leaf ref)))
738     (declare (type lambda-var leaf))
739     (flet ((note-not (x)
740              (if (fp-zero-p x)
741                  (push x not-fpz)
742                  (when (or constrain-symbols (null x) (not (symbolp x)))
743                    (add-to-xset x not-set)))))
744       (do-propagatable-constraints (con (in leaf))
745         (let* ((x (constraint-x con))
746                (y (constraint-y con))
747                (not-p (constraint-not-p con))
748                (other (if (eq x leaf) y x))
749                (kind (constraint-kind con)))
750           (case kind
751             (typep
752              (if not-p
753                  (if (member-type-p other)
754                      (mapc-member-type-members #'note-not other)
755                      (setq not-res (type-union not-res other)))
756                  (setq res (type-approx-intersection2 res other))))
757             (eql
758              (let ((other-type (leaf-type other)))
759                (if not-p
760                    (when (and (constant-p other)
761                               (member-type-p other-type))
762                      (note-not (constant-value other)))
763                    (let ((leaf-type (leaf-type leaf)))
764                      (cond
765                        ((or (constant-p other)
766                             (and (leaf-refs other) ; protect from
767                                         ; deleted vars
768                                  (csubtypep other-type leaf-type)
769                                  (not (type= other-type leaf-type))
770                                  ;; Don't change to a LEAF not visible here.
771                                  (leaf-visible-from-node-p other ref)))
772                         (change-ref-leaf ref other)
773                         (when (constant-p other) (return)))
774                        (t
775                         (setq res (type-approx-intersection2
776                                    res other-type))))))))
777             ((< >)
778              (cond
779                ((and (integer-type-p res) (integer-type-p y))
780                 (let ((greater (eq kind '>)))
781                   (let ((greater (if not-p (not greater) greater)))
782                     (setq res
783                           (constrain-integer-type res y greater not-p)))))
784                ((and (float-type-p res) (float-type-p y))
785                 (let ((greater (eq kind '>)))
786                   (let ((greater (if not-p (not greater) greater)))
787                     (setq res
788                           (constrain-float-type res y greater not-p)))))))))))
789     (cond ((and (if-p (node-dest ref))
790                 (or (xset-member-p nil not-set)
791                     (csubtypep (specifier-type 'null) not-res)))
792            (setf (node-derived-type ref) *wild-type*)
793            (change-ref-leaf ref (find-constant t)))
794           (t
795            (setf not-res
796                  (type-union not-res (make-member-type :xset not-set :fp-zeroes not-fpz)))
797            (derive-node-type ref
798                              (make-single-value-type
799                               (or (type-difference res not-res)
800                                   res)))
801            (maybe-terminate-block ref nil))))
802   (values))
803
804 ;;;; Flow analysis
805
806 (defun maybe-add-eql-var-lvar-constraint (ref gen)
807   (let ((lvar (ref-lvar ref))
808         (leaf (ref-leaf ref)))
809     (when (and (lambda-var-p leaf) lvar)
810       (conset-adjoin (find-or-create-constraint 'eql leaf lvar nil)
811                      gen))))
812
813 ;;; Copy all CONSTRAINTS involving FROM-VAR - except the (EQL VAR
814 ;;; LVAR) ones - to all of the variables in the VARS list.
815 (defun inherit-constraints (vars from-var constraints target)
816   (do-inheritable-constraints (con (constraints from-var))
817     (let ((eq-x (eq from-var (constraint-x con)))
818           (eq-y (eq from-var (constraint-y con))))
819       (dolist (var vars)
820         (conset-adjoin (find-or-create-constraint
821                         (constraint-kind con)
822                         (if eq-x var (constraint-x con))
823                         (if eq-y var (constraint-y con))
824                         (constraint-not-p con))
825                        target)))))
826
827 ;; Add an (EQL LAMBDA-VAR LAMBDA-VAR) constraint on VAR1 and VAR2 and
828 ;; inherit each other's constraints.
829 (defun add-eql-var-var-constraint (var1 var2 constraints
830                                    &optional (target constraints))
831   (let ((con (find-or-create-constraint 'eql var1 var2 nil)))
832     (when (conset-adjoin con target)
833       (collect ((eql1) (eql2))
834         (do-eql-vars (var1 (var1 constraints))
835           (eql1 var1))
836         (do-eql-vars (var2 (var2 constraints))
837           (eql2 var2))
838         (inherit-constraints (eql1) var2 constraints target)
839         (inherit-constraints (eql2) var1 constraints target))
840       t)))
841
842 ;; Add an (EQL LAMBDA-VAR LAMBDA-VAR) constraint on VAR and LVAR's
843 ;; LAMBDA-VAR if possible.
844 (defun maybe-add-eql-var-var-constraint (var lvar constraints
845                                          &optional (target constraints))
846   (declare (type lambda-var var) (type lvar lvar))
847   (let ((lambda-var (ok-lvar-lambda-var lvar constraints)))
848     (when lambda-var
849       (add-eql-var-var-constraint var lambda-var constraints target))))
850
851 ;;; Local propagation
852 ;;; -- [TODO: For any LAMBDA-VAR ref with a type check, add that
853 ;;;    constraint.]
854 ;;; -- For any LAMBDA-VAR set, delete all constraints on that var; add
855 ;;;    a type constraint based on the new value type.
856 (declaim (ftype (function (cblock conset boolean)
857                           conset)
858                 constraint-propagate-in-block))
859 (defun constraint-propagate-in-block (block gen preprocess-refs-p)
860   (do-nodes (node lvar block)
861     (typecase node
862       (bind
863        (let ((fun (bind-lambda node)))
864          (when (eq (functional-kind fun) :let)
865            (loop with call = (lvar-dest (node-lvar (first (lambda-refs fun))))
866                  for var in (lambda-vars fun)
867                  and val in (combination-args call)
868                  when (and val (lambda-var-constraints var))
869                  do (let ((type (lvar-type val)))
870                       (unless (eq type *universal-type*)
871                         (let ((con (find-or-create-constraint 'typep var type nil)))
872                           (conset-adjoin con gen))))
873                     (maybe-add-eql-var-var-constraint var val gen)))))
874       (ref
875        (when (ok-ref-lambda-var node)
876          (maybe-add-eql-var-lvar-constraint node gen)
877          (when preprocess-refs-p
878            (constrain-ref-type node gen))))
879       (cast
880        (let ((lvar (cast-value node)))
881          (let ((var (ok-lvar-lambda-var lvar gen)))
882            (when var
883              (let ((atype (single-value-type (cast-derived-type node)))) ;FIXME
884                (unless (eq atype *universal-type*)
885                  (do-eql-vars (var (var gen))
886                    (let ((con (find-or-create-constraint 'typep var atype nil)))
887                      (conset-adjoin con gen)))))))))
888       (cset
889        (binding* ((var (set-var node))
890                   (nil (lambda-var-p var) :exit-if-null)
891                   (cons (lambda-var-constraints var) :exit-if-null))
892          (conset-difference gen cons)
893          (let ((type (single-value-type (node-derived-type node))))
894            (unless (eq type *universal-type*)
895              (let ((con (find-or-create-constraint 'typep var type nil)))
896                (conset-adjoin con gen))))
897          (maybe-add-eql-var-var-constraint var (set-value node) gen)))))
898   gen)
899
900 (defun constraint-propagate-if (block gen)
901   (let ((node (block-last block)))
902     (when (if-p node)
903       (let ((use (lvar-uses (if-test node))))
904         (when (node-p use)
905           (add-test-constraints use node gen))))))
906
907 ;;; Starting from IN compute OUT and (consequent/alternative
908 ;;; constraints if the block ends with and IF). Return the list of
909 ;;; successors that may need to be recomputed.
910 (defun find-block-type-constraints (block final-pass-p)
911   (declare (type cblock block))
912   (let ((gen (constraint-propagate-in-block
913               block
914               (if final-pass-p
915                   (block-in block)
916                   (copy-conset (block-in block)))
917               final-pass-p)))
918     (setf (block-gen block) gen)
919     (multiple-value-bind (consequent-constraints alternative-constraints)
920         (constraint-propagate-if block gen)
921       (if consequent-constraints
922           (let* ((node (block-last block))
923                  (old-consequent-constraints (if-consequent-constraints node))
924                  (old-alternative-constraints (if-alternative-constraints node))
925                  (succ ()))
926             ;; Add the consequent and alternative constraints to GEN.
927             (cond ((conset-empty consequent-constraints)
928                    (setf (if-consequent-constraints node) gen)
929                    (setf (if-alternative-constraints node) gen))
930                   (t
931                    (setf (if-consequent-constraints node) (copy-conset gen))
932                    (conset-union (if-consequent-constraints node)
933                                  consequent-constraints)
934                    (setf (if-alternative-constraints node) gen)
935                    (conset-union (if-alternative-constraints node)
936                                  alternative-constraints)))
937             ;; Has the consequent been changed?
938             (unless (and old-consequent-constraints
939                          (conset= (if-consequent-constraints node)
940                                   old-consequent-constraints))
941               (push (if-consequent node) succ))
942             ;; Has the alternative been changed?
943             (unless (and old-alternative-constraints
944                          (conset= (if-alternative-constraints node)
945                                   old-alternative-constraints))
946               (push (if-alternative node) succ))
947             succ)
948           ;; There is no IF.
949           (unless (and (block-out block)
950                        (conset= gen (block-out block)))
951             (setf (block-out block) gen)
952             (block-succ block))))))
953
954 ;;; Deliver the results of constraint propagation to REFs in BLOCK.
955 ;;; During this pass, we also do local constraint propagation by
956 ;;; adding in constraints as we see them during the pass through the
957 ;;; block.
958 (defun use-result-constraints (block)
959   (declare (type cblock block))
960   (constraint-propagate-in-block block (block-in block) t))
961
962 ;;; Give an empty constraints set to any var that doesn't have one and
963 ;;; isn't a set closure var. Since a var that we previously rejected
964 ;;; looks identical to one that is new, so we optimistically keep
965 ;;; hoping that vars stop being closed over or lose their sets.
966 (defun init-var-constraints (component)
967   (declare (type component component))
968   (dolist (fun (component-lambdas component))
969     (flet ((frob (x)
970              (dolist (var (lambda-vars x))
971                (unless (lambda-var-constraints var)
972                  (when (or (null (lambda-var-sets var))
973                            (not (closure-var-p var)))
974                    (setf (lambda-var-constraints var) (make-conset)))))))
975       (frob fun)
976       (dolist (let (lambda-lets fun))
977         (frob let)))))
978
979 ;;; Return the constraints that flow from PRED to SUCC. This is
980 ;;; BLOCK-OUT unless PRED ends with an IF and test constraints were
981 ;;; added.
982 (defun block-out-for-successor (pred succ)
983   (declare (type cblock pred succ))
984   (let ((last (block-last pred)))
985     (or (when (if-p last)
986           (cond ((eq succ (if-consequent last))
987                  (if-consequent-constraints last))
988                 ((eq succ (if-alternative last))
989                  (if-alternative-constraints last))))
990         (block-out pred))))
991
992 (defun compute-block-in (block)
993   (let ((in nil))
994     (dolist (pred (block-pred block))
995       ;; If OUT has not been calculated, assume it to be the universal
996       ;; set.
997       (let ((out (block-out-for-successor pred block)))
998         (when out
999           (if in
1000               (conset-intersection in out)
1001               (setq in (copy-conset out))))))
1002     (or in (make-conset))))
1003
1004 (defun update-block-in (block)
1005   (let ((in (compute-block-in block)))
1006     (cond ((and (block-in block) (conset= in (block-in block)))
1007            nil)
1008           (t
1009            (setf (block-in block) in)))))
1010
1011 ;;; Return two lists: one of blocks that precede all loops and
1012 ;;; therefore require only one constraint propagation pass and the
1013 ;;; rest. This implementation does not find all such blocks.
1014 ;;;
1015 ;;; A more complete implementation would be:
1016 ;;;
1017 ;;;     (do-blocks (block component)
1018 ;;;       (if (every #'(lambda (pred)
1019 ;;;                      (or (member pred leading-blocks)
1020 ;;;                          (eq pred head)))
1021 ;;;                  (block-pred block))
1022 ;;;           (push block leading-blocks)
1023 ;;;           (push block rest-of-blocks)))
1024 ;;;
1025 ;;; Trailing blocks that succeed all loops could be found and handled
1026 ;;; similarly. In practice though, these more complex solutions are
1027 ;;; slightly worse performancewise.
1028 (defun leading-component-blocks (component)
1029   (declare (type component component))
1030   (flet ((loopy-p (block)
1031            (let ((n (block-number block)))
1032              (dolist (pred (block-pred block))
1033                (unless (< n (block-number pred))
1034                  (return t))))))
1035     (let ((leading-blocks ())
1036           (rest-of-blocks ())
1037           (seen-loop-p ()))
1038       (do-blocks (block component)
1039         (when (and (not seen-loop-p) (loopy-p block))
1040           (setq seen-loop-p t))
1041         (if seen-loop-p
1042             (push block rest-of-blocks)
1043             (push block leading-blocks)))
1044       (values (nreverse leading-blocks) (nreverse rest-of-blocks)))))
1045
1046 ;;; Append OBJ to the end of LIST as if by NCONC but only if it is not
1047 ;;; a member already.
1048 (defun nconc-new (obj list)
1049   (do ((x list (cdr x))
1050        (prev nil x))
1051       ((endp x) (if prev
1052                     (progn
1053                       (setf (cdr prev) (list obj))
1054                       list)
1055                     (list obj)))
1056     (when (eql (car x) obj)
1057       (return-from nconc-new list))))
1058
1059 (defun find-and-propagate-constraints (component)
1060   (let ((blocks-to-process ()))
1061     (flet ((enqueue (blocks)
1062              (dolist (block blocks)
1063                (setq blocks-to-process (nconc-new block blocks-to-process)))))
1064       (multiple-value-bind (leading-blocks rest-of-blocks)
1065           (leading-component-blocks component)
1066         ;; Update every block once to account for changes in the
1067         ;; IR1. The constraints of the lead blocks cannot be changed
1068         ;; after the first pass so we might as well use them and skip
1069         ;; USE-RESULT-CONSTRAINTS later.
1070         (dolist (block leading-blocks)
1071           (setf (block-in block) (compute-block-in block))
1072           (find-block-type-constraints block t))
1073         (setq blocks-to-process (copy-list rest-of-blocks))
1074         ;; The rest of the blocks.
1075         (dolist (block rest-of-blocks)
1076           (aver (eq block (pop blocks-to-process)))
1077           (setf (block-in block) (compute-block-in block))
1078           (enqueue (find-block-type-constraints block nil)))
1079         ;; Propagate constraints
1080         (loop for block = (pop blocks-to-process)
1081               while block do
1082               (unless (eq block (component-tail component))
1083                 (when (update-block-in block)
1084                   (enqueue (find-block-type-constraints block nil)))))
1085         rest-of-blocks))))
1086
1087 (defun constraint-propagate (component)
1088   (declare (type component component))
1089   (init-var-constraints component)
1090
1091   (unless (block-out (component-head component))
1092     (setf (block-out (component-head component)) (make-conset)))
1093
1094   (dolist (block (find-and-propagate-constraints component))
1095     (unless (block-delete-p block)
1096       (use-result-constraints block)))
1097
1098   (values))