[project @ 1999-10-05 09:02:30 by simonmar]
[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, splitProductType_maybe )
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                           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 lbl 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 lbl) 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   -- Byte-arrays, both mutable and otherwise; hack warning
138   | is_product_type &&
139     length data_con_arg_tys == 3 &&
140     maybeToBool maybe_arg3_tycon &&
141     (arg3_tycon ==  byteArrayPrimTyCon ||
142      arg3_tycon ==  mutableByteArrayPrimTyCon)
143     -- and, of course, it is an instance of CCallable
144   = newSysLocalDs arg_ty                `thenDs` \ case_bndr ->
145     newSysLocalsDs data_con_arg_tys     `thenDs` \ vars@[l_var, r_var, arr_cts_var] ->
146     returnDs (Var arr_cts_var,
147               \ body -> Case arg case_bndr [(DataCon data_con,vars,body)]
148     )
149
150   -- Data types with a single constructor, which has a single, primitive-typed arg
151   | maybeToBool maybe_boxed_prim_arg_ty
152   = newSysLocalDs arg_ty                `thenDs` \ case_bndr ->
153     newSysLocalDs the_prim_arg_ty       `thenDs` \ prim_arg ->
154     returnDs (Var prim_arg,
155               \ body -> Case arg case_bndr [(DataCon box_data_con,[prim_arg],body)]
156     )
157
158   | otherwise
159   = getSrcLocDs `thenDs` \ l ->
160     pprPanic "unboxArg: " (ppr l <+> ppr arg_ty)
161   where
162     arg_ty = coreExprType arg
163
164     maybe_boxed_prim_arg_ty = maybeBoxedPrimType arg_ty
165     (Just (box_data_con, the_prim_arg_ty)) = maybe_boxed_prim_arg_ty
166
167     maybe_product_type                            = splitProductType_maybe arg_ty
168     is_product_type                               = maybeToBool maybe_product_type
169     Just (tycon, _, data_con, data_con_arg_tys)   = maybe_product_type
170     (data_con_arg_ty1 : data_con_arg_ty2 : data_con_arg_ty3 :_)
171           = data_con_arg_tys
172
173     maybe_arg3_tycon = splitTyConApp_maybe data_con_arg_ty3
174     Just (arg3_tycon,_) = maybe_arg3_tycon
175
176 can'tSeeDataConsPanic thing ty
177   = pprPanic
178      "ERROR: Can't see the data constructor(s) for _ccall_/_casm_/foreign declaration"
179      (hcat [ text thing, text "; type: ", ppr ty
180            , text "(try compiling with -fno-prune-tydecls ..)\n"])
181 \end{code}
182
183
184 \begin{code}
185 boxResult :: Type                       -- Type of desired result
186           -> DsM (Type,                 -- Type of the result of the ccall itself
187                   CoreExpr -> CoreExpr) -- Wrapper for the ccall
188                                         -- to box the result
189 boxResult result_ty
190   -- Data types with a single nullary constructor
191   | (maybeToBool maybe_product_type) &&                         -- Data type
192     (null data_con_arg_tys)
193   =
194     newSysLocalDs realWorldStatePrimTy          `thenDs` \ prim_state_id ->
195 {-
196     wrapUnboxedValue result_ty                  `thenDs` \ (state_and_prim_datacon,
197                                                             state_and_prim_ty, prim_result_id, the_result) ->
198     mkConDs ioOkDataCon
199             [TyArg result_ty, VarArg (Var prim_state_id), VarArg the_result]
200                                                         `thenDs` \ the_pair ->
201 -}
202     let
203         the_pair = mkConApp unboxedPairDataCon
204                             [Type realWorldStatePrimTy, Type result_ty, 
205                              Var prim_state_id, 
206                              Con (DataCon unitDataCon) []]
207         the_alt  = (DataCon (unboxedTupleCon 1), [prim_state_id], the_pair)
208         scrut_ty = mkUnboxedTupleTy 1 [realWorldStatePrimTy]
209     in
210     returnDs (scrut_ty, \prim_app -> Case prim_app (mkWildId scrut_ty) [the_alt]
211     )
212
213   -- Data types with a single constructor, which has a single, primitive-typed arg
214   | (maybeToBool maybe_product_type) &&                         -- Data type
215     not (null data_con_arg_tys) && null other_args_tys  &&      -- Just one arg
216     isUnLiftedType the_prim_result_ty                           -- of primitive type
217   =
218     newSysLocalDs realWorldStatePrimTy          `thenDs` \ prim_state_id ->
219     newSysLocalDs the_prim_result_ty            `thenDs` \ prim_result_id ->
220     newSysLocalDs ccall_res_type                `thenDs` \ case_bndr ->
221
222     let
223         the_result = mkConApp data_con (map Type tycon_arg_tys ++ [Var prim_result_id])
224         the_pair   = mkConApp unboxedPairDataCon
225                                 [Type realWorldStatePrimTy, Type result_ty, 
226                                  Var prim_state_id, the_result]
227         the_alt    = (DataCon unboxedPairDataCon, [prim_state_id, prim_result_id], the_pair)
228     in
229     returnDs (ccall_res_type, \prim_app -> Case prim_app case_bndr [the_alt]
230     )
231
232   | otherwise
233   = pprPanic "boxResult: " (ppr result_ty)
234   where
235     maybe_product_type                                      = splitProductType_maybe result_ty
236     Just (tycon, tycon_arg_tys, data_con, data_con_arg_tys) = maybe_product_type
237     (the_prim_result_ty : other_args_tys)                   = data_con_arg_tys
238
239     ccall_res_type = mkUnboxedTupleTy 2 [realWorldStatePrimTy, the_prim_result_ty]
240
241 -- wrap up an unboxed value.
242 wrapUnboxedValue :: Type -> DsM (Type, Id, CoreExpr)
243 wrapUnboxedValue ty
244   | (maybeToBool maybe_product_type) &&                         -- Data type
245     not (null data_con_arg_tys) && null other_args_tys  &&      -- Just one arg
246     isUnLiftedType the_prim_result_ty                           -- of primitive type
247   =
248     newSysLocalDs the_prim_result_ty                     `thenDs` \ prim_result_id ->
249     let
250         the_result = mkConApp data_con (map Type tycon_arg_tys ++ [Var prim_result_id])
251     in
252     returnDs (ccall_res_type, prim_result_id, the_result)
253
254   -- Data types with a single nullary constructor
255   | (maybeToBool maybe_product_type) &&                         -- Data type
256     (null data_con_arg_tys)
257   =
258     let unit = dataConId unitDataCon
259         scrut_ty = mkUnboxedTupleTy 1 [realWorldStatePrimTy]
260     in
261     returnDs (scrut_ty, unit, mkConApp unitDataCon [])
262
263   | otherwise
264   = pprPanic "boxResult: " (ppr ty)
265  where
266    maybe_product_type                                      = splitProductType_maybe ty
267    Just (tycon, tycon_arg_tys, data_con, data_con_arg_tys) = maybe_product_type
268    (the_prim_result_ty : other_args_tys)                   = data_con_arg_tys
269    ccall_res_type = mkUnboxedTupleTy 2 [realWorldStatePrimTy, the_prim_result_ty]
270 \end{code}