2 % (c) The University of Glasgow 2006
3 % (c) The AQUA Project, Glasgow University, 1994-1998
6 Desugaring foreign calls
17 #include "HsVersions.h"
47 Desugaring of @ccall@s consists of adding some state manipulation,
48 unboxing any boxed primitive arguments and boxing the result if
51 The state stuff just consists of adding in
52 @PrimIO (\ s -> case s of { S# s# -> ... })@ in an appropriate place.
54 The unboxing is straightforward, as all information needed to unbox is
55 available from the type. For each boxed-primitive argument, we
58 _ccall_ foo [ r, t1, ... tm ] e1 ... em
62 case e1 of { T1# x1# ->
64 case em of { Tm# xm# -> xm#
65 ccall# foo [ r, t1#, ... tm# ] x1# ... xm#
69 The reboxing of a @_ccall_@ result is a bit tricker: the types don't
70 contain information about the state-pairing functions so we have to
71 keep a list of \tr{(type, s-p-function)} pairs. We transform as
74 ccall# foo [ r, t1#, ... tm# ] e1# ... em#
78 \ s# -> case (ccall# foo [ r, t1#, ... tm# ] s# e1# ... em#) of
79 (StateAnd<r># result# state#) -> (R# result#, realWorld#)
83 dsCCall :: CLabelString -- C routine to invoke
84 -> [CoreExpr] -- Arguments (desugared)
85 -> Safety -- Safety of the call
86 -> Type -- Type of the result: IO t
87 -> DsM CoreExpr -- Result, of type ???
89 dsCCall lbl args may_gc result_ty
90 = do (unboxed_args, arg_wrappers) <- mapAndUnzipM unboxArg args
91 (ccall_result_ty, res_wrapper) <- boxResult id Nothing result_ty
94 target = StaticTarget lbl
95 the_fcall = CCall (CCallSpec target CCallConv may_gc)
96 the_prim_app = mkFCall uniq the_fcall unboxed_args ccall_result_ty
97 return (foldr ($) (res_wrapper the_prim_app) arg_wrappers)
99 mkFCall :: Unique -> ForeignCall
100 -> [CoreExpr] -- Args
101 -> Type -- Result type
103 -- Construct the ccall. The only tricky bit is that the ccall Id should have
104 -- no free vars, so if any of the arg tys do we must give it a polymorphic type.
105 -- [I forget *why* it should have no free vars!]
107 -- mkCCall ... [s::StablePtr (a->b), x::Addr, c::Char]
109 -- Here we build a ccall thus
110 -- (ccallid::(forall a b. StablePtr (a -> b) -> Addr -> Char -> IO Addr))
112 mkFCall uniq the_fcall val_args res_ty
113 = mkApps (mkVarApps (Var the_fcall_id) tyvars) val_args
115 arg_tys = map exprType val_args
116 body_ty = (mkFunTys arg_tys res_ty)
117 tyvars = varSetElems (tyVarsOfType body_ty)
118 ty = mkForAllTys tyvars body_ty
119 the_fcall_id = mkFCallId uniq the_fcall ty
123 unboxArg :: CoreExpr -- The supplied argument
124 -> DsM (CoreExpr, -- To pass as the actual argument
125 CoreExpr -> CoreExpr -- Wrapper to unbox the arg
127 -- Example: if the arg is e::Int, unboxArg will return
128 -- (x#::Int#, \W. case x of I# x# -> W)
129 -- where W is a CoreExpr that probably mentions x#
132 -- Primtive types: nothing to unbox
133 | isPrimitiveType arg_ty
134 = return (arg, \body -> body)
136 -- Recursive newtypes
137 | Just(_rep_ty, co) <- splitNewTypeRepCo_maybe arg_ty
138 = unboxArg (mkCoerce co arg)
141 | Just (tc,_) <- splitTyConApp_maybe arg_ty,
142 tc `hasKey` boolTyConKey
143 = do prim_arg <- newSysLocalDs intPrimTy
144 return (Var prim_arg,
145 \ body -> Case (Case arg (mkWildId arg_ty) intPrimTy
146 [(DataAlt falseDataCon,[],mkIntLit 0),
147 (DataAlt trueDataCon, [],mkIntLit 1)])
148 -- In increasing tag order!
153 -- Data types with a single constructor, which has a single, primitive-typed arg
154 -- This deals with Int, Float etc; also Ptr, ForeignPtr
155 | is_product_type && data_con_arity == 1
156 = ASSERT2(isUnLiftedType data_con_arg_ty1, pprType arg_ty)
157 -- Typechecker ensures this
158 do case_bndr <- newSysLocalDs arg_ty
159 prim_arg <- newSysLocalDs data_con_arg_ty1
160 return (Var prim_arg,
161 \ body -> Case arg case_bndr (exprType body) [(DataAlt data_con,[prim_arg],body)]
164 -- Byte-arrays, both mutable and otherwise; hack warning
165 -- We're looking for values of type ByteArray, MutableByteArray
166 -- data ByteArray ix = ByteArray ix ix ByteArray#
167 -- data MutableByteArray s ix = MutableByteArray ix ix (MutableByteArray# s)
169 data_con_arity == 3 &&
170 maybeToBool maybe_arg3_tycon &&
171 (arg3_tycon == byteArrayPrimTyCon ||
172 arg3_tycon == mutableByteArrayPrimTyCon)
173 = do case_bndr <- newSysLocalDs arg_ty
174 vars@[_l_var, _r_var, arr_cts_var] <- newSysLocalsDs data_con_arg_tys
175 return (Var arr_cts_var,
176 \ body -> Case arg case_bndr (exprType body) [(DataAlt data_con,vars,body)]
179 ----- Cases for .NET; almost certainly bit-rotted ---------
180 | Just (tc, [arg_ty]) <- splitTyConApp_maybe arg_ty,
182 Just (cc,[]) <- splitTyConApp_maybe arg_ty,
184 -- String; dotnet only
185 = do unpack_id <- dsLookupGlobalId marshalStringName
186 prim_string <- newSysLocalDs addrPrimTy
187 return (Var prim_string,
190 io_ty = exprType body
191 Just (_,io_arg,_) = tcSplitIOType_maybe io_ty
193 mkApps (Var unpack_id)
196 , Lam prim_string body
198 | Just (tc, [_]) <- splitTyConApp_maybe arg_ty,
199 tyConName tc == objectTyConName
200 -- Object; dotnet only
201 = do unpack_id <- dsLookupGlobalId marshalObjectName
202 prim_obj <- newSysLocalDs addrPrimTy
203 return (Var prim_obj,
206 io_ty = exprType body
207 Just (_,io_arg,_) = tcSplitIOType_maybe io_ty
209 mkApps (Var unpack_id)
214 --------------- End of cases for .NET --------------------
217 = do l <- getSrcSpanDs
218 pprPanic "unboxArg: " (ppr l <+> ppr arg_ty)
220 arg_ty = exprType arg
221 maybe_product_type = splitProductType_maybe arg_ty
222 is_product_type = maybeToBool maybe_product_type
223 Just (_, _, data_con, data_con_arg_tys) = maybe_product_type
224 data_con_arity = dataConSourceArity data_con
225 (data_con_arg_ty1 : _) = data_con_arg_tys
227 (_ : _ : data_con_arg_ty3 : _) = data_con_arg_tys
228 maybe_arg3_tycon = splitTyConApp_maybe data_con_arg_ty3
229 Just (arg3_tycon,_) = maybe_arg3_tycon
234 boxResult :: ((Maybe Type, CoreExpr -> CoreExpr)
235 -> (Maybe Type, CoreExpr -> CoreExpr))
238 -> DsM (Type, CoreExpr -> CoreExpr)
240 -- Takes the result of the user-level ccall:
242 -- or maybe just t for an side-effect-free call
243 -- Returns a wrapper for the primitive ccall itself, along with the
244 -- type of the result of the primitive ccall. This result type
245 -- will be of the form
246 -- State# RealWorld -> (# State# RealWorld, t' #)
247 -- where t' is the unwrapped form of t. If t is simply (), then
248 -- the result type will be
249 -- State# RealWorld -> (# State# RealWorld #)
251 -- The gruesome 'augment' and 'mbTopCon' are to do with .NET foreign calls
252 -- It looks a mess: I wonder if it could be refactored.
254 boxResult augment mbTopCon result_ty
255 | Just (io_tycon, io_res_ty, co) <- tcSplitIOType_maybe result_ty
256 -- isIOType_maybe handles the case where the type is a
257 -- simple wrapping of IO. E.g.
258 -- newtype Wrap a = W (IO a)
259 -- No coercion necessary because its a non-recursive newtype
260 -- (If we wanted to handle a *recursive* newtype too, we'd need
261 -- another case, and a coercion.)
262 -- The result is IO t, so wrap the result in an IO constructor
263 = do { res <- resultWrapper io_res_ty
264 ; let aug_res = augment res
268 | isUnboxedTupleType ty
269 -> let (Just (_, ls)) = splitTyConApp_maybe ty in tail ls
272 return_result state anss
273 = mkConApp (tupleCon Unboxed (2 + length extra_result_tys))
274 (map Type (realWorldStatePrimTy : io_res_ty : extra_result_tys)
277 ; (ccall_res_ty, the_alt) <- mk_alt return_result aug_res
279 ; state_id <- newSysLocalDs realWorldStatePrimTy
280 ; let io_data_con = head (tyConDataCons io_tycon)
281 toIOCon = mbTopCon `orElse` dataConWrapId io_data_con
283 wrap the_call = mkCoerceI (mkSymCoI co) $
287 Case (App the_call (Var state_id))
288 (mkWildId ccall_res_ty)
289 (coreAltType the_alt)
293 ; return (realWorldStatePrimTy `mkFunTy` ccall_res_ty, wrap) }
295 boxResult augment _mbTopCon result_ty
296 = do -- It isn't IO, so do unsafePerformIO
297 -- It's not conveniently available, so we inline it
298 res <- resultWrapper result_ty
299 (ccall_res_ty, the_alt) <- mk_alt return_result (augment res)
301 wrap = \ the_call -> Case (App the_call (Var realWorldPrimId))
302 (mkWildId ccall_res_ty)
303 (coreAltType the_alt)
305 return (realWorldStatePrimTy `mkFunTy` ccall_res_ty, wrap)
307 return_result _ [ans] = ans
308 return_result _ _ = panic "return_result: expected single result"
311 mk_alt :: (Expr Var -> [Expr Var] -> Expr Var)
312 -> (Maybe Type, Expr Var -> Expr Var)
313 -> DsM (Type, (AltCon, [Id], Expr Var))
314 mk_alt return_result (Nothing, wrap_result)
315 = do -- The ccall returns ()
316 state_id <- newSysLocalDs realWorldStatePrimTy
318 the_rhs = return_result (Var state_id)
319 [wrap_result (panic "boxResult")]
321 ccall_res_ty = mkTyConApp unboxedSingletonTyCon [realWorldStatePrimTy]
322 the_alt = (DataAlt unboxedSingletonDataCon, [state_id], the_rhs)
324 return (ccall_res_ty, the_alt)
326 mk_alt return_result (Just prim_res_ty, wrap_result)
327 -- The ccall returns a non-() value
328 | isUnboxedTupleType prim_res_ty= do
330 Just (_, ls) = splitTyConApp_maybe prim_res_ty
331 arity = 1 + length ls
332 args_ids@(result_id:as) <- mapM newSysLocalDs ls
333 state_id <- newSysLocalDs realWorldStatePrimTy
335 the_rhs = return_result (Var state_id)
336 (wrap_result (Var result_id) : map Var as)
337 ccall_res_ty = mkTyConApp (tupleTyCon Unboxed arity)
338 (realWorldStatePrimTy : ls)
339 the_alt = ( DataAlt (tupleCon Unboxed arity)
340 , (state_id : args_ids)
343 return (ccall_res_ty, the_alt)
346 result_id <- newSysLocalDs prim_res_ty
347 state_id <- newSysLocalDs realWorldStatePrimTy
349 the_rhs = return_result (Var state_id)
350 [wrap_result (Var result_id)]
351 ccall_res_ty = mkTyConApp unboxedPairTyCon [realWorldStatePrimTy, prim_res_ty]
352 the_alt = (DataAlt unboxedPairDataCon, [state_id, result_id], the_rhs)
353 return (ccall_res_ty, the_alt)
356 resultWrapper :: Type
357 -> DsM (Maybe Type, -- Type of the expected result, if any
358 CoreExpr -> CoreExpr) -- Wrapper for the result
359 -- resultWrapper deals with the result *value*
360 -- E.g. foreign import foo :: Int -> IO T
361 -- Then resultWrapper deals with marshalling the 'T' part
362 resultWrapper result_ty
363 -- Base case 1: primitive types
364 | isPrimitiveType result_ty
365 = return (Just result_ty, \e -> e)
367 -- Base case 2: the unit type ()
368 | Just (tc,_) <- maybe_tc_app, tc `hasKey` unitTyConKey
369 = return (Nothing, \_ -> Var unitDataConId)
371 -- Base case 3: the boolean type
372 | Just (tc,_) <- maybe_tc_app, tc `hasKey` boolTyConKey
374 (Just intPrimTy, \e -> Case e (mkWildId intPrimTy)
376 [(DEFAULT ,[],Var trueDataConId ),
377 (LitAlt (mkMachInt 0),[],Var falseDataConId)])
379 -- Recursive newtypes
380 | Just (rep_ty, co) <- splitNewTypeRepCo_maybe result_ty
381 = do (maybe_ty, wrapper) <- resultWrapper rep_ty
382 return (maybe_ty, \e -> mkCoerce (mkSymCoercion co) (wrapper e))
384 -- The type might contain foralls (eg. for dummy type arguments,
385 -- referring to 'Ptr a' is legal).
386 | Just (tyvar, rest) <- splitForAllTy_maybe result_ty
387 = do (maybe_ty, wrapper) <- resultWrapper rest
388 return (maybe_ty, \e -> Lam tyvar (wrapper e))
390 -- Data types with a single constructor, which has a single arg
391 -- This includes types like Ptr and ForeignPtr
392 | Just (tycon, tycon_arg_tys, data_con, data_con_arg_tys) <- splitProductType_maybe result_ty,
393 dataConSourceArity data_con == 1
395 (unwrapped_res_ty : _) = data_con_arg_tys
396 narrow_wrapper = maybeNarrow tycon
397 (maybe_ty, wrapper) <- resultWrapper unwrapped_res_ty
399 (maybe_ty, \e -> mkApps (Var (dataConWrapId data_con))
400 (map Type tycon_arg_tys ++ [wrapper (narrow_wrapper e)]))
402 -- Strings; 'dotnet' only.
403 | Just (tc, [arg_ty]) <- maybe_tc_app, tc == listTyCon,
404 Just (cc,[]) <- splitTyConApp_maybe arg_ty, cc == charTyCon
405 = do pack_id <- dsLookupGlobalId unmarshalStringName
406 return (Just addrPrimTy,
407 \ e -> App (Var pack_id) e)
409 -- Objects; 'dotnet' only.
410 | Just (tc, [_]) <- maybe_tc_app,
411 tyConName tc == objectTyConName
412 = do pack_id <- dsLookupGlobalId unmarshalObjectName
413 return (Just addrPrimTy,
414 \ e -> App (Var pack_id) e)
417 = pprPanic "resultWrapper" (ppr result_ty)
419 maybe_tc_app = splitTyConApp_maybe result_ty
421 -- When the result of a foreign call is smaller than the word size, we
422 -- need to sign- or zero-extend the result up to the word size. The C
423 -- standard appears to say that this is the responsibility of the
424 -- caller, not the callee.
426 maybeNarrow :: TyCon -> (CoreExpr -> CoreExpr)
428 | tycon `hasKey` int8TyConKey = \e -> App (Var (mkPrimOpId Narrow8IntOp)) e
429 | tycon `hasKey` int16TyConKey = \e -> App (Var (mkPrimOpId Narrow16IntOp)) e
430 | tycon `hasKey` int32TyConKey
431 && wORD_SIZE > 4 = \e -> App (Var (mkPrimOpId Narrow32IntOp)) e
433 | tycon `hasKey` word8TyConKey = \e -> App (Var (mkPrimOpId Narrow8WordOp)) e
434 | tycon `hasKey` word16TyConKey = \e -> App (Var (mkPrimOpId Narrow16WordOp)) e
435 | tycon `hasKey` word32TyConKey
436 && wORD_SIZE > 4 = \e -> App (Var (mkPrimOpId Narrow32WordOp)) e