1 ;;;; optimizers for list and sequence functions
3 ;;;; This software is part of the SBCL system. See the README file for
6 ;;;; This software is derived from the CMU CL system, which was
7 ;;;; written at Carnegie Mellon University and released into the
8 ;;;; public domain. The software is in the public domain and is
9 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
10 ;;;; files for more information.
14 ;;;; mapping onto lists: the MAPFOO functions
16 (defun mapfoo-transform (fn arglists accumulate take-car)
17 (collect ((do-clauses)
20 (let ((n-first (gensym)))
21 (dolist (a (if accumulate
23 `(,n-first ,@(rest arglists))))
25 (do-clauses `(,v ,a (cdr ,v)))
27 (args-to-fn (if take-car `(car ,v) v))))
29 (let* ((fn-sym (gensym)) ; for ONCE-ONLY-ish purposes
30 (call `(funcall ,fn-sym . ,(args-to-fn)))
31 (endtest `(or ,@(tests))))
35 (map-result (gensym)))
37 (,map-result (list nil)))
38 (do-anonymous ((,temp ,map-result) . ,(do-clauses))
39 (,endtest (cdr ,map-result))
40 (setq ,temp (last (nconc ,temp ,call)))))))
43 (map-result (gensym)))
45 (,map-result (list nil)))
46 (do-anonymous ((,temp ,map-result) . ,(do-clauses))
47 (,endtest (cdr ,map-result))
48 (rplacd ,temp (setq ,temp (list ,call)))))))
51 (,n-first ,(first arglists)))
52 (do-anonymous ,(do-clauses)
53 (,endtest ,n-first) ,call))))))))
55 (define-source-transform mapc (function list &rest more-lists)
56 (mapfoo-transform function (cons list more-lists) nil t))
58 (define-source-transform mapcar (function list &rest more-lists)
59 (mapfoo-transform function (cons list more-lists) :list t))
61 (define-source-transform mapcan (function list &rest more-lists)
62 (mapfoo-transform function (cons list more-lists) :nconc t))
64 (define-source-transform mapl (function list &rest more-lists)
65 (mapfoo-transform function (cons list more-lists) nil nil))
67 (define-source-transform maplist (function list &rest more-lists)
68 (mapfoo-transform function (cons list more-lists) :list nil))
70 (define-source-transform mapcon (function list &rest more-lists)
71 (mapfoo-transform function (cons list more-lists) :nconc nil))
73 ;;;; mapping onto sequences: the MAP function
75 ;;; MAP is %MAP plus a check to make sure that any length specified in
76 ;;; the result type matches the actual result. We also wrap it in a
77 ;;; TRULY-THE for the most specific type we can determine.
78 (deftransform map ((result-type-arg fun &rest seqs) * * :node node)
79 (let* ((seq-names (make-gensym-list (length seqs)))
80 (bare `(%map result-type-arg fun ,@seq-names))
81 (constant-result-type-arg-p (constant-continuation-p result-type-arg))
82 ;; what we know about the type of the result. (Note that the
83 ;; "result type" argument is not necessarily the type of the
84 ;; result, since NIL means the result has NULL type.)
85 (result-type (if (not constant-result-type-arg-p)
87 (let ((result-type-arg-value
88 (continuation-value result-type-arg)))
89 (if (null result-type-arg-value)
91 result-type-arg-value)))))
92 `(lambda (result-type-arg fun ,@seq-names)
93 (truly-the ,result-type
94 ,(cond ((policy node (< safety 3))
95 ;; ANSI requires the length-related type check only
96 ;; when the SAFETY quality is 3... in other cases, we
97 ;; skip it, because it could be expensive.
99 ((not constant-result-type-arg-p)
100 `(sequence-of-checked-length-given-type ,bare
103 (let ((result-ctype (ir1-transform-specifier-type
105 (if (array-type-p result-ctype)
106 (let ((dims (array-type-dimensions result-ctype)))
107 (unless (and (listp dims) (= (length dims) 1))
108 (give-up-ir1-transform "invalid sequence type"))
109 (let ((dim (first dims)))
112 `(vector-of-checked-length-given-length ,bare
114 ;; FIXME: this is wrong, as not all subtypes of
115 ;; VECTOR are ARRAY-TYPEs [consider, for
116 ;; example, (OR (VECTOR T 3) (VECTOR T
117 ;; 4))]. However, it's difficult to see what we
118 ;; should put here... maybe we should
119 ;; GIVE-UP-IR1-TRANSFORM if the type is a
120 ;; subtype of VECTOR but not an ARRAY-TYPE?
123 ;;; Try to compile %MAP efficiently when we can determine sequence
124 ;;; argument types at compile time.
126 ;;; Note: This transform was written to allow open coding of
127 ;;; quantifiers by expressing them in terms of (MAP NIL ..). For
128 ;;; non-NIL values of RESULT-TYPE, it's still useful, but not
129 ;;; necessarily as efficient as possible. In particular, it will be
130 ;;; inefficient when RESULT-TYPE is a SIMPLE-ARRAY with specialized
131 ;;; numeric element types. It should be straightforward to make it
132 ;;; handle that case more efficiently, but it's left as an exercise to
133 ;;; the reader, because the code is complicated enough already and I
134 ;;; don't happen to need that functionality right now. -- WHN 20000410
135 (deftransform %map ((result-type fun &rest seqs) * * :policy (>= speed space))
137 (unless seqs (abort-ir1-transform "no sequence args"))
138 (unless (constant-continuation-p result-type)
139 (give-up-ir1-transform "RESULT-TYPE argument not constant"))
140 (labels (;; 1-valued SUBTYPEP, fails unless second value of SUBTYPEP is true
141 (fn-1subtypep (fn x y)
142 (multiple-value-bind (subtype-p valid-p) (funcall fn x y)
145 (give-up-ir1-transform
146 "can't analyze sequence type relationship"))))
147 (1subtypep (x y) (fn-1subtypep #'sb!xc:subtypep x y))
148 (1csubtypep (x y) (fn-1subtypep #'csubtypep x y))
150 (let ((ctype (continuation-type seq)))
151 (cond ((1csubtypep ctype (specifier-type 'vector)) 'vector)
152 ((1csubtypep ctype (specifier-type 'list)) 'list)
154 (give-up-ir1-transform
155 "can't determine sequence argument type"))))))
156 (let* ((result-type-value (continuation-value result-type))
157 (result-supertype (cond ((null result-type-value) 'null)
158 ((1subtypep result-type-value 'vector)
160 ((1subtypep result-type-value 'list)
163 (give-up-ir1-transform
164 "can't determine result type"))))
165 (seq-supertypes (mapcar #'seq-supertype seqs)))
166 (cond ((and result-type-value (= 1 (length seqs)))
167 ;; The consing arity-1 cases can be implemented
168 ;; reasonably efficiently as function calls, and the cost
169 ;; of consing should be significantly larger than
170 ;; function call overhead, so we always compile these
171 ;; cases as full calls regardless of speed-versus-space
172 ;; optimization policy.
173 (cond ((subtypep 'list result-type-value)
174 '(apply #'%map-to-list-arity-1 fun seqs))
175 (;; (This one can be inefficient due to COERCE, but
176 ;; the current open-coded implementation has the
178 (subtypep result-type-value 'vector)
179 `(coerce (apply #'%map-to-simple-vector-arity-1 fun seqs)
180 ',result-type-value))
181 (t (bug "impossible (?) sequence type"))))
183 (let* ((seq-args (make-gensym-list (length seqs)))
185 (mapcar (lambda (seq-arg seq-supertype)
186 (let ((i (gensym "I")))
188 (vector `(,i 0 (1+ ,i)))
189 (list `(,i ,seq-arg (rest ,i))))))
190 seq-args seq-supertypes))
191 (indices (mapcar #'first index-bindingoids))
192 (index-decls (mapcar (lambda (index seq-supertype)
193 `(type ,(ecase seq-supertype
197 indices seq-supertypes))
198 (tests (mapcar (lambda (seq-arg seq-supertype index)
200 (vector `(>= ,index (length ,seq-arg)))
201 (list `(endp ,index))))
202 seq-args seq-supertypes indices))
203 (values (mapcar (lambda (seq-arg seq-supertype index)
205 (vector `(aref ,seq-arg ,index))
206 (list `(first ,index))))
207 seq-args seq-supertypes indices)))
208 (multiple-value-bind (push-dacc final-result)
209 (ecase result-supertype
210 (null (values nil nil))
211 (list (values `(push dacc acc) `(nreverse acc)))
212 (vector (values `(push dacc acc)
213 `(coerce (nreverse acc)
214 ',result-type-value))))
215 ;; (We use the same idiom, of returning a LAMBDA from
216 ;; DEFTRANSFORM, as is used in the DEFTRANSFORMs for
217 ;; FUNCALL and ALIEN-FUNCALL, and for the same
218 ;; reason: we need to get the runtime values of each
219 ;; of the &REST vars.)
220 `(lambda (result-type fun ,@seq-args)
221 (declare (ignore result-type))
222 (do ((really-fun (%coerce-callable-to-fun fun))
227 (declare ,@index-decls)
228 (declare (type list acc))
229 (declare (ignorable acc))
230 (let ((dacc (funcall really-fun ,@values)))
231 (declare (ignorable dacc))
234 ;;; FIXME: once the confusion over doing transforms with known-complex
235 ;;; arrays is over, we should also transform the calls to (AND (ARRAY
236 ;;; * (*)) (NOT (SIMPLE-ARRAY * (*)))) objects.
237 (deftransform elt ((s i) ((simple-array * (*)) *) *)
240 (deftransform elt ((s i) (list *) * :policy (< safety 3))
243 (deftransform %setelt ((s i v) ((simple-array * (*)) * *) *)
246 (deftransform %setelt ((s i v) (list * *) * :policy (< safety 3))
247 '(setf (car (nthcdr i s)) v))
249 (deftransform %check-vector-sequence-bounds ((vector start end)
252 (if (policy node (< safety speed))
253 '(or end (length vector))
254 '(let ((length (length vector)))
255 (if (<= 0 start (or end length) length)
257 (sb!impl::signal-bounding-indices-bad-error vector start end)))))
259 (macrolet ((def (name)
260 `(deftransform ,name ((e l &key (test #'eql)) * *
262 (unless (constant-continuation-p l)
263 (give-up-ir1-transform))
265 (let ((val (continuation-value l)))
268 (and (>= speed space)
269 (<= (length val) 5))))
270 (give-up-ir1-transform))
274 `(if (funcall test e ',(car els))
282 ;;; FIXME: We have rewritten the original code that used DOLIST to this
283 ;;; more natural MACROLET. However, the original code suggested that when
284 ;;; this was done, a few bytes could be saved by a call to a shared
285 ;;; function. This remains to be done.
286 (macrolet ((def (fun eq-fun)
287 `(deftransform ,fun ((item list &key test) (t list &rest t) *)
289 ;; FIXME: The scope of this transformation could be
290 ;; widened somewhat, letting it work whenever the test is
291 ;; 'EQL and we know from the type of ITEM that it #'EQ
292 ;; works like #'EQL on it. (E.g. types FIXNUM, CHARACTER,
294 ;; If TEST is EQ, apply transform, else
295 ;; if test is not EQL, then give up on transform, else
296 ;; if ITEM is not a NUMBER or is a FIXNUM, apply
297 ;; transform, else give up on transform.
299 (unless (continuation-fun-is test '(eq))
300 (give-up-ir1-transform)))
301 ((types-equal-or-intersect (continuation-type item)
302 (specifier-type 'number))
303 (give-up-ir1-transform "Item might be a number.")))
304 `(,',eq-fun item list))))
309 (deftransform delete-if ((pred list) (t list))
311 '(do ((x list (cdr x))
314 (cond ((funcall pred (car x))
317 (rplacd splice (cdr x))))
318 (T (setq splice x)))))
320 (deftransform fill ((seq item &key (start 0) (end (length seq)))
321 (vector t &key (:start t) (:end index))
323 :policy (> speed space))
325 (let ((element-type (upgraded-element-type-specifier-or-give-up seq)))
327 `(with-array-data ((data seq)
330 (declare (type (simple-array ,element-type 1) data))
331 (declare (type fixnum start end))
332 (do ((i start (1+ i)))
334 (declare (type index i))
335 ;; WITH-ARRAY-DATA did our range checks once and for all, so
336 ;; it'd be wasteful to check again on every AREF...
337 (declare (optimize (safety 0)))
338 (setf (aref data i) item)))
339 ;; ... though we still need to check that the new element can fit
340 ;; into the vector in safe code. -- CSR, 2002-07-05
341 `((declare (type ,element-type item))))))
345 ;;; Return true if CONT's only use is a non-NOTINLINE reference to a
346 ;;; global function with one of the specified NAMES.
347 (defun continuation-fun-is (cont names)
348 (declare (type continuation cont) (list names))
349 (let ((use (continuation-use cont)))
351 (let ((leaf (ref-leaf use)))
352 (and (global-var-p leaf)
353 (eq (global-var-kind leaf) :global-function)
354 (not (null (member (leaf-source-name leaf) names
355 :test #'equal))))))))
357 ;;; If CONT is a constant continuation, the return the constant value.
358 ;;; If it is null, then return default, otherwise quietly give up the
361 ;;; ### Probably should take an ARG and flame using the NAME.
362 (defun constant-value-or-lose (cont &optional default)
363 (declare (type (or continuation null) cont))
364 (cond ((not cont) default)
365 ((constant-continuation-p cont)
366 (continuation-value cont))
368 (give-up-ir1-transform))))
370 ;;; FIXME: Why is this code commented out? (Why *was* it commented
371 ;;; out? We inherited this situation from cmucl-2.4.8, with no
372 ;;; explanation.) Should we just delete this code?
374 ;;; This is a frob whose job it is to make it easier to pass around
375 ;;; the arguments to IR1 transforms. It bundles together the name of
376 ;;; the argument (which should be referenced in any expansion), and
377 ;;; the continuation for that argument (or NIL if unsupplied.)
378 (defstruct (arg (:constructor %make-arg (name cont))
380 (name nil :type symbol)
381 (cont nil :type (or continuation null)))
382 (defmacro make-arg (name)
383 `(%make-arg ',name ,name))
385 ;;; If Arg is null or its CONT is null, then return Default, otherwise
386 ;;; return Arg's NAME.
387 (defun default-arg (arg default)
388 (declare (type (or arg null) arg))
389 (if (and arg (arg-cont arg))
393 ;;; If Arg is null or has no CONT, return the default. Otherwise, Arg's
394 ;;; CONT must be a constant continuation whose value we return. If not, we
396 (defun arg-constant-value (arg default)
397 (declare (type (or arg null) arg))
398 (if (and arg (arg-cont arg))
399 (let ((cont (arg-cont arg)))
400 (unless (constant-continuation-p cont)
401 (give-up-ir1-transform "Argument is not constant: ~S."
403 (continuation-value from-end))
406 ;;; If Arg is a constant and is EQL to X, then return T, otherwise NIL. If
407 ;;; Arg is NIL or its CONT is NIL, then compare to the default.
408 (defun arg-eql (arg default x)
409 (declare (type (or arg null) x))
410 (if (and arg (arg-cont arg))
411 (let ((cont (arg-cont arg)))
412 (and (constant-continuation-p cont)
413 (eql (continuation-value cont) x)))
416 (defstruct (iterator (:copier nil))
417 ;; The kind of iterator.
418 (kind nil (member :normal :result))
419 ;; A list of LET* bindings to create the initial state.
420 (binds nil :type list)
421 ;; A list of declarations for Binds.
422 (decls nil :type list)
423 ;; A form that returns the current value. This may be set with SETF to set
424 ;; the current value.
425 (current (error "Must specify CURRENT."))
426 ;; In a :NORMAL iterator, a form that tests whether there is a current value.
428 ;; In a :RESULT iterator, a form that truncates the result at the current
429 ;; position and returns it.
431 ;; A form that returns the initial total number of values. The result is
432 ;; undefined after NEXT has been evaluated.
433 (length (error "Must specify LENGTH."))
434 ;; A form that advances the state to the next value. It is an error to call
435 ;; this when the iterator is Done.
436 (next (error "Must specify NEXT.")))
438 ;;; Type of an index var that can go negative (in the from-end case.)
439 (deftype neg-index ()
440 `(integer -1 ,most-positive-fixnum))
442 ;;; Return an ITERATOR structure describing how to iterate over an arbitrary
443 ;;; sequence. Sequence is a variable bound to the sequence, and Type is the
444 ;;; type of the sequence. If true, INDEX is a variable that should be bound to
445 ;;; the index of the current element in the sequence.
447 ;;; If we can't tell whether the sequence is a list or a vector, or whether
448 ;;; the iteration is forward or backward, then GIVE-UP.
449 (defun make-sequence-iterator (sequence type &key start end from-end index)
450 (declare (symbol sequence) (type ctype type)
451 (type (or arg null) start end from-end)
452 (type (or symbol null) index))
453 (let ((from-end (arg-constant-value from-end nil)))
454 (cond ((csubtypep type (specifier-type 'vector))
455 (let* ((n-stop (gensym))
456 (n-idx (or index (gensym)))
457 (start (default-arg 0 start))
458 (end (default-arg `(length ,sequence) end)))
461 :binds `((,n-idx ,(if from-end `(1- ,end) ,start))
462 (,n-stop ,(if from-end `(1- ,start) ,end)))
463 :decls `((type neg-index ,n-idx ,n-stop))
464 :current `(aref ,sequence ,n-idx)
465 :done `(,(if from-end '<= '>=) ,n-idx ,n-stop)
467 ,(if from-end `(1- ,n-idx) `(1+ ,n-idx)))
470 `(- ,n-stop ,n-idx)))))
471 ((csubtypep type (specifier-type 'list))
472 (let* ((n-stop (if (and end (not from-end)) (gensym) nil))
474 (start-p (not (arg-eql start 0 0)))
475 (end-p (not (arg-eql end nil nil)))
476 (start (default-arg start 0))
477 (end (default-arg end nil)))
481 (if (or start-p end-p)
482 `(nreverse (subseq ,sequence ,start
483 ,@(when end `(,end))))
484 `(reverse ,sequence))
486 `(nthcdr ,start ,sequence)
489 `((,n-stop (nthcdr (the index
493 `((,index ,(if from-end `(1- ,end) start)))))
495 :decls `((list ,n-current ,n-end)
496 ,@(when index `((type neg-index ,index))))
497 :current `(car ,n-current)
498 :done `(eq ,n-current ,n-stop)
499 :length `(- ,(or end `(length ,sequence)) ,start)
501 (setq ,n-current (cdr ,n-current))
508 (give-up-ir1-transform
509 "can't tell whether sequence is a list or a vector")))))
511 ;;; Make an iterator used for constructing result sequences. Name is a
512 ;;; variable to be bound to the result sequence. Type is the type of result
513 ;;; sequence to make. Length is an expression to be evaluated to get the
514 ;;; maximum length of the result (not evaluated in list case.)
515 (defun make-result-sequence-iterator (name type length)
516 (declare (symbol name) (type ctype type))
518 ;;; Define each NAME as a local macro that will call the value of the
519 ;;; function arg with the given arguments. If the argument isn't known to be a
520 ;;; function, give them an efficiency note and reference a coerced version.
521 (defmacro coerce-funs (specs &body body)
523 "COERCE-FUNCTIONS ({(Name Fun-Arg Default)}*) Form*"
527 `(let ((body (progn ,@body))
528 (n-fun (arg-name ,(second spec)))
529 (fun-cont (arg-cont ,(second spec))))
530 (cond ((not fun-cont)
531 `(macrolet ((,',(first spec) (&rest args)
532 `(,',',(third spec) ,@args)))
534 ((not (csubtypep (continuation-type fun-cont)
535 (specifier-type 'function)))
536 (when (policy *compiler-error-context*
537 (> speed inhibit-warnings))
539 "~S may not be a function, so must coerce at run-time."
541 (once-only ((n-fun `(if (functionp ,n-fun)
543 (symbol-function ,n-fun))))
544 `(macrolet ((,',(first spec) (&rest args)
545 `(funcall ,',n-fun ,@args)))
548 `(macrolet ((,',(first spec) (&rest args)
549 `(funcall ,',n-fun ,@args)))
552 ;;; Wrap code around the result of the body to define Name as a local macro
553 ;;; that returns true when its arguments satisfy the test according to the Args
554 ;;; Test and Test-Not. If both Test and Test-Not are supplied, abort the
556 (defmacro with-sequence-test ((name test test-not) &body body)
557 `(let ((not-p (arg-cont ,test-not)))
558 (when (and (arg-cont ,test) not-p)
559 (abort-ir1-transform "Both ~S and ~S were supplied."
561 (arg-name ,test-not)))
562 (coerce-funs ((,name (if not-p ,test-not ,test) eql))
566 ;;;; hairy sequence transforms
568 ;;; FIXME: no hairy sequence transforms in SBCL?
570 ;;;; string operations
572 ;;; We transform the case-sensitive string predicates into a non-keyword
573 ;;; version. This is an IR1 transform so that we don't have to worry about
574 ;;; changing the order of evaluation.
575 (macrolet ((def (fun pred*)
576 `(deftransform ,fun ((string1 string2 &key (start1 0) end1
579 `(,',pred* string1 string2 start1 end1 start2 end2))))
580 (def string< string<*)
581 (def string> string>*)
582 (def string<= string<=*)
583 (def string>= string>=*)
584 (def string= string=*)
585 (def string/= string/=*))
587 ;;; Return a form that tests the free variables STRING1 and STRING2
588 ;;; for the ordering relationship specified by LESSP and EQUALP. The
589 ;;; start and end are also gotten from the environment. Both strings
590 ;;; must be SIMPLE-STRINGs.
591 (macrolet ((def (name lessp equalp)
592 `(deftransform ,name ((string1 string2 start1 end1 start2 end2)
593 (simple-string simple-string t t t t) *)
594 `(let* ((end1 (if (not end1) (length string1) end1))
595 (end2 (if (not end2) (length string2) end2))
596 (index (sb!impl::%sp-string-compare
597 string1 start1 end1 string2 start2 end2)))
599 (cond ((= index ,(if ',lessp 'end1 'end2)) index)
600 ((= index ,(if ',lessp 'end2 'end1)) nil)
601 ((,(if ',lessp 'char< 'char>)
602 (schar string1 index)
611 ,(if ',equalp 'end1 nil))))))
614 (def string>* nil nil)
615 (def string>=* nil t))
617 (macrolet ((def (name result-fun)
618 `(deftransform ,name ((string1 string2 start1 end1 start2 end2)
619 (simple-string simple-string t t t t) *)
621 (sb!impl::%sp-string-compare
622 string1 start1 (or end1 (length string1))
623 string2 start2 (or end2 (length string2)))))))
625 (def string/=* identity))
628 ;;;; string-only transforms for sequence functions
630 ;;;; Note: CMU CL had more of these, including transforms for
631 ;;;; functions which cons. In SBCL, we've gotten rid of most of the
632 ;;;; transforms for functions which cons, since our GC overhead is
633 ;;;; sufficiently large that it doesn't seem worth it to try to
634 ;;;; economize on function call overhead or on the overhead of runtime
635 ;;;; type dispatch in AREF. The exception is CONCATENATE, since
636 ;;;; a full call to CONCATENATE would have to look up the sequence
637 ;;;; type, which can be really slow.
639 ;;;; FIXME: It would be nicer for these transforms to work for any
640 ;;;; calls when all arguments are vectors with the same element type,
641 ;;;; rather than restricting them to STRINGs only.
643 ;;; Moved here from generic/vm-tran.lisp to satisfy clisp
645 ;;; FIXME: Add a comment telling whether this holds for all vectors
646 ;;; or only for vectors based on simple arrays (non-adjustable, etc.).
647 (def!constant vector-data-bit-offset
648 (* sb!vm:vector-data-offset sb!vm:n-word-bits))
650 (deftransform replace ((string1 string2 &key (start1 0) (start2 0)
652 (simple-string simple-string &rest t)
654 ;; FIXME: consider replacing this policy test
655 ;; with some tests for the STARTx and ENDx
656 ;; indices being valid, conditional on high
659 ;; FIXME: It turns out that this transform is
660 ;; critical for the performance of string
661 ;; streams. Make this more explicit.
662 :policy (< (max safety space) 3))
664 (declare (optimize (safety 0)))
665 (bit-bash-copy string2
667 (+ (the index (* start2 sb!vm:n-byte-bits))
668 ,vector-data-bit-offset))
671 (+ (the index (* start1 sb!vm:n-byte-bits))
672 ,vector-data-bit-offset))
674 (* (min (the index (- (or end1 (length string1))
676 (the index (- (or end2 (length string2))
681 ;;; FIXME: It seems as though it should be possible to make a DEFUN
682 ;;; %CONCATENATE (with a DEFTRANSFORM to translate constant RTYPE to
683 ;;; CTYPE before calling %CONCATENATE) which is comparably efficient,
684 ;;; at least once DYNAMIC-EXTENT works.
686 ;;; FIXME: currently KLUDGEed because of bug 188
687 (deftransform concatenate ((rtype &rest sequences)
688 (t &rest simple-string)
690 :policy (< safety 3))
695 (dolist (seq sequences)
696 (declare (ignorable seq))
697 (let ((n-seq (gensym))
700 (lets `(,n-length (the index (* (length ,n-seq) sb!vm:n-byte-bits))))
701 (all-lengths n-length)
702 (forms `(bit-bash-copy ,n-seq ,vector-data-bit-offset
705 (forms `(setq start (opaque-identity (+ start ,n-length))))))
706 `(lambda (rtype ,@(args))
707 (declare (ignore rtype))
709 (flet ((opaque-identity (x) x))
710 (declare (notinline opaque-identity))
712 (res (make-string (truncate (the index (+ ,@(all-lengths)))
714 (start ,vector-data-bit-offset))
715 (declare (type index start ,@(all-lengths)))
719 ;;;; CONS accessor DERIVE-TYPE optimizers
721 (defoptimizer (car derive-type) ((cons))
722 (let ((type (continuation-type cons))
723 (null-type (specifier-type 'null)))
724 (cond ((eq type null-type)
727 (cons-type-car-type type)))))
729 (defoptimizer (cdr derive-type) ((cons))
730 (let ((type (continuation-type cons))
731 (null-type (specifier-type 'null)))
732 (cond ((eq type null-type)
735 (cons-type-cdr-type type)))))
737 ;;;; FIND, POSITION, and their -IF and -IF-NOT variants
739 ;;; We want to make sure that %FIND-POSITION is inline-expanded into
740 ;;; %FIND-POSITION-IF only when %FIND-POSITION-IF has an inline
741 ;;; expansion, so we factor out the condition into this function.
742 (defun check-inlineability-of-find-position-if (sequence from-end)
743 (let ((ctype (continuation-type sequence)))
744 (cond ((csubtypep ctype (specifier-type 'vector))
745 ;; It's not worth trying to inline vector code unless we
746 ;; know a fair amount about it at compile time.
747 (upgraded-element-type-specifier-or-give-up sequence)
748 (unless (constant-continuation-p from-end)
749 (give-up-ir1-transform
750 "FROM-END argument value not known at compile time")))
751 ((csubtypep ctype (specifier-type 'list))
752 ;; Inlining on lists is generally worthwhile.
755 (give-up-ir1-transform
756 "sequence type not known at compile time")))))
758 ;;; %FIND-POSITION-IF and %FIND-POSITION-IF-NOT for LIST data
759 (macrolet ((def (name condition)
760 `(deftransform ,name ((predicate sequence from-end start end key)
761 (function list t t t function)
763 :policy (> speed space)
769 (declare (type index index))
771 (if (and end (> end index))
772 (sb!impl::signal-bounding-indices-bad-error
774 (values find position)))
775 (let ((key-i (funcall key i)))
776 (when (and end (>= index end))
777 (return (values find position)))
778 (when (>= index start)
779 (,',condition (funcall predicate key-i)
780 ;; This hack of dealing with non-NIL
781 ;; FROM-END for list data by iterating
782 ;; forward through the list and keeping
783 ;; track of the last time we found a match
784 ;; might be more screwy than what the user
785 ;; expects, but it seems to be allowed by
786 ;; the ANSI standard. (And if the user is
787 ;; screwy enough to ask for FROM-END
788 ;; behavior on list data, turnabout is
791 ;; It's also not enormously efficient,
792 ;; calling PREDICATE and KEY more often
793 ;; than necessary; but all the
794 ;; alternatives seem to have their own
795 ;; efficiency problems.
799 (return (values i index))))))
801 (def %find-position-if when)
802 (def %find-position-if-not unless))
804 ;;; %FIND-POSITION for LIST data can be expanded into %FIND-POSITION-IF
805 ;;; without loss of efficiency. (I.e., the optimizer should be able
806 ;;; to straighten everything out.)
807 (deftransform %find-position ((item sequence from-end start end key test)
810 :policy (> speed space)
813 '(%find-position-if (let ((test-fun (%coerce-callable-to-fun test)))
814 ;; The order of arguments for asymmetric tests
815 ;; (e.g. #'<, as opposed to order-independent
816 ;; tests like #'=) is specified in the spec
817 ;; section 17.2.1 -- the O/Zi stuff there.
819 (funcall test-fun item i)))
824 (%coerce-callable-to-fun key)))
826 ;;; The inline expansions for the VECTOR case are saved as macros so
827 ;;; that we can share them between the DEFTRANSFORMs and the default
828 ;;; cases in the DEFUNs. (This isn't needed for the LIST case, because
829 ;;; the DEFTRANSFORMs for LIST are less choosy about when to expand.)
830 (defun %find-position-or-find-position-if-vector-expansion (sequence-arg
836 (let ((offset (gensym "OFFSET"))
837 (block (gensym "BLOCK"))
838 (index (gensym "INDEX"))
839 (n-sequence (gensym "N-SEQUENCE-"))
840 (sequence (gensym "SEQUENCE"))
841 (n-end (gensym "N-END-"))
842 (end (gensym "END-")))
843 `(let ((,n-sequence ,sequence-arg)
845 (with-array-data ((,sequence ,n-sequence :offset-var ,offset)
847 (,end (%check-vector-sequence-bounds
848 ,n-sequence ,start ,n-end)))
850 (macrolet ((maybe-return ()
851 '(let ((,element (aref ,sequence ,index)))
855 (- ,index ,offset)))))))
858 ;; (If we aren't fastidious about declaring that
859 ;; INDEX might be -1, then (FIND 1 #() :FROM-END T)
860 ;; can send us off into never-never land, since
861 ;; INDEX is initialized to -1.)
862 of-type index-or-minus-1
863 from (1- ,end) downto ,start do
865 (loop for ,index of-type index from ,start below ,end do
867 (values nil nil))))))
869 (def!macro %find-position-vector-macro (item sequence
870 from-end start end key test)
871 (let ((element (gensym "ELEMENT")))
872 (%find-position-or-find-position-if-vector-expansion
878 ;; (See the LIST transform for a discussion of the correct
879 ;; argument order, i.e. whether the searched-for ,ITEM goes before
880 ;; or after the checked sequence element.)
881 `(funcall ,test ,item (funcall ,key ,element)))))
883 (def!macro %find-position-if-vector-macro (predicate sequence
884 from-end start end key)
885 (let ((element (gensym "ELEMENT")))
886 (%find-position-or-find-position-if-vector-expansion
892 `(funcall ,predicate (funcall ,key ,element)))))
894 (def!macro %find-position-if-not-vector-macro (predicate sequence
895 from-end start end key)
896 (let ((element (gensym "ELEMENT")))
897 (%find-position-or-find-position-if-vector-expansion
903 `(not (funcall ,predicate (funcall ,key ,element))))))
905 ;;; %FIND-POSITION, %FIND-POSITION-IF and %FIND-POSITION-IF-NOT for
907 (deftransform %find-position-if ((predicate sequence from-end start end key)
908 (function vector t t t function)
910 :policy (> speed space)
913 (check-inlineability-of-find-position-if sequence from-end)
914 '(%find-position-if-vector-macro predicate sequence
915 from-end start end key))
917 (deftransform %find-position-if-not ((predicate sequence from-end start end key)
918 (function vector t t t function)
920 :policy (> speed space)
923 (check-inlineability-of-find-position-if sequence from-end)
924 '(%find-position-if-not-vector-macro predicate sequence
925 from-end start end key))
927 (deftransform %find-position ((item sequence from-end start end key test)
928 (t vector t t t function function)
930 :policy (> speed space)
933 (check-inlineability-of-find-position-if sequence from-end)
934 '(%find-position-vector-macro item sequence
935 from-end start end key test))
937 ;;; logic to unravel :TEST, :TEST-NOT, and :KEY options in FIND,
938 ;;; POSITION-IF, etc.
939 (define-source-transform effective-find-position-test (test test-not)
940 (once-only ((test test)
943 ((and ,test ,test-not)
944 (error "can't specify both :TEST and :TEST-NOT"))
945 (,test (%coerce-callable-to-fun ,test))
947 ;; (Without DYNAMIC-EXTENT, this is potentially horribly
948 ;; inefficient, but since the TEST-NOT option is deprecated
949 ;; anyway, we don't care.)
950 (complement (%coerce-callable-to-fun ,test-not)))
952 (define-source-transform effective-find-position-key (key)
953 (once-only ((key key))
955 (%coerce-callable-to-fun ,key)
958 (macrolet ((define-find-position (fun-name values-index)
959 `(deftransform ,fun-name ((item sequence &key
960 from-end (start 0) end
962 '(nth-value ,values-index
963 (%find-position item sequence
966 (effective-find-position-key key)
967 (effective-find-position-test
969 (define-find-position find 0)
970 (define-find-position position 1))
972 (macrolet ((define-find-position-if (fun-name values-index)
973 `(deftransform ,fun-name ((predicate sequence &key
978 (%find-position-if (%coerce-callable-to-fun predicate)
981 (effective-find-position-key key))))))
982 (define-find-position-if find-if 0)
983 (define-find-position-if position-if 1))
985 ;;; the deprecated functions FIND-IF-NOT and POSITION-IF-NOT. We
986 ;;; didn't bother to worry about optimizing them, except note that on
987 ;;; Sat, Oct 06, 2001 at 04:22:38PM +0100, Christophe Rhodes wrote on
990 ;;; My understanding is that while the :test-not argument is
991 ;;; deprecated in favour of :test (complement #'foo) because of
992 ;;; semantic difficulties (what happens if both :test and :test-not
993 ;;; are supplied, etc) the -if-not variants, while officially
994 ;;; deprecated, would be undeprecated were X3J13 actually to produce
995 ;;; a revised standard, as there are perfectly legitimate idiomatic
996 ;;; reasons for allowing the -if-not versions equal status,
997 ;;; particularly remove-if-not (== filter).
999 ;;; This is only an informal understanding, I grant you, but
1000 ;;; perhaps it's worth optimizing the -if-not versions in the same
1001 ;;; way as the others?
1003 ;;; FIXME: Maybe remove uses of these deprecated functions (and
1004 ;;; definitely of :TEST-NOT) within the implementation of SBCL.
1005 (macrolet ((define-find-position-if-not (fun-name values-index)
1006 `(deftransform ,fun-name ((predicate sequence &key
1011 (%find-position-if-not (%coerce-callable-to-fun predicate)
1014 (effective-find-position-key key))))))
1015 (define-find-position-if-not find-if-not 0)
1016 (define-find-position-if-not position-if-not 1))