[project @ 2000-04-13 20:41:30 by panne]
[ghc-hetmet.git] / ghc / compiler / deSugar / DsCCall.lhs
1 %
2 % (c) The AQUA Project, Glasgow University, 1994-1998
3 %
4 \section[DsCCall]{Desugaring \tr{_ccall_}s and \tr{_casm_}s}
5
6 \begin{code}
7 module DsCCall 
8         ( dsCCall
9         , mkCCall
10         , unboxArg
11         , boxResult
12         , resultWrapper
13         ) where
14
15 #include "HsVersions.h"
16
17 import CoreSyn
18
19 import DsMonad
20 import DsUtils
21
22 import CoreUtils        ( exprType, mkCoerce )
23 import Id               ( Id, mkWildId )
24 import MkId             ( mkCCallOpId, realWorldPrimId )
25 import Maybes           ( maybeToBool )
26 import PrimOp           ( PrimOp(..), CCall(..), CCallTarget(..) )
27 import DataCon          ( DataCon, splitProductType_maybe, dataConSourceArity, dataConWrapId )
28 import CallConv
29 import Type             ( isUnLiftedType, splitAlgTyConApp_maybe, mkFunTys,
30                           splitTyConApp_maybe, tyVarsOfType, mkForAllTys, 
31                           isNewType, repType, isUnLiftedType, mkFunTy,
32                           Type
33                         )
34 import PprType          ( {- instance Outputable Type -} )
35 import TysPrim          ( byteArrayPrimTy, realWorldStatePrimTy,
36                           byteArrayPrimTyCon, mutableByteArrayPrimTyCon, intPrimTy
37                         )
38 import TysWiredIn       ( unitDataConId, stringTy,
39                           unboxedPairDataCon,
40                           mkUnboxedTupleTy, unboxedTupleCon,
41                           boolTy, trueDataCon, falseDataCon, trueDataConId, falseDataConId,
42                           unitTy
43                         )
44 import Literal          ( mkMachInt )
45 import CStrings         ( CLabelString )
46 import Unique           ( Unique, Uniquable(..), ioTyConKey )
47 import VarSet           ( varSetElems )
48 import Outputable
49 \end{code}
50
51 Desugaring of @ccall@s consists of adding some state manipulation,
52 unboxing any boxed primitive arguments and boxing the result if
53 desired.
54
55 The state stuff just consists of adding in
56 @PrimIO (\ s -> case s of { S# s# -> ... })@ in an appropriate place.
57
58 The unboxing is straightforward, as all information needed to unbox is
59 available from the type.  For each boxed-primitive argument, we
60 transform:
61 \begin{verbatim}
62    _ccall_ foo [ r, t1, ... tm ] e1 ... em
63    |
64    |
65    V
66    case e1 of { T1# x1# ->
67    ...
68    case em of { Tm# xm# -> xm#
69    ccall# foo [ r, t1#, ... tm# ] x1# ... xm#
70    } ... }
71 \end{verbatim}
72
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
76 follows:
77 \begin{verbatim}
78    ccall# foo [ r, t1#, ... tm# ] e1# ... em#
79    |
80    |
81    V
82    \ s# -> case (ccall# foo [ r, t1#, ... tm# ] s# e1# ... em#) of
83           (StateAnd<r># result# state#) -> (R# result#, realWorld#)
84 \end{verbatim}
85
86 \begin{code}
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
92         -> DsM CoreExpr
93
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 ->
98     let
99         the_ccall    = CCall (StaticTarget lbl) is_asm may_gc cCallConv
100         the_prim_app = mkCCall uniq the_ccall unboxed_args ccall_result_ty
101     in
102     returnDs (foldr ($) (res_wrapper the_prim_app) arg_wrappers)
103
104 mkCCall :: Unique -> CCall 
105         -> [CoreExpr]   -- Args
106         -> Type         -- Result type
107         -> CoreExpr
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!]
111 -- For example:
112 --      mkCCall ... [s::StablePtr (a->b), x::Addr, c::Char]
113 --
114 -- Here we build a ccall thus
115 --      (ccallid::(forall a b.  StablePtr (a -> b) -> Addr -> Char -> IO Addr))
116 --                      a b s x c
117 mkCCall uniq the_ccall val_args res_ty
118   = mkApps (mkVarApps (Var the_ccall_id) tyvars) val_args
119   where
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
125 \end{code}
126
127 \begin{code}
128 unboxArg :: CoreExpr                    -- The supplied argument
129          -> DsM (CoreExpr,              -- To pass as the actual argument
130                  CoreExpr -> CoreExpr   -- Wrapper to unbox the arg
131                 )
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#
135
136 unboxArg arg
137   -- Unlifted types: nothing to unbox
138   | isUnLiftedType arg_ty
139   = returnDs (arg, \body -> body)
140
141   -- Newtypes
142   | isNewType arg_ty
143   = unboxArg (mkCoerce (repType arg_ty) arg_ty arg)
144       
145   -- Booleans
146   | arg_ty == boolTy
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)])
152                              prim_arg 
153                              [(DEFAULT,[],body)])
154
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)]
163     )
164
165   -- Byte-arrays, both mutable and otherwise; hack warning
166   | is_product_type &&
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)]
176     )
177
178   | otherwise
179   = getSrcLocDs `thenDs` \ l ->
180     pprPanic "unboxArg: " (ppr l <+> ppr arg_ty)
181   where
182     arg_ty     = exprType arg
183     arg_rep_ty = repType arg_ty
184
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
190
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
194 \end{code}
195
196
197 \begin{code}
198 boxResult :: Type -> DsM (Type, CoreExpr -> CoreExpr)
199
200 -- Takes the result of the user-level ccall: 
201 --      either (IO t), 
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 #)
210
211 boxResult result_ty
212   = case splitAlgTyConApp_maybe result_ty of
213
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 ->
219                    let
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)
224                                                                           [the_alt]]
225                    in
226                    returnDs (realWorldStatePrimTy `mkFunTy` ccall_res_ty, wrap)
227                 where
228                    return_result state ans = mkConApp unboxedPairDataCon 
229                                                       [Type realWorldStatePrimTy, Type io_res_ty, 
230                                                        state, ans]
231
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) ->
236                  let
237                     wrap = \ the_call -> Case (App the_call (Var realWorldPrimId)) 
238                                               (mkWildId ccall_res_ty)
239                                               [the_alt]
240                  in
241                  returnDs (realWorldStatePrimTy `mkFunTy` ccall_res_ty, wrap)
242               where
243                  return_result state ans = ans
244   where
245     mk_alt return_result (Nothing, wrap_result)
246         =       -- The ccall returns ()
247           newSysLocalDs realWorldStatePrimTy    `thenDs` \ state_id ->
248           let
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)
252           in
253           returnDs (ccall_res_ty, the_alt)
254
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 ->
259           let
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)
263           in
264           returnDs (ccall_res_ty, the_alt)
265
266
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)
274
275   -- Base case 1: the unit type ()
276   | result_ty == unitTy
277   = (Nothing, \e -> Var unitDataConId)
278
279   | result_ty == boolTy
280   = (Just intPrimTy, \e -> Case e (mkWildId intPrimTy)
281                                   [(LitAlt (mkMachInt 0),[],Var falseDataConId),
282                                    (DEFAULT             ,[],Var trueDataConId )])
283
284   -- Data types with a single constructor, which has a single arg
285   | is_product_type && data_con_arity == 1
286   = let
287         (maybe_ty, wrapper)    = resultWrapper unwrapped_res_ty
288         (unwrapped_res_ty : _) = data_con_arg_tys
289     in
290     (maybe_ty, \e -> mkApps (Var (dataConWrapId data_con)) 
291                             (map Type tycon_arg_tys ++ [wrapper e]))
292
293   -- newtypes
294   | isNewType result_ty
295   = let
296         rep_ty              = repType result_ty
297         (maybe_ty, wrapper) = resultWrapper rep_ty
298     in
299     (maybe_ty, \e -> mkCoerce result_ty rep_ty (wrapper e))
300
301   | otherwise
302   = pprPanic "resultWrapper" (ppr result_ty)
303   where
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
308 \end{code}