[project @ 1998-12-02 13:17:09 by simonm]
[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         , unboxArg
10         , boxResult
11         ,  wrapUnboxedValue
12         , can'tSeeDataConsPanic
13         
14         ) where
15
16 #include "HsVersions.h"
17
18 import CoreSyn
19
20 import DsMonad
21 import DsUtils
22
23 import TcHsSyn          ( maybeBoxedPrimType )
24 import CoreUtils        ( coreExprType )
25 import Id               ( Id, mkWildId )
26 import Const            ( Con(..) )
27 import Maybes           ( maybeToBool )
28 import PrelInfo         ( packStringForCId )
29 import PrimOp           ( PrimOp(..) )
30 import DataCon          ( DataCon, dataConId, dataConArgTys )
31 import CallConv
32 import Type             ( isUnLiftedType, splitAlgTyConApp_maybe, mkFunTys,
33                           splitTyConApp_maybe, Type
34                         )
35 import TysPrim          ( byteArrayPrimTy, realWorldStatePrimTy,
36                           byteArrayPrimTyCon, mutableByteArrayPrimTyCon )
37 import TysWiredIn       ( unitDataCon, stringTy,
38                           mkUnboxedTupleTy, unboxedPairDataCon,
39                           mkUnboxedTupleTy, unboxedTupleCon
40                         )
41 import Outputable
42 \end{code}
43
44 Desugaring of @ccall@s consists of adding some state manipulation,
45 unboxing any boxed primitive arguments and boxing the result if
46 desired.
47
48 The state stuff just consists of adding in
49 @PrimIO (\ s -> case s of { S# s# -> ... })@ in an appropriate place.
50
51 The unboxing is straightforward, as all information needed to unbox is
52 available from the type.  For each boxed-primitive argument, we
53 transform:
54 \begin{verbatim}
55    _ccall_ foo [ r, t1, ... tm ] e1 ... em
56    |
57    |
58    V
59    case e1 of { T1# x1# ->
60    ...
61    case em of { Tm# xm# -> xm#
62    ccall# foo [ r, t1#, ... tm# ] x1# ... xm#
63    } ... }
64 \end{verbatim}
65
66 The reboxing of a @_ccall_@ result is a bit tricker: the types don't
67 contain information about the state-pairing functions so we have to
68 keep a list of \tr{(type, s-p-function)} pairs.  We transform as
69 follows:
70 \begin{verbatim}
71    ccall# foo [ r, t1#, ... tm# ] e1# ... em#
72    |
73    |
74    V
75    \ s# -> case (ccall# foo [ r, t1#, ... tm# ] s# e1# ... em#) of
76           (StateAnd<r># result# state#) -> (R# result#, realWorld#)
77 \end{verbatim}
78
79 \begin{code}
80 dsCCall :: FAST_STRING  -- C routine to invoke
81         -> [CoreExpr]   -- Arguments (desugared)
82         -> Bool         -- True <=> might cause Haskell GC
83         -> Bool         -- True <=> really a "_casm_"
84         -> Type         -- Type of the result (a boxed-prim IO type)
85         -> DsM CoreExpr
86
87 dsCCall label args may_gc is_asm result_ty
88   = newSysLocalDs realWorldStatePrimTy  `thenDs` \ old_s ->
89
90     mapAndUnzipDs unboxArg args `thenDs` \ (unboxed_args, arg_wrappers) ->
91     boxResult result_ty         `thenDs` \ (final_result_ty, res_wrapper) ->
92
93     let
94         val_args   = Var old_s : unboxed_args
95         final_args = Type inst_ty : val_args
96
97         -- A CCallOp has type (forall a. a), so we must instantiate
98         -- it at the full type, including the state argument
99         inst_ty = mkFunTys (map coreExprType val_args) final_result_ty
100
101         the_ccall_op = CCallOp (Left label) is_asm may_gc cCallConv
102         the_prim_app = mkPrimApp the_ccall_op final_args
103
104         the_body = foldr ($) (res_wrapper the_prim_app) arg_wrappers
105     in
106     returnDs (Lam old_s the_body)
107 \end{code}
108
109 \begin{code}
110 unboxArg :: CoreExpr                    -- The supplied argument
111          -> DsM (CoreExpr,              -- To pass as the actual argument
112                  CoreExpr -> CoreExpr   -- Wrapper to unbox the arg
113                 )
114 unboxArg arg
115
116   -- Primitive types
117   -- ADR Question: can this ever be used?  None of the PrimTypes are
118   -- instances of the CCallable class.
119   --
120   -- SOF response:
121   --    Oh yes they are, I've just added them :-) Having _ccall_ and _casm_
122   --  that accept unboxed arguments is a Good Thing if you have a stub generator
123   --  which generates the boiler-plate box-unbox code for you, i.e., it may help
124   --  us nuke this very module :-)
125   --
126   | isUnLiftedType arg_ty
127   = returnDs (arg, \body -> body)
128
129   -- Strings
130   | arg_ty == stringTy
131   -- ToDo (ADR): - allow synonyms of Strings too?
132   = newSysLocalDs byteArrayPrimTy               `thenDs` \ prim_arg ->
133     returnDs (Var prim_arg,
134               \body -> Case (App (Var packStringForCId) arg) 
135                             prim_arg [(DEFAULT,[],body)])
136
137   | null data_cons
138     -- oops: we can't see the data constructors!!!
139   = can'tSeeDataConsPanic "argument" arg_ty
140
141   -- Byte-arrays, both mutable and otherwise; hack warning
142   | is_data_type &&
143     length data_con_arg_tys == 2 &&
144     maybeToBool maybe_arg2_tycon &&
145     (arg2_tycon ==  byteArrayPrimTyCon ||
146      arg2_tycon ==  mutableByteArrayPrimTyCon)
147     -- and, of course, it is an instance of CCallable
148   = newSysLocalDs arg_ty                `thenDs` \ case_bndr ->
149     newSysLocalsDs data_con_arg_tys     `thenDs` \ vars@[ixs_var, arr_cts_var] ->
150     returnDs (Var arr_cts_var,
151               \ body -> Case arg case_bndr [(DataCon the_data_con,vars,body)]
152     )
153
154   -- Data types with a single constructor, which has a single, primitive-typed arg
155   | maybeToBool maybe_boxed_prim_arg_ty
156   = newSysLocalDs arg_ty                `thenDs` \ case_bndr ->
157     newSysLocalDs the_prim_arg_ty       `thenDs` \ prim_arg ->
158     returnDs (Var prim_arg,
159               \ body -> Case arg case_bndr [(DataCon box_data_con,[prim_arg],body)]
160     )
161
162   | otherwise
163   = getSrcLocDs `thenDs` \ l ->
164     pprPanic "unboxArg: " (ppr l <+> ppr arg_ty)
165   where
166     arg_ty = coreExprType arg
167
168     maybe_boxed_prim_arg_ty = maybeBoxedPrimType arg_ty
169     (Just (box_data_con, the_prim_arg_ty)) = maybe_boxed_prim_arg_ty
170
171     maybe_data_type                        = splitAlgTyConApp_maybe arg_ty
172     is_data_type                           = maybeToBool maybe_data_type
173     (Just (tycon, tycon_arg_tys, data_cons)) = maybe_data_type
174     (the_data_con : other_data_cons)       = data_cons
175
176     data_con_arg_tys = dataConArgTys the_data_con tycon_arg_tys
177     (data_con_arg_ty1 : data_con_arg_ty2 : _) = data_con_arg_tys
178
179     maybe_arg2_tycon = splitTyConApp_maybe data_con_arg_ty2
180     Just (arg2_tycon,_) = maybe_arg2_tycon
181
182 can'tSeeDataConsPanic thing ty
183   = pprPanic "ERROR: Can't see the data constructor(s) for _ccall_/_casm_/foreign declaration"
184              (hcat [text thing, text "; type: ", ppr ty, text "(try compiling with -fno-prune-tydecls ..)\n"])
185
186 \end{code}
187
188
189 \begin{code}
190 boxResult :: Type                       -- Type of desired result
191           -> DsM (Type,                 -- Type of the result of the ccall itself
192                   CoreExpr -> CoreExpr) -- Wrapper for the ccall
193                                         -- to box the result
194 boxResult result_ty
195   | null data_cons
196   -- oops! can't see the data constructors
197   = can'tSeeDataConsPanic "result" result_ty
198
199   -- Data types with a single nullary constructor
200   | (maybeToBool maybe_data_type) &&                            -- Data type
201     (null other_data_cons) &&                                   -- Just one constr
202     (null data_con_arg_tys)
203   =
204     newSysLocalDs realWorldStatePrimTy          `thenDs` \ prim_state_id ->
205 {-
206     wrapUnboxedValue result_ty                  `thenDs` \ (state_and_prim_datacon,
207                                                             state_and_prim_ty, prim_result_id, the_result) ->
208     mkConDs ioOkDataCon
209             [TyArg result_ty, VarArg (Var prim_state_id), VarArg the_result]
210                                                         `thenDs` \ the_pair ->
211 -}
212     let
213         the_pair = mkConApp unboxedPairDataCon
214                             [Type realWorldStatePrimTy, Type result_ty, 
215                              Var prim_state_id, 
216                              Con (DataCon unitDataCon) []]
217         the_alt  = (DataCon (unboxedTupleCon 1), [prim_state_id], the_pair)
218         scrut_ty = mkUnboxedTupleTy 1 [realWorldStatePrimTy]
219     in
220     returnDs (scrut_ty, \prim_app -> Case prim_app (mkWildId scrut_ty) [the_alt]
221     )
222
223   -- Data types with a single constructor, which has a single, primitive-typed arg
224   | (maybeToBool maybe_data_type) &&                            -- Data type
225     (null other_data_cons) &&                                   -- Just one constr
226     not (null data_con_arg_tys) && null other_args_tys  &&      -- Just one arg
227     isUnLiftedType the_prim_result_ty                           -- of primitive type
228   =
229     newSysLocalDs realWorldStatePrimTy          `thenDs` \ prim_state_id ->
230     newSysLocalDs the_prim_result_ty            `thenDs` \ prim_result_id ->
231     newSysLocalDs ccall_res_type                `thenDs` \ case_bndr ->
232
233     let
234         the_result = mkConApp the_data_con (map Type tycon_arg_tys ++ [Var prim_result_id])
235         the_pair   = mkConApp unboxedPairDataCon
236                                 [Type realWorldStatePrimTy, Type result_ty, 
237                                  Var prim_state_id, the_result]
238         the_alt    = (DataCon unboxedPairDataCon, [prim_state_id, prim_result_id], the_pair)
239     in
240     returnDs (ccall_res_type, \prim_app -> Case prim_app case_bndr [the_alt]
241     )
242
243   | otherwise
244   = pprPanic "boxResult: " (ppr result_ty)
245   where
246     maybe_data_type                        = splitAlgTyConApp_maybe result_ty
247     Just (tycon, tycon_arg_tys, data_cons) = maybe_data_type
248     (the_data_con : other_data_cons)       = data_cons
249     ccall_res_type = mkUnboxedTupleTy 2 
250                         [realWorldStatePrimTy, the_prim_result_ty]
251
252     data_con_arg_tys                       = dataConArgTys the_data_con tycon_arg_tys
253     (the_prim_result_ty : other_args_tys)  = data_con_arg_tys
254
255 -- wrap up an unboxed value.
256 wrapUnboxedValue :: Type -> DsM (Type, Id, CoreExpr)
257 wrapUnboxedValue ty
258   | null data_cons
259       -- oops! can't see the data constructors
260   = can'tSeeDataConsPanic "result" ty
261     -- Data types with a single constructor, which has a single, primitive-typed arg
262   | (maybeToBool maybe_data_type) &&                            -- Data type
263     (null other_data_cons) &&                                   -- Just one constr
264     not (null data_con_arg_tys) && null other_args_tys  &&      -- Just one arg
265     isUnLiftedType the_prim_result_ty                           -- of primitive type
266   =
267     newSysLocalDs the_prim_result_ty                     `thenDs` \ prim_result_id ->
268     let
269         the_result = mkConApp the_data_con (map Type tycon_arg_tys ++ [Var prim_result_id])
270     in
271     returnDs (ccall_res_type, prim_result_id, the_result)
272
273   -- Data types with a single nullary constructor
274   | (maybeToBool maybe_data_type) &&                            -- Data type
275     (null other_data_cons) &&                                   -- Just one constr
276     (null data_con_arg_tys)
277   =
278     let unit = dataConId unitDataCon
279         scrut_ty = mkUnboxedTupleTy 1 [realWorldStatePrimTy]
280     in
281     returnDs (scrut_ty, unit, mkConApp unitDataCon [])
282   | otherwise
283   = pprPanic "boxResult: " (ppr ty)
284  where
285    maybe_data_type                        = splitAlgTyConApp_maybe ty
286    Just (tycon, tycon_arg_tys, data_cons) = maybe_data_type
287    (the_data_con : other_data_cons)       = data_cons
288    ccall_res_type = mkUnboxedTupleTy 2 
289                         [realWorldStatePrimTy, the_prim_result_ty]
290
291    data_con_arg_tys                       = dataConArgTys the_data_con tycon_arg_tys
292    (the_prim_result_ty : other_args_tys)  = data_con_arg_tys
293
294 \end{code}