1.0.27.32: implement and use SB!XC:GENSYM
[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 (defun find-constraint (kind x y not-p)
325   (declare (type lambda-var x) (type constraint-y y) (type boolean not-p))
326   (etypecase y
327     (ctype
328      (do-conset-elements (con (lambda-var-constraints x) nil)
329        (when (and (eq (constraint-kind con) kind)
330                   (eq (constraint-not-p con) not-p)
331                   (type= (constraint-y con) y))
332          (return con))))
333     ((or lvar constant)
334      (do-conset-elements (con (lambda-var-constraints x) nil)
335        (when (and (eq (constraint-kind con) kind)
336                   (eq (constraint-not-p con) not-p)
337                   (eq (constraint-y con) y))
338          (return con))))
339     (lambda-var
340      (do-conset-elements (con (lambda-var-constraints x) nil)
341        (when (and (eq (constraint-kind con) kind)
342                   (eq (constraint-not-p con) not-p)
343                   (let ((cx (constraint-x con)))
344                     (eq (if (eq cx x)
345                             (constraint-y con)
346                             cx)
347                         y)))
348          (return con))))))
349
350 ;;; Return a constraint for the specified arguments. We only create a
351 ;;; new constraint if there isn't already an equivalent old one,
352 ;;; guaranteeing that all equivalent constraints are EQ. This
353 ;;; shouldn't be called on LAMBDA-VARs with no CONSTRAINTS set.
354 (defun find-or-create-constraint (kind x y not-p)
355   (declare (type lambda-var x) (type constraint-y y) (type boolean not-p))
356   (or (find-constraint kind x y not-p)
357       (let ((new (make-constraint (length *constraint-universe*)
358                                   kind x y not-p)))
359         (vector-push-extend new *constraint-universe*
360                             (1+ (length *constraint-universe*)))
361         (conset-adjoin new (lambda-var-constraints x))
362         (when (lambda-var-p y)
363           (conset-adjoin new (lambda-var-constraints y)))
364         new)))
365
366 ;;; If REF is to a LAMBDA-VAR with CONSTRAINTs (i.e. we can do flow
367 ;;; analysis on it), then return the LAMBDA-VAR, otherwise NIL.
368 #!-sb-fluid (declaim (inline ok-ref-lambda-var))
369 (defun ok-ref-lambda-var (ref)
370   (declare (type ref ref))
371   (let ((leaf (ref-leaf ref)))
372     (when (and (lambda-var-p leaf)
373                (lambda-var-constraints leaf))
374       leaf)))
375
376 ;;; See if LVAR's single USE is a REF to a LAMBDA-VAR and they are EQL
377 ;;; according to CONSTRAINTS. Return LAMBDA-VAR if so.
378 (defun ok-lvar-lambda-var (lvar constraints)
379   (declare (type lvar lvar))
380   (let ((use (lvar-uses lvar)))
381     (cond ((ref-p use)
382            (let ((lambda-var (ok-ref-lambda-var use)))
383              (when lambda-var
384                (let ((constraint (find-constraint 'eql lambda-var lvar nil)))
385                  (when (and constraint (conset-member constraint constraints))
386                    lambda-var)))))
387           ((cast-p use)
388            (ok-lvar-lambda-var (cast-value use) constraints)))))
389
390 (defmacro do-eql-vars ((symbol (var constraints) &optional result) &body body)
391   (once-only ((var var))
392     `(let ((,symbol ,var))
393        (flet ((body-fun ()
394                 ,@body))
395          (body-fun)
396          (do-conset-elements (con ,constraints ,result)
397            (let ((other (and (eq (constraint-kind con) 'eql)
398                              (eq (constraint-not-p con) nil)
399                              (cond ((eq ,var (constraint-x con))
400                                     (constraint-y con))
401                                    ((eq ,var (constraint-y con))
402                                     (constraint-x con))
403                                    (t
404                                     nil)))))
405              (when other
406                (setq ,symbol other)
407                (when (lambda-var-p ,symbol)
408                  (body-fun)))))))))
409
410 ;;;; Searching constraints
411
412 ;;; Add the indicated test constraint to BLOCK. We don't add the
413 ;;; constraint if the block has multiple predecessors, since it only
414 ;;; holds on this particular path.
415 (defun add-test-constraint (fun x y not-p constraints target)
416   (cond ((and (eq 'eql fun) (lambda-var-p y) (not not-p))
417          (add-eql-var-var-constraint x y constraints target))
418         (t
419          (do-eql-vars (x (x constraints))
420            (let ((con (find-or-create-constraint fun x y not-p)))
421              (conset-adjoin con target)))))
422   (values))
423
424 ;;; Add complementary constraints to the consequent and alternative
425 ;;; blocks of IF. We do nothing if X is NIL.
426 (defun add-complement-constraints (fun x y not-p constraints
427                                    consequent-constraints
428                                    alternative-constraints)
429   (when x
430     (add-test-constraint fun x y not-p constraints
431                          consequent-constraints)
432     (add-test-constraint fun x y (not not-p) constraints
433                          alternative-constraints))
434   (values))
435
436 ;;; Add test constraints to the consequent and alternative blocks of
437 ;;; the test represented by USE.
438 (defun add-test-constraints (use if constraints)
439   (declare (type node use) (type cif if))
440   ;; Note: Even if we do (IF test exp exp) => (PROGN test exp)
441   ;; optimization, the *MAX-OPTIMIZE-ITERATIONS* cutoff means that we
442   ;; can't guarantee that the optimization will be done, so we still
443   ;; need to avoid barfing on this case.
444   (unless (eq (if-consequent if) (if-alternative if))
445     (let ((consequent-constraints (make-conset))
446           (alternative-constraints (make-conset)))
447       (macrolet ((add (fun x y not-p)
448                    `(add-complement-constraints ,fun ,x ,y ,not-p
449                                                 constraints
450                                                 consequent-constraints
451                                                 alternative-constraints)))
452         (typecase use
453           (ref
454            (add 'typep (ok-lvar-lambda-var (ref-lvar use) constraints)
455                 (specifier-type 'null) t))
456           (combination
457            (unless (eq (combination-kind use)
458                        :error)
459              (let ((name (lvar-fun-name
460                           (basic-combination-fun use)))
461                    (args (basic-combination-args use)))
462                (case name
463                  ((%typep %instance-typep)
464                   (let ((type (second args)))
465                     (when (constant-lvar-p type)
466                       (let ((val (lvar-value type)))
467                         (add 'typep
468                              (ok-lvar-lambda-var (first args) constraints)
469                              (if (ctype-p val)
470                                  val
471                                  (specifier-type val))
472                              nil)))))
473                  ((eq eql)
474                   (let* ((arg1 (first args))
475                          (var1 (ok-lvar-lambda-var arg1 constraints))
476                          (arg2 (second args))
477                          (var2 (ok-lvar-lambda-var arg2 constraints)))
478                     ;; The code below assumes that the constant is the
479                     ;; second argument in case of variable to constant
480                     ;; comparision which is sometimes true (see source
481                     ;; transformations for EQ, EQL and CHAR=). Fixing
482                     ;; that would result in more constant substitutions
483                     ;; which is not a universally good thing, thus the
484                     ;; unnatural asymmetry of the tests.
485                     (cond ((not var1)
486                            (when var2
487                              (add-test-constraint 'typep var2 (lvar-type arg1)
488                                                   nil constraints
489                                                   consequent-constraints)))
490                           (var2
491                            (add 'eql var1 var2 nil))
492                           ((constant-lvar-p arg2)
493                            (add 'eql var1 (ref-leaf (principal-lvar-use arg2))
494                                 nil))
495                           (t
496                            (add-test-constraint 'typep var1 (lvar-type arg2)
497                                                 nil constraints
498                                                 consequent-constraints)))))
499                  ((< >)
500                   (let* ((arg1 (first args))
501                          (var1 (ok-lvar-lambda-var arg1 constraints))
502                          (arg2 (second args))
503                          (var2 (ok-lvar-lambda-var arg2 constraints)))
504                     (when var1
505                       (add name var1 (lvar-type arg2) nil))
506                     (when var2
507                       (add (if (eq name '<) '> '<) var2 (lvar-type arg1) nil))))
508                  (t
509                   (let ((ptype (gethash name *backend-predicate-types*)))
510                     (when ptype
511                       (add 'typep (ok-lvar-lambda-var (first args) constraints)
512                            ptype nil))))))))))
513       (values consequent-constraints alternative-constraints))))
514
515 ;;;; Applying constraints
516
517 ;;; Return true if X is an integer NUMERIC-TYPE.
518 (defun integer-type-p (x)
519   (declare (type ctype x))
520   (and (numeric-type-p x)
521        (eq (numeric-type-class x) 'integer)
522        (eq (numeric-type-complexp x) :real)))
523
524 ;;; Given that an inequality holds on values of type X and Y, return a
525 ;;; new type for X. If GREATER is true, then X was greater than Y,
526 ;;; otherwise less. If OR-EQUAL is true, then the inequality was
527 ;;; inclusive, i.e. >=.
528 ;;;
529 ;;; If GREATER (or not), then we max (or min) in Y's lower (or upper)
530 ;;; bound into X and return that result. If not OR-EQUAL, we can go
531 ;;; one greater (less) than Y's bound.
532 (defun constrain-integer-type (x y greater or-equal)
533   (declare (type numeric-type x y))
534   (flet ((exclude (x)
535            (cond ((not x) nil)
536                  (or-equal x)
537                  (greater (1+ x))
538                  (t (1- x))))
539          (bound (x)
540            (if greater (numeric-type-low x) (numeric-type-high x))))
541     (let* ((x-bound (bound x))
542            (y-bound (exclude (bound y)))
543            (new-bound (cond ((not x-bound) y-bound)
544                             ((not y-bound) x-bound)
545                             (greater (max x-bound y-bound))
546                             (t (min x-bound y-bound)))))
547       (if greater
548           (modified-numeric-type x :low new-bound)
549           (modified-numeric-type x :high new-bound)))))
550
551 ;;; Return true if X is a float NUMERIC-TYPE.
552 (defun float-type-p (x)
553   (declare (type ctype x))
554   (and (numeric-type-p x)
555        (eq (numeric-type-class x) 'float)
556        (eq (numeric-type-complexp x) :real)))
557
558 ;;; Exactly the same as CONSTRAIN-INTEGER-TYPE, but for float numbers.
559 (defun constrain-float-type (x y greater or-equal)
560   (declare (type numeric-type x y))
561   (declare (ignorable x y greater or-equal)) ; for CROSS-FLOAT-INFINITY-KLUDGE
562
563   (aver (eql (numeric-type-class x) 'float))
564   (aver (eql (numeric-type-class y) 'float))
565   #+sb-xc-host                    ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
566   x
567   #-sb-xc-host                    ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
568   (labels ((exclude (x)
569              (cond ((not x) nil)
570                    (or-equal x)
571                    (t
572                     (if (consp x)
573                         x
574                         (list x)))))
575            (bound (x)
576              (if greater (numeric-type-low x) (numeric-type-high x)))
577            (tighter-p (x ref)
578              (cond ((null x) nil)
579                    ((null ref) t)
580                    ((and or-equal
581                          (= (type-bound-number x) (type-bound-number ref)))
582                     ;; X is tighter if REF is not an open bound and X is
583                     (and (not (consp ref)) (consp x)))
584                    (greater
585                     (< (type-bound-number ref) (type-bound-number x)))
586                    (t
587                     (> (type-bound-number ref) (type-bound-number x))))))
588     (let* ((x-bound (bound x))
589            (y-bound (exclude (bound y)))
590            (new-bound (cond ((not x-bound)
591                              y-bound)
592                             ((not y-bound)
593                              x-bound)
594                             ((tighter-p y-bound x-bound)
595                              y-bound)
596                             (t
597                              x-bound))))
598       (if greater
599           (modified-numeric-type x :low new-bound)
600           (modified-numeric-type x :high new-bound)))))
601
602 ;;; Given the set of CONSTRAINTS for a variable and the current set of
603 ;;; restrictions from flow analysis IN, set the type for REF
604 ;;; accordingly.
605 (defun constrain-ref-type (ref constraints in)
606   (declare (type ref ref) (type conset constraints in))
607   ;; KLUDGE: The NOT-SET and NOT-FPZ here are so that we don't need to
608   ;; cons up endless union types when propagating large number of EQL
609   ;; constraints -- eg. from large CASE forms -- instead we just
610   ;; directly accumulate one XSET, and a set of fp zeroes, which we at
611   ;; the end turn into a MEMBER-TYPE.
612   ;;
613   ;; Since massive symbol cases are an especially atrocious pattern
614   ;; and the (NOT (MEMBER ...ton of symbols...)) will never turn into
615   ;; a more useful type, don't propagate their negation except for NIL
616   ;; unless SPEED > COMPILATION-SPEED.
617   (let ((res (single-value-type (node-derived-type ref)))
618         (constrain-symbols (policy ref (> speed compilation-speed)))
619         (not-set (alloc-xset))
620         (not-fpz nil)
621         (not-res *empty-type*)
622         (leaf (ref-leaf ref)))
623     (flet ((note-not (x)
624              (if (fp-zero-p x)
625                  (push x not-fpz)
626                  (when (or constrain-symbols (null x) (not (symbolp x)))
627                    (add-to-xset x not-set)))))
628       ;; KLUDGE: the implementations of DO-CONSET-INTERSECTION will
629       ;; probably run faster when the smaller set comes first, so
630       ;; don't change the order here.
631       (do-conset-intersection (con constraints in)
632         (let* ((x (constraint-x con))
633                (y (constraint-y con))
634                (not-p (constraint-not-p con))
635                (other (if (eq x leaf) y x))
636                (kind (constraint-kind con)))
637           (case kind
638             (typep
639              (if not-p
640                  (if (member-type-p other)
641                      (mapc-member-type-members #'note-not other)
642                      (setq not-res (type-union not-res other)))
643                  (setq res (type-approx-intersection2 res other))))
644             (eql
645              (unless (lvar-p other)
646                (let ((other-type (leaf-type other)))
647                  (if not-p
648                      (when (and (constant-p other)
649                                 (member-type-p other-type))
650                        (note-not (constant-value other)))
651                      (let ((leaf-type (leaf-type leaf)))
652                        (cond
653                          ((or (constant-p other)
654                               (and (leaf-refs other) ; protect from
655                                         ; deleted vars
656                                    (csubtypep other-type leaf-type)
657                                    (not (type= other-type leaf-type))))
658                           (change-ref-leaf ref other)
659                           (when (constant-p other) (return)))
660                          (t
661                           (setq res (type-approx-intersection2
662                                      res other-type)))))))))
663             ((< >)
664              (cond
665                ((and (integer-type-p res) (integer-type-p y))
666                 (let ((greater (eq kind '>)))
667                   (let ((greater (if not-p (not greater) greater)))
668                     (setq res
669                           (constrain-integer-type res y greater not-p)))))
670                ((and (float-type-p res) (float-type-p y))
671                 (let ((greater (eq kind '>)))
672                   (let ((greater (if not-p (not greater) greater)))
673                     (setq res
674                           (constrain-float-type res y greater not-p)))))))))))
675     (cond ((and (if-p (node-dest ref))
676                 (or (xset-member-p nil not-set)
677                     (csubtypep (specifier-type 'null) not-res)))
678            (setf (node-derived-type ref) *wild-type*)
679            (change-ref-leaf ref (find-constant t)))
680           (t
681            (setf not-res
682                  (type-union not-res (make-member-type :xset not-set :fp-zeroes not-fpz)))
683            (derive-node-type ref
684                              (make-single-value-type
685                               (or (type-difference res not-res)
686                                   res)))
687            (maybe-terminate-block ref nil))))
688   (values))
689
690 ;;;; Flow analysis
691
692 (defun maybe-add-eql-var-lvar-constraint (ref gen)
693   (let ((lvar (ref-lvar ref))
694         (leaf (ref-leaf ref)))
695     (when (and (lambda-var-p leaf) lvar)
696       (conset-adjoin (find-or-create-constraint 'eql leaf lvar nil)
697                      gen))))
698
699 ;;; Copy all CONSTRAINTS involving FROM-VAR - except the (EQL VAR
700 ;;; LVAR) ones - to all of the variables in the VARS list.
701 (defun inherit-constraints (vars from-var constraints target)
702   (do-conset-elements (con constraints)
703     ;; Constant substitution is controversial.
704     (unless (constant-p (constraint-y con))
705       (dolist (var vars)
706         (let ((eq-x (eq from-var (constraint-x con)))
707               (eq-y (eq from-var (constraint-y con))))
708           (when (or (and eq-x (not (lvar-p (constraint-y con))))
709                     eq-y)
710             (conset-adjoin (find-or-create-constraint
711                             (constraint-kind con)
712                             (if eq-x var (constraint-x con))
713                             (if eq-y var (constraint-y con))
714                             (constraint-not-p con))
715                            target)))))))
716
717 ;; Add an (EQL LAMBDA-VAR LAMBDA-VAR) constraint on VAR1 and VAR2 and
718 ;; inherit each other's constraints.
719 (defun add-eql-var-var-constraint (var1 var2 constraints
720                                    &optional (target constraints))
721   (let ((con (find-or-create-constraint 'eql var1 var2 nil)))
722     (when (conset-adjoin con target)
723       (collect ((eql1) (eql2))
724         (do-eql-vars (var1 (var1 constraints))
725           (eql1 var1))
726         (do-eql-vars (var2 (var2 constraints))
727           (eql2 var2))
728         (inherit-constraints (eql1) var2 constraints target)
729         (inherit-constraints (eql2) var1 constraints target))
730       t)))
731
732 ;; Add an (EQL LAMBDA-VAR LAMBDA-VAR) constraint on VAR and LVAR's
733 ;; LAMBDA-VAR if possible.
734 (defun maybe-add-eql-var-var-constraint (var lvar constraints
735                                          &optional (target constraints))
736   (declare (type lambda-var var) (type lvar lvar))
737   (let ((lambda-var (ok-lvar-lambda-var lvar constraints)))
738     (when lambda-var
739       (add-eql-var-var-constraint var lambda-var constraints target))))
740
741 ;;; Local propagation
742 ;;; -- [TODO: For any LAMBDA-VAR ref with a type check, add that
743 ;;;    constraint.]
744 ;;; -- For any LAMBDA-VAR set, delete all constraints on that var; add
745 ;;;    a type constraint based on the new value type.
746 (declaim (ftype (function (cblock conset boolean)
747                           conset)
748                 constraint-propagate-in-block))
749 (defun constraint-propagate-in-block (block gen preprocess-refs-p)
750   (do-nodes (node lvar block)
751     (typecase node
752       (bind
753        (let ((fun (bind-lambda node)))
754          (when (eq (functional-kind fun) :let)
755            (loop with call = (lvar-dest (node-lvar (first (lambda-refs fun))))
756                  for var in (lambda-vars fun)
757                  and val in (combination-args call)
758                  when (and val (lambda-var-constraints var))
759                  do (let* ((type (lvar-type val))
760                            (con (find-or-create-constraint 'typep var type
761                                                            nil)))
762                       (conset-adjoin con gen))
763                  (maybe-add-eql-var-var-constraint var val gen)))))
764       (ref
765        (when (ok-ref-lambda-var node)
766          (maybe-add-eql-var-lvar-constraint node gen)
767          (when preprocess-refs-p
768            (let* ((var (ref-leaf node))
769                   (con (lambda-var-constraints var)))
770              (constrain-ref-type node con gen)))))
771       (cast
772        (let ((lvar (cast-value node)))
773          (let ((var (ok-lvar-lambda-var lvar gen)))
774            (when var
775              (let ((atype (single-value-type (cast-derived-type node)))) ;FIXME
776                (do-eql-vars (var (var gen))
777                  (let ((con (find-or-create-constraint 'typep var atype nil)))
778                    (conset-adjoin con gen))))))))
779       (cset
780        (binding* ((var (set-var node))
781                   (nil (lambda-var-p var) :exit-if-null)
782                   (cons (lambda-var-constraints var) :exit-if-null))
783          (conset-difference gen cons)
784          (let* ((type (single-value-type (node-derived-type node)))
785                 (con (find-or-create-constraint 'typep var type nil)))
786            (conset-adjoin con gen))
787          (maybe-add-eql-var-var-constraint var (set-value node) gen)))))
788   gen)
789
790 (defun constraint-propagate-if (block gen)
791   (let ((node (block-last block)))
792     (when (if-p node)
793       (let ((use (lvar-uses (if-test node))))
794         (when (node-p use)
795           (add-test-constraints use node gen))))))
796
797 ;;; Starting from IN compute OUT and (consequent/alternative
798 ;;; constraints if the block ends with and IF). Return the list of
799 ;;; successors that may need to be recomputed.
800 (defun find-block-type-constraints (block final-pass-p)
801   (declare (type cblock block))
802   (let ((gen (constraint-propagate-in-block
803               block
804               (if final-pass-p
805                   (block-in block)
806                   (copy-conset (block-in block)))
807               final-pass-p)))
808     (setf (block-gen block) gen)
809     (multiple-value-bind (consequent-constraints alternative-constraints)
810         (constraint-propagate-if block gen)
811       (if consequent-constraints
812           (let* ((node (block-last block))
813                  (old-consequent-constraints (if-consequent-constraints node))
814                  (old-alternative-constraints (if-alternative-constraints node))
815                  (succ ()))
816             ;; Add the consequent and alternative constraints to GEN.
817             (cond ((conset-empty consequent-constraints)
818                    (setf (if-consequent-constraints node) gen)
819                    (setf (if-alternative-constraints node) gen))
820                   (t
821                    (setf (if-consequent-constraints node) (copy-conset gen))
822                    (conset-union (if-consequent-constraints node)
823                                  consequent-constraints)
824                    (setf (if-alternative-constraints node) gen)
825                    (conset-union (if-alternative-constraints node)
826                                  alternative-constraints)))
827             ;; Has the consequent been changed?
828             (unless (and old-consequent-constraints
829                          (conset= (if-consequent-constraints node)
830                                   old-consequent-constraints))
831               (push (if-consequent node) succ))
832             ;; Has the alternative been changed?
833             (unless (and old-alternative-constraints
834                          (conset= (if-alternative-constraints node)
835                                   old-alternative-constraints))
836               (push (if-alternative node) succ))
837             succ)
838           ;; There is no IF.
839           (unless (and (block-out block)
840                        (conset= gen (block-out block)))
841             (setf (block-out block) gen)
842             (block-succ block))))))
843
844 ;;; Deliver the results of constraint propagation to REFs in BLOCK.
845 ;;; During this pass, we also do local constraint propagation by
846 ;;; adding in constraints as we see them during the pass through the
847 ;;; block.
848 (defun use-result-constraints (block)
849   (declare (type cblock block))
850   (constraint-propagate-in-block block (block-in block) t))
851
852 ;;; Give an empty constraints set to any var that doesn't have one and
853 ;;; isn't a set closure var. Since a var that we previously rejected
854 ;;; looks identical to one that is new, so we optimistically keep
855 ;;; hoping that vars stop being closed over or lose their sets.
856 (defun init-var-constraints (component)
857   (declare (type component component))
858   (dolist (fun (component-lambdas component))
859     (flet ((frob (x)
860              (dolist (var (lambda-vars x))
861                (unless (lambda-var-constraints var)
862                  (when (or (null (lambda-var-sets var))
863                            (not (closure-var-p var)))
864                    (setf (lambda-var-constraints var) (make-conset)))))))
865       (frob fun)
866       (dolist (let (lambda-lets fun))
867         (frob let)))))
868
869 ;;; Return the constraints that flow from PRED to SUCC. This is
870 ;;; BLOCK-OUT unless PRED ends with an IF and test constraints were
871 ;;; added.
872 (defun block-out-for-successor (pred succ)
873   (declare (type cblock pred succ))
874   (let ((last (block-last pred)))
875     (or (when (if-p last)
876           (cond ((eq succ (if-consequent last))
877                  (if-consequent-constraints last))
878                 ((eq succ (if-alternative last))
879                  (if-alternative-constraints last))))
880         (block-out pred))))
881
882 (defun compute-block-in (block)
883   (let ((in nil))
884     (dolist (pred (block-pred block))
885       ;; If OUT has not been calculated, assume it to be the universal
886       ;; set.
887       (let ((out (block-out-for-successor pred block)))
888         (when out
889           (if in
890               (conset-intersection in out)
891               (setq in (copy-conset out))))))
892     (or in (make-conset))))
893
894 (defun update-block-in (block)
895   (let ((in (compute-block-in block)))
896     (cond ((and (block-in block) (conset= in (block-in block)))
897            nil)
898           (t
899            (setf (block-in block) in)))))
900
901 ;;; Return two lists: one of blocks that precede all loops and
902 ;;; therefore require only one constraint propagation pass and the
903 ;;; rest. This implementation does not find all such blocks.
904 ;;;
905 ;;; A more complete implementation would be:
906 ;;;
907 ;;;     (do-blocks (block component)
908 ;;;       (if (every #'(lambda (pred)
909 ;;;                      (or (member pred leading-blocks)
910 ;;;                          (eq pred head)))
911 ;;;                  (block-pred block))
912 ;;;           (push block leading-blocks)
913 ;;;           (push block rest-of-blocks)))
914 ;;;
915 ;;; Trailing blocks that succeed all loops could be found and handled
916 ;;; similarly. In practice though, these more complex solutions are
917 ;;; slightly worse performancewise.
918 (defun leading-component-blocks (component)
919   (declare (type component component))
920   (flet ((loopy-p (block)
921            (let ((n (block-number block)))
922              (dolist (pred (block-pred block))
923                (unless (< n (block-number pred))
924                  (return t))))))
925     (let ((leading-blocks ())
926           (rest-of-blocks ())
927           (seen-loop-p ()))
928       (do-blocks (block component)
929         (when (and (not seen-loop-p) (loopy-p block))
930           (setq seen-loop-p t))
931         (if seen-loop-p
932             (push block rest-of-blocks)
933             (push block leading-blocks)))
934       (values (nreverse leading-blocks) (nreverse rest-of-blocks)))))
935
936 ;;; Append OBJ to the end of LIST as if by NCONC but only if it is not
937 ;;; a member already.
938 (defun nconc-new (obj list)
939   (do ((x list (cdr x))
940        (prev nil x))
941       ((endp x) (if prev
942                     (progn
943                       (setf (cdr prev) (list obj))
944                       list)
945                     (list obj)))
946     (when (eql (car x) obj)
947       (return-from nconc-new list))))
948
949 (defun find-and-propagate-constraints (component)
950   (let ((blocks-to-process ()))
951     (flet ((enqueue (blocks)
952              (dolist (block blocks)
953                (setq blocks-to-process (nconc-new block blocks-to-process)))))
954       (multiple-value-bind (leading-blocks rest-of-blocks)
955           (leading-component-blocks component)
956         ;; Update every block once to account for changes in the
957         ;; IR1. The constraints of the lead blocks cannot be changed
958         ;; after the first pass so we might as well use them and skip
959         ;; USE-RESULT-CONSTRAINTS later.
960         (dolist (block leading-blocks)
961           (setf (block-in block) (compute-block-in block))
962           (find-block-type-constraints block t))
963         (setq blocks-to-process (copy-list rest-of-blocks))
964         ;; The rest of the blocks.
965         (dolist (block rest-of-blocks)
966           (aver (eq block (pop blocks-to-process)))
967           (setf (block-in block) (compute-block-in block))
968           (enqueue (find-block-type-constraints block nil)))
969         ;; Propagate constraints
970         (loop for block = (pop blocks-to-process)
971               while block do
972               (unless (eq block (component-tail component))
973                 (when (update-block-in block)
974                   (enqueue (find-block-type-constraints block nil)))))
975         rest-of-blocks))))
976
977 (defun constraint-propagate (component)
978   (declare (type component component))
979   (init-var-constraints component)
980
981   (unless (block-out (component-head component))
982     (setf (block-out (component-head component)) (make-conset)))
983
984   (dolist (block (find-and-propagate-constraints component))
985     (unless (block-delete-p block)
986       (use-result-constraints block)))
987
988   (values))