[project @ 2001-04-18 01:49:22 by dsyme]
[ghc-hetmet.git] / ghc / compiler / ilxGen / IlxGen.lhs
1 %
2 \section{Generate COM+ extended assembler}
3
4 \begin{code}
5 module IlxGen( ilxGen ) where
6
7 #include "HsVersions.h"
8
9 import Char     ( ord, chr )
10 import StgSyn
11 import Id       ( idType, idName, isDeadBinder, idArityInfo )
12 import IdInfo   ( arityLowerBound )
13 import Var      ( Var, Id, TyVar, isId, isTyVar, tyVarKind, tyVarName )
14 import VarEnv
15 import TyCon    ( TyCon,  tyConPrimRep, isUnboxedTupleTyCon, tyConDataCons, 
16                   newTyConRep, tyConTyVars, isDataTyCon, isAlgTyCon, tyConArity
17                 )
18 import Type     ( liftedTypeKind, openTypeKind, unliftedTypeKind,
19                   isUnLiftedType, isTyVarTy, mkTyVarTy, predRepTy,
20                   splitForAllTys, splitFunTys, applyTy, applyTys
21                 )
22 import TypeRep  ( Type(..) )
23 import DataCon  ( isUnboxedTupleCon, dataConTyCon, dataConRepType, dataConRepArgTys )
24 import Literal  ( Literal(..) )
25 import PrelNames        -- Lots of keys
26 import PrimOp           ( PrimOp(..), CCallTarget(..),CCall(..) )
27 import TysWiredIn       ( mkTupleTy, tupleCon )
28 import PrimRep          ( PrimRep(..) )
29 import Name             ( nameModule, nameOccName, isGlobalName, isLocalName, NamedThing(getName) )
30 import Subst            ( substTy, mkTyVarSubst )
31
32 import Module           ( Module, PackageName, ModuleName, moduleName, 
33                           modulePackage, preludePackage,
34                           isHomeModule, isVanillaModule,
35                           pprModuleName, mkHomeModule, mkModuleName
36                         )
37
38 import UniqFM
39 import BasicTypes       ( Boxity(..) )
40 import CStrings         ( CLabelString, pprCLabelString )
41 import CallConv         ( CallConv )
42 import Outputable
43 import Char             ( ord )
44 import List             ( partition, elem, insertBy,any  )
45 import UniqSet
46 import {-# SOURCE #-}   PprType( pprType )      -- Only called in debug messages
47
48 import TysPrim  ( foreignObjPrimTyCon, weakPrimTyCon, byteArrayPrimTyCon, mutableByteArrayPrimTyCon )
49
50 -- opt_SimplDoEtaReduction is used to help with assembly naming conventions for different
51 -- versions of compiled Haskell code.  We add a ".O" to all assembly and module 
52 -- names when this is set (because that's clue that -O was set).  
53 -- One day this will be configured by the command line.
54 import CmdLineOpts      ( opt_InPackage, opt_SimplDoEtaReduction )
55
56 \end{code}
57
58
59
60 %************************************************************************
61 %*                                                                      *
62 \subsection{Main driver}
63 %*                                                                      *
64 %************************************************************************
65
66 \begin{code}
67 ilxGen :: Module -> [TyCon] -> [(StgBinding,[Id])] -> SDoc
68         -- The TyCons should include those arising from classes
69 ilxGen mod tycons binds_w_srts
70   =  vcat [vcat (map (ilxImportPackage topenv) (uniqSetToList import_packages)),
71             vcat (map (ilxImportModule topenv) (uniqSetToList import_modules)),
72             vcat (map (ilxImportTyCon topenv) (uniqSetToList import_tycons)),
73             vcat (map (ilxImportCCall topenv) (map snd (ufmToList import_ccalls))),
74             vcat (map (ilxTyCon topenv) data_tycons),
75             vcat (map (ilxBindClosures topenv) binds),
76             ilxTopBind mod topenv toppairs
77          ]
78     where
79       binds = map fst binds_w_srts
80       toppairs = ilxPairs binds
81       topenv = extendIlxEnvWithTops (emptyIlxEnv False mod) mod toppairs
82         -- Generate info from class decls as well
83       (import_packages,import_modules,import_tycons,import_ccalls) = importsBinds topenv binds (importsPrelude emptyImpInfo)
84       data_tycons = filter isDataTyCon tycons
85 \end{code}
86
87 %************************************************************************
88 %*                                                                      *
89 \subsection{Find Imports}
90 %*                                                                      *
91 %************************************************************************
92
93 \begin{code}
94
95 importsBinds :: IlxEnv -> [StgBinding] -> ImportsInfo-> ImportsInfo
96 importsBinds env binds = foldR (importsBind env) binds
97
98 importsNone :: ImportsInfo -> ImportsInfo
99 importsNone sofar = sofar
100
101 importsBind :: IlxEnv -> StgBinding -> ImportsInfo -> ImportsInfo
102 importsBind env (StgNonRec _ b rhs) = importsRhs env rhs.importsVar env b
103 importsBind env (StgRec _ pairs) = foldR (\(b,rhs) -> importsRhs env rhs . importsVar env b) pairs
104
105 importsRhs :: IlxEnv -> StgRhs -> ImportsInfo -> ImportsInfo
106 importsRhs env (StgRhsCon _ con args) = importsDataCon env con . importsStgArgs env args
107 importsRhs env (StgRhsClosure _ _ _ _ args body) = importsExpr env body. importsVars env args
108
109 importsExpr :: IlxEnv -> StgExpr -> ImportsInfo -> ImportsInfo
110 importsExpr env (StgLit _) = importsNone
111 importsExpr env (StgApp f args) = importsVar env f.importsStgArgs env args
112 importsExpr env (StgConApp con args) = importsDataCon env con.importsStgArgs env args
113 importsExpr env (StgPrimApp (CCallOp (CCall (StaticTarget c) _ _ cc)) args rty)
114   = addCCallInfo (c,cc, map stgArgType tm_args, rty) . importsStgArgs env args
115   where 
116     (ty_args,tm_args) = splitTyArgs1 args 
117
118 importsExpr env (StgPrimApp _ args res_ty) = importsType env res_ty. importsStgArgs env args
119
120
121 importsExpr env (StgSCC _ expr) = importsExpr env expr
122 importsExpr env (StgCase scrut _ _ bndr _ alts)
123   = importsExpr env scrut. imports_alts alts. importsVar env bndr
124    where
125     imports_alts (StgAlgAlts _ alg_alts deflt)  -- The Maybe TyCon part is dealt with 
126                                                 -- by the case-binder's type
127       = foldR imports_alg_alt alg_alts .  imports_deflt deflt
128        where
129         imports_alg_alt (con, bndrs, _, rhs)
130           = importsExpr env rhs . importsDataCon env con. importsVars env bndrs
131
132     imports_alts (StgPrimAlts _ alg_alts deflt)
133       = foldR imports_prim_alt alg_alts . imports_deflt deflt
134        where
135         imports_prim_alt (_, rhs) = importsExpr env rhs
136     imports_deflt StgNoDefault = importsNone
137     imports_deflt (StgBindDefault rhs) = importsExpr env rhs
138
139
140 importsExpr env (StgLetNoEscape _ _ bind body) = importsExpr env (StgLet bind body)
141 importsExpr env (StgLet bind body)
142   = importsBind env bind .  importsExpr env body
143
144 importsApp env v args = importsVar env v.  importsStgArgs env args
145 importsStgArgs env args = foldR (importsStgArg env) args
146
147 importsStgArg :: IlxEnv -> StgArg -> ImportsInfo -> ImportsInfo
148 importsStgArg env (StgTypeArg ty) = importsType env ty
149 importsStgArg env (StgVarArg v) = importsVar env v
150 importsStgArg env _ = importsNone
151
152 importsVars env vs = foldR (importsVar env) vs
153 importsVar env v = importsName env (idName v). importsType env (idType v)
154
155 importsName env n
156    | isLocalName n = importsNone
157    | ilxEnvModule env == nameModule n  = importsNone
158    | isHomeModule (nameModule n) =  addModuleImpInfo (moduleName (nameModule n))
159 -- See HACK below
160    | isVanillaModule (nameModule n)  && not inPrelude =  importsPrelude
161    | isVanillaModule (nameModule n)  && inPrelude =   addModuleImpInfo (moduleName (nameModule n))
162 -- End HACK
163    | otherwise = addPackageImpInfo (modulePackage (nameModule n))
164
165
166 importsType :: IlxEnv -> Type -> ImportsInfo -> ImportsInfo
167 importsType env ty = importsType2 env (deepIlxRepType ty)
168
169 importsType2 :: IlxEnv -> Type -> ImportsInfo -> ImportsInfo
170 importsType2 env (AppTy f x) =  importsType2 env f .  importsType2 env x
171 importsType2 env (TyVarTy _) = importsNone
172 importsType2 env (TyConApp tc args) =importsTyCon env tc . importsTypeArgs2 env args
173 importsType2 env (FunTy arg res) =  importsType env arg .  importsType2 env res
174 importsType2 env (ForAllTy tv body_ty) =  importsType2 env body_ty
175 importsType2 env (NoteTy _ ty) = importsType2 env ty
176 importsType2 _ _ = panic "IlxGen.lhs: importsType2 ty"
177 importsTypeArgs2 env tys = foldR (importsType2 env) tys
178
179 importsDataCon env dcon = importsTyCon env (dataConTyCon dcon)
180
181 importsTyCon env tc | (not (isDataTyCon tc) || 
182                    isLocalName (getName tc) || 
183                    ilxEnvModule env == nameModule (getName tc)) = importsNone
184 importsTyCon env tc | otherwise = importsName env (getName tc) . addTyConImpInfo tc
185
186 importsPrelude | inPrelude = addModuleImpInfo (mkModuleName "PrelGHC")
187                | otherwise = addPackageImpInfo preludePackage
188
189 type StaticCCallInfo = (CLabelString,CallConv,[Type],Type)
190 type ImportsInfo = (UniqSet PackageName, UniqSet ModuleName, UniqSet TyCon, UniqFM StaticCCallInfo)
191    -- (Packages, Modules, Datatypes, Imported CCalls)
192
193 emptyImpInfo :: ImportsInfo
194 emptyImpInfo = (emptyUniqSet, emptyUniqSet, emptyUniqSet, emptyUFM)
195 addPackageImpInfo p (w,x,y,z) = (addOneToUniqSet w p, x, y,z)
196 addModuleImpInfo m (w,x,y,z) = (w, addOneToUniqSet x m, y,z)
197 addTyConImpInfo tc (w,x,y,z) = (w, x, addOneToUniqSet y tc,z)
198 addCCallInfo info@(nm,a,b,c) (w,x,y,z) = (w, x, y,addToUFM z nm info)
199
200 ilxImportTyCon :: IlxEnv -> TyCon -> SDoc
201 ilxImportTyCon env tycon | isDataTyCon tycon = ilxTyConDef True env tycon
202 ilxImportTyCon _ _ | otherwise =  empty
203
204 ilxImportPackage :: IlxEnv -> PackageName -> SDoc
205 ilxImportPackage _ p = text ".assembly extern ilx" <+> singleQuotes (ppr p <> hscOptionQual) <+> text "{ }"
206
207 ilxImportModule :: IlxEnv -> ModuleName -> SDoc
208 ilxImportModule _ m = text ".module extern ilx" <+> singleQuotes (ppr m  <> hscOptionQual <> text ".dll")
209
210 -- Emit a P/Invoke declaration for the imported C function
211 -- TODO: emit the right DLL name
212 ilxImportCCall :: IlxEnv -> StaticCCallInfo -> SDoc
213 ilxImportCCall env (c,cc,args,ret) = 
214     text ".method static assembly pinvokeimpl" <+> 
215     parens (doubleQuotes (text "HSstd_cbits.dll") <+> text "cdecl") <+> retdoc <+> singleQuotes (pprCLabelString c) <+> 
216     pprCValArgTys ilxTypeL env (map deepIlxRepType (filter (not. isVoidIlxRepType) args)) <+> 
217     text "native unmanaged preservesig { }"
218   where 
219     retdoc = 
220           if isVoidIlxRepType ret then text "void" 
221           else ilxTypeR env (deepIlxRepType ret)
222
223
224 \end{code}
225
226 %************************************************************************
227 %*                                                                      *
228 \subsection{Type declarations}
229 %*                                                                      *
230 %************************************************************************
231
232 \begin{code}
233
234
235 ilxTyCon :: IlxEnv -> TyCon -> SDoc
236 ilxTyCon env tycon =  ilxTyConDef False env tycon
237
238 -- filter to get only dataTyCons?
239 ilxTyConDef importing env tycon = 
240         vcat [empty $$ line,
241               text ".classunion" <+> (if importing then text "extern" else empty) <+> text "thunk" 
242                   <+> ((nameReference env (getName tycon)) <> (ppr tycon))   <+> tyvars_text <+> alts_text]
243    where
244      tyvars = tyConTyVars tycon
245      (ilx_tvs, _) = categorizeTyVars tyvars
246      alts_env = extendIlxEnvWithFormalTyVars env ilx_tvs 
247      tyvars_text = pprTyVarBinders alts_env ilx_tvs 
248      alts = vcat (map (pprIlxDataCon alts_env) (tyConDataCons tycon))
249      alts_text = nest 2 (braces alts)
250
251 pprIlxDataCon env dcon =
252         text ".alternative" <+> pprId dcon <+> 
253         parens (pprSepWithCommas (ilxTypeL env) (map deepIlxRepType (filter (not. isVoidIlxRepType) (dataConRepArgTys dcon))))
254 \end{code}
255
256
257 %************************************************************************
258 %*                                                                      *
259 \subsection{Getting the .closures and literals out}                     *
260 %************************************************************************
261
262 \begin{code}
263
264 ilxBindClosures :: IlxEnv -> StgBinding -> SDoc
265 ilxBindClosures env (StgNonRec _ b rhs) = ilxRhsClosures env (b,rhs)
266 ilxBindClosures env (StgRec _ pairs)  
267   = vcat (map (ilxRhsClosures new_env) pairs)
268   where
269      new_env = extendIlxEnvWithBinds env pairs
270
271 ---------------
272 ilxRhsClosures _ (_, StgRhsCon _ _ _)
273   = empty
274
275 ilxRhsClosures env (bndr, StgRhsClosure _ _ fvs upd args rhs)
276   = vcat [ilxExprClosures next_env rhs,
277
278          empty $$ line,
279          kind_text <+> singleQuotes cloname <+>  free_vs_text,
280          nest 2 (braces (
281             nest 2 (vcat [empty,
282                           vcat [text ".apply" <+> closure_sig_text,
283                                 body_text
284                           ],
285                           empty
286                     ])
287                 ))
288     ]
289   where
290     kind_of_thing = case upd of
291                           Updatable -> ASSERT( null args ) ".thunk"
292                           otherwise -> ".closure"
293     kind_text = text kind_of_thing 
294                 
295     cloname = ilxEnvQualifyByModule env (ppr bndr)
296     next_env = ilxPlaceStgRhsClosure env bndr 
297     (free_vs_text,env_with_fvs) = pprFreeBinders next_env fvs
298
299
300     closure_sig_text =     
301       vcat [ text "()",
302              (case args of 
303                []        -> empty
304                otherwise -> args_text),
305              text "-->" <+>  rty_text]
306
307     (args_text,env_with_args) = pprArgBinders env_with_fvs args
308
309         -- Find the type returned, from the no. of args and the type of "bndr"
310     rty_text = 
311       case retType env_with_fvs (idIlxRepType bndr) args of
312        Just (env,ty) -> 
313           if isVoidIlxRepType ty  then  (text "void")
314           else ilxTypeR env ty 
315        Nothing -> trace "WARNING!  IlxGen.trace could not find return type - see generated ILX for context where this occurs." (text "// Could not find return type:" <+> ilxTypeR env_with_fvs (idIlxRepType bndr)<+> text ", non representation: " <+> ilxTypeR env_with_fvs (idType bndr))
316
317     -- strip off leading ForAll and Fun type constructions
318     -- up to the given number of arguments, extending the environment as
319     -- we go.  
320     retType env ty [] = Just (env, ty)
321     retType env (ForAllTy tv ty) (arg:args) = retType (extendIlxEnvWithTyArgs env [tv]) ty args
322     retType env (FunTy l r) (arg:args) = retType env r args
323     retType _ _ _  = Nothing
324
325         -- Code for the local variables
326     locals = ilxExprLocals env_with_args rhs
327
328     env_with_locals = extendIlxEnvWithLocals env_with_args locals
329
330         -- Code for the body of the main apply method
331     body_code = vcat [empty,
332                       pprIlxLocals env_with_args locals,
333                       ilxExpr (IlxEEnv env_with_locals (mkUniqSet (filter (not.isTyVar) args))) rhs Return,
334                       empty
335                 ]
336
337     body_text = nest 2 (braces (text ".maxstack 100" <+> nest 2 body_code))
338
339
340 pprIlxLocals env [] = empty
341 pprIlxLocals env vs 
342    = text ".locals" <+> parens (pprSepWithCommas (pprIlxLocal env) (filter nonVoidLocal vs))
343   where
344     nonVoidLocal (LocalId v,_) = not (isVoidIlxRepId v)
345     nonVoidLocal _ = True
346
347 pprIlxLocal env (LocalId v,_) = ilxTypeL env (idIlxRepType v) <+> pprId v
348 pprIlxLocal env (LocalSDoc (ty,doc,pin),_) = ilxTypeL env (deepIlxRepType ty) <+> (if pin then text "pinned" else empty) <+> doc
349
350
351 pprFreeBinders env fvs 
352     = (ilx_tvs_text <+> vs_text, env2)
353     where   
354        (free_ilx_tvs, _,free_vs) = categorizeVars fvs
355        real_free_vs = filter (not . isVoidIlxRepId) free_vs
356         -- ignore the higher order type parameters for the moment
357        env1 = extendIlxEnvWithFreeTyVars env free_ilx_tvs 
358        ilx_tvs_text = pprTyVarBinders env1 free_ilx_tvs
359        vs_text = parens (pprSepWithCommas ppr_id real_free_vs)
360        ppr_id v = ilxTypeL env1 (idIlxRepType v) <+> pprId v 
361        env2 = extendIlxEnvWithFreeVars env1 real_free_vs 
362
363 pprIdBinder env v = parens (ilxTypeL env (idIlxRepType v) <+> pprId v)
364
365         -- Declarations for the arguments of the main apply method
366 pprArgBinders env [] = (empty,env)
367 pprArgBinders env (arg:args)
368     = (arg_text <+> rest_text, res_env)
369    where 
370      (arg_text,env') = pprArgBinder env arg
371      (rest_text,res_env) = pprArgBinders env' args 
372
373 -- We could probably omit some void argument binders, but
374 -- don't...
375 pprArgBinder env arg 
376   | isVoidIlxRepId arg = (text "()", extendIlxEnvWithArgs env [arg])
377   | otherwise 
378       = if isTyVar arg then 
379          let env' = extendIlxEnvWithTyArgs env [arg] in 
380          (pprTyVarBinder env' arg, env')
381       else (pprIdBinder env arg,extendIlxEnvWithArgs env [arg])
382
383 --------------
384 -- Compute local variables used by generated method.
385 -- The names of some generated locals are recorded as SDocs.
386
387 data LocalSpec = LocalId Id | LocalSDoc (Type, SDoc, Bool)  -- flag is for pinning
388
389 ilxExprLocals :: IlxEnv -> StgExpr -> [(LocalSpec,Maybe (IlxEnv,StgRhs))]
390 ilxExprLocals env (StgLet bind body)              = ilxBindLocals env bind ++ ilxExprLocals env body
391 ilxExprLocals env (StgLetNoEscape _ _ bind body)  = ilxBindLocals env bind ++ ilxExprLocals env body  -- TO DO????
392 ilxExprLocals env (StgCase scrut _ _ bndr _ alts) 
393      = ilxExprLocals (ilxPlaceStgCaseScrut env) scrut ++ 
394        (if isDeadBinder bndr then [] else [(LocalId bndr,Nothing)]) ++ 
395        ilxAltsLocals env alts
396 ilxExprLocals env (StgPrimApp (CCallOp (CCall (StaticTarget _)_ _ _)) args _) 
397      = concat (ilxMapPlaceArgs 0 ilxCCallArgLocals env args)
398 ilxExprLocals _ _  = []
399
400 -- Generate locals to use for pinning arguments as we cross the boundary
401 -- to C.
402 ilxCCallArgLocals env (StgVarArg v) | pinCCallArg v = 
403    [(LocalSDoc (idType v, ilxEnvQualifyByExact env (ppr v) <> text "pin", True), Nothing)]
404 ilxCCallArgLocals _ _ | otherwise = []
405
406 ilxBindLocals env (StgNonRec _ b rhs) = [(LocalId b,Just (env, rhs))]
407 ilxBindLocals env (StgRec _ pairs)    = map (\(x,y) -> (LocalId x,Just (env, y))) pairs
408
409 ilxAltsLocals env (StgAlgAlts  _ alts deflt) = ilxDefltLocals env deflt ++ concat (ilxMapPlaceAlts ilxAlgAltLocals env alts)
410 ilxAltsLocals env (StgPrimAlts _ alts deflt) = ilxDefltLocals env deflt ++ concat (ilxMapPlaceAlts ilxPrimAltLocals env alts)
411
412 ilxAlgAltLocals env (_, bndrs, _, rhs) = map (\x -> (LocalId x,Nothing)) (filter (\v -> isId v && not (isDeadBinder v)) bndrs) ++ ilxExprLocals env rhs
413 ilxPrimAltLocals env (_, rhs)          = ilxExprLocals env rhs
414
415 ilxDefltLocals _ StgNoDefault   = []
416 ilxDefltLocals env (StgBindDefault rhs) = ilxExprLocals (ilxPlaceStgBindDefault env) rhs
417
418 --------------
419 ilxExprClosures :: IlxEnv -> StgExpr -> SDoc
420 ilxExprClosures env (StgApp _ args)
421   = vcat (ilxMapPlaceArgs 0 (ilxArgClosures) env args)  -- get strings
422 ilxExprClosures env (StgConApp _ args)
423   = vcat (ilxMapPlaceArgs 0 (ilxArgClosures) env args) -- get strings
424 ilxExprClosures env (StgPrimApp _ args _)
425   = vcat (ilxMapPlaceArgs 0 (ilxArgClosures) env args) -- get strings
426 ilxExprClosures env (StgLet bind body)
427   = ilxBindClosures env bind $$ ilxExprClosures (extendIlxEnvWithBinds env (ilxPairs1 bind)) body
428 ilxExprClosures env (StgLetNoEscape _ _ bind body)  -- TO DO????
429   = ilxBindClosures env bind $$ ilxExprClosures (extendIlxEnvWithBinds env (ilxPairs1 bind)) body
430 ilxExprClosures env (StgCase scrut _ _ _ _ alts)
431   = ilxExprClosures (ilxPlaceStgCaseScrut env) scrut $$ ilxAltsClosures env alts 
432 ilxExprClosures env (StgLit lit) 
433   = ilxGenLit env lit 
434 ilxExprClosures _ _ 
435   = empty
436
437 ilxAltsClosures env (StgAlgAlts _ alts deflt)
438   = vcat [ilxExprClosures (ilxPlaceAlt env i) rhs | (i,(_, _, _, rhs))  <- [1..] `zip` alts]
439     $$ 
440     ilxDefltClosures env deflt
441
442 ilxAltsClosures env (StgPrimAlts _ alts deflt)
443   = vcat [ilxExprClosures (ilxPlaceAlt env i) rhs | (i,(_, rhs)) <- [1..] `zip` alts]
444     $$ 
445     vcat [ ilxGenLit (ilxPlacePrimAltLit env i) lit | (i,(lit,_)) <- [1..] `zip` alts]
446     $$ 
447     ilxDefltClosures  env deflt
448
449 ilxDefltClosures env (StgBindDefault rhs) = ilxExprClosures (ilxPlaceStgBindDefault env) rhs
450 ilxDefltClosures _ StgNoDefault   = empty
451
452 ilxArgClosures env (StgLitArg lit) = ilxGenLit env lit 
453 ilxArgClosures _ _ = empty
454
455
456
457 ilxGenLit env (MachStr fs) 
458   = vcat [text ".field static assembly char "  <+> singleQuotes nm <+> text "at" <+> nm <> text "L",
459           text ".data" <+> nm <> text "L" <+> text "= char *("  <> pprFSInILStyle fs  <> text ")"
460          ]
461  where
462    nm = ilxEnvQualifyByExact env (text "string")
463
464 ilxGenLit  _ _ = empty
465
466 \end{code}
467
468
469 %************************************************************************
470 %*                                                                      *
471 \subsection{Generating code}
472 %*                                                                      *
473 %************************************************************************
474
475
476 \begin{code}
477
478 -- Environment when generating expressions
479 data IlxEEnv = IlxEEnv IlxEnv (UniqSet Id)
480
481 data Sequel = Return | Jump IlxLabel
482
483 ilxSequel Return     = text "ret"
484 ilxSequel (Jump lbl) = text "br" <+> pprIlxLabel lbl
485
486 isReturn Return = True
487 isReturn (Jump _) = False
488
489
490 ilxExpr :: IlxEEnv -> StgExpr 
491         -> Sequel       -- What to do at the end
492         -> SDoc
493
494 ilxExpr (IlxEEnv env _) (StgApp fun args) sequel
495   = ilxFunApp env fun args (isReturn sequel) $$ ilxSequel sequel
496
497 -- ilxExpr eenv (StgLit lit) sequel
498 ilxExpr (IlxEEnv env _) (StgLit lit) sequel
499   = pushLit env lit $$ ilxSequel sequel
500
501 -- ilxExpr eenv (StgConApp data_con args) sequel
502 ilxExpr (IlxEEnv env _) (StgConApp data_con args) sequel
503   = text " /* ilxExpr:StgConApp */ " <+>  ilxConApp env data_con args $$ ilxSequel sequel
504
505 -- ilxExpr eenv (StgPrimApp primop args _) sequel
506 ilxExpr (IlxEEnv env _) (StgPrimApp primop args ret_ty) sequel
507   = ilxPrimApp env primop args ret_ty $$ ilxSequel sequel
508
509 --BEGIN TEMPORARY
510 -- The following are versions of a peephole optimizations for "let t = \[] t2[fvs] in t"
511 -- I think would be subsumed by a general treatmenet of let-no-rec bindings??
512 ilxExpr eenv@(IlxEEnv env _) (StgLet (StgNonRec _ bndr (StgRhsClosure _ _ _ _ [] rhs)) (StgApp fun [])) sequel 
513               | (bndr == fun && null (ilxExprLocals env rhs)) -- TO DO???
514   = ilxExpr eenv rhs sequel
515 ilxExpr eenv@(IlxEEnv env _) (StgLetNoEscape _ _ (StgNonRec _ bndr (StgRhsClosure _ _ _ _ [] rhs)) (StgApp fun [])) sequel 
516               | (bndr == fun && null (ilxExprLocals env rhs)) -- TO DO???
517   = ilxExpr eenv rhs sequel
518 --END TEMPORARY
519
520 ilxExpr eenv (StgLet bind body) sequel
521   = ilxBind eenv bind $$ ilxExpr eenv body sequel
522
523
524 ilxExpr eenv (StgLetNoEscape _ _ bind body) sequel -- TO DO???
525   = ilxBind eenv bind $$ ilxExpr eenv body sequel
526
527 -- StgCase: Special case 1 to avoid spurious branch.
528 ilxExpr eenv@(IlxEEnv env live) (StgCase (StgApp fun args) live_in_case _live_in_alts bndr _ alts) sequel
529   = vcat [ilxWipe env (uniqSetToList (live `minusUniqSet` live_in_case)),
530           ilxFunApp (ilxPlaceStgCaseScrut env) fun args False,
531           --ilxWipe env (uniqSetToList (live_in_case `minusUniqSet` _live_in_alts)),
532           --ilxAlts (IlxEEnv env _live_in_alts) bndr alts sequel
533           ilxAlts (IlxEEnv env live_in_case) bndr alts sequel
534     ]
535
536 -- StgCase: Special case 2 to avoid spurious branch.
537 ilxExpr eenv@(IlxEEnv env live) (StgCase (StgPrimApp primop args ret_ty) live_in_case _live_in_alts bndr _ alts) sequel
538   = vcat [ilxWipe env (uniqSetToList (live `minusUniqSet` live_in_case)),
539           ilxPrimApp (ilxPlaceStgCaseScrut env) primop args ret_ty,
540           --ilxWipe env (uniqSetToList (live_in_case `minusUniqSet` _live_in_alts)),
541           --ilxAlts (IlxEEnv env _live_in_alts) bndr alts sequel
542           ilxAlts (IlxEEnv env live_in_case) bndr alts sequel
543     ]
544
545 -- StgCase: Normal case.
546 ilxExpr eenv@(IlxEEnv env live) (StgCase scrut live_in_case _live_in_alts bndr _ alts) sequel
547   = vcat [ilxWipe env (uniqSetToList (live `minusUniqSet` live_in_case)),
548           ilxExpr (IlxEEnv (ilxPlaceStgCaseScrut env) live_in_case) scrut (Jump join_lbl),
549           ilxLabel join_lbl,
550           --ilxWipe env (uniqSetToList (live_in_case `minusUniqSet` _live_in_alts)),
551           --ilxAlts (IlxEEnv env _live_in_alts) bndr alts sequel
552           ilxAlts (IlxEEnv env live_in_case) bndr alts sequel
553     ]
554   where
555     join_lbl = mkJoinLabel bndr
556
557 ilxExpr _ _ _ 
558   = panic "ilxExpr:  Patterns not matched:(IlxEEnv _ _) (StgSCC _ _) _ (IlxEEnv _ _) (StgLam _ _ _) _"
559
560
561 -- Wipe out locals and arguments that are no longer in use, to
562 -- prevent space leaks. If the VM is implemented 100% correctly then
563 -- this should probably not be needed, as the live variable analysis
564 -- in the JIT would tell the GC that these locals and arguments are
565 -- no longer live.  However I'm putting it in here so we can
566 -- check out if it helps.
567 --
568 -- Also, in any case this doesn't capture everything we need.  e.g.
569 -- when making a call:
570 --     case f x of ...
571 -- where x is not used in the alternatives, then the variable x
572 -- is no longer live from the point it is transferred to the call
573 -- onwards.  We should expunge "live_in_case - live_in_alts" right
574 -- before making the call, not after returning from the call....
575 --
576 -- Strictly speaking we also don't need to do this for primitive
577 -- values such as integers and addresses, i.e. things not
578 -- mapped down to GC'able objects.
579 ilxWipe env ids 
580    = vcat (map (ilxWipeOne env) (filter (not.isVoidIlxRepId) ids))
581
582 ilxWipeOne env id
583    = case lookupIlxVarEnv env id of
584           Just Local  -> text "ldloca " <+> pprId id <+> text "initobj" <+> (ilxTypeL env (idIlxRepType id))
585           Just Arg   -> text "deadarg " <+> pprId id <+> text "," <+> (ilxTypeL env (idIlxRepType id))
586           Just (CloVar _)  -> ilxComment (text "not yet wiping closure variable" <+> pprId id )
587           _ -> ilxComment (text "cannot wipe non-local/non-argument" <+> pprId id )
588   where 
589       
590
591 ----------------------
592
593 ilxAlts :: IlxEEnv -> Id -> StgCaseAlts -> Sequel -> SDoc
594 ilxAlts (IlxEEnv env live) bndr alts sequel
595         -- At the join label, the result is on top
596         -- of the stack
597   = vcat [store_in_bndr,
598           do_case_analysis alts
599     ]
600   where
601     scrut_rep_ty = deepIlxRepType (idType bndr)
602
603     store_in_bndr | isDeadBinder bndr = empty
604                   | isVoidIlxRepId bndr 
605                         = ilxComment (text "ignoring store of zero-rep value to be analyzed")
606                   | otherwise         = text "dup" $$ (text "stloc" <+> pprId bndr)
607
608     do_case_analysis (StgAlgAlts _ []    deflt)
609         = do_deflt deflt
610
611     do_case_analysis (StgAlgAlts _ args deflt) 
612         = do_alg_alts ([1..] `zip` args) deflt
613
614     do_case_analysis (StgPrimAlts _ alts deflt)
615         = do_prim_alts ([1..] `zip` alts) $$ do_deflt deflt
616
617     do_alg_alts [(i, alt@(data_con,bndrs,used_flags, rhs))] StgNoDefault | isUnboxedTupleCon data_con
618       -- Collapse the analysis of unboxed tuples where 
619       -- some or all elements are zero-sized
620       --
621       -- TO DO: add bndrs to set of live variables
622           = case bndrs' of
623                   [h] -> bind_collapse bndrs used_flags <+> do_rhs_no_pop alt_env rhs
624                   _ -> bind_components alt_env dcon' bndrs 0 used_flags <+> do_rhs alt_env rhs
625            where 
626             bndrs' = filter (not. isVoidIlxRepId) bndrs
627             -- Replacement unboxed tuple type constructor, used if any of the
628             -- arguments have zero-size and more than one remains.
629             dcon'  = tupleCon Unboxed (length bndrs')
630
631             alt_env = IlxEEnv (ilxPlaceAlt env i) live
632             --alt_env = IlxEEnv (ilxPlaceAlt env i) 
633
634             bind_collapse [] _ = panic "bind_collapse: unary element not found"
635             bind_collapse (h:t) (is_used:used_flags) 
636                 | isVoidIlxRepId h = ilxComment (text "zero-rep binding eliminated") <+> (bind_collapse t used_flags)
637                 | not is_used = ilxComment (text "not used") <+> text "pop"
638                 | otherwise = text "stloc" <+> pprId h
639
640
641     do_alg_alts [(i, alt@(data_con,bndrs,used_flags, rhs))] StgNoDefault 
642             = vcat [text "castdata" <+> sep [ilxTypeR env scrut_rep_ty <> comma,
643                                              ilxConRef env data_con],
644                 do_alg_alt (IlxEEnv (ilxPlaceAlt env i) live) alt
645               ]
646
647     do_alg_alts alts deflt
648         = vcat [text "datacase" <+> sep [ilxTypeR env scrut_rep_ty,text ",",
649                                          pprSepWithCommas pp_case labels_w_alts],
650                 do_deflt deflt,
651                 vcat (map do_labelled_alg_alt labels_w_alts)
652           ]
653         where
654           pp_case (i, (lbl, (data_con, _, _, _))) = parens (ilxConRef env data_con <> comma <> pprIlxLabel lbl)
655           labels_w_alts = [(i,(mkAltLabel bndr i, alt)) | (i, alt) <- alts]
656
657     do_prim_alts [] = empty
658     do_prim_alts ((i, (lit,alt)) : alts) 
659         = vcat [text "dup", pushLit (ilxPlacePrimAltLit env i) lit, text "bne.un" <+> pprIlxLabel lbl, 
660                 do_rhs (IlxEEnv (ilxPlaceAlt env i) live) alt, 
661                 ilxLabel lbl, do_prim_alts alts]
662         where
663           lbl = mkAltLabel bndr i
664
665     do_labelled_alg_alt (i,(lbl, alt)) 
666         = ilxLabel lbl $$ do_alg_alt (IlxEEnv (ilxPlaceAlt env i) live) alt
667
668     do_alg_alt alt_eenv (data_con, bndrs, used_flags, rhs) 
669       = vcat [bind_components alt_eenv data_con bndrs 0 used_flags,
670               do_rhs alt_eenv rhs
671              ]
672
673     bind_components alt_eenv data_con [] n _ = empty
674     bind_components alt_eenv data_con (h:t) n (is_used:used_flags) 
675        | isVoidIlxRepId h 
676              -- don't increase the count in this case
677              = ilxComment (text "zero-rep binding eliminated") 
678                <+> bind_components alt_eenv data_con t n used_flags
679        | otherwise 
680              = bind_component alt_eenv data_con h is_used n 
681                <+> bind_components alt_eenv data_con t (n + 1) used_flags
682
683     bind_component alt_eenv@(IlxEEnv alt_env _) data_con bndr is_used reduced_fld_no 
684         | not is_used 
685             = ilxComment (text "not used")
686         | isVoidIlxRepId bndr 
687             = ilxComment (text "ignoring bind of zero-rep variable")
688         | otherwise   = vcat [text "dup",
689                               ld_data alt_env data_con reduced_fld_no bndr,
690                               text "stloc" <+> pprId bndr]
691
692     do_deflt (StgBindDefault rhs) = do_rhs (IlxEEnv (ilxPlaceStgBindDefault env) live) rhs
693     do_deflt StgNoDefault         = empty
694
695     do_rhs alt_eenv rhs  
696         | isVoidIlxRepId bndr = do_rhs_no_pop alt_eenv rhs     -- void on the stack, nothing to pop
697         | otherwise = text "pop" $$ do_rhs_no_pop alt_eenv rhs  -- drop the value
698
699     do_rhs_no_pop alt_env rhs = ilxExpr alt_env rhs sequel
700
701     ld_data alt_env data_con reduced_fld_no bndr
702       | isUnboxedTupleCon data_con
703       = text "ldfld" <+> sep [text "!" <> integer reduced_fld_no,
704                               ilxTypeR alt_env scrut_rep_ty <> text "::fld" <> integer reduced_fld_no]
705       | otherwise 
706       = text "lddata" <+> sep [ilxTypeR alt_env scrut_rep_ty <> comma, 
707                                ilxConRef env data_con <> comma,
708                                integer reduced_fld_no]
709
710
711 -------------------------
712
713 ilxBestTermArity = 3
714 ilxBestTypeArity = 7
715
716
717 -- Constants of unlifted types are represented as
718 -- applications to no arguments.
719 ilxFunApp env fun [] _ | isUnLiftedType (idType fun)
720   = pushId env fun
721
722 ilxFunApp env fun args tail_call 
723   =     -- For example:
724         --      ldloc f         function of type forall a. a->a
725         --      ldloc x         arg of type Int
726         --      .tail callfunc <Int32> (!0) --> !0
727         --
728     vcat [pushId env fun,ilxFunAppArgs env 0 (idIlxRepType fun) args tail_call known_clo]
729   where
730     known_clo =
731       case lookupIlxBindEnv env fun of
732           Just (_, StgRhsClosure  _ _ _ Updatable _ _) ->  Nothing 
733           Just (place, StgRhsClosure  _ _ fvs _ args _)  -> Just (place,fun,args,fvs)
734           _ ->  trace (show fun ++ " --> " ++ show (arityLowerBound (idArityInfo fun)))  Nothing 
735
736 -- Push as many arguments as ILX allows us to in one go.
737 -- Recurse until we're done.
738 ilxFunAppArgs env num_sofar funty args tail_call known_clo
739  =   vcat [vcat (ilxMapPlaceArgs num_sofar pushArgWithVoids env now_args),
740            call_instr <+> (if num_sofar == 0 then text "() /* first step in every Haskell app. is to a thunk */ " else empty)
741                      <+> now_args_text
742                      <+> text "-->" 
743                      <+> later_ty_text,
744            later
745           ]
746   where
747     now_args_text = 
748       case now_arg_tys of
749         [] -> empty
750         _ -> hsep (map (pprIlxArgInfo env_after_now_tyvs) now_arg_tys)
751
752     later_ty_text
753         | isVoidIlxRepType later_ty = text "void"
754         | otherwise = ilxTypeR env_after_now_tyvs later_ty
755
756     (now_args,now_arg_tys,env_after_now_tyvs,later_args,later_ty) = 
757         case args of
758           (StgTypeArg v:rest) -> get_type_args ilxBestTypeArity args env funty
759           _ -> get_term_args 0 ilxBestTermArity args env funty
760
761      -- Only apply up to maxArity real (non-type) arguments
762      -- at a time.  ILX should, in principle, allow us to apply
763      -- arbitrary numbers, but you will get more succinct 
764      -- (and perhaps more efficient) IL code
765      -- if you apply in clumps according to its maxArity setting.
766      -- This is because it has to unwind the stack and store it away
767      -- in local variables to do the partial applications.
768      --
769      -- Similarly, ILX only allows one type application at a time, at
770      -- least until we implement unwinding the stack for this case.
771      --
772      -- NB: In the future we may have to be more careful 
773      -- all the way through 
774      -- this file to bind type variables as we move through
775      -- type abstractions and "forall" types.  This would apply
776      -- especially if the type variables were ever bound by expressions
777      -- involving the type variables.  
778
779     -- This part strips off at most "max" term applications or one type application
780     get_type_args 0 args env funty = ([],[],env,args,funty)
781     get_type_args max args env (NoteTy _ ty) = 
782           trace "IlxGen Internal Error: non representation type passed to get_args" (get_type_args max args env ty)
783     get_type_args max ((arg@(StgTypeArg v)):rest) env (ForAllTy tv rem_funty) 
784         = if isIlxTyVar tv then 
785             let env2 = extendIlxEnvWithFormalTyVars env [tv] in 
786             let rest_ty = deepIlxRepType (substTy (mkTyVarSubst [tv] [v]) rem_funty) in 
787             let (now,now_tys,env3,later,later_ty) = get_type_args (max - 1) rest env rest_ty in 
788             let arg_ty = mkTyVarTy tv in 
789             (arg:now,(arg,arg_ty):now_tys,env2, later, later_ty)
790           else 
791              get_type_args max rest env rem_funty  -- ? subst??
792     get_type_args _ (StgTypeArg _:_) _ _ = trace "IlxGen Internal Error: get_type_args could not get ForAllTy for corresponding arg" ([],[],env,[],funty)
793     get_type_args _ args env funty = ([],[],env,args,funty)
794
795     get_term_args n max args env (NoteTy _ ty)
796        -- Skip NoteTy types 
797        = trace "IlxGen Internal Error: non representation type passed to get_term_args" (get_term_args n max args env ty)
798     get_term_args n 0 args env funty
799        -- Stop if we've hit the maximum number of ILX arguments to apply n one hit.
800        = ([],[],env,args,funty)
801     get_term_args n max args env funty
802       | (case known_clo of
803            Just (_,_,needed,_) -> (length needed == n)
804            Nothing -> False)
805        -- Stop if we have the optimal number for a direct call
806        = ([],[],env,args,funty)
807     get_term_args _ _ (args@(StgTypeArg _:_)) env funty 
808        -- Stop if we hit a type arg.
809        = ([],[],env,args,funty)
810     get_term_args n max (h:t) env (FunTy dom ran)
811        -- Take an argument.
812        = let (now,now_tys,env2,later,later_ty) = get_term_args (n+1) (max - 1) t env ran in 
813          (h:now, (h,dom):now_tys,env2,later,later_ty)
814     get_term_args _ max (h:t) env funty = trace "IlxGen Internal Error: get_term_args could not get FunTy or ForAllTy for corresponding arg" ([],[],env,[],funty)
815     get_term_args _ max args env funty = ([],[],env,args,funty)
816
817     -- Are there any remaining arguments?
818     done  = case later_args of
819           [] -> True
820           _ -> False
821
822     -- If so, generate the subsequent calls.
823     later = if done then text "// done"  
824             else ilxFunAppArgs env (num_sofar + length now_args) later_ty later_args tail_call Nothing
825
826     -- Work out whether to issue a direct call a known closure (callclo) or
827     -- an indirect call (callfunc).  Basically, see if the identifier has
828     -- been let-bound, and then check we are applying exactly the right 
829     -- number of arguments.  Also check that it's not a thunk (actually, this
830     -- is done up above).
831     -- 
832     -- The nasty "all" check makes sure that 
833     -- the set of type variables in scope at the callsite is a superset 
834     -- of the set of type variables needed for the direct call.  This is
835     -- is needed because not all of the type variables captured by a 
836     -- let-bound binding will get propogated down to the callsite, and 
837     -- the ILX system of polymorphism demands that the free type variables
838     -- get reapplied when we issue the direct "callclo".  The
839     -- type variables are in reality also "bound up" in the closure that is
840     -- passed as the first argument, so when we do an indirect call
841     -- to that closure we're fine, which is why we don't need them in 
842     -- the "callfunc" case.
843     basic_call_instr =
844       case known_clo of
845         Just (known_env,fun,needed,fvs) | (length needed == length now_args) && 
846                                           all (\x -> elemIlxTyEnv x env) free_ilx_tvs -> 
847            vcat [text "callclo class",
848                  nameReference env (idName fun) <+> singleQuotes (ilxEnvQualifyByModule env (ppr fun)),
849                  pprTypeArgs ilxTypeR env (map mkTyVarTy free_ilx_tvs)]
850            <> text ","
851           where 
852            (free_ilx_tvs, free_non_ilx_tvs,free_vs) = categorizeVars fvs
853         otherwise -> text "callfunc"
854     call_instr =
855            if (tail_call && done) then text "tail." <+> basic_call_instr
856            else basic_call_instr
857
858
859 --------------------------
860 -- Print the arg info at the call site
861 -- For type args we are, at the moment, required to
862 -- give both the actual and the formal (bound).  The formal
863 -- bound is always System.Object at the moment (bounds are
864 -- not properly implemented in ILXASM in any case, and nor do
865 -- we plan on making use og them) For
866 -- non-type args the actuals are on the stack, and we just give the
867 -- formal type.
868 pprIlxArgInfo env (StgTypeArg  arg,ty) =  
869     angleBrackets (ilxTypeR env (deepIlxRepType arg) <+> ilxComment (text "actual for tyvar")) <+> text "<class [mscorlib] System.Object>" 
870 pprIlxArgInfo env (_,ty) =  
871     parens (ilxTypeL env ty)
872
873
874 ----------------------------
875 -- Code for a binding
876 ilxBind :: IlxEEnv -> StgBinding -> SDoc
877 ilxBind eenv@(IlxEEnv env _) bind = 
878     vcat [vcat (map (ilxRhs env rec) pairs), 
879           vcat (map (ilxFixupRec env rec) pairs)]
880        where 
881          rec = ilxRecIds1 bind
882          pairs = ilxPairs1 bind
883
884
885 ----------------------------
886 -- Allocate a closure or constructor.  Fix up recursive definitions.
887 ilxRhs :: IlxEnv -> [Id] -> (Id, StgRhs) -> SDoc
888
889 ilxRhs env rec (bndr, _) | isVoidIlxRepId bndr  
890   = empty
891
892 ilxRhs env rec (bndr, StgRhsCon _ con args)
893   = vcat [text " /* ilxRhs:StgRhsCon */ " <+> ilxConApp env con args,
894            text "stloc" <+> pprId bndr
895           ]
896
897 ilxRhs env rec (bndr, StgRhsClosure _ _ fvs upd args rhs)
898   =     -- Assume .closure v<any A>(int64,!A) { 
899         --              .apply <any B> (int32) (B) { ... }
900         --         }
901         -- Then
902         --    let v = \B (x:int32) (y:B). ... 
903         -- becomes:
904         --    newclo v<int32>(int64,!0)
905         --    stloc v
906     vcat [vcat (map pushFv free_vs),
907           (if null free_non_ilx_tvs then empty else (ilxComment (text "ignored some higher order type arguments in application - code will be non-verifiable"))),
908           text "newclo" <+> clotext,
909           text "stloc" <+> pprId bndr
910     ]
911   where
912     pushFv id = if elem id rec then text "ldnull" else pushId env id
913     (free_ilx_tvs, free_non_ilx_tvs,free_vs) = categorizeVars fvs
914     clotext = pprIlxBoxedTyConApp env (ilxEnvQualifyByModule env (ppr bndr)) (map mkTyVarTy free_ilx_tvs)
915
916 ilxFixupRec env rec (bndr, _) | isVoidIlxRepId bndr = ilxComment (text "no recursive fixup for void-rep-id")
917
918 ilxFixupRec env rec (bndr, StgRhsCon _ con args)
919   = text "// no recursive fixup"
920
921 ilxFixupRec env rec (bndr, StgRhsClosure _ _ fvs upd args rhs)
922      = vcat [vcat (map fixFv rec)]
923   where
924     fixFv recid = if elem recid fvs then 
925                     vcat [pushId env bndr,
926                           pushId env recid,
927                           text "stclofld" <+> clotext <> text "," <+> pprId recid] 
928                 else text "//no fixup needed for" <+> pprId recid
929     (free_ilx_tvs, free_non_ilx_tvs,free_vs) = categorizeVars fvs
930     clotext = pprIlxBoxedTyConApp env (ilxEnvQualifyByModule env (ppr bndr)) (map mkTyVarTy free_ilx_tvs)
931
932
933
934 ---------------------------------------------
935 -- Code for a top-level binding in a module
936 ilxPairs binds = concat (map ilxPairs1 binds)
937
938 ilxPairs1 (StgNonRec _ bndr rhs) = [(bndr,rhs)]
939 ilxPairs1 (StgRec _ pairs)       = pairs
940
941 ilxRecIds1 (StgNonRec _ bndr rhs) = []
942 ilxRecIds1 (StgRec _ pairs)       = map fst pairs
943
944 ---------------------------------------------
945 -- Code for a top-level binding in a module
946 -- TODO: fix up recursions amongst CAF's
947 -- e.g. 
948 --    x = S x
949 -- for infinity...
950 -- 
951 -- For the moment I've put in a completely spurious "reverse"...
952 --
953 -- Consider: make fixing up of CAF's part of ILX?  i.e.
954 -- put static, constant, allocated datastructures into ILX. 
955
956 stableSortBy :: (a -> a -> Ordering) -> [a] -> [a]
957 stableSortBy f (h:t) = insertBy f h (stableSortBy f t)
958 stableSortBy f [] = []
959
960 usedBy :: (Id,StgRhs) -> (Id,StgRhs) -> Ordering
961 usedBy (m,_) (_,StgRhsCon _ data_con args) | any (isArg m) args = LT
962 usedBy (m,_) (n,_) | m == n = EQ
963 usedBy (m,_) (_,_) = GT
964
965 isArg m  (StgVarArg n) = (n == m)
966 isArg m _ = False
967
968
969 ilxTopBind :: Module -> IlxEnv -> [(Id,StgRhs)] -> SDoc
970 --ilxTopBind mod env (StgNonRec _ bndr rhs) = 
971 --ilxTopRhs env (bndr,rhs)
972 ilxTopBind mod env pairs       = 
973    vcat [text ".class" <+> pprId mod,
974          nest 2 (braces (nest 2 (vcat [empty,cctor, flds, empty])))]
975      where
976        cctor = vcat [text ".method static rtspecialname specialname void .cctor()",
977                      nest 2 (braces 
978                       (nest 2 (vcat [text ".maxstack 100",
979                                      text "ldstr \"LOG: initializing module" <+> pprId mod <+> text "\" call void ['mscorlib']System.Console::WriteLine(class [mscorlib]System.String)",
980                                      vcat (map (ilxTopRhs mod env) (stableSortBy usedBy pairs)), 
981                                      text "ldstr \"LOG: initialized module" <+> pprId mod <+> text "\" call void ['mscorlib']System.Console::WriteLine(class [mscorlib]System.String)",
982                                      text "ret",
983                                      empty])))]
984        flds =   vcat (map (ilxTopRhsStorage mod env) pairs)
985
986 --ilxTopRhs mod env (bndr, _) | isVoidIlxRepId bndr 
987 --  = empty
988
989 ilxTopRhs mod env (bndr, StgRhsClosure _ _ fvs upd args rhs)
990   = vcat [vcat (map (pushId env) free_vs),
991          (if null free_non_ilx_tvs then empty else (ilxComment (text "ignored some higher order type arguments in application - code will be non verifiable...."))),
992           text "newclo" <+> pprIlxBoxedTyConApp env (ilxEnvQualifyByModule env (ppr bndr)) (map mkTyVarTy free_ilx_tvs),
993           text "stsfld"  <+> pprFieldRef env (mod,bndTy,bndr)
994     ]
995   where
996     (free_ilx_tvs, free_non_ilx_tvs,free_vs) = categorizeVars fvs
997     bndTy = idIlxRepType bndr
998
999 ilxTopRhs mod env (bndr, StgRhsCon _ data_con args)
1000   = vcat [ text " /* ilxTopRhs: StgRhsCon */ " <+> ilxConApp env data_con args, 
1001            text "stsfld" <+> pprFieldRef env (mod,bndTy,bndr)
1002     ]
1003   where
1004     bndTy = idIlxRepType bndr
1005
1006 pprFieldRef env (mod,ty,id) 
1007   =  ilxTypeL env ty <+> moduleReference env mod <+> pprId mod <> text "::" <> pprId id
1008
1009 ilxTopRhsStorage mod env (bndr, StgRhsClosure _ _ _ _ _ _) 
1010   =   text ".field public static " <+> ilxTypeL env bndTy <+> pprId bndr
1011   where
1012     bndTy = idIlxRepType bndr
1013 ilxTopRhsStorage mod env (bndr, StgRhsCon _ _ _) 
1014   =   text ".field public static " <+> ilxTypeL env bndTy <+> pprId bndr
1015   where
1016     bndTy = idIlxRepType bndr
1017
1018 --------------------------------------
1019 -- Push an argument
1020 pushArgWithVoids =  pushArg_aux True
1021 pushArg = pushArg_aux False
1022
1023 pushArg_aux voids env (StgTypeArg ty) = empty
1024 pushArg_aux voids env (StgVarArg var) = pushId_aux voids env var
1025 pushArg_aux voids env (StgLitArg lit) = pushLit env lit
1026
1027
1028 mapi f l = mapi_aux f l 0
1029
1030 mapi_aux f [] n = []
1031 mapi_aux f (h:t) n = f n h : mapi_aux f t (n+1)
1032
1033 --------------------------------------
1034 -- Push an Id
1035 pushId = pushId_aux False
1036
1037 pushId_aux :: Bool -> IlxEnv -> Id -> SDoc
1038 pushId_aux voids _ id | isVoidIlxRepId id =
1039    /* if voids then  text "ldunit" else */ ilxComment (text "pushId: void rep skipped")
1040 pushId_aux _ env var 
1041   = case lookupIlxVarEnv env var of
1042           Just Arg    -> text "ldarg"    <+> pprId var
1043           Just (CloVar n) -> text "ldenv" <+> int n
1044           Just Local  -> text "ldloc"    <+> pprId var
1045           Just (Top m)  -> 
1046              vcat [ilxComment (text "pushId (Top) " <+> pprId m), 
1047                    text "ldsfld" <+> ilxTypeL env (idIlxRepType var)
1048                       <+> moduleReference env m <+> pprId (moduleName m) <> text "::" <> pprId var]
1049
1050           Nothing ->  
1051              vcat [ilxComment (text "pushId (import) " <+> pprIlxTopVar env var), 
1052                    text "ldsfld" <+> ilxTypeL env (idIlxRepType var) 
1053                     <+> pprIlxTopVar env var]
1054
1055 --------------------------------------
1056 -- Push a literal
1057 pushLit env (MachChar c)   = text "ldc.i4" <+> int c
1058 pushLit env (MachStr s)    = text "ldsflda char "  <+> ilxEnvQualifyByExact env (text "string") -- pprFSInILStyle s 
1059 pushLit env (MachInt i)    = text "ldc.i4" <+> integer i
1060 pushLit env (MachInt64 i)  = text "ldc.i8" <+> integer i
1061 pushLit env (MachWord w)   = text "ldc.i4" <+> integer w <+> text "conv.u4"
1062 pushLit env (MachWord64 w) = text "ldc.i8" <+> integer w <+> text "conv.u8"
1063 pushLit env (MachFloat f)  = text "ldc.r4" <+> rational f
1064 pushLit env (MachDouble f) = text "ldc.r8" <+> rational f
1065 pushLit env (MachLitLit _ _) = trace "WARNING: Cannot compile MachLitLit to ILX in IlxGen.lhs" (text "// MachLitLit!!!  Not valid in ILX!!")
1066 pushLit env (MachAddr w) = text "ldc.i4" <+> integer w <+> text "conv.i"
1067
1068
1069 pprIlxTopVar env v
1070   | isGlobalName n = (nameReference env n) <> pprId (nameModule n) <> text "::" <> singleQuotes (ppr (nameModule n) <> text "_" <> ppr (nameOccName n))
1071   | otherwise      = pprId (nameOccName n)
1072   where
1073     n = idName v
1074
1075 \end{code}
1076
1077
1078 %************************************************************************
1079 %*                                                                      *
1080 \subsection{Printing types}
1081 %*                                                                      *
1082 %************************************************************************
1083
1084
1085 \begin{code}
1086
1087 isVoidIlxRepType (NoteTy   _ ty) = isVoidIlxRepType ty
1088 isVoidIlxRepType (TyConApp tc _) | (tyConPrimRep tc == VoidRep) = True
1089 isVoidIlxRepType (TyConApp tc tys) 
1090   = case newTyConRep tc of
1091          Just rep_ty -> isVoidIlxRepType (applyTys rep_ty tys)
1092          Nothing     -> 
1093             isUnboxedTupleTyCon tc && 
1094             null (filter (not. isVoidIlxRepType) tys)
1095 isVoidIlxRepType _ = False
1096
1097 isVoidIlxRepId id = isVoidIlxRepType (idType id)
1098
1099
1100
1101 -- Get rid of all NoteTy and NewTy artifacts
1102 deepIlxRepType :: Type -> Type
1103 deepIlxRepType (FunTy l r)
1104   = FunTy (deepIlxRepType l) (deepIlxRepType r)
1105
1106 deepIlxRepType ty@(TyConApp tc tys) 
1107   = case newTyConRep tc of
1108          Just rep_ty -> 
1109            let res = deepIlxRepType (applyTys rep_ty tys) in 
1110            if not (length tys == tyConArity tc ) then 
1111              pprTrace "deepIlxRepType" (text "length tys <> tyConArity tc, ty = " <+> pprType ty <+> text ", length tys = " <+> ppr (length tys) <+> text ", tyConArity = " <+> ppr (tyConArity tc)) res 
1112            else res
1113                 -- The assert should hold because deepIlxRepType should
1114                 -- only be applied to *types* (of kind *)
1115          Nothing     -> 
1116            -- collapse UnboxedTupleTyCon down when it contains VoidRep types.
1117             if isUnboxedTupleTyCon tc then 
1118                let tys' = map deepIlxRepType (filter (not. isVoidIlxRepType) tys) in 
1119                case tys' of
1120                   [h] -> h
1121                   _ -> mkTupleTy Unboxed (length tys') tys'
1122             else 
1123               TyConApp tc (map deepIlxRepType tys)
1124 deepIlxRepType (AppTy f x)  = AppTy (deepIlxRepType f) (deepIlxRepType x)
1125 deepIlxRepType (ForAllTy b ty) = ForAllTy b (deepIlxRepType ty)
1126 deepIlxRepType (NoteTy   _ ty) = deepIlxRepType ty
1127 deepIlxRepType (PredTy p)      = deepIlxRepType (predRepTy p)
1128 deepIlxRepType ty@(TyVarTy tv) = ty
1129
1130 idIlxRepType id = deepIlxRepType (idType id)
1131
1132 --------------------------
1133 -- Some primitive type constructors are not thunkable.
1134 -- Everything else needs to be marked thunkable.
1135 ilxTypeL :: IlxEnv -> Type -> SDoc
1136
1137 ilxTypeL env ty | isUnLiftedType ty ||  isVoidIlxRepType ty = ilxTypeR env ty
1138 ilxTypeL env ty = text "thunk" <> angleBrackets (ilxTypeR env ty)
1139
1140
1141 --------------------------
1142 -- Print non-thunkable version of type.
1143 --
1144
1145 ilxTypeR :: IlxEnv -> Type -> SDoc
1146 ilxTypeR env ty | isVoidIlxRepType ty = text "/* unit skipped */"
1147 ilxTypeR env ty@(AppTy f _) | isTyVarTy f    = ilxComment (text "type app:" <+> pprType ty) <+> (text "class [mscorlib]System.Object")
1148 ilxTypeR env ty@(AppTy f x)     = trace "ilxTypeR: should I be beta reducing types?!" (ilxComment (text "ilxTypeR: should I be beta reducing types...") <+> ilxTypeR env (applyTy f x))
1149 ilxTypeR env (TyVarTy tv)       = ilxTyVar env tv
1150
1151 -- The following is a special rule for types constructed out of 
1152 -- higher kinds, e.g. Monad f or Functor f.  
1153 --
1154 -- The code below is not as general as it should be, but as I
1155 -- have no idea if this approach will even work, I'm going to
1156 -- just try it out on some simple cases arising from the prelude.
1157 ilxTypeR env ty@(TyConApp tc (h:t)) | isAlgTyCon tc && null (tyConTyVars tc)
1158    = ilxComment (text "what on earth? 2") <+> (ilxTypeR env (TyConApp tc t))
1159 ilxTypeR env ty@(TyConApp tc (h:t)) | isAlgTyCon tc && not (isIlxTyVar (hd (tyConTyVars tc)))
1160    = ilxTypeR env (TyConApp tc t)
1161 ilxTypeR env (TyConApp tc args) = ilxTyConApp env tc args
1162
1163   -- nb. the only legitimate place for VoidIlxRepTypes to occur in normalized IlxRepTypes 
1164   -- is on the left of an arrow
1165   --  We could probably eliminate all but a final occurrence of these.
1166 ilxTypeR env (FunTy arg res)| isVoidIlxRepType res 
1167     = pprIlxFunTy (ilxTypeL env arg) (text "void")
1168 ilxTypeR env (FunTy arg res)
1169     = pprIlxFunTy (ilxTypeL env arg) (ilxTypeR env res)
1170
1171 ilxTypeR env ty@(ForAllTy tv body_ty) | isIlxTyVar tv
1172   = parens (text "forall" <+> pprTyVarBinders env' [tv] <+> nest 2 (ilxTypeR env' body_ty))
1173     where
1174        env' = extendIlxEnvWithFormalTyVars env [tv]
1175
1176 ilxTypeR env ty@(ForAllTy tv body_ty) | otherwise
1177   = ilxComment (text "higher order type var " <+> pprId tv) <+>
1178     pprIlxFunTy (text "class [mscorlib]System.Object") (ilxTypeR env body_ty)
1179
1180 ilxTypeR env (NoteTy _ ty)       
1181    = trace "WARNING! non-representation type given to ilxTypeR: see generated ILX for context where this occurs"
1182      (vcat [text "/* WARNING! non-representation type given to ilxTypeR! */",
1183            ilxTypeR env ty ])
1184
1185 pprIlxFunTy dom ran = parens (hsep [text "func",parens dom,text "-->", ran])
1186
1187 ilxTyConApp env tc args =
1188    case lookupUFM tyPrimConTable (getUnique tc) of
1189         Just f  -> f args env
1190         Nothing -> 
1191             (if isUnboxedTupleTyCon tc then pprIlxUnBoxedTyConApp else pprIlxBoxedTyConApp)
1192               env ((nameReference env (getName tc)) <> (ppr tc)) args
1193
1194 pprIlxUnBoxedTyConApp env tcdoc args = text "value class" <+> tcdoc <> pprTypeArgs ilxTypeL env args
1195 pprIlxBoxedTyConApp env tcdoc args = text "class" <+> tcdoc <> pprTypeArgs ilxTypeR env args
1196
1197 -- Returns e.g: <Int32, Bool>
1198 pprTypeArgs f env tys = pprTypeArgs_aux f env (filter (not . isVoidIlxRepType) tys)
1199
1200 pprTypeArgs_aux f env []  = empty
1201 pprTypeArgs_aux f env tys = angleBrackets (pprSepWithCommas (f env) tys)
1202
1203
1204 pprTyVarBinders :: IlxEnv -> [TyVar] -> SDoc
1205 -- Returns e.g: <class [mscorlib]System.Object> <class [mscorlib]System.Object>
1206 -- plus a new environment with the type variables added.
1207 pprTyVarBinders env [] = empty
1208 pprTyVarBinders env tvs = angleBrackets (pprSepWithCommas (pprTyVarBinder_aux env) tvs)
1209
1210 pprTyVarBinder :: IlxEnv -> TyVar -> SDoc
1211 pprTyVarBinder env tv = 
1212     if isIlxTyVar tv then 
1213        angleBrackets (pprTyVarBinder_aux env tv)
1214     else
1215        ilxComment (text "higher order tyvar" <+> pprId tv <+> 
1216                          text ":" <+> ilxTypeR env (tyVarKind tv)) <+>
1217              ilxComment (text "omitted")
1218              -- parens (text "class [mscorlib]System.Object" <+> pprId tv)
1219
1220
1221 pprTyVarBinder_aux env tv = 
1222    ilxComment (text "tyvar" <+> pprId tv <+> text ":" <+> 
1223                         ilxTypeR env (tyVarKind tv)) <+>
1224              (text "class [mscorlib]System.Object")
1225
1226 -- Only a subset of Haskell types can be generalized using the type quantification
1227 -- of ILX
1228 isIlxForAllKind h = 
1229         ( h == liftedTypeKind) ||
1230         ( h == unliftedTypeKind) ||
1231         ( h == openTypeKind)
1232
1233 isIlxTyVar v = isTyVar v && isIlxForAllKind (tyVarKind v)
1234
1235 categorizeVars fvs = (ilx_tvs, non_ilx_tvs, vs)
1236          where
1237            (tvs, vs) = partition isTyVar fvs
1238            (ilx_tvs, non_ilx_tvs) = categorizeTyVars tvs
1239
1240 categorizeTyVars tyvs = partition isIlxTyVar tyvs
1241
1242 pprValArgTys ppr_ty env tys = parens (pprSepWithCommas (ppr_ty env) tys)
1243
1244 pprId id = singleQuotes (ppr id)
1245
1246 \end{code}                      
1247
1248 %************************************************************************
1249 %*                                                                      *
1250 \subsection{IlxEnv}     
1251 %*                                                                      *
1252 %************************************************************************
1253
1254 \begin{code}
1255 type IlxTyEnv = [TyVar]
1256 emptyIlxTyEnv = []
1257
1258 -- Nb. There is currently no distinction between the kinds of type variables.
1259 -- We may need to add this to print out correct numbers, esp. for
1260 -- "forall" types
1261 extendIlxTyEnvWithFreeTyVars env tyvars = env ++ mkIlxTyEnv tyvars -- bound by .closure x<...> in a closure declared with type parameters
1262 extendIlxTyEnvWithFormalTyVars env tyvars = env ++ mkIlxTyEnv tyvars -- bound by "forall <...>" in a type
1263 extendIlxTyEnvWithTyArgs env tyvars = env ++ mkIlxTyEnv tyvars -- bound by "<...>" in a closure implementing a universal type
1264
1265 formalIlxTyEnv tyvars = mkIlxTyEnv tyvars
1266 mkIlxTyEnv tyvars = [ v | v <- tyvars, isIlxTyVar v ]
1267
1268 data HowBound = Top Module      -- Bound in a modules
1269               | Arg     -- Arguments to the enclosing closure
1270               | CloVar Int -- A free variable of the enclosing closure
1271                            -- The int is the index of the field in the 
1272                            -- environment
1273               | Local   -- Local let binding
1274
1275 -- The SDoc prints a unique name for the syntactic block we're currently processing,
1276 -- e.g. Foo_bar_baz when inside closure baz inside closure bar inside module Foo.
1277 data IlxEnv = IlxEnv (Module, IlxTyEnv, IdEnv HowBound,IdEnv (IlxEnv, StgRhs), Place,Bool)
1278 type Place = (SDoc,SDoc)
1279
1280 ilxTyVar  env tv
1281   = go 0 (ilxEnvTyEnv env)
1282   where
1283     go n []                 
1284       = pprTrace "ilxTyVar" (pprId tv <+> text "tv_env = { "
1285            <+> pprSepWithCommas
1286                  (\x -> pprId x <+> text ":" <+> ilxTypeR env (tyVarKind x)) 
1287                (ilxEnvTyEnv env) <+> text "}") 
1288         (char '!' <> pprId tv) 
1289     go n (x:xs)
1290       = {- pprTrace "go" (ppr (tyVarName tv) <+> ppr (tyVarName x)) -}
1291         (if tyVarName x== tyVarName tv then  char '!' <> int n <+> ilxComment (char '!' <> pprId tv) 
1292          else go (n+1) xs)
1293
1294 emptyIlxEnv :: Bool -> Module -> IlxEnv
1295 emptyIlxEnv trace mod = IlxEnv (mod, emptyIlxTyEnv, emptyVarEnv, emptyVarEnv, (ppr mod,empty),trace)
1296
1297 nextPlace place sdoc = place <> sdoc
1298 usePlace  place sdoc = place <> sdoc
1299
1300 ilxEnvModule (IlxEnv (m, _, _,  _, _,_)) = m
1301 ilxEnvSetPlace (IlxEnv (m, tv_env, id_env,  bind_env, (mod,exact),tr)) sdoc 
1302    = IlxEnv (m, tv_env, id_env,  bind_env, (mod, sdoc),tr)
1303 ilxEnvNextPlace (IlxEnv (m, tv_env, id_env,  bind_env, (mod,exact),tr)) sdoc 
1304    = IlxEnv (m, tv_env, id_env,  bind_env, (mod, nextPlace exact sdoc),tr)
1305 ilxEnvQualifyByModule (IlxEnv (_, _, _, _,(mod,_),_)) sdoc = usePlace mod sdoc
1306 ilxEnvQualifyByExact (IlxEnv (_, _, _, _,(mod,exact),_)) sdoc = usePlace mod sdoc <> usePlace exact sdoc
1307
1308 ilxPlaceStgBindDefault env = ilxEnvNextPlace env (text "D")
1309 ilxPlaceStgRhsClosure env bndr = ilxEnvSetPlace env (ppr bndr) -- binders are already unique
1310 ilxPlaceStgCaseScrut env = ilxEnvNextPlace env (text "S")
1311
1312 ilxPlaceAlt :: IlxEnv -> Int -> IlxEnv
1313 ilxPlaceAlt env i = ilxEnvNextPlace env (text "a" <> int i)
1314 ilxPlacePrimAltLit env i = ilxEnvNextPlace env (text "P" <> int i)
1315 ilxMapPlaceArgs start f env args = [ f (ilxEnvNextPlace env (text "A" <> int i)) a | (i,a) <- [start..] `zip` args ]
1316 ilxMapPlaceAlts f env alts = [ f (ilxPlaceAlt env i) alt | (i,alt) <- [1..] `zip` alts ]
1317
1318 extendIlxEnvWithFreeTyVars (IlxEnv (mod, tv_env, id_env,  bind_env, place,tr)) tyvars 
1319   = IlxEnv (mod, extendIlxTyEnvWithFreeTyVars tv_env tyvars,id_env,  bind_env, place,tr)
1320
1321 extendIlxEnvWithFormalTyVars (IlxEnv (mod, tv_env, id_env,  bind_env, place,tr)) tyvars 
1322   = IlxEnv (mod, extendIlxTyEnvWithFormalTyVars tv_env tyvars,id_env,  bind_env, place,tr)
1323
1324 extendIlxEnvWithTyArgs (IlxEnv (mod, tv_env, id_env,  bind_env, place,tr)) tyvars 
1325   = IlxEnv (mod, extendIlxTyEnvWithTyArgs tv_env tyvars,id_env,  bind_env, place,tr)
1326
1327 extendIlxEnvWithArgs :: IlxEnv -> [Var] -> IlxEnv
1328 extendIlxEnvWithArgs (IlxEnv (mod, tv_env, id_env,  bind_env, place,tr)) args
1329   = IlxEnv (mod, extendIlxTyEnvWithTyArgs tv_env [tv      | tv <- args, isIlxTyVar tv],
1330             extendVarEnvList id_env [(v,Arg) | v  <- args, not (isIlxTyVar v)], 
1331              bind_env, place,tr)
1332
1333 extendIlxEnvWithFreeVars (IlxEnv (mod, tv_env, id_env,  bind_env, place,tr)) args
1334   = IlxEnv (mod, 
1335             extendIlxTyEnvWithFreeTyVars tv_env [tv | tv <- args, isIlxTyVar tv],
1336             extendVarEnvList id_env (clovs 0 args), 
1337             bind_env, 
1338             place,tr)
1339    where
1340      clovs _ [] = []
1341      clovs n (x:xs) = if not (isIlxTyVar x) then (x,CloVar n):clovs (n+1) xs else clovs n xs
1342
1343 extendIlxEnvWithBinds env@(IlxEnv (mod, tv_env, id_env, bind_env, place,tr)) bnds
1344   = IlxEnv (mod, tv_env, id_env, 
1345             extendVarEnvList bind_env [(v,(env,rhs)) | (v,rhs) <- bnds], 
1346             place,tr)
1347
1348 extendIlxEnvWithLocals (IlxEnv (m, tv_env, id_env, bind_env, p,tr)) locals
1349   = IlxEnv (m, tv_env, 
1350             extendVarEnvList id_env [(v,Local) | (LocalId v,_) <- locals],
1351             extendVarEnvList bind_env [(v,(env,rhs)) | (LocalId v,Just (env,rhs)) <- locals], 
1352             p,tr)
1353 extendIlxEnvWithTops env@(IlxEnv (m, tv_env, id_env, bind_env, place,tr)) mod binds
1354   = IlxEnv (m, tv_env, 
1355             extendVarEnvList id_env [(bndr,Top mod) | (bndr,rhs) <- binds], 
1356             extendVarEnvList bind_env [(bndr,(env, rhs)) | (bndr,rhs) <- binds], 
1357             place,tr)
1358
1359 formalIlxEnv (IlxEnv (m, tv_env, id_env, bind_env, place, tr)) tyvars 
1360   = IlxEnv (m, formalIlxTyEnv tyvars, id_env, bind_env, place, tr)
1361
1362 ilxEnvTyEnv :: IlxEnv -> IlxTyEnv
1363 ilxEnvTyEnv (IlxEnv (_, tv_env, _,_,_,_)) = tv_env 
1364 elemIlxTyEnv var env = elem var (ilxEnvTyEnv env )
1365 elemIlxVarEnv var (IlxEnv (_, _, id_env,_,_,_)) = elemVarEnv var id_env 
1366 lookupIlxVarEnv (IlxEnv (_, _, id_env,_,_,_)) var = lookupVarEnv id_env var
1367 lookupIlxBindEnv (IlxEnv (_, _, _, bind_env,_,_)) var = lookupVarEnv bind_env var
1368
1369 \end{code}
1370
1371
1372 \begin{code}
1373 type IlxLabel = SDoc
1374
1375 pprIlxLabel lbl = lbl
1376
1377 mkJoinLabel :: Id -> IlxLabel
1378 mkJoinLabel v = text "J_" <> ppr v
1379
1380 mkAltLabel  :: Id -> Int -> IlxLabel
1381 mkAltLabel v n = text "A" <> int n <> ppr v
1382
1383 ilxLabel :: IlxLabel -> SDoc
1384 ilxLabel lbl =  line $$ (pprIlxLabel lbl <> colon)
1385 \end{code}
1386
1387
1388 %************************************************************************
1389 %*                                                                      *
1390 \subsection{Local pretty helper functions}
1391 %*                                                                      *
1392 %************************************************************************
1393
1394 \begin{code}
1395 pprSepWithCommas :: (a -> SDoc) -> [a] -> SDoc
1396 pprSepWithCommas pp xs = sep (punctuate comma (map pp xs))
1397 ilxComment pp   = text "/*" <+> pp <+> text "*/"
1398 singleQuotes pp = char '\'' <> pp <> char '\''
1399
1400 line = text "// ----------------------------------"
1401
1402 hscOptionQual = if opt_SimplDoEtaReduction then text ".ilx-O" else text ".ilx-Onot"
1403
1404 nameReference env n
1405   | isLocalName n = empty
1406   | ilxEnvModule env == nameModule n  = text ""
1407   | isHomeModule (nameModule n)   = moduleNameReference (moduleName (nameModule n))
1408 -- HACK: no Vanilla modules should be around, but they are!!  This
1409 -- gets things working for the scenario "standard library linked as one
1410 -- assembly with multiple modules + a one module program running on top of this"
1411 -- Same applies to all other mentions of Vailla modules in this file
1412   | isVanillaModule (nameModule n)  && not inPrelude =  preludePackageReference
1413   | isVanillaModule (nameModule n)  && inPrelude =   moduleNameReference (moduleName (nameModule n))
1414 -- end hack
1415   | otherwise = packageReference (modulePackage (nameModule n))
1416
1417 packageReference p = brackets ((text "ilx") <+> singleQuotes (ppr p  <> hscOptionQual))
1418 moduleNameReference m = brackets ((text ".module") <+> (text "ilx") <+> singleQuotes (pprModuleName m <> hscOptionQual <> text ".dll"))
1419
1420 moduleReference env m
1421   | ilxEnvModule env   == m = text ""
1422   | isHomeModule m = moduleNameReference (moduleName m)
1423 -- See hack above
1424   | isVanillaModule m && not inPrelude =  preludePackageReference
1425   | isVanillaModule m && inPrelude =  moduleNameReference (moduleName m)
1426 -- end hack
1427   | otherwise  =  packageReference (modulePackage m)
1428
1429 preludePackageReference = packageReference preludePackage
1430 inPrelude = preludePackage == opt_InPackage
1431
1432 ------------------------------------------------
1433 -- This code is copied from absCSyn/CString.lhs,
1434 -- and modified to do the correct thing!  It's
1435 -- still a mess though.  Also, still have to do the
1436 -- right thing for embedded nulls.
1437
1438 pprFSInILStyle :: FAST_STRING -> SDoc
1439 pprFSInILStyle fs = doubleQuotes (text (stringToC (_UNPK_ fs)))
1440
1441 stringToC   :: String -> String
1442 -- Convert a string to the form required by C in a C literal string
1443 -- Tthe hassle is what to do w/ strings like "ESC 0"...
1444 stringToC ""  = ""
1445 stringToC [c] = charToC c
1446 stringToC (c:cs)
1447     -- if we have something "octifiable" in "c", we'd better "octify"
1448     -- the rest of the string, too.
1449   = if (c < ' ' || c > '~')
1450     then (charToC c) ++ (concat (map char_to_C cs))
1451     else (charToC c) ++ (stringToC cs)
1452   where
1453     char_to_C c | c == '\n' = "\\n"     -- use C escapes when we can
1454                 | c == '\a' = "\\a"
1455                 | c == '\b' = "\\b"     -- ToDo: chk some of these...
1456                 | c == '\r' = "\\r"
1457                 | c == '\t' = "\\t"
1458                 | c == '\f' = "\\f"
1459                 | c == '\v' = "\\v"
1460                 | otherwise = '\\' : (trigraph (ord c))
1461
1462 charToC :: Char -> String
1463 -- Convert a character to the form reqd in a C character literal
1464 charToC c = if (c >= ' ' && c <= '~')   -- non-portable...
1465             then case c of
1466                   '\'' -> "\\'"
1467                   '\\' -> "\\\\"
1468                   '"'  -> "\\\""
1469                   '\n' -> "\\n"
1470                   '\a' -> "\\a"
1471                   '\b' -> "\\b"
1472                   '\r' -> "\\r"
1473                   '\t' -> "\\t"
1474                   '\f' -> "\\f"
1475                   '\v' -> "\\v"
1476                   _    -> [c]
1477             else '\\' : (trigraph (ord c))
1478
1479 trigraph :: Int -> String
1480 trigraph n
1481   = [chr ((n `div` 100) `rem` 10 + ord '0'),
1482      chr ((n `div` 10) `rem` 10 + ord '0'),
1483      chr (n `rem` 10 + ord '0')]
1484
1485
1486 \end{code}
1487
1488 %************************************************************************
1489 %*                                                                      *
1490 \subsection{PrimOps and Constructors}
1491 %*                                                                      *
1492 %************************************************************************
1493
1494 \begin{code}
1495 ----------------------------
1496 -- Allocate a fresh constructor
1497
1498 ilxConApp env data_con args
1499   | isUnboxedTupleCon data_con
1500      = let tm_args' = filter (not. isVoidIlxRepType . stgArgType) tm_args in 
1501        case tm_args' of
1502         [h] -> 
1503           -- Collapse the construction of an unboxed tuple type where
1504           -- every element is zero-sized
1505             vcat (ilxMapPlaceArgs 0 pushArg env tm_args')
1506         _ -> 
1507           -- Minimize the construction of an unboxed tuple type, which
1508           -- may contain zero-sized elements.  Recompute all the 
1509           -- bits and pieces from the simpler case below for the new data
1510           -- type constructor....
1511            let data_con' = tupleCon Unboxed (length tm_args') in 
1512            let rep_ty_args' = filter (not . isVoidIlxRepType) rep_ty_args in 
1513
1514            let tycon' = dataConTyCon data_con' in
1515            let (formal_tyvars', formal_tau_ty') = splitForAllTys (dataConRepType data_con') in 
1516            let (formal_arg_tys', _)     = splitFunTys formal_tau_ty' in
1517            let formal_env'           = formalIlxEnv env formal_tyvars' in 
1518
1519            vcat [vcat (ilxMapPlaceArgs 0 pushArg env tm_args'),
1520                    sep [text "newobj void ",
1521                         ilxTyConApp env tycon' rep_ty_args',
1522                         text "::.ctor",
1523                         pprValArgTys ilxTypeR formal_env' (map deepIlxRepType formal_arg_tys')
1524                    ]
1525              ]
1526  | otherwise
1527     -- Now all other constructions
1528      =  --  Assume C :: forall a. a -> T a -> T a
1529         --      ldloc x         arg of type Int
1530         --      ldloc y         arg of type T Int
1531         --      newdata classunion T<Int32>, C(!0, T <!0>)
1532         --
1533         let tycon   = dataConTyCon data_con in 
1534         let (formal_tyvars, formal_tau_ty) = splitForAllTys (dataConRepType data_con) in
1535         let (formal_arg_tys, _)     = splitFunTys formal_tau_ty in 
1536
1537        vcat [vcat (ilxMapPlaceArgs 0 pushArg env tm_args),
1538           sep [ text "newdata",
1539                 nest 2 (ilxTyConApp env tycon rep_ty_args <> comma),
1540                 nest 2 (ilxConRef env data_con)
1541           ]
1542         ]
1543  where
1544    tycon   = dataConTyCon data_con 
1545    rep_ty_args = map deepIlxRepType ty_args
1546    (ty_args,tm_args) = if isAlgTyCon tycon then splitTyArgs (tyConTyVars tycon) args  else splitTyArgs1 args
1547
1548 -- split some type arguments off, throwing away the higher kinded ones for the moment
1549 -- base the higher-kinded checks off a corresponding list of formals
1550 splitTyArgs (htv:ttv) (StgTypeArg h:t) 
1551    | isIlxTyVar htv = ((h:l), r) 
1552    | otherwise = trace "splitTyArgs: threw away higher kinded type arg" (l, r) 
1553    where (l,r) = splitTyArgs ttv t 
1554 splitTyArgs _ l = ([],l)
1555  
1556 -- split some type arguments off, where none should be higher kinded
1557 splitTyArgs1 (StgTypeArg h:t) 
1558    = ((h:l), r) 
1559    where (l,r) = splitTyArgs1 t 
1560 splitTyArgs1 l = ([],l)
1561  
1562
1563 ilxConRef env data_con
1564     = pprId data_con <> pprValArgTys ilxTypeL env' (map deepIlxRepType (filter (not . isVoidIlxRepType) arg_tys))
1565   where
1566     (tyvars, tau_ty) = splitForAllTys (dataConRepType data_con)
1567     (arg_tys, _)     = splitFunTys tau_ty
1568     env'             = formalIlxEnv env tyvars
1569
1570
1571
1572
1573 \end{code}
1574
1575
1576 %************************************************************************
1577 %*                                                                      *
1578 \subsection{PrimOps and Prim Representations}                           *
1579 %************************************************************************
1580
1581 \begin{code}
1582
1583 ilxPrimApp env (CCallOp ccall) args ret_ty = ilxCCall env ccall args ret_ty
1584 ilxPrimApp env op              args ret_ty = ilxPrimOpTable op args env
1585
1586
1587 type IlxTyFrag = IlxEnv -> SDoc
1588 ilxType s env = text s
1589
1590 ilxLift ty env = text "thunk" <> angleBrackets (ty env)
1591
1592 ilxTypeSeq :: [IlxTyFrag] -> IlxTyFrag
1593 ilxTypeSeq ops env = hsep (map (\x -> x env) ops)
1594
1595 tyPrimConTable :: UniqFM ([Type] -> IlxTyFrag)
1596 tyPrimConTable = 
1597   listToUFM [(addrPrimTyConKey,         (\_ -> repAddr)),
1598 --           (fileStreamPrimTyConKey,   (\_ -> repFileStream)),
1599              (foreignObjPrimTyConKey,   (\_ -> repForeign)),
1600              (stablePtrPrimTyConKey,    (\[ty] -> repStablePtr {- (ilxTypeL2 ty) -})),
1601              (stableNamePrimTyConKey,   (\[ty] -> repStableName {- (ilxTypeL2 ty) -} )),
1602              (charPrimTyConKey,         (\_ -> repChar)),
1603              (wordPrimTyConKey,         (\_ -> repWord)),
1604              (byteArrayPrimTyConKey,    (\_ -> repByteArray)),
1605              (intPrimTyConKey,          (\_ -> repInt)),
1606              (int64PrimTyConKey,        (\_ -> repInt64)),
1607              (word64PrimTyConKey,       (\_ -> repWord64)),
1608              (floatPrimTyConKey,        (\_ -> repFloat)),
1609              (doublePrimTyConKey,       (\_ -> repDouble)),
1610               -- These can all also accept unlifted parameter types so we explicitly lift.
1611              (arrayPrimTyConKey,        (\[ty] -> repArray (ilxTypeL2 ty))),
1612              (mutableArrayPrimTyConKey,         (\[_, ty] -> repMutArray (ilxTypeL2 ty))),
1613              (weakPrimTyConKey,         (\[_, ty] -> repWeak (ilxTypeL2 ty))),
1614              (mVarPrimTyConKey,         (\[_, ty] -> repMVar (ilxTypeL2 ty))),
1615              (mutVarPrimTyConKey,       (\[ty1, ty2] -> repMutVar (ilxTypeL2 ty1) (ilxTypeL2 ty2))),
1616              (mutableByteArrayPrimTyConKey,     (\_ -> repByteArray)),
1617              (threadIdPrimTyConKey,     (\_ -> repThread)),
1618              (bcoPrimTyConKey,  (\_ -> repBCO))
1619              ]
1620
1621 ilxTypeL2 :: Type -> IlxTyFrag
1622 ilxTypeL2 ty env = ilxTypeL env ty
1623 ilxTypeR2 :: Type -> IlxTyFrag
1624 ilxTypeR2 ty env = ilxTypeR env ty
1625
1626 ilxMethA = ilxType "!!0"
1627 ilxMethB = ilxType "!!1"
1628 prelGHCReference :: IlxTyFrag
1629 prelGHCReference env =
1630    if ilxEnvModule env == mkHomeModule (mkModuleName "PrelGHC") then empty
1631    else if inPrelude then moduleNameReference (mkModuleName "PrelGHC")
1632    else preludePackageReference
1633
1634 prelBaseReference :: IlxTyFrag
1635 prelBaseReference env =
1636    if ilxEnvModule env == mkHomeModule (mkModuleName "PrelBase") then empty
1637    else if inPrelude then moduleNameReference (mkModuleName "PrelBase")
1638    else preludePackageReference
1639
1640 repThread = ilxType "class [mscorlib]System.Threading.Thread /* ThreadId# */ "
1641 repByteArray = ilxType "unsigned int8[] /* ByteArr# */ "
1642 --repFileStream = text "void * /* FileStream# */ "  -- text "class [mscorlib]System.IO.FileStream"
1643 repInt = ilxType "int32"
1644 repWord = ilxType "unsigned int32"
1645 repAddr =ilxType "/* Addr */ void *"
1646 repInt64 = ilxType "int64"
1647 repWord64 = ilxType "unsigned int64"
1648 repFloat = ilxType "float32"
1649 repDouble = ilxType "float64"
1650 repChar = ilxType "/* Char */ unsigned int8"
1651 repForeign = ilxTypeSeq [ilxType "class ",prelGHCReference,ilxType "PrelGHC_Foreignzh"]
1652 repInteger = ilxUnboxedPairRep repInt repByteArray
1653 repIntegerPair = ilxUnboxedQuadRep repInt repByteArray repInt repByteArray
1654 repArray ty = ilxTypeSeq [ty,ilxType "[]"]
1655 repMutArray ty = ilxTypeSeq [ty,ilxType "[]"]
1656 repMVar ty = ilxTypeSeq [ilxType "class ",prelGHCReference,ilxType "PrelGHC_MVarzh",ilxTyParams [ty]]
1657 repMutVar _ ty2 = ilxTypeSeq [ilxType "class ",prelGHCReference,ilxType "PrelGHC_MutVarzh",ilxTyParams [ty2]]
1658 repWeak ty1 = ilxTypeSeq [ilxType "class ",prelGHCReference,ilxType "PrelGHC_Weakzh",ilxTyParams [ty1]]
1659 repStablePtr {- ty1 -} = ilxTypeSeq [ilxType "class ",prelGHCReference,ilxType "PrelGHC_StablePtrzh" {- ,ilxTyParams [ty1] -} ]
1660 repStableName {- ty1 -}  = ilxTypeSeq [ilxType "class ",prelGHCReference,ilxType "PrelGHC_StableNamezh" {- ,ilxTyParams [ty1] -} ]
1661 classWeak = ilxTypeSeq [ilxType "class ",prelGHCReference,ilxType "PrelGHC_Weakzh"]
1662 repBCO = ilxTypeSeq [ilxType "class ",prelGHCReference,ilxType "PrelGHC_BCOzh"]
1663
1664 ilxTyPair l r = ilxTyParams [l,r]
1665 ilxTyTriple l m r = ilxTyParams [l,m,r]
1666 ilxTyQuad l m1 m2 r = ilxTyParams [l,m1,m2,r]
1667 ilxUnboxedPairRep l r = ilxTypeSeq [ilxType "value class",prelGHCReference,ilxType "PrelGHC_Z1H",ilxTyPair l r]
1668 ilxUnboxedTripleRep l m r = ilxTypeSeq [ilxType "value class",prelGHCReference,ilxType "PrelGHC_Z2H",ilxTyTriple l m r]
1669 ilxUnboxedQuadRep l m1 m2 r = ilxTypeSeq [ilxType "value class",prelGHCReference,ilxType "PrelGHC_Z3H",ilxTyQuad l m1 m2 r]
1670
1671 ilxTyParams :: [IlxTyFrag] -> IlxTyFrag
1672 ilxTyParams [] env = empty
1673 ilxTyParams l env = angleBrackets (ilxTyParamsAux l env)
1674   where
1675    ilxTyParamsAux [] env = empty
1676    ilxTyParamsAux [h] env = h env
1677    ilxTyParamsAux (h:t) env = h env <> text "," <+> ilxTyParamsAux t env
1678    ilxTyParams [] env = empty
1679
1680
1681 type IlxOpFrag = IlxEnv -> SDoc
1682 ilxOp :: String -> IlxOpFrag
1683 ilxOp s env = text s
1684 ilxOpSeq :: [IlxOpFrag] -> IlxOpFrag
1685 ilxOpSeq ops env = hsep (map (\x -> x env) ops)
1686
1687 ilxParams :: [IlxOpFrag] -> IlxOpFrag
1688 ilxParams l env = parens (ilxParamsAux l env)
1689   where
1690    ilxParamsAux [] env = empty
1691    ilxParamsAux [h] env = h env
1692    ilxParamsAux (h:t) env = h env <> text "," <+> ilxParamsAux t env
1693
1694
1695 ilxMethodRef rty cls nm tyargs args = 
1696     ilxOpSeq [rty,cls,ilxOp "::",ilxOp nm,
1697               ilxTyParams tyargs,ilxParams args]
1698
1699 ilxCall m = ilxOpSeq [ilxOp "call", m]
1700
1701 ilxSupportClass = ilxOpSeq [prelGHCReference, ilxOp "'GHC.support'"]
1702 ilxSuppMeth rty nm tyargs args = ilxMethodRef rty ilxSupportClass nm tyargs args
1703
1704 ilxCallSuppMeth rty nm tyargs args  = ilxCall (ilxSuppMeth rty nm tyargs args)
1705
1706 ilxMkBool :: IlxOpFrag
1707 ilxMkBool =  ilxOpSeq [ilxOp "call class",prelBaseReference,
1708                        ilxOp "PrelBase_Bool",
1709                        prelGHCReference,ilxOp "GHC.support::mkBool(bool)"]
1710 ilxCgt = ilxOpSeq [ilxOp "cgt",ilxMkBool]
1711 ilxCge = ilxOpSeq [ilxOp "clt ldc.i4 0 ceq ",ilxMkBool]
1712 ilxClt = ilxOpSeq [ilxOp "clt ",ilxMkBool]
1713 ilxCle = ilxOpSeq [ilxOp "cgt ldc.i4 0 ceq ",ilxMkBool]
1714 ilxCeq = ilxOpSeq [ilxOp "ceq ",ilxMkBool]
1715 ilxCne = ilxOpSeq [ilxOp "ceq ldc.i4 0 ceq " ,ilxMkBool]
1716 ilxCgtUn = ilxOpSeq [ilxOp "cgt.un ",ilxMkBool]
1717 ilxCgeUn  = ilxOpSeq [ilxOp "clt.un ldc.i4 0 ceq ",ilxMkBool]
1718 ilxCltUn = ilxOpSeq [ilxOp "clt.un ",ilxMkBool]
1719 ilxCleUn = ilxOpSeq [ilxOp "cgt.un ldc.i4 0 ceq ",ilxMkBool]
1720
1721 ilxAddrOfForeignOp = ilxOpSeq [ilxOp "ldfld void *" , repForeign, ilxOp "::contents"]
1722 ilxAddrOfByteArrOp = ilxOp "ldc.i4 0 ldelema unsigned int8"
1723
1724 ilxPrimOpTable :: PrimOp -> [StgArg] -> IlxOpFrag
1725 ilxPrimOpTable op
1726   = case op of
1727         CharGtOp    -> simp_op ilxCgt
1728         CharGeOp    -> simp_op ilxCge
1729         CharEqOp    -> simp_op ilxCeq
1730         CharNeOp    -> simp_op ilxCne
1731         CharLtOp    -> simp_op ilxClt
1732         CharLeOp    -> simp_op ilxCle
1733
1734         OrdOp       -> simp_op (ilxOp "conv.i4") -- chars represented by UInt32 (u4)
1735         ChrOp       -> simp_op (ilxOp "conv.u4")
1736
1737         IntGtOp     -> simp_op ilxCgt
1738         IntGeOp     -> simp_op ilxCge
1739         IntEqOp     -> simp_op ilxCeq
1740         IntNeOp     -> simp_op ilxCne
1741         IntLtOp     -> simp_op ilxClt
1742         IntLeOp     -> simp_op ilxCle
1743
1744         IntToInt8Op  -> simp_op  (ilxOp"conv.i1")
1745         IntToInt16Op  -> simp_op (ilxOp "conv.i2")
1746         IntToInt32Op  -> simp_op (ilxOp "conv.i4")
1747         WordToWord8Op  -> simp_op (ilxOp "conv.u1")
1748         WordToWord16Op  -> simp_op (ilxOp "conv.u2")
1749         WordToWord32Op  -> simp_op (ilxOp "conv.u4")
1750
1751         WordGtOp     -> simp_op ilxCgtUn
1752         WordGeOp     -> simp_op ilxCgeUn
1753         WordEqOp     -> simp_op ilxCeq
1754         WordNeOp     -> simp_op ilxCne
1755         WordLtOp     -> simp_op ilxCltUn
1756         WordLeOp     -> simp_op ilxCleUn
1757
1758         AddrGtOp     -> simp_op ilxCgt
1759         AddrGeOp     -> simp_op ilxCge
1760         AddrEqOp     -> simp_op ilxCeq
1761         AddrNeOp     -> simp_op ilxCne
1762         AddrLtOp     -> simp_op ilxClt
1763         AddrLeOp     -> simp_op ilxCle
1764
1765         FloatGtOp     -> simp_op ilxCgt
1766         FloatGeOp     -> simp_op ilxCge
1767         FloatEqOp     -> simp_op ilxCeq
1768         FloatNeOp     -> simp_op ilxCne
1769         FloatLtOp     -> simp_op ilxClt
1770         FloatLeOp     -> simp_op ilxCle
1771
1772         DoubleGtOp     -> simp_op ilxCgt
1773         DoubleGeOp     -> simp_op ilxCge
1774         DoubleEqOp     -> simp_op ilxCeq
1775         DoubleNeOp     -> simp_op ilxCne
1776         DoubleLtOp     -> simp_op ilxClt
1777         DoubleLeOp     -> simp_op ilxCle
1778
1779     -- Int#-related ops:
1780         IntAddOp    -> simp_op (ilxOp "add")
1781         IntSubOp    -> simp_op (ilxOp "sub")
1782         IntMulOp    -> simp_op (ilxOp "mul")
1783         IntQuotOp   -> simp_op (ilxOp "div")
1784         IntNegOp    -> simp_op (ilxOp "neg")
1785         IntRemOp    -> simp_op (ilxOp "rem")
1786
1787     -- Word#-related ops:
1788         WordAddOp    -> simp_op (ilxOp "add")
1789         WordSubOp    -> simp_op (ilxOp "sub")
1790         WordMulOp    -> simp_op (ilxOp "mul")
1791         WordQuotOp   -> simp_op (ilxOp "div")
1792         WordRemOp    -> simp_op (ilxOp "rem")
1793
1794         Addr2IntOp  -> simp_op (ilxOp "conv.i4") -- Addresses are very dodgy for ILX.  They are used for both C-strings and 
1795         Int2AddrOp  -> simp_op (ilxOp "conv.i")  -- the FFI.  This needs more work.
1796         ISllOp      -> simp_op (ilxOp "shl")
1797         ISraOp      -> simp_op (ilxOp "shr")
1798         ISrlOp      -> simp_op (ilxOp "shr.un")
1799         IntAddCOp   -> simp_op (ilxCallSuppMeth (ilxUnboxedPairRep repInt repInt) "IntAddCOp" [] [repInt, repInt])
1800         IntSubCOp   -> simp_op (ilxCallSuppMeth (ilxUnboxedPairRep repInt repInt) "IntSubCOp" [] [repInt, repInt])
1801         IntMulCOp   -> simp_op (ilxCallSuppMeth (ilxUnboxedPairRep repInt repInt) "IntMulCOp" [] [repInt, repInt])
1802         IntGcdOp    -> simp_op (ilxCallSuppMeth repInt "IntGcdOp" [] [repInt, repInt])
1803
1804
1805     -- Word#-related ops:
1806         AndOp       -> simp_op (ilxOp "and") 
1807         OrOp        -> simp_op (ilxOp "or") 
1808         NotOp       -> simp_op (ilxOp "not") 
1809         XorOp       -> simp_op (ilxOp "xor") 
1810         SllOp       -> simp_op (ilxOp "shl") 
1811         SrlOp       -> simp_op (ilxOp "shr") 
1812         Word2IntOp  -> simp_op (ilxOp "conv.i4")
1813         Int2WordOp  -> simp_op (ilxOp "conv.u4")
1814
1815     -- Float#-related ops:
1816         FloatAddOp   -> simp_op (ilxOp "add")
1817         FloatSubOp   -> simp_op (ilxOp "sub")
1818         FloatMulOp   -> simp_op (ilxOp "mul")
1819         FloatDivOp   -> simp_op (ilxOp "div")
1820         FloatNegOp   -> simp_op (ilxOp "neg")
1821         Float2IntOp  -> simp_op (ilxOp "conv.i4")
1822         Int2FloatOp  -> simp_op (ilxOp "conv.r4")
1823
1824         DoubleAddOp     -> simp_op (ilxOp "add")
1825         DoubleSubOp     -> simp_op (ilxOp "sub")
1826         DoubleMulOp     -> simp_op (ilxOp "mul")
1827         DoubleDivOp     -> simp_op (ilxOp "div")
1828         DoubleNegOp     -> simp_op (ilxOp "neg")
1829         Double2IntOp    -> simp_op (ilxOp "conv.i4")
1830         Int2DoubleOp    -> simp_op (ilxOp "conv.r4")
1831         Double2FloatOp  -> simp_op (ilxOp "conv.r4")
1832         Float2DoubleOp  -> simp_op (ilxOp "conv.r8")
1833         DoubleDecodeOp  -> simp_op (ilxCallSuppMeth (ilxUnboxedTripleRep repInt repInt repByteArray) "decodeDouble" [] [ilxType "float64"])
1834         FloatDecodeOp   -> simp_op (ilxCallSuppMeth (ilxUnboxedTripleRep repInt repInt repByteArray) "decodeFloat" [] [ilxType "float32"])
1835
1836         FloatExpOp   -> simp_op (ilxOp "conv.r8 call float64 [mscorlib]System.Math::Exp(float64) conv.r4")
1837         FloatLogOp   -> simp_op (ilxOp "conv.r8 call float64 [mscorlib]System.Math::Log(float64) conv.r4")
1838         FloatSqrtOp  -> simp_op (ilxOp "conv.r8 call float64 [mscorlib]System.Math::Sqrt(float64) conv.r4")
1839         FloatSinOp   -> simp_op (ilxOp "conv.r8 call float64 [mscorlib]System.Math::Sin(float64) conv.r4")
1840         FloatCosOp   -> simp_op (ilxOp "conv.r8 call float64 [mscorlib]System.Math::Cos(float64) conv.r4")
1841         FloatTanOp   -> simp_op (ilxOp "conv.r8 call float64 [mscorlib]System.Math::Tan(float64) conv.r4")
1842         FloatAsinOp  -> simp_op (ilxOp "conv.r8 call float64 [mscorlib]System.Math::Asin(float64) conv.r4")
1843         FloatAcosOp  -> simp_op (ilxOp "conv.r8 call float64 [mscorlib]System.Math::Acos(float64) conv.r4")
1844         FloatAtanOp  -> simp_op (ilxOp "conv.r8 call float64 [mscorlib]System.Math::Atan(float64) conv.r4")
1845         FloatSinhOp  -> simp_op (ilxOp "conv.r8 call float64 [mscorlib]System.Math::Sinh(float64) conv.r4")
1846         FloatCoshOp  -> simp_op (ilxOp "conv.r8 call float64 [mscorlib]System.Math::Cosh(float64) conv.r4")
1847         FloatTanhOp  -> simp_op (ilxOp "conv.r8 call float64 [mscorlib]System.Math::Tanh(float64) conv.r4")
1848         FloatPowerOp -> simp_op (ilxOp "call float64 [mscorlib]System.Math::Pow(float64, float64) conv.r4") -- ** op, make use of implicit cast to r8...
1849
1850         DoubleExpOp   -> simp_op (ilxOp "call float64 [mscorlib]System.Math::Exp(float64)")
1851         DoubleLogOp   -> simp_op (ilxOp "call float64 [mscorlib]System.Math::Log(float64)")
1852         DoubleSqrtOp  -> simp_op (ilxOp "call float64 [mscorlib]System.Math::Sqrt(float64)")
1853           
1854         DoubleSinOp   -> simp_op (ilxOp "call float64 [mscorlib]System.Math::Sin(float64)")
1855         DoubleCosOp   -> simp_op (ilxOp "call float64 [mscorlib]System.Math::Cos(float64)")
1856         DoubleTanOp   -> simp_op (ilxOp "call float64 [mscorlib]System.Math::Tan(float64)")
1857           
1858         DoubleAsinOp   -> simp_op (ilxOp "call float64 [mscorlib]System.Math::Asin(float64)")
1859         DoubleAcosOp   -> simp_op (ilxOp "call float64 [mscorlib]System.Math::Acos(float64)")
1860         DoubleAtanOp   -> simp_op (ilxOp "call float64 [mscorlib]System.Math::Atan(float64)")
1861           
1862         DoubleSinhOp   -> simp_op (ilxOp "call float64 [mscorlib]System.Math::Sinh(float64)")
1863         DoubleCoshOp   -> simp_op (ilxOp "call float64 [mscorlib]System.Math::Cosh(float64)")
1864         DoubleTanhOp   -> simp_op (ilxOp "call float64 [mscorlib]System.Math::Tanh(float64)")
1865           
1866         DoublePowerOp  -> simp_op (ilxOp "call float64 [mscorlib]System.Math::Pow(float64, float64)")
1867
1868     -- Integer (and related...) ops: bail out to support routines
1869         IntegerAndOp       -> simp_op (ilxCallSuppMeth repInteger "IntegerAndOp" [] [repInt, repByteArray, repInt, repByteArray])
1870         IntegerOrOp        -> simp_op (ilxCallSuppMeth repInteger "IntegerOrOp" [] [repInt, repByteArray, repInt, repByteArray])
1871         IntegerXorOp       -> simp_op (ilxCallSuppMeth repInteger "IntegerXorOp" [] [repInt, repByteArray, repInt, repByteArray])
1872         IntegerComplementOp -> simp_op (ilxCallSuppMeth repInteger "IntegerComplementOp" [] [repInt, repByteArray])
1873         IntegerAddOp       -> simp_op (ilxCallSuppMeth repInteger "IntegerAddOp" [] [repInt, repByteArray, repInt, repByteArray])
1874         IntegerSubOp       -> simp_op (ilxCallSuppMeth repInteger "IntegerSubOp" [] [repInt, repByteArray, repInt, repByteArray])
1875         IntegerMulOp       -> simp_op (ilxCallSuppMeth repInteger "IntegerMulOp" [] [repInt, repByteArray, repInt, repByteArray])
1876         IntegerGcdOp       -> simp_op (ilxCallSuppMeth repInteger "IntegerGcdOp" [] [repInt, repByteArray, repInt, repByteArray])
1877         IntegerQuotRemOp   -> simp_op (ilxCallSuppMeth repIntegerPair "IntegerQuotRemOp" [] [repInt, repByteArray, repInt, repByteArray])
1878         IntegerDivModOp    -> simp_op (ilxCallSuppMeth repIntegerPair "IntegerDivModOp" [] [repInt, repByteArray, repInt, repByteArray])
1879         IntegerIntGcdOp    -> simp_op (ilxCallSuppMeth repInt "IntegerIntGcdOp" [] [repInt, repByteArray, repInt])
1880         IntegerDivExactOp  -> simp_op (ilxCallSuppMeth repInteger "IntegerDivExactOp" [] [repInt, repByteArray, repInt, repByteArray])
1881         IntegerQuotOp      -> simp_op (ilxCallSuppMeth repInteger "IntegerQuotOp" [] [repInt, repByteArray, repInt, repByteArray])
1882         IntegerRemOp       -> simp_op (ilxCallSuppMeth repInteger "IntegerRemOp" [] [repInt, repByteArray, repInt, repByteArray])
1883         IntegerCmpOp       -> simp_op (ilxCallSuppMeth repInt "IntegerCmpOp" [] [repInt, repByteArray, repInt, repByteArray])
1884         IntegerCmpIntOp    -> simp_op (ilxCallSuppMeth repInt "IntegerCmpIntOp" [] [repInt, repByteArray, repInt])
1885         Integer2IntOp      -> simp_op (ilxCallSuppMeth repInt "Integer2IntOp" [] [repInt, repByteArray])
1886         Integer2WordOp     -> simp_op (ilxCallSuppMeth repWord "Integer2WordOp" [] [repInt, repByteArray])
1887         Int2IntegerOp      -> simp_op (ilxCallSuppMeth repInteger "Int2IntegerOp" [] [repInt])
1888         Word2IntegerOp     -> simp_op (ilxCallSuppMeth repInteger "Word2IntegerOp" [] [repWord])
1889         IntegerToInt64Op   -> simp_op (ilxCallSuppMeth repInt64 "IntegerToInt64Op" [] [repInt,repByteArray])
1890         Int64ToIntegerOp   -> simp_op (ilxCallSuppMeth repInteger "Int64ToIntegerOp" [] [repInt64])
1891         IntegerToWord64Op  -> simp_op (ilxCallSuppMeth repWord64 "IntegerToWord64Op" [] [repInt,repByteArray])
1892         Word64ToIntegerOp  -> simp_op (ilxCallSuppMeth repInteger "Word64ToIntegerOp" [] [repWord64])
1893
1894
1895
1896         IndexByteArrayOp_Char      -> simp_op (ilxOp "ldelem.u1")
1897         IndexByteArrayOp_WideChar  -> simp_op (ilxOp "ldelem.u4")
1898         IndexByteArrayOp_Int       -> simp_op (ilxOp "ldelem.i4")
1899         IndexByteArrayOp_Word      -> simp_op (ilxOp "ldelem.u4")
1900         IndexByteArrayOp_Addr      -> simp_op (ilxOp "ldelem.u")
1901         IndexByteArrayOp_Float     -> simp_op (ilxOp "ldelem.r4")
1902         IndexByteArrayOp_Double    -> simp_op (ilxOp "ldelem.r8")
1903         IndexByteArrayOp_StablePtr -> simp_op (ilxOp "ldelem.ref")
1904         IndexByteArrayOp_Int8     -> simp_op (ilxOp "ldelem.i1")
1905         IndexByteArrayOp_Int16     -> simp_op (ilxOp "ldelem.i2")
1906         IndexByteArrayOp_Int32     -> simp_op (ilxOp "ldelem.i4")
1907         IndexByteArrayOp_Int64     -> simp_op (ilxOp "ldelem.i8")
1908         IndexByteArrayOp_Word8    -> simp_op (ilxOp "ldelem.u1")
1909         IndexByteArrayOp_Word16    -> simp_op (ilxOp "ldelem.u2")
1910         IndexByteArrayOp_Word32    -> simp_op (ilxOp "ldelem.u4")
1911         IndexByteArrayOp_Word64    -> simp_op (ilxOp "ldelem.u8")
1912
1913             {- should be monadic??? -}
1914         ReadByteArrayOp_Char      -> simp_op (ilxOp "ldelem.u1")
1915         ReadByteArrayOp_WideChar  -> simp_op (ilxOp "ldelem.u4")
1916         ReadByteArrayOp_Int       -> simp_op (ilxOp "ldelem.i4")
1917         ReadByteArrayOp_Word      -> simp_op (ilxOp "ldelem.u4")
1918         ReadByteArrayOp_Addr      -> simp_op (ilxOp "ldelem.u")
1919         ReadByteArrayOp_Float     -> simp_op (ilxOp "ldelem.r4")
1920         ReadByteArrayOp_Double    -> simp_op (ilxOp "ldelem.r8")
1921         ReadByteArrayOp_StablePtr -> simp_op (ilxOp "ldelem.ref")
1922         ReadByteArrayOp_Int8     -> simp_op (ilxOp "ldelem.i1")
1923         ReadByteArrayOp_Int16     -> simp_op (ilxOp "ldelem.i2")
1924         ReadByteArrayOp_Int32     -> simp_op (ilxOp "ldelem.i4")
1925         ReadByteArrayOp_Int64     -> simp_op (ilxOp "ldelem.i8")
1926         ReadByteArrayOp_Word8    -> simp_op (ilxOp "ldelem.u1")
1927         ReadByteArrayOp_Word16    -> simp_op (ilxOp "ldelem.u2")
1928         ReadByteArrayOp_Word32    -> simp_op (ilxOp "ldelem.u4")
1929         ReadByteArrayOp_Word64    -> simp_op (ilxOp "ldelem.u8")
1930                  {-   MutByteArr# s -> Int# -> State# s -> (# State# s, Char# #) -}
1931                  {- ByteArr# -> Int# -> Char# -}
1932
1933
1934         WriteByteArrayOp_Char      -> simp_op (ilxOp "stelem.u1")
1935         WriteByteArrayOp_WideChar   -> simp_op (ilxOp "stelem.u4")
1936         WriteByteArrayOp_Int       -> simp_op (ilxOp "stelem.i4")
1937         WriteByteArrayOp_Word      -> simp_op (ilxOp "stelem.u4")
1938         WriteByteArrayOp_Addr      -> simp_op (ilxOp "stelem.u")
1939         WriteByteArrayOp_Float     -> simp_op (ilxOp "stelem.r4")
1940         WriteByteArrayOp_Double    -> simp_op (ilxOp "stelem.r8")
1941         WriteByteArrayOp_StablePtr -> simp_op (ilxOp "stelem.ref")
1942         WriteByteArrayOp_Int8     -> simp_op (ilxOp "stelem.i1")
1943         WriteByteArrayOp_Int16     -> simp_op (ilxOp "stelem.i2")
1944         WriteByteArrayOp_Int32     -> simp_op (ilxOp "stelem.i4")
1945         WriteByteArrayOp_Int64     -> simp_op (ilxOp "stelem.i8")
1946         WriteByteArrayOp_Word8    -> simp_op (ilxOp "stelem.u1")
1947         WriteByteArrayOp_Word16    -> simp_op (ilxOp "stelem.u2")
1948         WriteByteArrayOp_Word32    -> simp_op (ilxOp "stelem.u4")
1949         WriteByteArrayOp_Word64    -> simp_op (ilxOp "stelem.i8 /* nb. no stelem.u8 */")
1950                  {- MutByteArr# s -> Int# -> Char# -> State# s -> State# s -}
1951
1952         IndexOffAddrOp_Char    -> simp_op (ilxOp "sizeof unsigned int8 mul add ldind.u1")
1953         IndexOffAddrOp_WideChar    -> simp_op (ilxOp "sizeof int32 mul add ldind.u4")
1954         IndexOffAddrOp_Int     -> simp_op (ilxOp "sizeof int32 mul add ldind.i4")
1955         IndexOffAddrOp_Word    -> simp_op (ilxOp "sizeof int32 mul add ldind.u4")
1956         IndexOffAddrOp_Addr    -> simp_op (ilxOp "sizeof native unsigned int mul add ldind.i")
1957         IndexOffAddrOp_StablePtr   -> simp_op (ilxOp "sizeof native unsigned int mul add ldind.ref")
1958         IndexOffAddrOp_Float   -> simp_op (ilxOp "sizeof float32 mul add ldind.r4")
1959         IndexOffAddrOp_Double  -> simp_op (ilxOp "sizeof float64 mul add ldind.r8")
1960         IndexOffAddrOp_Int8   -> simp_op (ilxOp "sizeof int8 mul add ldind.i1")
1961         IndexOffAddrOp_Int16   -> simp_op (ilxOp "sizeof int16 mul add ldind.i2")
1962         IndexOffAddrOp_Int32   -> simp_op (ilxOp "sizeof int32 mul add ldind.i4")
1963         IndexOffAddrOp_Int64   -> simp_op (ilxOp "sizeof int64 mul add ldind.i8")
1964         IndexOffAddrOp_Word8  -> simp_op (ilxOp "sizeof unsigned int8 mul add ldind.u1")
1965         IndexOffAddrOp_Word16 -> simp_op (ilxOp "sizeof unsigned int16 mul add ldind.u2")
1966         IndexOffAddrOp_Word32  -> simp_op (ilxOp "sizeof unsigned int32 mul add ldind.u4")
1967         IndexOffAddrOp_Word64  -> simp_op (ilxOp "sizeof int64 mul add ldind.u8")
1968
1969         -- ForeignObj: load the address inside the object first
1970         -- TODO: is this remotely right?
1971         IndexOffForeignObjOp_Char    -> arg2_op (\fobj n -> ilxOpSeq [fobj, ilxAddrOfForeignOp, n, ilxOp "sizeof unsigned int8 mul add ldind.u1"])
1972         IndexOffForeignObjOp_WideChar    -> arg2_op (\fobj n -> ilxOpSeq [fobj, ilxAddrOfForeignOp, n, ilxOp "sizeof int32 mul add ldind.u4"])
1973         IndexOffForeignObjOp_Int     -> arg2_op (\fobj n -> ilxOpSeq [fobj, ilxAddrOfForeignOp, n, ilxOp "sizeof int32 mul add ldind.i4"])
1974         IndexOffForeignObjOp_Word    -> arg2_op (\fobj n -> ilxOpSeq [fobj, ilxAddrOfForeignOp, n, ilxOp "sizeof unsigned int32 mul add ldind.u4"])
1975         IndexOffForeignObjOp_Addr    ->  arg2_op (\fobj n -> ilxOpSeq [fobj, ilxAddrOfForeignOp, n, ilxOp "sizeof native unsigned int mul add ldind.i  "])
1976         IndexOffForeignObjOp_StablePtr    ->  ty1_arg2_op (\ty fobj n -> ilxOpSeq [fobj, ilxAddrOfForeignOp, n, ilxOp "sizeof native unsigned int mul add ldind.ref  "])
1977         IndexOffForeignObjOp_Float   -> arg2_op (\fobj n -> ilxOpSeq [fobj, ilxAddrOfForeignOp, n, ilxOp "sizeof float32 mul add ldind.r4"])
1978         IndexOffForeignObjOp_Double  -> arg2_op (\fobj n -> ilxOpSeq [fobj, ilxAddrOfForeignOp, n, ilxOp "sizeof float64 mul add ldind.r8"])
1979         IndexOffForeignObjOp_Int8   -> arg2_op (\fobj n -> ilxOpSeq [fobj, ilxAddrOfForeignOp, n, ilxOp "sizeof int8 mul add ldind.i1"])
1980         IndexOffForeignObjOp_Int16   -> arg2_op (\fobj n -> ilxOpSeq [fobj, ilxAddrOfForeignOp, n, ilxOp "sizeof int16 mul add ldind.i2"])
1981         IndexOffForeignObjOp_Int32   -> arg2_op (\fobj n -> ilxOpSeq [fobj, ilxAddrOfForeignOp, n, ilxOp "sizeof int32 mul add ldind.i4"])
1982         IndexOffForeignObjOp_Int64   -> arg2_op (\fobj n -> ilxOpSeq [fobj, ilxAddrOfForeignOp, n, ilxOp "sizeof int64 mul add ldind.i8"])
1983         IndexOffForeignObjOp_Word8  -> arg2_op (\fobj n -> ilxOpSeq [fobj, ilxAddrOfForeignOp, n, ilxOp "sizeof unsigned int8 mul add ldind.u1"])
1984         IndexOffForeignObjOp_Word16  -> arg2_op (\fobj n -> ilxOpSeq [fobj, ilxAddrOfForeignOp, n, ilxOp "sizeof unsigned int16 mul add ldind.u2"])
1985         IndexOffForeignObjOp_Word32  -> arg2_op (\fobj n -> ilxOpSeq [fobj, ilxAddrOfForeignOp, n, ilxOp "sizeof unsigned int32 mul add ldind.u4"])
1986         IndexOffForeignObjOp_Word64  -> arg2_op (\fobj n -> ilxOpSeq [fobj, ilxAddrOfForeignOp, n, ilxOp "sizeof unsigned int64 mul add ldind.u8"])
1987
1988         ReadOffAddrOp_Char   -> simp_op (ilxOp "sizeof unsigned int8 mul add ldind.u1")
1989         ReadOffAddrOp_WideChar -> simp_op (ilxOp "sizeof int32 mul add ldind.u4")
1990         ReadOffAddrOp_Int    -> simp_op (ilxOp "sizeof int32 mul add ldind.i4")
1991         ReadOffAddrOp_Word   -> simp_op (ilxOp "sizeof unsigned int32 mul add ldind.u4")
1992         ReadOffAddrOp_Addr   -> simp_op (ilxOp "sizeof native unsigned int mul add ldind.i")
1993         ReadOffAddrOp_Float  -> simp_op (ilxOp "sizeof float32 mul add ldind.r4")
1994         ReadOffAddrOp_Double -> simp_op (ilxOp "sizeof float64 mul add ldind.r8")
1995         ReadOffAddrOp_StablePtr  -> simp_op (ilxOp "sizeof native unsigned int mul add ldind.ref")
1996         ReadOffAddrOp_Int8  -> simp_op (ilxOp "sizeof int8 mul add ldind.i1")
1997         ReadOffAddrOp_Int16  -> simp_op (ilxOp "sizeof int16 mul add ldind.i2")
1998         ReadOffAddrOp_Int32  -> simp_op (ilxOp "sizeof int32 mul add ldind.i4")
1999         ReadOffAddrOp_Int64  -> simp_op (ilxOp "sizeof int64 mul add ldind.i8")
2000         ReadOffAddrOp_Word8 -> simp_op (ilxOp "sizeof unsigned int8 mul add ldind.u1")
2001         ReadOffAddrOp_Word16 -> simp_op (ilxOp "sizeof unsigned int16 mul add ldind.u2")
2002         ReadOffAddrOp_Word32 -> simp_op (ilxOp "sizeof unsigned int32 mul add ldind.u4")
2003         ReadOffAddrOp_Word64 -> simp_op (ilxOp "sizeof unsigned int64 mul add ldind.u8")
2004                   {-    Addr# -> Int# -> Char# -> State# s -> State# s -} 
2005
2006         WriteOffAddrOp_Char   -> ty1_arg4_op (\sty addr n v s -> ilxOpSeq [addr, n, ilxOp "add", v, ilxOp "stind.u1"])
2007         WriteOffAddrOp_WideChar   -> ty1_arg4_op (\sty addr n v s -> ilxOpSeq [addr, n, ilxOp "sizeof int32 mul add", v, ilxOp "stind.u4"])
2008         WriteOffAddrOp_Int    -> ty1_arg4_op (\sty addr n v s -> ilxOpSeq [addr, n, ilxOp "sizeof int32 mul add", v, ilxOp "stind.i4"])
2009         WriteOffAddrOp_Word   -> ty1_arg4_op (\sty addr n v s -> ilxOpSeq [addr, n, ilxOp "sizeof int32 mul add", v, ilxOp "stind.u4"])
2010         WriteOffAddrOp_Addr   -> ty1_arg4_op (\sty addr n v s -> ilxOpSeq [addr, n, ilxOp "sizeof native unsigned int mul add", v, ilxOp "stind.i"])
2011         WriteOffAddrOp_ForeignObj   -> ty1_arg4_op (\sty addr n v s -> ilxOpSeq [addr, n, ilxOp "sizeof native unsigned int mul add", v, ilxOp "stind.ref"])
2012         WriteOffAddrOp_Float  -> ty1_arg4_op (\sty addr n v s -> ilxOpSeq [addr, n, ilxOp "sizeof float32 mul add", v,ilxOp "stind.r4"])
2013         WriteOffAddrOp_StablePtr   -> ty2_arg4_op (\ty1 sty addr n v s -> ilxOpSeq [addr, n, ilxOp "sizeof native unsigned int mul add", v, ilxOp "stind.ref"])
2014         WriteOffAddrOp_Double -> ty1_arg4_op (\sty addr n v s -> ilxOpSeq [addr,n,ilxOp "sizeof float64 mul add",v,ilxOp "stind.r8"])
2015         WriteOffAddrOp_Int8  -> ty1_arg4_op (\sty addr n v s -> ilxOpSeq [addr,n,ilxOp "sizeof int8 mul add",v,ilxOp "stind.i1"])
2016         WriteOffAddrOp_Int16  -> ty1_arg4_op (\sty addr n v s -> ilxOpSeq [addr,n,ilxOp "sizeof int16 mul add",v,ilxOp "stind.i2"])
2017         WriteOffAddrOp_Int32  -> ty1_arg4_op (\sty addr n v s -> ilxOpSeq [addr,n,ilxOp "sizeof int32 mul add",v,ilxOp "stind.i4"])
2018         WriteOffAddrOp_Int64  -> ty1_arg4_op (\sty addr n v s -> ilxOpSeq [addr,n,ilxOp "sizeof int64 mul add",v,ilxOp "stind.i8"])
2019         WriteOffAddrOp_Word8 -> ty1_arg4_op (\sty addr n v s -> ilxOpSeq [addr,n,ilxOp "sizeof unsigned int8 mul add",v,ilxOp "stind.u1"])
2020         WriteOffAddrOp_Word16 -> ty1_arg4_op (\sty addr n v s -> ilxOpSeq [addr,n,ilxOp "sizeof unsigned int16 mul add",v,ilxOp "stind.u2"])
2021         WriteOffAddrOp_Word32 -> ty1_arg4_op (\sty addr n v s -> ilxOpSeq [addr,n,ilxOp "sizeof unsigned int32 mul add",v,ilxOp "stind.u4"])
2022         WriteOffAddrOp_Word64 -> ty1_arg4_op (\sty addr n v s -> ilxOpSeq [addr,n,ilxOp "sizeof unsigned int64 mul add",v,ilxOp "stind.u8"])
2023                   {-    Addr# -> Int# -> Char# -> State# s -> State# s -} 
2024
2025             {- should be monadic??? -}
2026         NewByteArrayOp_Char      -> simp_op (ilxOp "newarr [mscorlib]System.Byte")
2027 --      NewByteArrayOp_Int       -> simp_op (ilxOp "newarr [mscorlib]System.Int32")
2028 --      NewByteArrayOp_Word      -> simp_op (ilxOp "newarr [mscorlib]System.UInt32")
2029 --      NewByteArrayOp_Addr      -> simp_op (ilxOp "newarr [mscorlib]System.UInt64")
2030 --      NewByteArrayOp_Float     -> simp_op (ilxOp "newarr [mscorlib]System.Single")
2031 --      NewByteArrayOp_Double    -> simp_op (ilxOp "newarr [mscorlib]System.Double")
2032 --      NewByteArrayOp_StablePtr -> simp_op (ilxOp "newarr [mscorlib]System.UInt32")
2033 --      NewByteArrayOp_Int64     -> simp_op (ilxOp "newarr [mscorlib]System.Int64")  TODO: there is no unique for this one -}
2034 --      NewByteArrayOp_Word64    -> simp_op (ilxOp "newarr  [mscorlib]System.UInt64") -}
2035                   {- Int# -> State# s -> (# State# s, MutByteArr# s #) -}
2036
2037         UnsafeFreezeByteArrayOp ->   ty1_op (\ty1  -> ilxOp "nop ")
2038                   {- MutByteArr# s -> State# s -> (# State# s, ByteArr# #) -}
2039         SizeofByteArrayOp  -> simp_op (ilxOp "ldlen")
2040                   {- ByteArr# -> Int# -}
2041
2042         SameMutableByteArrayOp -> ty1_op (\ty1  -> ilxCeq)
2043                  {- MutByteArr# s -> MutByteArr# s -> Bool -}
2044         SizeofMutableByteArrayOp -> ty1_op (\ty1  -> ilxOp "ldlen")
2045                  {- MutByteArr# s -> Int# -}
2046
2047         SameMutVarOp -> ty2_op (\ty1 ty2 -> ilxCeq)
2048                  {- MutVar# s a -> MutVar# s a -> Bool -}
2049         NewMutVarOp -> ty2_op (\ty1 ty2 -> ilxOpSeq [ilxOp "newobj void" , repMutVar ty1 ty2 , ilxOp "::.ctor(!0)"])
2050                  {- a -> State# s -> (# State# s, MutVar# s a #) -}
2051         ReadMutVarOp -> ty2_op (\ty1 ty2 ->  ilxOpSeq [ilxOp "ldfld !0" , repMutVar ty1 ty2 , ilxOp "::contents"])
2052                  {-  MutVar# s a -> State# s -> (# State# s, a #) -}
2053         WriteMutVarOp -> ty2_op (\ty1 ty2 -> ilxOpSeq [ilxOp "stfld !0" , repMutVar ty1 ty2 , ilxOp "::contents"])
2054                  {- MutVar# s a -> a -> State# s -> State# s -}
2055
2056         NewArrayOp -> ty2_op (\ty1 ty2 -> ilxCallSuppMeth (ilxType "!!0[]") "newArray" [ty1] [repInt,ilxMethA])
2057                  {- Int# -> a -> State# s -> (# State# s, MutArr# s a #) -}
2058         IndexArrayOp -> ty1_op (\ty1 -> ilxOp "ldelem.ref")
2059                  {- Array# a -> Int# -> (# a #) -}
2060         WriteArrayOp -> ty2_op (\ty1 ty2 -> ilxOp "stelem.ref")
2061                  {- MutArr# s a -> Int# -> a -> State# s -> State# s -}
2062         ReadArrayOp -> ty2_op (\ty1 ty2 -> ilxOp "ldelem.ref")
2063                  {- MutArr# s a -> Int# -> State# s -> (# State# s, a #) -}
2064         UnsafeFreezeArrayOp -> ty2_op (\ty1 ty2 -> ilxOp "nop")
2065                  {-   MutArr# s a -> State# s -> (# State# s, Array# a #) -}
2066         UnsafeThawArrayOp -> ty2_op (\ty1 ty2 -> ilxOp "nop")
2067                  {-  Array# a -> State# s -> (# State# s, MutArr# s a #) -}
2068
2069         SameMutableArrayOp -> ty2_op (\ty1 ty2 -> ilxCeq)
2070                  {- MutArr# s a -> MutArr# s a -> Bool -}
2071
2072
2073         RaiseOp -> ty2_op (\ty1 ty2 -> ilxOp "throw")
2074         CatchOp -> ty2_op (\ty1 ty2 -> 
2075                 ilxCallSuppMeth ilxMethA "'catch'" [ty1,ty2] [ilxOp "thunk<(func ( /* unit skipped */ ) --> !!0)>", ilxOp "thunk<(func (!!1) --> (func ( /* unit skipped */ ) --> !!0))>"])
2076                             {-        (State# RealWorld -> (# State# RealWorld, a #) )
2077                                    -> (b -> State# RealWorld -> (# State# RealWorld, a #) ) 
2078                                    -> State# RealWorld
2079                                    -> (# State# RealWorld, a #) 
2080                              -} 
2081
2082         BlockAsyncExceptionsOp -> ty1_op (\ty1 -> 
2083                 ilxCallSuppMeth ilxMethA "blockAsyncExceptions" [ty1] [ilxOp "thunk<(func ( /* unit skipped */ ) --> !!0)>"])
2084
2085                 {-     (State# RealWorld -> (# State# RealWorld, a #))
2086                     -> (State# RealWorld -> (# State# RealWorld, a #))
2087                 -}
2088
2089         UnblockAsyncExceptionsOp -> ty1_op (\ty1 -> 
2090                 ilxCallSuppMeth ilxMethA "unblockAsyncExceptions" [ty1] [ilxOp "thunk<(func ( /* unit skipped */ ) --> !!0)>"])
2091
2092                 {-
2093                     State# RealWorld -> (# State# RealWorld, a #))
2094                     -> (State# RealWorld -> (# State# RealWorld, a #))
2095                 -}
2096  
2097         NewMVarOp -> ty2_op (\sty ty -> 
2098                 ilxOpSeq [ilxOp "newobj void " , repMVar ty , ilxOp "::.ctor()"])
2099                  {- State# s -> (# State# s, MVar# s a #) -}
2100
2101         TakeMVarOp -> ty2_op (\sty ty -> 
2102                 ilxCallSuppMeth ilxMethA "takeMVar" [ty] [repMVar ilxMethA])
2103                   {-  MVar# s a -> State# s -> (# State# s, a #) -}
2104
2105         -- These aren't yet right
2106         TryTakeMVarOp -> ty2_op (\sty ty -> 
2107                 ilxCallSuppMeth (ilxUnboxedPairRep repInt ilxMethA) "tryTakeMVar" [ty] [repMVar ilxMethA])
2108                   {-  MVar# s a -> State# s -> (# State# s, a #) -}
2109
2110         TryPutMVarOp -> ty2_op (\sty ty -> 
2111                 ilxCallSuppMeth repInt "tryPutMVar" [ty] [repMVar ilxMethA,ilxMethA])
2112                   {-  MVar# s a -> State# s -> (# State# s, a #) -}
2113
2114         PutMVarOp -> ty2_op (\sty ty -> 
2115                 ilxCallSuppMeth (ilxOp "void") "putMVar" [ty] [repMVar ilxMethA, ilxMethA])
2116                    {- MVar# s a -> a -> State# s -> State# s -}
2117
2118         SameMVarOp -> ty2_op (\sty ty -> ilxCeq)
2119                    {- MVar# s a -> MVar# s a -> Bool -}
2120
2121 --      TakeMaybeMVarOp -> ty2_op (\sty ty -> 
2122 --              (ilxCallSuppMeth (ilxUnboxedPairRep repInt ilxMethA) "tryTakeMVar" [ty] [repMVar ilxMethA]))
2123 --              {- MVar# s a -> State# s -> (# State# s, Int#, a #) -}
2124
2125         IsEmptyMVarOp -> ty2_op (\sty ty -> 
2126                 ilxCallSuppMeth repInt "isEmptyMVar" [ty] [repMVar ilxMethA])
2127                {- MVar# s a -> State# s -> (# State# s, Int# #) -}
2128
2129         TouchOp -> warn_op "touch" (ty1_op (\ty1 -> ilxOp "pop /* PrimOp touch */ "))
2130
2131                {- a -> Int# -}
2132         DataToTagOp -> ty1_op (\ty1 -> 
2133                 ilxCallSuppMeth repInt "dataToTag" [ty1] [ilxMethA])
2134                {- a -> Int# -}
2135
2136         TagToEnumOp -> ty1_op (\ty1 -> 
2137                 ilxCallSuppMeth ilxMethA "tagToEnum" [ty1] [repInt])
2138                {- Int# -> a -}
2139
2140         MakeStablePtrOp -> ty1_op (\ty1 -> ilxOpSeq [ilxOp "box", ty1, ilxOp "newobj void", repStablePtr {- ty1 -}, ilxOp "::.ctor(class [mscorlib]System.Object)"])
2141                  {-   a -> State# RealWorld -> (# State# RealWorld, StablePtr# a #) -}
2142         MakeStableNameOp -> ty1_op (\ty1 -> ilxOpSeq [ilxOp "pop newobj void", repStableName {- ty1 -}, ilxOp "::.ctor()"])
2143                         -- primOpInfo MakeStableNameOp = mkGenPrimOp SLIT("makeStableName#")  [alphaTyVar] [alphaTy, mkStatePrimTy realWorldTy] ((mkTupleTy Unboxed 2 [mkStatePrimTy realWorldTy, mkStableNamePrimTy alphaTy]))
2144
2145         EqStableNameOp -> ty1_op (\ty1 -> ilxOp "ceq")
2146                -- [alphaTyVar] [mkStableNamePrimTy alphaTy, mkStableNamePrimTy alphaTy] (intPrimTy)
2147         StableNameToIntOp -> warn_op "StableNameToIntOp" (ty1_op (\ty1 -> ilxOp "pop ldc.i4 0"))
2148                -- [alphaTyVar] [mkStableNamePrimTy alphaTy] (intPrimTy)
2149
2150         DeRefStablePtrOp -> ty1_op (\ty1 -> ilxOpSeq [ilxOp "ldfld class [mscorlib]System.Object", repStablePtr {- ty1 -}, ilxOp "::contents"])
2151                  {-  StablePtr# a -> State# RealWorld -> (# State# RealWorld, a #) -}
2152
2153         EqStablePtrOp -> ty1_op (\ty1 -> ilxOp "ceq")
2154                  {-  StablePtr# a -> StablePtr# a -> Int# -}
2155
2156         MkWeakOp -> ty3_op (\ty1 ty2 ty3 ->  ilxCall (ilxMethodRef (repWeak ilxMethB) classWeak "bake" [ilxLift ty1,ilxLift ty2,ty3] [ilxMethA, ilxMethB, ilxLift (ilxOp "!!2")]))
2157                  {- o -> b -> c -> State# RealWorld -> (# State# RealWorld, Weak# b #) -}
2158
2159         DeRefWeakOp -> ty1_op (\ty1 ->  ilxCall (ilxMethodRef (ilxUnboxedPairRep repInt ilxMethA) classWeak "deref" [ty1] [repWeak ilxMethA]))
2160         FinalizeWeakOp -> ty1_op (\ty1 ->  ilxCall (ilxMethodRef (ilxUnboxedPairRep repInt (ilxOp "thunk<(func ( /* unit skipped */ ) --> class '()')>")) classWeak "finalizer" [ty1] [repWeak ilxMethA]))
2161                    {-    Weak# a -> State# RealWorld -> (# State# RealWorld, Int#, 
2162         State# RealWorld -> (# State# RealWorld, Unit #)) #) -}
2163
2164         MkForeignObjOp -> simp_op (ilxOpSeq [ilxOp "newobj void", repForeign, ilxOp "::.ctor(void *)"])
2165         WriteForeignObjOp -> ty1_op (\sty -> ilxOpSeq [ilxOp "stfld void *", repForeign, ilxOp "::contents"])
2166         ForeignObjToAddrOp -> simp_op ilxAddrOfForeignOp
2167         YieldOp -> simp_op (ilxOpSeq [ilxOp "call class [mscorlib]System.Threading.Thread class [mscorlib]System.Threading.Thread::get_CurrentThread() 
2168                                 call instance void class [mscorlib]System.Threading.Thread::Suspend()"])
2169         MyThreadIdOp -> simp_op (ilxOpSeq [ilxOp "call default  class [mscorlib]System.Threading.Thread class [mscorlib]System.Threading.Thread::get_CurrentThread() "])
2170         KillThreadOp -> ty1_op (\ty -> ilxOpSeq [ilxOp "box", ty, ilxOp "call instance void class [mscorlib]System.Threading.Thread::Abort(class [mscorlib]System.Object) "])
2171               {-   ThreadId# -> a -> State# RealWorld -> State# RealWorld -}
2172
2173         ForkOp -> warn_op "ForkOp" (simp_op (ilxOp "/* ForkOp skipped... */ newobj void [mscorlib]System.Object::.ctor() throw"))
2174         ParOp ->  warn_op "ParOp" (simp_op (ilxOp "/* ParOp skipped... */ newobj void [mscorlib]System.Object::.ctor() throw"))
2175         DelayOp -> simp_op (ilxOp "call void class [mscorlib]System.Threading.Thread::Sleep(int32) ")
2176                  {-    Int# -> State# s -> State# s -}
2177
2178         WaitReadOp  -> warn_op "WaitReadOp" (simp_op (ilxOp "/* WaitReadOp skipped... */ pop"))
2179         WaitWriteOp -> warn_op "WaitWriteOp" (simp_op (ilxOp " /* WaitWriteOp skipped... */ newobj void [mscorlib]System.Object::.ctor() throw"))
2180         CCallOp _ ->  panic "CCallOp should already be done..."
2181         ParAtForNowOp -> warn_op "ParAtForNowOp" (simp_op (ilxOp " /* ParAtForNowOp skipped... */ newobj void [mscorlib]System.Object::.ctor() throw"))
2182         ParAtRelOp -> warn_op "ParAtRelOp" (simp_op (ilxOp " /* ParAtRelOp skipped... */ newobj void [mscorlib]System.Object::.ctor() throw"))
2183         ParAtAbsOp -> warn_op "ParAtAbsOp" (simp_op (ilxOp " /* ParAtAbsOp skipped... */ newobj void [mscorlib]System.Object::.ctor() throw"))
2184         ParAtOp -> warn_op "ParAtOp" (simp_op (ilxOp " /* ParAtOp skipped... */ newobj void [mscorlib]System.Object::.ctor() throw"))
2185         ParLocalOp -> warn_op "ParLocalOp" (simp_op (ilxOp " /* ParLocalOp skipped... */ newobj void [mscorlib]System.Object::.ctor() throw"))
2186         ParGlobalOp -> warn_op "ParGlobalOp" (simp_op (ilxOp " /* ParGlobalOp skipped... */ newobj void [mscorlib]System.Object::.ctor() throw"))
2187         SeqOp -> warn_op "SeqOp" (simp_op (ilxOp " newobj void [mscorlib]System.Object::.ctor() throw "))
2188         AddrToHValueOp -> warn_op "AddrToHValueOp" (simp_op (ilxOp "newobj void [mscorlib]System.Object::.ctor() throw"))
2189         ReallyUnsafePtrEqualityOp -> simp_op (ilxOp "ceq")
2190
2191         MkApUpd0_Op ->  warn_op "MkApUpd0_Op" (simp_op (ilxOp " newobj void [mscorlib]System.Object::.ctor() throw"))
2192         NewBCOOp ->  warn_op "NewBCOOp" (simp_op (ilxOp " newobj void [mscorlib]System.Object::.ctor() throw"))
2193                   -- ("newBCO#")  [alphaTyVar, deltaTyVar] [byteArrayPrimTy, byteArrayPrimTy, mkArrayPrimTy alphaTy, byteArrayPrimTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed 2 [mkStatePrimTy deltaTy, bcoPrimTy]))
2194
2195
2196 ty1_op :: (IlxTyFrag -> IlxOpFrag) -> [StgArg] ->  IlxOpFrag 
2197 ty1_op  op ((StgTypeArg ty1):rest)  = 
2198       ilxOpSeq [getArgsStartingAt 1 rest, 
2199                 op (ilxTypeR2 (deepIlxRepType ty1))]
2200
2201 ty2_op :: (IlxTyFrag -> IlxTyFrag -> IlxOpFrag) -> [StgArg] ->  IlxOpFrag 
2202 ty2_op  op ((StgTypeArg ty1):(StgTypeArg ty2):rest)  = 
2203       ilxOpSeq [getArgsStartingAt 2 rest, 
2204                 op (ilxTypeR2 (deepIlxRepType ty1)) 
2205                    (ilxTypeR2 (deepIlxRepType ty2))]
2206
2207 ty3_op :: (IlxTyFrag -> IlxTyFrag -> IlxTyFrag -> IlxOpFrag) -> [StgArg] ->  IlxOpFrag 
2208 ty3_op  op ((StgTypeArg ty1):(StgTypeArg ty2):(StgTypeArg ty3):rest) = 
2209       ilxOpSeq [getArgsStartingAt 3 rest, 
2210                 op (ilxTypeR2 (deepIlxRepType ty1)) 
2211                    (ilxTypeR2 (deepIlxRepType ty2))
2212                    (ilxTypeR2 (deepIlxRepType ty3))]
2213
2214 arg2_op :: (IlxTyFrag -> IlxOpFrag -> IlxOpFrag) -> [StgArg] ->  IlxOpFrag 
2215 arg2_op  op [a1, a2] = 
2216        op (getAsArg 1 a1)
2217           (getAsArg 2 a2)
2218
2219 ty1_arg2_op :: (IlxTyFrag -> IlxOpFrag ->  IlxOpFrag -> IlxOpFrag) -> [StgArg] ->  IlxOpFrag 
2220 ty1_arg2_op  op [(StgTypeArg ty1), a1, a2] = 
2221        op (ilxTypeR2 (deepIlxRepType ty1)) 
2222           (getAsArg 1 a1)
2223           (getAsArg 2 a2)
2224
2225 ty1_arg4_op :: (IlxTyFrag -> IlxOpFrag -> IlxOpFrag -> IlxOpFrag -> IlxOpFrag -> IlxOpFrag) -> [StgArg] ->  IlxOpFrag 
2226 ty1_arg4_op  op [(StgTypeArg ty1), a1, a2, a3, a4] = 
2227        op (ilxTypeR2 (deepIlxRepType ty1)) 
2228           (getAsArg 1 a1)
2229           (getAsArg 2 a2)
2230           (getAsArg 3 a3)
2231           (getAsArg 4 a4)
2232
2233 ty2_arg4_op :: (IlxTyFrag -> IlxTyFrag -> IlxOpFrag -> IlxOpFrag -> IlxOpFrag -> IlxOpFrag -> IlxOpFrag) -> [StgArg] ->  IlxOpFrag 
2234 ty2_arg4_op  op [(StgTypeArg ty1), (StgTypeArg ty2),a1, a2, a3, a4] = 
2235        op (ilxTypeR2 (deepIlxRepType ty1)) 
2236           (ilxTypeR2 (deepIlxRepType ty2)) 
2237           (getAsArg 2 a1)
2238           (getAsArg 3 a2)
2239           (getAsArg 4 a3)
2240           (getAsArg 5 a4)
2241
2242 hd (h:t) = h
2243
2244 getAsArg n a env = hd (ilxMapPlaceArgs n pushArg env [a])
2245 getArgsStartingAt n a env = vcat (ilxMapPlaceArgs n pushArg env a)
2246
2247 simp_op :: IlxOpFrag -> [StgArg] -> IlxOpFrag
2248 simp_op  op args env    = vcat (ilxMapPlaceArgs 0 pushArg env args) $$ op env
2249 warn_op  warning f args = trace ("WARNING! IlxGen cannot translate primop " ++ warning) (f args)
2250 \end{code}
2251
2252 %************************************************************************
2253 %*                                                                      *
2254 \subsection{C Calls}
2255 %*                                                                      *
2256 %************************************************************************
2257
2258 \begin{code}
2259
2260 -- Call the P/Invoke stub wrapper generated in the import section.
2261 -- We eliminate voids in and around an IL C Call.  
2262 -- We also do some type-directed translation for pinning Haskell-managed blobs
2263 -- of data as we throw them across the boundary.
2264 ilxCCall env (CCall (StaticTarget c) casm gc cconv) args ret_ty =
2265    ilxComment (text "C call <+> pprCLabelString c") <+> 
2266         vcat [vcat (ilxMapPlaceArgs 0 pushCArg env args),
2267               text "call" <+> retdoc <+> pprCLabelString c  <+> pprTypeArgs ilxTypeR env ty_args
2268                     <+> pprCValArgTys ilxTypeL env (map deepIlxRepType (filter (not. isVoidIlxRepType) (map stgArgType tm_args))) ]
2269   where 
2270     retdoc = 
2271           if isVoidIlxRepType ret_ty then text "void" 
2272           else ilxTypeR env (deepIlxRepType ret_ty)
2273     (ty_args,tm_args) = splitTyArgs1 args 
2274
2275
2276 hasTyCon (TyConApp tc _) tc2 = tc == tc2
2277 hasTyCon _  _ = False
2278
2279 isByteArrayCArgTy ty = hasTyCon ty byteArrayPrimTyCon || hasTyCon ty mutableByteArrayPrimTyCon
2280 isByteArrayCArg v = isByteArrayCArgTy (deepIlxRepType (idType v))
2281
2282 isForeignObjCArgTy ty = hasTyCon ty foreignObjPrimTyCon
2283 isForeignObjCArg v = isForeignObjCArgTy (deepIlxRepType (idType v))
2284
2285 pinCCallArg v = isByteArrayCArg v || isForeignObjCArg v  
2286
2287 pinCArg  env arg v = pushArg env arg <+> text "dup stloc" <+> singleQuotes (ilxEnvQualifyByExact env (ppr v) <> text "pin") 
2288 pushCArg  env arg@(StgVarArg v) | isByteArrayCArg v = pinCArg env arg v <+> ilxAddrOfByteArrOp env
2289 pushCArg env arg@(StgVarArg v) | isForeignObjCArg v = pinCArg env arg v <+> ilxAddrOfForeignOp env
2290 pushCArg env arg | otherwise = pushArg env arg
2291
2292 pprCValArgTys f env tys = parens (pprSepWithCommas (pprCValArgTy f env) tys)
2293 pprCValArgTy f env ty | isByteArrayCArgTy ty = text "void *" <+> ilxComment (text "interior pointer into ByteArr#")
2294 pprCValArgTy f env ty | isForeignObjCArgTy ty = text "void *" <+> ilxComment (text "foreign object")
2295 pprCValArgTy f env ty | otherwise = f env ty
2296
2297
2298 foldR            :: (a -> b -> b) -> [a] -> b -> b
2299 -- foldR _ [] z     =  z
2300 -- foldR f (x:xs) z =  f x (foldR f xs z) 
2301 {-# INLINE foldR #-}
2302 foldR k xs z = go xs
2303              where
2304                go []     = z
2305                go (y:ys) = y `k` go ys
2306
2307 \end{code}
2308