[project @ 1999-07-14 14:40:20 by simonpj]
[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 == 2 &&
140     maybeToBool maybe_arg2_tycon &&
141     (arg2_tycon ==  byteArrayPrimTyCon ||
142      arg2_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@[ixs_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_tys
171
172     maybe_arg2_tycon = splitTyConApp_maybe data_con_arg_ty2
173     Just (arg2_tycon,_) = maybe_arg2_tycon
174
175 can'tSeeDataConsPanic thing ty
176   = pprPanic
177      "ERROR: Can't see the data constructor(s) for _ccall_/_casm_/foreign declaration"
178      (hcat [ text thing, text "; type: ", ppr ty
179            , text "(try compiling with -fno-prune-tydecls ..)\n"])
180 \end{code}
181
182
183 \begin{code}
184 boxResult :: Type                       -- Type of desired result
185           -> DsM (Type,                 -- Type of the result of the ccall itself
186                   CoreExpr -> CoreExpr) -- Wrapper for the ccall
187                                         -- to box the result
188 boxResult result_ty
189   -- Data types with a single nullary constructor
190   | (maybeToBool maybe_product_type) &&                         -- Data type
191     (null data_con_arg_tys)
192   =
193     newSysLocalDs realWorldStatePrimTy          `thenDs` \ prim_state_id ->
194 {-
195     wrapUnboxedValue result_ty                  `thenDs` \ (state_and_prim_datacon,
196                                                             state_and_prim_ty, prim_result_id, the_result) ->
197     mkConDs ioOkDataCon
198             [TyArg result_ty, VarArg (Var prim_state_id), VarArg the_result]
199                                                         `thenDs` \ the_pair ->
200 -}
201     let
202         the_pair = mkConApp unboxedPairDataCon
203                             [Type realWorldStatePrimTy, Type result_ty, 
204                              Var prim_state_id, 
205                              Con (DataCon unitDataCon) []]
206         the_alt  = (DataCon (unboxedTupleCon 1), [prim_state_id], the_pair)
207         scrut_ty = mkUnboxedTupleTy 1 [realWorldStatePrimTy]
208     in
209     returnDs (scrut_ty, \prim_app -> Case prim_app (mkWildId scrut_ty) [the_alt]
210     )
211
212   -- Data types with a single constructor, which has a single, primitive-typed arg
213   | (maybeToBool maybe_product_type) &&                         -- Data type
214     not (null data_con_arg_tys) && null other_args_tys  &&      -- Just one arg
215     isUnLiftedType the_prim_result_ty                           -- of primitive type
216   =
217     newSysLocalDs realWorldStatePrimTy          `thenDs` \ prim_state_id ->
218     newSysLocalDs the_prim_result_ty            `thenDs` \ prim_result_id ->
219     newSysLocalDs ccall_res_type                `thenDs` \ case_bndr ->
220
221     let
222         the_result = mkConApp data_con (map Type tycon_arg_tys ++ [Var prim_result_id])
223         the_pair   = mkConApp unboxedPairDataCon
224                                 [Type realWorldStatePrimTy, Type result_ty, 
225                                  Var prim_state_id, the_result]
226         the_alt    = (DataCon unboxedPairDataCon, [prim_state_id, prim_result_id], the_pair)
227     in
228     returnDs (ccall_res_type, \prim_app -> Case prim_app case_bndr [the_alt]
229     )
230
231   | otherwise
232   = pprPanic "boxResult: " (ppr result_ty)
233   where
234     maybe_product_type                                      = splitProductType_maybe result_ty
235     Just (tycon, tycon_arg_tys, data_con, data_con_arg_tys) = maybe_product_type
236     (the_prim_result_ty : other_args_tys)                   = data_con_arg_tys
237
238     ccall_res_type = mkUnboxedTupleTy 2 [realWorldStatePrimTy, the_prim_result_ty]
239
240 -- wrap up an unboxed value.
241 wrapUnboxedValue :: Type -> DsM (Type, Id, CoreExpr)
242 wrapUnboxedValue ty
243   | (maybeToBool maybe_product_type) &&                         -- Data type
244     not (null data_con_arg_tys) && null other_args_tys  &&      -- Just one arg
245     isUnLiftedType the_prim_result_ty                           -- of primitive type
246   =
247     newSysLocalDs the_prim_result_ty                     `thenDs` \ prim_result_id ->
248     let
249         the_result = mkConApp data_con (map Type tycon_arg_tys ++ [Var prim_result_id])
250     in
251     returnDs (ccall_res_type, prim_result_id, the_result)
252
253   -- Data types with a single nullary constructor
254   | (maybeToBool maybe_product_type) &&                         -- Data type
255     (null data_con_arg_tys)
256   =
257     let unit = dataConId unitDataCon
258         scrut_ty = mkUnboxedTupleTy 1 [realWorldStatePrimTy]
259     in
260     returnDs (scrut_ty, unit, mkConApp unitDataCon [])
261
262   | otherwise
263   = pprPanic "boxResult: " (ppr ty)
264  where
265    maybe_product_type                                      = splitProductType_maybe ty
266    Just (tycon, tycon_arg_tys, data_con, data_con_arg_tys) = maybe_product_type
267    (the_prim_result_ty : other_args_tys)                   = data_con_arg_tys
268    ccall_res_type = mkUnboxedTupleTy 2 [realWorldStatePrimTy, the_prim_result_ty]
269 \end{code}