2 % (c) The AQUA Project, Glasgow University, 1994-1998
4 \section[DsCCall]{Desugaring \tr{_ccall_}s and \tr{_casm_}s}
15 #include "HsVersions.h"
22 import CoreUtils ( exprType, mkCoerce )
23 import Id ( Id, mkWildId )
24 import MkId ( mkCCallOpId, realWorldPrimId )
25 import Maybes ( maybeToBool )
26 import PrelInfo ( packStringForCId )
27 import PrimOp ( PrimOp(..), CCall(..), CCallTarget(..) )
28 import DataCon ( DataCon, splitProductType_maybe, dataConSourceArity, dataConWrapId )
30 import Type ( isUnLiftedType, splitAlgTyConApp_maybe, mkFunTys,
31 splitTyConApp_maybe, tyVarsOfType, mkForAllTys,
32 isNewType, repType, isUnLiftedType, mkFunTy,
35 import TysPrim ( byteArrayPrimTy, realWorldStatePrimTy,
36 byteArrayPrimTyCon, mutableByteArrayPrimTyCon, intPrimTy
38 import TysWiredIn ( unitDataConId, stringTy,
40 mkUnboxedTupleTy, unboxedTupleCon,
41 boolTy, trueDataCon, falseDataCon, trueDataConId, falseDataConId,
44 import Literal ( mkMachInt )
45 import CStrings ( CLabelString )
46 import Unique ( Unique, Uniquable(..), ioTyConKey )
47 import VarSet ( varSetElems )
51 Desugaring of @ccall@s consists of adding some state manipulation,
52 unboxing any boxed primitive arguments and boxing the result if
55 The state stuff just consists of adding in
56 @PrimIO (\ s -> case s of { S# s# -> ... })@ in an appropriate place.
58 The unboxing is straightforward, as all information needed to unbox is
59 available from the type. For each boxed-primitive argument, we
62 _ccall_ foo [ r, t1, ... tm ] e1 ... em
66 case e1 of { T1# x1# ->
68 case em of { Tm# xm# -> xm#
69 ccall# foo [ r, t1#, ... tm# ] x1# ... xm#
73 The reboxing of a @_ccall_@ result is a bit tricker: the types don't
74 contain information about the state-pairing functions so we have to
75 keep a list of \tr{(type, s-p-function)} pairs. We transform as
78 ccall# foo [ r, t1#, ... tm# ] e1# ... em#
82 \ s# -> case (ccall# foo [ r, t1#, ... tm# ] s# e1# ... em#) of
83 (StateAnd<r># result# state#) -> (R# result#, realWorld#)
87 dsCCall :: CLabelString -- C routine to invoke
88 -> [CoreExpr] -- Arguments (desugared)
89 -> Bool -- True <=> might cause Haskell GC
90 -> Bool -- True <=> really a "_casm_"
91 -> Type -- Type of the result: IO t
94 dsCCall lbl args may_gc is_asm result_ty
95 = mapAndUnzipDs unboxArg args `thenDs` \ (unboxed_args, arg_wrappers) ->
96 boxResult result_ty `thenDs` \ (ccall_result_ty, res_wrapper) ->
97 getUniqueDs `thenDs` \ uniq ->
99 the_ccall = CCall (StaticTarget lbl) is_asm may_gc cCallConv
100 the_prim_app = mkCCall uniq the_ccall unboxed_args ccall_result_ty
102 returnDs (foldr ($) (res_wrapper the_prim_app) arg_wrappers)
104 mkCCall :: Unique -> CCall
105 -> [CoreExpr] -- Args
106 -> Type -- Result type
108 -- Construct the ccall. The only tricky bit is that the ccall Id should have
109 -- no free vars, so if any of the arg tys do we must give it a polymorphic type.
110 -- [I forget *why* it should have no free vars!]
112 -- mkCCall ... [s::StablePtr (a->b), x::Addr, c::Char]
114 -- Here we build a ccall thus
115 -- (ccallid::(forall a b. StablePtr (a -> b) -> Addr -> Char -> IO Addr))
117 mkCCall uniq the_ccall val_args res_ty
118 = mkApps (mkVarApps (Var the_ccall_id) tyvars) val_args
120 arg_tys = map exprType val_args
121 body_ty = (mkFunTys arg_tys res_ty)
122 tyvars = varSetElems (tyVarsOfType body_ty)
123 ty = mkForAllTys tyvars body_ty
124 the_ccall_id = mkCCallOpId uniq the_ccall ty
128 unboxArg :: CoreExpr -- The supplied argument
129 -> DsM (CoreExpr, -- To pass as the actual argument
130 CoreExpr -> CoreExpr -- Wrapper to unbox the arg
132 -- Example: if the arg is e::Int, unboxArg will return
133 -- (x#::Int#, \W. case x of I# x# -> W)
134 -- where W is a CoreExpr that probably mentions x#
137 -- Unlifted types: nothing to unbox
138 | isUnLiftedType arg_ty
139 = returnDs (arg, \body -> body)
143 = unboxArg (mkCoerce (repType arg_ty) arg_ty arg)
147 = newSysLocalDs intPrimTy `thenDs` \ prim_arg ->
148 returnDs (Var prim_arg,
149 \ body -> Case (Case arg (mkWildId arg_ty)
150 [(DataAlt falseDataCon,[],mkIntLit 0),
151 (DataAlt trueDataCon, [],mkIntLit 1)])
155 -- Data types with a single constructor, which has a single, primitive-typed arg
156 -- This deals with Int, Float etc
157 | is_product_type && data_con_arity == 1
158 = ASSERT(isUnLiftedType data_con_arg_ty1 ) -- Typechecker ensures this
159 newSysLocalDs arg_ty `thenDs` \ case_bndr ->
160 newSysLocalDs data_con_arg_ty1 `thenDs` \ prim_arg ->
161 returnDs (Var prim_arg,
162 \ body -> Case arg case_bndr [(DataAlt data_con,[prim_arg],body)]
165 -- Byte-arrays, both mutable and otherwise; hack warning
167 data_con_arity == 3 &&
168 maybeToBool maybe_arg3_tycon &&
169 (arg3_tycon == byteArrayPrimTyCon ||
170 arg3_tycon == mutableByteArrayPrimTyCon)
171 -- and, of course, it is an instance of CCallable
172 = newSysLocalDs arg_ty `thenDs` \ case_bndr ->
173 newSysLocalsDs data_con_arg_tys `thenDs` \ vars@[l_var, r_var, arr_cts_var] ->
174 returnDs (Var arr_cts_var,
175 \ body -> Case arg case_bndr [(DataAlt data_con,vars,body)]
179 = getSrcLocDs `thenDs` \ l ->
180 pprPanic "unboxArg: " (ppr l <+> ppr arg_ty)
182 arg_ty = exprType arg
183 arg_rep_ty = repType arg_ty
185 maybe_product_type = splitProductType_maybe arg_ty
186 is_product_type = maybeToBool maybe_product_type
187 Just (tycon, _, data_con, data_con_arg_tys) = maybe_product_type
188 data_con_arity = dataConSourceArity data_con
189 (data_con_arg_ty1 : _) = data_con_arg_tys
191 (_ : _ : data_con_arg_ty3 : _) = data_con_arg_tys
192 maybe_arg3_tycon = splitTyConApp_maybe data_con_arg_ty3
193 Just (arg3_tycon,_) = maybe_arg3_tycon
198 boxResult :: Type -> DsM (Type, CoreExpr -> CoreExpr)
200 -- Takes the result of the user-level ccall:
202 -- or maybe just t for an side-effect-free call
203 -- Returns a wrapper for the primitive ccall itself, along with the
204 -- type of the result of the primitive ccall. This result type
205 -- will be of the form
206 -- State# RealWorld -> (# State# RealWorld, t' #)
207 -- where t' is the unwrapped form of t. If t is simply (), then
208 -- the result type will be
209 -- State# RealWorld -> (# State# RealWorld #)
212 = case splitAlgTyConApp_maybe result_ty of
214 -- The result is IO t, so wrap the result in an IO constructor
215 Just (io_tycon, [io_res_ty], [io_data_con]) | getUnique io_tycon == ioTyConKey
216 -> mk_alt return_result
217 (resultWrapper io_res_ty) `thenDs` \ (ccall_res_ty, the_alt) ->
218 newSysLocalDs realWorldStatePrimTy `thenDs` \ state_id ->
220 wrap = \ the_call -> mkApps (Var (dataConWrapId io_data_con))
221 [Type io_res_ty, Lam state_id $
222 Case (App the_call (Var state_id))
223 (mkWildId ccall_res_ty)
226 returnDs (realWorldStatePrimTy `mkFunTy` ccall_res_ty, wrap)
228 return_result state ans = mkConApp unboxedPairDataCon
229 [Type realWorldStatePrimTy, Type io_res_ty,
232 -- It isn't, so do unsafePerformIO
233 -- It's not conveniently available, so we inline it
234 other -> mk_alt return_result
235 (resultWrapper result_ty) `thenDs` \ (ccall_res_ty, the_alt) ->
237 wrap = \ the_call -> Case (App the_call (Var realWorldPrimId))
238 (mkWildId ccall_res_ty)
241 returnDs (realWorldStatePrimTy `mkFunTy` ccall_res_ty, wrap)
243 return_result state ans = ans
245 mk_alt return_result (Nothing, wrap_result)
246 = -- The ccall returns ()
247 newSysLocalDs realWorldStatePrimTy `thenDs` \ state_id ->
249 the_rhs = return_result (Var state_id) (wrap_result (panic "boxResult"))
250 ccall_res_ty = mkUnboxedTupleTy 1 [realWorldStatePrimTy]
251 the_alt = (DataAlt (unboxedTupleCon 1), [state_id], the_rhs)
253 returnDs (ccall_res_ty, the_alt)
255 mk_alt return_result (Just prim_res_ty, wrap_result)
256 = -- The ccall returns a non-() value
257 newSysLocalDs realWorldStatePrimTy `thenDs` \ state_id ->
258 newSysLocalDs prim_res_ty `thenDs` \ result_id ->
260 the_rhs = return_result (Var state_id) (wrap_result (Var result_id))
261 ccall_res_ty = mkUnboxedTupleTy 2 [realWorldStatePrimTy, prim_res_ty]
262 the_alt = (DataAlt unboxedPairDataCon, [state_id, result_id], the_rhs)
264 returnDs (ccall_res_ty, the_alt)
267 resultWrapper :: Type
268 -> (Maybe Type, -- Type of the expected result, if any
269 CoreExpr -> CoreExpr) -- Wrapper for the result
270 resultWrapper result_ty
271 -- Base case 1: primitive types
272 | isUnLiftedType result_ty
273 = (Just result_ty, \e -> e)
275 -- Base case 1: the unit type ()
276 | result_ty == unitTy
277 = (Nothing, \e -> Var unitDataConId)
279 | result_ty == boolTy
280 = (Just intPrimTy, \e -> Case e (mkWildId intPrimTy)
281 [(LitAlt (mkMachInt 0),[],Var falseDataConId),
282 (DEFAULT ,[],Var trueDataConId )])
284 -- Data types with a single constructor, which has a single arg
285 | is_product_type && data_con_arity == 1
287 (maybe_ty, wrapper) = resultWrapper unwrapped_res_ty
288 (unwrapped_res_ty : _) = data_con_arg_tys
290 (maybe_ty, \e -> mkApps (Var (dataConWrapId data_con))
291 (map Type tycon_arg_tys ++ [wrapper e]))
294 | isNewType result_ty
296 rep_ty = repType result_ty
297 (maybe_ty, wrapper) = resultWrapper rep_ty
299 (maybe_ty, \e -> mkCoerce result_ty rep_ty (wrapper e))
302 = pprPanic "resultWrapper" (ppr result_ty)
304 maybe_product_type = splitProductType_maybe result_ty
305 is_product_type = maybeToBool maybe_product_type
306 Just (tycon, tycon_arg_tys, data_con, data_con_arg_tys) = maybe_product_type
307 data_con_arity = dataConSourceArity data_con