[project @ 1997-06-05 21:05:57 by sof]
[ghc-hetmet.git] / ghc / compiler / deSugar / DsCCall.lhs
1 %
2 % (c) The AQUA Project, Glasgow University, 1994-1996
3 %
4 \section[DsCCall]{Desugaring \tr{_ccall_}s and \tr{_casm_}s}
5
6 \begin{code}
7 #include "HsVersions.h"
8
9 module DsCCall ( dsCCall ) where
10
11 IMP_Ubiq()
12
13 import CmdLineOpts (opt_PprUserLength)
14 import CoreSyn
15
16 import DsMonad
17 import DsUtils
18
19 import CoreUtils        ( coreExprType )
20 import Id               ( dataConArgTys )
21 import Maybes           ( maybeToBool )
22 import Outputable       ( PprStyle(..), Outputable(..) )
23 import PprType          ( GenType{-instances-} )
24 import Pretty
25 import PrelVals         ( packStringForCId )
26 import PrimOp           ( PrimOp(..) )
27 import Type             ( isPrimType, maybeAppDataTyConExpandingDicts, maybeAppTyCon,
28                           eqTy, maybeBoxedPrimType, SYN_IE(Type) )
29 import TysPrim          ( byteArrayPrimTy, realWorldTy,  realWorldStatePrimTy,
30                           byteArrayPrimTyCon, mutableByteArrayPrimTyCon )
31 import TysWiredIn       ( getStatePairingConInfo,
32                           realWorldStateTy, stateDataCon, pairDataCon, unitDataCon,
33                           stringTy
34                         )
35 import Util             ( pprPanic, pprError, panic )
36
37 \end{code}
38
39 Desugaring of @ccall@s consists of adding some state manipulation,
40 unboxing any boxed primitive arguments and boxing the result if
41 desired.
42
43 The state stuff just consists of adding in
44 @PrimIO (\ s -> case s of { S# s# -> ... })@ in an appropriate place.
45
46 The unboxing is straightforward, as all information needed to unbox is
47 available from the type.  For each boxed-primitive argument, we
48 transform:
49 \begin{verbatim}
50    _ccall_ foo [ r, t1, ... tm ] e1 ... em
51    |
52    |
53    V
54    case e1 of { T1# x1# ->
55    ...
56    case em of { Tm# xm# -> xm#
57    ccall# foo [ r, t1#, ... tm# ] x1# ... xm#
58    } ... }
59 \end{verbatim}
60
61 The reboxing of a @_ccall_@ result is a bit tricker: the types don't
62 contain information about the state-pairing functions so we have to
63 keep a list of \tr{(type, s-p-function)} pairs.  We transform as
64 follows:
65 \begin{verbatim}
66    ccall# foo [ r, t1#, ... tm# ] e1# ... em#
67    |
68    |
69    V
70    \ s# -> case (ccall# foo [ r, t1#, ... tm# ] s# e1# ... em#) of
71           (StateAnd<r># result# state#) -> (R# result#, realWorld#)
72 \end{verbatim}
73
74 \begin{code}
75 dsCCall :: FAST_STRING  -- C routine to invoke
76         -> [CoreExpr]   -- Arguments (desugared)
77         -> Bool         -- True <=> might cause Haskell GC
78         -> Bool         -- True <=> really a "_casm_"
79         -> Type         -- Type of the result (a boxed-prim type)
80         -> DsM CoreExpr
81
82 dsCCall label args may_gc is_asm result_ty
83   = newSysLocalDs realWorldStateTy      `thenDs` \ old_s ->
84
85     mapAndUnzipDs unboxArg (Var old_s : args)   `thenDs` \ (final_args, arg_wrappers) ->
86
87     boxResult result_ty                         `thenDs` \ (final_result_ty, res_wrapper) ->
88
89     let
90         the_ccall_op = CCallOp label is_asm may_gc
91                                (map coreExprType final_args)
92                                final_result_ty
93     in
94     mkPrimDs the_ccall_op (map VarArg final_args) `thenDs` \ the_prim_app ->
95     let
96         the_body = foldr ($) (res_wrapper the_prim_app) arg_wrappers
97     in
98     returnDs (Lam (ValBinder old_s) the_body)
99 \end{code}
100
101 \begin{code}
102 unboxArg :: CoreExpr                    -- The supplied argument
103          -> DsM (CoreExpr,              -- To pass as the actual argument
104                  CoreExpr -> CoreExpr   -- Wrapper to unbox the arg
105                 )
106 unboxArg arg
107
108   -- Primitive types
109   -- ADR Question: can this ever be used?  None of the PrimTypes are
110   -- instances of the CCallable class.
111   --
112   -- SOF response:
113   --    Oh yes they are, I've just added them :-) Having _ccall_ and _casm_
114   --  that accept unboxed arguments is a Good Thing if you have a stub generator
115   --  which generates the boiler-plate box-unbox code for you, i.e., it may help
116   --  us nuke this very module :-)
117   --
118   | isPrimType arg_ty
119   = returnDs (arg, \body -> body)
120
121   -- Strings
122   | arg_ty `eqTy` stringTy
123   -- ToDo (ADR): - allow synonyms of Strings too?
124   = newSysLocalDs byteArrayPrimTy               `thenDs` \ prim_arg ->
125     mkAppDs (Var packStringForCId) [VarArg arg] `thenDs` \ pack_appn ->
126     returnDs (Var prim_arg,
127               \body -> Case pack_appn (PrimAlts []
128                                                     (BindDefault prim_arg body))
129     )
130
131   | null data_cons
132     -- oops: we can't see the data constructors!!!
133   = can't_see_datacons_error "argument" arg_ty
134
135   -- Byte-arrays, both mutable and otherwise; hack warning
136   | is_data_type &&
137     length data_con_arg_tys == 2 &&
138     maybeToBool maybe_arg2_tycon &&
139     (arg2_tycon ==  byteArrayPrimTyCon ||
140      arg2_tycon ==  mutableByteArrayPrimTyCon)
141     -- and, of course, it is an instance of CCallable
142   = newSysLocalsDs data_con_arg_tys             `thenDs` \ vars@[ixs_var, arr_cts_var] ->
143     returnDs (Var arr_cts_var,
144               \ body -> Case arg (AlgAlts [(the_data_con,vars,body)]
145                                               NoDefault)
146     )
147
148   -- Data types with a single constructor, which has a single, primitive-typed arg
149   | maybeToBool maybe_boxed_prim_arg_ty
150   = newSysLocalDs the_prim_arg_ty               `thenDs` \ prim_arg ->
151     returnDs (Var prim_arg,
152               \ body -> Case arg (AlgAlts [(box_data_con,[prim_arg],body)]
153                                               NoDefault)
154     )
155
156   | otherwise
157   = pprPanic "unboxArg: " (ppr PprDebug arg_ty)
158   where
159     arg_ty = coreExprType arg
160
161     maybe_boxed_prim_arg_ty = maybeBoxedPrimType arg_ty
162     (Just (box_data_con, the_prim_arg_ty)) = maybe_boxed_prim_arg_ty
163
164     maybe_data_type                        = maybeAppDataTyConExpandingDicts arg_ty
165     is_data_type                           = maybeToBool maybe_data_type
166     (Just (tycon, tycon_arg_tys, data_cons)) = maybe_data_type
167     (the_data_con : other_data_cons)       = data_cons
168
169     data_con_arg_tys = dataConArgTys the_data_con tycon_arg_tys
170     (data_con_arg_ty1 : data_con_arg_ty2 : _) = data_con_arg_tys
171
172     maybe_arg2_tycon = maybeAppTyCon data_con_arg_ty2
173     Just (arg2_tycon,_) = maybe_arg2_tycon
174
175 can't_see_datacons_error thing ty
176   = pprError "ERROR: Can't see the data constructor(s) for _ccall_/_casm_ (try compiling with -fno-prune-tydecls ..)"
177              (hcat [text thing, text "; type: ", ppr (PprForUser opt_PprUserLength) ty])
178 \end{code}
179
180
181 \begin{code}
182 boxResult :: Type                               -- Type of desired result
183           -> DsM (Type,                 -- Type of the result of the ccall itself
184                   CoreExpr -> CoreExpr) -- Wrapper for the ccall
185                                                         -- to box the result
186 boxResult result_ty
187   | null data_cons
188   -- oops! can't see the data constructors
189   = can't_see_datacons_error "result" result_ty
190
191   -- Data types with a single constructor, which has a single, primitive-typed arg
192   | (maybeToBool maybe_data_type) &&                            -- Data type
193     (null other_data_cons) &&                                   -- Just one constr
194     not (null data_con_arg_tys) && null other_args_tys  &&      -- Just one arg
195     isPrimType the_prim_result_ty                               -- of primitive type
196   =
197     newSysLocalDs realWorldStatePrimTy                  `thenDs` \ prim_state_id ->
198     newSysLocalDs the_prim_result_ty                    `thenDs` \ prim_result_id ->
199
200     mkConDs stateDataCon [TyArg realWorldTy, VarArg (Var prim_state_id)]  `thenDs` \ new_state ->
201     mkConDs the_data_con (map TyArg tycon_arg_tys ++ [VarArg (Var prim_result_id)]) `thenDs` \ the_result ->
202
203     mkConDs pairDataCon
204             [TyArg result_ty, TyArg realWorldStateTy, VarArg the_result, VarArg new_state]
205                                                         `thenDs` \ the_pair ->
206     let
207         the_alt = (state_and_prim_datacon, [prim_state_id, prim_result_id], the_pair)
208     in
209     returnDs (state_and_prim_ty,
210               \prim_app -> Case prim_app (AlgAlts [the_alt] NoDefault)
211     )
212
213   -- Data types with a single nullary constructor
214   | (maybeToBool maybe_data_type) &&                            -- Data type
215     (null other_data_cons) &&                                   -- Just one constr
216     (null data_con_arg_tys)
217   =
218     newSysLocalDs realWorldStatePrimTy          `thenDs` \ prim_state_id ->
219
220     mkConDs stateDataCon [TyArg realWorldTy, VarArg (Var prim_state_id)]
221                                                 `thenDs` \ new_state ->
222     mkConDs pairDataCon
223             [TyArg result_ty, TyArg realWorldStateTy, VarArg (Var unitDataCon), VarArg new_state]
224                                                 `thenDs` \ the_pair ->
225
226     let
227         the_alt  = (stateDataCon, [prim_state_id], the_pair)
228     in
229     returnDs (realWorldStateTy,
230               \prim_app -> Case prim_app (AlgAlts [the_alt] NoDefault)
231     )
232
233   | otherwise
234   = pprPanic "boxResult: " (ppr PprDebug result_ty)
235
236   where
237     maybe_data_type                        = maybeAppDataTyConExpandingDicts result_ty
238     Just (tycon, tycon_arg_tys, data_cons) = maybe_data_type
239     (the_data_con : other_data_cons)       = data_cons
240
241     data_con_arg_tys                       = dataConArgTys the_data_con tycon_arg_tys
242     (the_prim_result_ty : other_args_tys)  = data_con_arg_tys
243
244     (state_and_prim_datacon, state_and_prim_ty) = getStatePairingConInfo the_prim_result_ty
245 \end{code}
246