Boxed foreign prim

Simon Marlow marlowsd at gmail.com
Tue Mar 13 09:57:52 CET 2012


On 12/03/2012 14:22, Edward Kmett wrote:
> On Mon, Mar 12, 2012 at 6:45 AM, Simon Marlow <marlowsd at gmail.com
> <mailto:marlowsd at gmail.com>> wrote:
>
>         But I can only pass unboxed types to foreign prim.
>
>         Is this an intrinsic limitation or just an artifact of the use cases
>         that have presented themselves to date?
>
>
>     It's an intrinsic limitation - the I# box is handled entirely at the
>     Haskell level, primitives only deal with primitive types.
>
>
> Ah. I was reasoning by comparison to atomicModifyMutVar#, which deals
> with unboxed polymorphic types, and even lies with a too general return
> type. Though the result there is returned in an unboxed tuple, the
> argument is passed unboxed.
>
> Is that implemented specially?

I'm a little bit confused.

atomicModifyMutVar#
    :: MutVar# s a -> (a -> b) -> State# s -> (# State# s, c #)

Is the "unboxed polymorphic type" you're referring to the "MutVar# s a"? 
  Perhaps the confusion is around the term "unboxed" - we normally say 
that MutVar# is "unlifted" (no _|_), but it is not "unboxed" because its 
representation is a pointer to a heap object.

>     But anyway, I suspect your first definition of unsafeIndex will be
>     faster than the one using foreign import prim, because calling
>     out-of-line to do the indexing is slow.
>
>
> Sure though, I suppose that balance of may shift as the side of the
> short vector grows. (e.g. with Johan it'd probably be 16 items).
>
>     Also pseq is slow - use seq instead.
>
>
> Of course. I was being paranoid at the time and trying to get it to work
> at all. ;)
>
>     what you really want is built-in support for unsafeField#, which is
>     certainly do-able.  It's very similar to dataToTag# in the way that
>     the argument is required to be evaluated - this is the main
>     fragility, unfortunately GHC doesn't have a way to talk about things
>     that are unlifted (except for the primitive unlifted types).  But it
>     just about works if you make sure there's a seq in the right place.
>
>
> I'd be happy even if I had to seq the argument myself before applying
> it, as I was trying above.

The problem is, that can't be done reliably.  For dataToTag# the 
compiler automatically inserts the seq just before code generation if it 
can't prove that the argument is already evaluated, I think we would 
want to do the same thing for unsafeField#.

See CorePrep.saturateDataToTag in the GHC sources.

Cheers,
	Simon



More information about the Glasgow-haskell-users mailing list