[project @ 2002-03-13 13:48:04 by simonmar]
[ghc-hetmet.git] / ghc / compiler / absCSyn / PprAbsC.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 %************************************************************************
5 %*                                                                      *
6 \section[PprAbsC]{Pretty-printing Abstract~C}
7 %*                                                                      *
8 %************************************************************************
9
10 \begin{code}
11 module PprAbsC (
12         writeRealC,
13         dumpRealC,
14         pprAmode,
15         pprMagicId
16     ) where
17
18 #include "HsVersions.h"
19
20 import IO       ( Handle )
21
22 import PrimRep 
23 import AbsCSyn
24 import ClosureInfo
25 import AbsCUtils        ( getAmodeRep, nonemptyAbsC,
26                           mixedPtrLocn, mixedTypeLocn
27                         )
28
29 import ForeignCall      ( CCallSpec(..), CCallTarget(..), playSafe,
30                           playThreadSafe, ccallConvAttribute )
31 import CLabel           ( externallyVisibleCLabel,
32                           needsCDecl, pprCLabel,
33                           mkReturnInfoLabel, mkReturnPtLabel, mkClosureTblLabel,
34                           mkClosureLabel, mkErrorStdEntryLabel,
35                           CLabel, CLabelType(..), labelType, labelDynamic
36                         )
37
38 import CmdLineOpts      ( opt_SccProfilingOn, opt_GranMacros )
39 import CostCentre       ( pprCostCentreDecl, pprCostCentreStackDecl )
40
41 import Costs            ( costs, addrModeCosts, CostRes(..), Side(..) )
42 import CStrings         ( pprStringInCStyle, pprCLabelString )
43 import FiniteMap        ( addToFM, emptyFM, lookupFM, FiniteMap )
44 import Literal          ( Literal(..) )
45 import TyCon            ( tyConDataCons )
46 import Name             ( NamedThing(..) )
47 import DataCon          ( dataConWrapId )
48 import Maybes           ( maybeToBool, catMaybes )
49 import PrimOp           ( primOpNeedsWrapper )
50 import MachOp           ( MachOp(..) )
51 import ForeignCall      ( ForeignCall(..) )
52 import PrimRep          ( isFloatingRep, PrimRep(..), getPrimRepSize )
53 import SMRep            ( pprSMRep )
54 import Unique           ( pprUnique, Unique{-instance NamedThing-} )
55 import UniqSet          ( emptyUniqSet, elementOfUniqSet,
56                           addOneToUniqSet, UniqSet
57                         )
58 import StgSyn           ( StgOp(..) )
59 import BitSet           ( BitSet, intBS )
60 import Outputable
61 import GlaExts
62 import Util             ( lengthExceeds, listLengthCmp )
63
64 import ST
65
66 infixr 9 `thenTE`
67 \end{code}
68
69 For spitting out the costs of an abstract~C expression, @writeRealC@
70 now not only prints the C~code of the @absC@ arg but also adds a macro
71 call to a cost evaluation function @GRAN_EXEC@. For that,
72 @pprAbsC@ has a new ``costs'' argument.  %% HWL
73
74 \begin{code}
75 {-
76 writeRealC :: Handle -> AbstractC -> IO ()
77 writeRealC handle absC
78      -- avoid holding on to the whole of absC in the !Gransim case.
79      if opt_GranMacros
80         then printForCFast fp (pprAbsC absC (costs absC))
81         else printForCFast fp (pprAbsC absC (panic "costs"))
82              --printForC handle (pprAbsC absC (panic "costs"))
83 dumpRealC :: AbstractC -> SDoc
84 dumpRealC absC = pprAbsC absC (costs absC)
85 -}
86
87 writeRealC :: Handle -> AbstractC -> IO ()
88 --writeRealC handle absC = 
89 -- _scc_ "writeRealC" 
90 -- printDoc LeftMode handle (pprAbsC absC (costs absC))
91
92 writeRealC handle absC
93  | opt_GranMacros = _scc_ "writeRealC" printForC handle $ 
94                                        pprCode CStyle (pprAbsC absC (costs absC))
95  | otherwise      = _scc_ "writeRealC" printForC handle $
96                                        pprCode CStyle (pprAbsC absC (panic "costs"))
97
98 dumpRealC :: AbstractC -> SDoc
99 dumpRealC absC
100  | opt_GranMacros = pprCode CStyle (pprAbsC absC (costs absC))
101  | otherwise      = pprCode CStyle (pprAbsC absC (panic "costs"))
102
103 \end{code}
104
105 This emits the macro,  which is used in GrAnSim  to compute the total costs
106 from a cost 5 tuple. %%  HWL
107
108 \begin{code}
109 emitMacro :: CostRes -> SDoc
110
111 emitMacro _ | not opt_GranMacros = empty
112
113 emitMacro (Cost (i,b,l,s,f))
114   = hcat [ ptext SLIT("GRAN_EXEC"), char '(',
115                           int i, comma, int b, comma, int l, comma,
116                           int s, comma, int f, pp_paren_semi ]
117
118 pp_paren_semi = text ");"
119 \end{code}
120
121 New type: Now pprAbsC also takes the costs for evaluating the Abstract C
122 code as an argument (that's needed when spitting out the GRAN_EXEC macro
123 which must be done before the return i.e. inside absC code)   HWL
124
125 \begin{code}
126 pprAbsC :: AbstractC -> CostRes -> SDoc
127 pprAbsC AbsCNop _ = empty
128 pprAbsC (AbsCStmts s1 s2) c = ($$) (pprAbsC s1 c) (pprAbsC s2 c)
129
130 pprAbsC (CAssign dest src) _ = pprAssign (getAmodeRep dest) dest src
131
132 pprAbsC (CJump target) c
133   = ($$) (hcat [emitMacro c {-WDP:, text "/* <--++  CJump */"-} ])
134              (hcat [ text jmp_lit, pprAmode target, pp_paren_semi ])
135
136 pprAbsC (CFallThrough target) c
137   = ($$) (hcat [emitMacro c {-WDP:, text "/* <--++  CFallThrough */"-} ])
138              (hcat [ text jmp_lit, pprAmode target, pp_paren_semi ])
139
140 -- --------------------------------------------------------------------------
141 -- Spit out GRAN_EXEC macro immediately before the return                 HWL
142
143 pprAbsC (CReturn am return_info)  c
144   = ($$) (hcat [emitMacro c {-WDP:, text "/* <----  CReturn */"-} ])
145              (hcat [text jmp_lit, target, pp_paren_semi ])
146   where
147    target = case return_info of
148         DirectReturn -> hcat [ptext SLIT("ENTRY_CODE"), lparen,
149                               pprAmode am, rparen]
150         DynamicVectoredReturn am' -> mk_vector (pprAmode am')
151         StaticVectoredReturn n -> mk_vector (int n)     -- Always positive
152    mk_vector x = hcat [ptext SLIT("RET_VEC"), char '(', pprAmode am, comma,
153                        x, rparen ]
154
155 pprAbsC (CSplitMarker) _ = ptext SLIT("__STG_SPLIT_MARKER")
156
157 -- we optimise various degenerate cases of CSwitches.
158
159 -- --------------------------------------------------------------------------
160 -- Assume: CSwitch is also end of basic block
161 --         costs function yields nullCosts for whole switch
162 --         ==> inherited costs c are those of basic block up to switch
163 --         ==> inherit c + costs for the corresponding branch
164 --                                                                       HWL
165 -- --------------------------------------------------------------------------
166
167 pprAbsC (CSwitch discrim [] deflt) c
168   = pprAbsC deflt (c + costs deflt)
169     -- Empty alternative list => no costs for discrim as nothing cond. here HWL
170
171 pprAbsC (CSwitch discrim [(tag,alt_code)] deflt) c -- only one alt
172   = case (nonemptyAbsC deflt) of
173       Nothing ->                -- one alt and no default
174                  pprAbsC alt_code (c + costs alt_code)
175                  -- Nothing conditional in here either  HWL
176
177       Just dc ->                -- make it an "if"
178                  do_if_stmt discrim tag alt_code dc c
179
180 -- What problem is the re-ordering trying to solve ?
181 pprAbsC (CSwitch discrim [(tag1@(MachInt i1), alt_code1),
182                           (tag2@(MachInt i2), alt_code2)] deflt) c
183   | empty_deflt && ((i1 == 0 && i2 == 1) || (i1 == 1 && i2 == 0))
184   = if (i1 == 0) then
185         do_if_stmt discrim tag1 alt_code1 alt_code2 c
186     else
187         do_if_stmt discrim tag2 alt_code2 alt_code1 c
188   where
189     empty_deflt = not (maybeToBool (nonemptyAbsC deflt))
190
191 pprAbsC (CSwitch discrim alts deflt) c -- general case
192   | isFloatingRep (getAmodeRep discrim)
193     = pprAbsC (foldr ( \ a -> CSwitch discrim [a]) deflt alts) c
194   | otherwise
195     = vcat [
196         hcat [text "switch (", pp_discrim, text ") {"],
197         nest 2 (vcat (map ppr_alt alts)),
198         (case (nonemptyAbsC deflt) of
199            Nothing -> empty
200            Just dc ->
201             nest 2 (vcat [ptext SLIT("default:"),
202                                   pprAbsC dc (c + switch_head_cost
203                                                     + costs dc),
204                                   ptext SLIT("break;")])),
205         char '}' ]
206   where
207     pp_discrim
208       = pprAmode discrim
209
210     ppr_alt (lit, absC)
211       = vcat [ hcat [ptext SLIT("case "), pprBasicLit lit, char ':'],
212                    nest 2 (($$) (pprAbsC absC (c + switch_head_cost + costs absC))
213                                        (ptext SLIT("break;"))) ]
214
215     -- Costs for addressing header of switch and cond. branching        -- HWL
216     switch_head_cost = addrModeCosts discrim Rhs + (Cost (0, 1, 0, 0, 0))
217
218 pprAbsC stmt@(COpStmt results (StgFCallOp fcall uniq) args vol_regs) _
219   = pprFCall fcall uniq args results vol_regs
220
221 pprAbsC stmt@(COpStmt results (StgPrimOp op) args vol_regs) _
222   = let
223         non_void_args = grab_non_void_amodes args
224         non_void_results = grab_non_void_amodes results
225         -- if just one result, we print in the obvious "assignment" style;
226         -- if 0 or many results, we emit a macro call, w/ the results
227         -- followed by the arguments.  The macro presumably knows which
228         -- are which :-)
229
230         the_op = ppr_op_call non_void_results non_void_args
231                 -- liveness mask is *in* the non_void_args
232     in
233     if primOpNeedsWrapper op then
234         case (ppr_vol_regs vol_regs) of { (pp_saves, pp_restores) ->
235         vcat [  pp_saves,
236                 the_op,
237                 pp_restores
238              ]
239         }
240     else
241         the_op
242   where
243     ppr_op_call results args
244       = hcat [ ppr op, lparen,
245         hcat (punctuate comma (map ppr_op_result results)),
246         if null results || null args then empty else comma,
247         hcat (punctuate comma (map pprAmode args)),
248         pp_paren_semi ]
249
250     ppr_op_result r = ppr_amode r
251       -- primop macros do their own casting of result;
252       -- hence we can toss the provided cast...
253
254 -- NEW CASES FOR EXPANDED PRIMOPS
255
256 pprAbsC stmt@(CMachOpStmt res mop [arg1,arg2] maybe_vols) _
257   = let prefix_fn = mop `elem` [MO_Dbl_Pwr, MO_Flt_Pwr, MO_NatS_MulMayOflo]
258     in
259     case ppr_maybe_vol_regs maybe_vols of {(saves,restores) ->
260     saves $$
261     hcat (
262        [ppr_amode res, equals]
263        ++ (if prefix_fn 
264            then [pprMachOp_for_C mop, parens (pprAmode arg1 <> comma <> pprAmode arg2)]
265            else [pprAmode arg1, pprMachOp_for_C mop, pprAmode arg2])
266        ++ [semi]
267     )
268     $$ restores
269     }
270
271 pprAbsC stmt@(CMachOpStmt res mop [arg1] maybe_vols) _
272   = case ppr_maybe_vol_regs maybe_vols of {(saves,restores) ->
273     saves $$
274     hcat [ppr_amode res, equals, 
275           pprMachOp_for_C mop, parens (pprAmode arg1),
276           semi]
277     $$ restores
278     }
279
280 pprAbsC stmt@(CSequential stuff) c
281   = vcat (map (flip pprAbsC c) stuff)
282
283 -- end of NEW CASES FOR EXPANDED PRIMOPS
284
285 pprAbsC stmt@(CSRT lbl closures) c
286   = case (pprTempAndExternDecls stmt) of { (_, pp_exts) ->
287          pp_exts
288       $$ ptext SLIT("SRT") <> lparen <> pprCLabel lbl <> rparen
289       $$ nest 2 (hcat (punctuate comma (map pp_closure_lbl closures)))
290          <> ptext SLIT("};")
291   }
292
293 pprAbsC stmt@(CBitmap lbl mask) c
294   = pp_bitmap_switch mask semi $
295     hcat [ ptext SLIT("BITMAP"), lparen,
296            pprCLabel lbl, comma,
297            int (length mask), comma,
298            pp_bitmap mask, rparen ]
299
300 pprAbsC (CSimultaneous abs_c) c
301   = hcat [ptext SLIT("{{"), pprAbsC abs_c c, ptext SLIT("}}")]
302
303 pprAbsC (CCheck macro as code) c
304   = hcat [ptext (cCheckMacroText macro), lparen,
305        hcat (punctuate comma (map ppr_amode as)), comma,
306        pprAbsC code c, pp_paren_semi
307     ]
308 pprAbsC (CMacroStmt macro as) _
309   = hcat [ptext (cStmtMacroText macro), lparen,
310         hcat (punctuate comma (map ppr_amode as)),pp_paren_semi] -- no casting
311 pprAbsC (CCallProfCtrMacro op as) _
312   = hcat [ptext op, lparen,
313         hcat (punctuate comma (map ppr_amode as)),pp_paren_semi]
314 pprAbsC (CCallProfCCMacro op as) _
315   = hcat [ptext op, lparen,
316         hcat (punctuate comma (map ppr_amode as)),pp_paren_semi]
317 pprAbsC stmt@(CCallTypedef is_tdef (CCallSpec op_str cconv _) uniq results args) _
318   =  hsep [ ptext (if is_tdef then SLIT("typedef") else SLIT("extern"))
319           , ccall_res_ty
320           , fun_nm
321           , parens (hsep (punctuate comma ccall_decl_ty_args))
322           ] <> semi
323     where
324     {-
325       In the non-casm case, to ensure that we're entering the given external
326       entry point using the correct calling convention, we have to do the following:
327
328         - When entering via a function pointer (the `dynamic' case) using the specified
329           calling convention, we emit a typedefn declaration attributed with the
330           calling convention to use together with the result and parameter types we're
331           assuming. Coerce the function pointer to this type and go.
332
333         - to enter the function at a given code label, we emit an extern declaration
334           for the label here, stating the calling convention together with result and
335           argument types we're assuming. 
336
337           The C compiler will hopefully use this extern declaration to good effect,
338           reporting any discrepancies between our extern decl and any other that
339           may be in scope.
340     
341           Re: calling convention, notice that gcc (2.8.1 and egcs-1.0.2) will for
342           the external function `foo' use the calling convention of the first `foo'
343           prototype it encounters (nor does it complain about conflicting attribute
344           declarations). The consequence of this is that you cannot override the
345           calling convention of `foo' using an extern declaration (you'd have to use
346           a typedef), but why you would want to do such a thing in the first place
347           is totally beyond me.
348           
349           ToDo: petition the gcc folks to add code to warn about conflicting attribute
350           declarations.
351
352     -}
353
354      fun_nm
355        | is_tdef   = parens (text (ccallConvAttribute cconv) <+> char '*' <> ccall_fun_ty)
356        | otherwise = text (ccallConvAttribute cconv) <+> ccall_fun_ty
357
358      ccall_fun_ty = 
359         case op_str of
360           DynamicTarget  -> ptext SLIT("_ccall_fun_ty") <> ppr uniq
361           StaticTarget x -> pprCLabelString x
362
363      ccall_res_ty = 
364        case non_void_results of
365           []       -> ptext SLIT("void")
366           [amode]  -> ppr (getAmodeRep amode)
367           _        -> panic "pprAbsC{CCallTypedef}: ccall_res_ty"
368
369      ccall_decl_ty_args 
370        | is_tdef   = tail ccall_arg_tys
371        | otherwise = ccall_arg_tys
372
373      ccall_arg_tys      = map (ppr . getAmodeRep) non_void_args
374
375       -- the first argument will be the "I/O world" token (a VoidRep)
376       -- all others should be non-void
377      non_void_args =
378         let nvas = init args
379         in ASSERT (all non_void nvas) nvas
380
381       -- there will usually be two results: a (void) state which we
382       -- should ignore and a (possibly void) result.
383      non_void_results =
384         let nvrs = grab_non_void_amodes results
385         in ASSERT (listLengthCmp nvrs 1 /= GT) nvrs
386
387 pprAbsC (CCodeBlock lbl abs_C) _
388   = if not (maybeToBool(nonemptyAbsC abs_C)) then
389         pprTrace "pprAbsC: curious empty code block for" (pprCLabel lbl) empty
390     else
391     case (pprTempAndExternDecls abs_C) of { (pp_temps, pp_exts) ->
392     vcat [
393         empty,
394         pp_exts, 
395         hcat [text (if (externallyVisibleCLabel lbl)
396                           then "FN_("   -- abbreviations to save on output
397                           else "IFN_("),
398                    pprCLabel lbl, text ") {"],
399
400         pp_temps,
401
402         nest 8 (ptext SLIT("FB_")),
403         nest 8 (pprAbsC abs_C (costs abs_C)),
404         nest 8 (ptext SLIT("FE_")),
405         char '}',
406         char ' ' ]
407     }
408
409
410 pprAbsC (CInitHdr cl_info amode cost_centre size) _
411   = hcat [ ptext SLIT("SET_HDR_"), char '(',
412                 ppr_amode amode, comma,
413                 pprCLabelAddr info_lbl, comma,
414                 if_profiling (pprAmode cost_centre), comma,
415                 if_profiling (int size),
416                 pp_paren_semi ]
417   where
418     info_lbl    = infoTableLabelFromCI cl_info
419
420
421 pprAbsC stmt@(CStaticClosure cl_info cost_centre amodes) _
422   = case (pprTempAndExternDecls stmt) of { (_, pp_exts) ->
423     vcat [
424         pp_exts,
425         hcat [
426                 ptext SLIT("SET_STATIC_HDR"), char '(',
427                 pprCLabel closure_lbl,                          comma,
428                 pprCLabel info_lbl,                             comma,
429                 if_profiling (pprAmode cost_centre),            comma,
430                 ppLocalness closure_lbl,                        comma,
431                 ppLocalnessMacro True{-include dyn-} info_lbl,
432                 char ')'
433                 ],
434         nest 2 (ppr_payload amodes),
435         ptext SLIT("};") ]
436     }
437   where
438     closure_lbl = closureLabelFromCI cl_info
439     info_lbl    = infoTableLabelFromCI cl_info
440
441     ppr_payload [] = empty
442     ppr_payload ls = 
443         comma <+> 
444           (braces $ hsep $ punctuate comma $
445            map (text "(L_)" <>) (foldr ppr_item [] ls))
446
447     ppr_item item rest
448       | rep == VoidRep   = rest
449       | rep == FloatRep  = ppr_amode (floatToWord item) : rest
450       | rep == DoubleRep = map ppr_amode (doubleToWords item) ++ rest
451       | otherwise        = ppr_amode item : rest
452       where 
453         rep  = getAmodeRep item
454
455
456 pprAbsC stmt@(CClosureInfoAndCode cl_info slow maybe_fast cl_descr) _
457   = vcat [
458         hcat [
459              ptext SLIT("INFO_TABLE"),
460              ( if is_selector then
461                  ptext SLIT("_SELECTOR")
462                else if is_constr then
463                  ptext SLIT("_CONSTR")
464                else if needs_srt then
465                  ptext SLIT("_SRT")
466                else empty ), char '(',
467
468             pprCLabel info_lbl,                         comma,
469             pprCLabel slow_lbl,                         comma,
470             pp_rest, {- ptrs,nptrs,[srt,]type,-}        comma,
471
472             ppLocalness info_lbl,                          comma,
473             ppLocalnessMacro True{-include dyn-} slow_lbl, comma,
474
475             if_profiling pp_descr, comma,
476             if_profiling pp_type,
477             text ");"
478              ],
479         pp_slow,
480         case maybe_fast of
481             Nothing -> empty
482             Just fast -> let stuff = CCodeBlock fast_lbl fast in
483                          pprAbsC stuff (costs stuff)
484     ]
485   where
486     info_lbl    = infoTableLabelFromCI cl_info
487     fast_lbl    = fastLabelFromCI cl_info
488
489     (slow_lbl, pp_slow)
490       = case (nonemptyAbsC slow) of
491           Nothing -> (mkErrorStdEntryLabel, empty)
492           Just xx -> (entryLabelFromCI cl_info,
493                        let stuff = CCodeBlock slow_lbl xx in
494                        pprAbsC stuff (costs stuff))
495
496     maybe_selector = maybeSelectorInfo cl_info
497     is_selector = maybeToBool maybe_selector
498     (Just select_word_i) = maybe_selector
499
500     maybe_tag = closureSemiTag cl_info
501     is_constr = maybeToBool maybe_tag
502     (Just tag) = maybe_tag
503
504     srt       = closureSRT cl_info
505     needs_srt = case srt of
506                    NoC_SRT -> False
507                    other   -> True
508
509
510     size = closureNonHdrSize cl_info
511
512     ptrs        = closurePtrsSize cl_info
513     nptrs       = size - ptrs
514
515     pp_rest | is_selector      = int select_word_i
516             | otherwise        = hcat [
517                   int ptrs,             comma,
518                   int nptrs,            comma,
519                   if is_constr then
520                         hcat [ int tag, comma ]
521                   else if needs_srt then
522                         pp_srt_info srt
523                   else empty,
524                   type_str ]
525
526     type_str = pprSMRep (closureSMRep cl_info)
527
528     pp_descr = pprStringInCStyle cl_descr
529     pp_type  = pprStringInCStyle (closureTypeDescr cl_info)
530
531 pprAbsC stmt@(CClosureTbl tycon) _
532   = vcat (
533         ptext SLIT("CLOSURE_TBL") <> 
534            lparen <> pprCLabel (mkClosureTblLabel tycon) <> rparen :
535         punctuate comma (
536            map (pp_closure_lbl . mkClosureLabel . getName . dataConWrapId) (tyConDataCons tycon)
537         )
538    ) $$ ptext SLIT("};")
539
540 pprAbsC stmt@(CRetDirect uniq code srt liveness) _
541   = vcat [
542       hcat [
543           ptext SLIT("INFO_TABLE_SRT_BITMAP"), lparen, 
544           pprCLabel info_lbl,           comma,
545           pprCLabel entry_lbl,          comma,
546           pp_liveness liveness,         comma,    -- bitmap
547           pp_srt_info srt,                        -- SRT
548           closure_type,                 comma,    -- closure type
549           ppLocalness info_lbl,         comma,    -- info table storage class
550           ppLocalnessMacro True{-include dyn-} entry_lbl,       comma,    -- entry pt storage class
551           int 0, comma,
552           int 0, text ");"
553       ],
554       pp_code
555     ]
556   where
557      info_lbl     = mkReturnInfoLabel uniq
558      entry_lbl    = mkReturnPtLabel uniq
559
560      pp_code      = let stuff = CCodeBlock entry_lbl code in
561                     pprAbsC stuff (costs stuff)
562
563      closure_type = pp_liveness_switch liveness
564                        (ptext SLIT("RET_SMALL"))
565                        (ptext SLIT("RET_BIG"))
566
567 pprAbsC stmt@(CRetVector lbl amodes srt liveness) _
568   = case (pprTempAndExternDecls stmt) of { (_, pp_exts) ->
569     vcat [
570         pp_exts,
571         hcat [
572           ptext SLIT("VEC_INFO_") <> int size,
573           lparen, 
574           pprCLabel lbl, comma,
575           pp_liveness liveness, comma,  -- bitmap liveness mask
576           pp_srt_info srt,              -- SRT
577           closure_type, comma,
578           ppLocalness lbl, comma
579         ],
580         nest 2 (sep (punctuate comma (map ppr_item amodes))),
581         text ");"
582     ]
583     }
584
585   where
586     ppr_item item = (<>) (text "(F_) ") (ppr_amode item)
587     size = length amodes
588
589     closure_type = pp_liveness_switch liveness
590                       (ptext SLIT("RET_VEC_SMALL"))
591                       (ptext SLIT("RET_VEC_BIG"))
592
593
594 pprAbsC stmt@(CModuleInitBlock lbl code) _
595   = vcat [
596         ptext SLIT("START_MOD_INIT") <> parens (pprCLabel lbl),
597         case (pprTempAndExternDecls stmt) of { (_, pp_exts) -> pp_exts },
598         pprAbsC code (costs code),
599         hcat [ptext SLIT("END_MOD_INIT"), lparen, rparen]
600     ]
601
602 pprAbsC (CCostCentreDecl is_local cc) _ = pprCostCentreDecl is_local cc
603 pprAbsC (CCostCentreStackDecl ccs)    _ = pprCostCentreStackDecl ccs
604 \end{code}
605
606 \begin{code}
607 -- Print a CMachOp in a way suitable for emitting via C.
608 pprMachOp_for_C MO_Nat_Add       = char '+'
609 pprMachOp_for_C MO_Nat_Sub       = char '-'
610 pprMachOp_for_C MO_Nat_Eq        = text "==" 
611 pprMachOp_for_C MO_Nat_Ne        = text "!="
612
613 pprMachOp_for_C MO_NatS_Ge       = text ">="
614 pprMachOp_for_C MO_NatS_Le       = text "<="
615 pprMachOp_for_C MO_NatS_Gt       = text ">"
616 pprMachOp_for_C MO_NatS_Lt       = text "<"
617
618 pprMachOp_for_C MO_NatU_Ge       = text ">="
619 pprMachOp_for_C MO_NatU_Le       = text "<="
620 pprMachOp_for_C MO_NatU_Gt       = text ">"
621 pprMachOp_for_C MO_NatU_Lt       = text "<"
622
623 pprMachOp_for_C MO_NatS_Mul      = char '*'
624 pprMachOp_for_C MO_NatS_MulMayOflo = text "mulIntMayOflo"
625 pprMachOp_for_C MO_NatS_Quot     = char '/'
626 pprMachOp_for_C MO_NatS_Rem      = char '%'
627 pprMachOp_for_C MO_NatS_Neg      = char '-'
628
629 pprMachOp_for_C MO_NatU_Mul      = char '*'
630 pprMachOp_for_C MO_NatU_Quot     = char '/'
631 pprMachOp_for_C MO_NatU_Rem      = char '%'
632
633 pprMachOp_for_C MO_Nat_And       = text "&"
634 pprMachOp_for_C MO_Nat_Or        = text "|"
635 pprMachOp_for_C MO_Nat_Xor       = text "^"
636 pprMachOp_for_C MO_Nat_Not       = text "~"
637 pprMachOp_for_C MO_Nat_Shl       = text "<<"
638 pprMachOp_for_C MO_Nat_Shr       = text ">>"
639 pprMachOp_for_C MO_Nat_Sar       = text ">>"
640
641 pprMachOp_for_C MO_32U_Eq        = text "=="
642 pprMachOp_for_C MO_32U_Ne        = text "!="
643 pprMachOp_for_C MO_32U_Ge        = text ">="
644 pprMachOp_for_C MO_32U_Le        = text "<="
645 pprMachOp_for_C MO_32U_Gt        = text ">"
646 pprMachOp_for_C MO_32U_Lt        = text "<"
647
648 pprMachOp_for_C MO_Dbl_Eq        = text "=="
649 pprMachOp_for_C MO_Dbl_Ne        = text "!="
650 pprMachOp_for_C MO_Dbl_Ge        = text ">="
651 pprMachOp_for_C MO_Dbl_Le        = text "<="
652 pprMachOp_for_C MO_Dbl_Gt        = text ">"
653 pprMachOp_for_C MO_Dbl_Lt        = text "<"
654
655 pprMachOp_for_C MO_Dbl_Add       = text "+"
656 pprMachOp_for_C MO_Dbl_Sub       = text "-"
657 pprMachOp_for_C MO_Dbl_Mul       = text "*"
658 pprMachOp_for_C MO_Dbl_Div       = text "/"
659 pprMachOp_for_C MO_Dbl_Pwr       = text "pow"
660
661 pprMachOp_for_C MO_Dbl_Sin       = text "sin"
662 pprMachOp_for_C MO_Dbl_Cos       = text "cos"
663 pprMachOp_for_C MO_Dbl_Tan       = text "tan"
664 pprMachOp_for_C MO_Dbl_Sinh      = text "sinh"
665 pprMachOp_for_C MO_Dbl_Cosh      = text "cosh"
666 pprMachOp_for_C MO_Dbl_Tanh      = text "tanh"
667 pprMachOp_for_C MO_Dbl_Asin      = text "asin"
668 pprMachOp_for_C MO_Dbl_Acos      = text "acos"
669 pprMachOp_for_C MO_Dbl_Atan      = text "atan"
670 pprMachOp_for_C MO_Dbl_Log       = text "log"
671 pprMachOp_for_C MO_Dbl_Exp       = text "exp"
672 pprMachOp_for_C MO_Dbl_Sqrt      = text "sqrt"
673 pprMachOp_for_C MO_Dbl_Neg       = text "-"
674
675 pprMachOp_for_C MO_Flt_Add       = text "+"
676 pprMachOp_for_C MO_Flt_Sub       = text "-"
677 pprMachOp_for_C MO_Flt_Mul       = text "*"
678 pprMachOp_for_C MO_Flt_Div       = text "/"
679 pprMachOp_for_C MO_Flt_Pwr       = text "pow"
680
681 pprMachOp_for_C MO_Flt_Eq        = text "=="
682 pprMachOp_for_C MO_Flt_Ne        = text "!="
683 pprMachOp_for_C MO_Flt_Ge        = text ">="
684 pprMachOp_for_C MO_Flt_Le        = text "<="
685 pprMachOp_for_C MO_Flt_Gt        = text ">"
686 pprMachOp_for_C MO_Flt_Lt        = text "<"
687
688 pprMachOp_for_C MO_Flt_Sin       = text "sin"
689 pprMachOp_for_C MO_Flt_Cos       = text "cos"
690 pprMachOp_for_C MO_Flt_Tan       = text "tan"
691 pprMachOp_for_C MO_Flt_Sinh      = text "sinh"
692 pprMachOp_for_C MO_Flt_Cosh      = text "cosh"
693 pprMachOp_for_C MO_Flt_Tanh      = text "tanh"
694 pprMachOp_for_C MO_Flt_Asin      = text "asin"
695 pprMachOp_for_C MO_Flt_Acos      = text "acos"
696 pprMachOp_for_C MO_Flt_Atan      = text "atan"
697 pprMachOp_for_C MO_Flt_Log       = text "log"
698 pprMachOp_for_C MO_Flt_Exp       = text "exp"
699 pprMachOp_for_C MO_Flt_Sqrt      = text "sqrt"
700 pprMachOp_for_C MO_Flt_Neg       = text "-"
701
702 pprMachOp_for_C MO_32U_to_NatS   = text "(StgInt)"
703 pprMachOp_for_C MO_NatS_to_32U   = text "(StgWord32)"
704
705 pprMachOp_for_C MO_NatS_to_Dbl   = text "(StgDouble)"
706 pprMachOp_for_C MO_Dbl_to_NatS   = text "(StgInt)"
707
708 pprMachOp_for_C MO_NatS_to_Flt   = text "(StgFloat)"
709 pprMachOp_for_C MO_Flt_to_NatS   = text "(StgInt)"
710
711 pprMachOp_for_C MO_NatS_to_NatU  = text "(StgWord)"
712 pprMachOp_for_C MO_NatU_to_NatS  = text "(StgInt)"
713
714 pprMachOp_for_C MO_NatS_to_NatP  = text "(void*)"
715 pprMachOp_for_C MO_NatP_to_NatS  = text "(StgInt)"
716 pprMachOp_for_C MO_NatU_to_NatP  = text "(void*)"
717 pprMachOp_for_C MO_NatP_to_NatU  = text "(StgWord)"
718
719 pprMachOp_for_C MO_Dbl_to_Flt    = text "(StgFloat)"
720 pprMachOp_for_C MO_Flt_to_Dbl    = text "(StgDouble)"
721
722 pprMachOp_for_C MO_8S_to_NatS    = text "(StgInt8)(StgInt)"
723 pprMachOp_for_C MO_16S_to_NatS   = text "(StgInt16)(StgInt)"
724 pprMachOp_for_C MO_32S_to_NatS   = text "(StgInt32)(StgInt)"
725
726 pprMachOp_for_C MO_8U_to_NatU    = text "(StgWord8)(StgWord)"
727 pprMachOp_for_C MO_16U_to_NatU   = text "(StgWord16)(StgWord)"
728 pprMachOp_for_C MO_32U_to_NatU   = text "(StgWord32)(StgWord)"
729
730 pprMachOp_for_C MO_8U_to_32U     = text "(StgWord32)"
731 pprMachOp_for_C MO_32U_to_8U     = text "(StgWord8)"
732
733
734 ppLocalness lbl
735   = if (externallyVisibleCLabel lbl) 
736                 then empty 
737                 else ptext SLIT("static ")
738
739 -- Horrible macros for declaring the types and locality of labels (see
740 -- StgMacros.h).
741
742 ppLocalnessMacro include_dyn_prefix clabel =
743      hcat [
744         visiblity_prefix,
745         dyn_prefix,
746         case label_type of
747           ClosureType    -> ptext SLIT("C_")
748           CodeType       -> ptext SLIT("F_")
749           InfoTblType    -> ptext SLIT("I_")
750           ClosureTblType -> ptext SLIT("CP_")
751           DataType       -> ptext SLIT("D_")
752      ]
753   where
754    is_visible = externallyVisibleCLabel clabel
755    label_type = labelType clabel
756
757    visiblity_prefix
758      | is_visible = char 'E'
759      | otherwise  = char 'I'
760
761    dyn_prefix
762      | include_dyn_prefix && labelDynamic clabel = char 'D'
763      | otherwise                                 = empty
764
765 \end{code}
766
767 \begin{code}
768 jmp_lit = "JMP_("
769
770 grab_non_void_amodes amodes
771   = filter non_void amodes
772
773 non_void amode
774   = case (getAmodeRep amode) of
775       VoidRep -> False
776       k -> True
777 \end{code}
778
779 \begin{code}
780 ppr_maybe_vol_regs :: Maybe [MagicId] -> (SDoc, SDoc)
781 ppr_maybe_vol_regs Nothing
782    = (empty, empty)
783 ppr_maybe_vol_regs (Just vrs)
784    = case ppr_vol_regs vrs of
785         (saves, restores) 
786            -> (pp_basic_saves $$ saves,
787                pp_basic_restores $$ restores)
788
789 ppr_vol_regs :: [MagicId] -> (SDoc, SDoc)
790
791 ppr_vol_regs [] = (empty, empty)
792 ppr_vol_regs (VoidReg:rs) = ppr_vol_regs rs
793 ppr_vol_regs (r:rs)
794   = let pp_reg = case r of
795                     VanillaReg pk n -> pprVanillaReg n
796                     _ -> pprMagicId r
797         (more_saves, more_restores) = ppr_vol_regs rs
798     in
799     (($$) ((<>) (ptext SLIT("CALLER_SAVE_"))    pp_reg) more_saves,
800      ($$) ((<>) (ptext SLIT("CALLER_RESTORE_")) pp_reg) more_restores)
801
802 -- pp_basic_{saves,restores}: The BaseReg, Sp, Su, Hp and
803 -- HpLim (see StgRegs.lh) may need to be saved/restored around CCalls,
804 -- depending on the platform.  (The "volatile regs" stuff handles all
805 -- other registers.)  Just be *sure* BaseReg is OK before trying to do
806 -- anything else. The correct sequence of saves&restores are
807 -- encoded by the CALLER_*_SYSTEM macros.
808 pp_basic_saves    = ptext SLIT("CALLER_SAVE_SYSTEM")
809 pp_basic_restores = ptext SLIT("CALLER_RESTORE_SYSTEM")
810 \end{code}
811
812 \begin{code}
813 pp_srt_info NoC_SRT = hcat [ int 0, comma, 
814                              int 0, comma, 
815                              int 0, comma ]
816 pp_srt_info (C_SRT lbl off len) = hcat [ pprCLabel lbl, comma,
817                                          int off, comma,
818                                          int len, comma ]
819 \end{code}
820
821 \begin{code}
822 pp_closure_lbl lbl
823       | labelDynamic lbl = text "DLL_SRT_ENTRY" <> parens (pprCLabel lbl)
824       | otherwise        = char '&' <> pprCLabel lbl
825 \end{code}
826
827 \begin{code}
828 if_profiling pretty
829   = if  opt_SccProfilingOn
830     then pretty
831     else char '0' -- leave it out!
832 -- ---------------------------------------------------------------------------
833 -- Changes for GrAnSim:
834 --  draw costs for computation in head of if into both branches;
835 --  as no abstractC data structure is given for the head, one is constructed
836 --  guessing unknown values and fed into the costs function
837 -- ---------------------------------------------------------------------------
838
839 do_if_stmt discrim tag alt_code deflt c
840    = let
841        cond = hcat [ pprAmode discrim
842                    , ptext SLIT(" == ")
843                    , tcast
844                    , pprAmode (CLit tag)
845                    ]
846         -- to be absolutely sure that none of the 
847         -- conversion rules hit, e.g.,
848         --
849         --     minInt is different to (int)minInt
850         --
851         -- in C (when minInt is a number not a constant
852         --  expression which evaluates to it.)
853         -- 
854        tcast = case tag of
855                    MachInt _  -> ptext SLIT("(I_)")
856                    _          -> empty
857      in
858      ppr_if_stmt cond
859                  alt_code deflt
860                  (addrModeCosts discrim Rhs) c
861
862 ppr_if_stmt pp_pred then_part else_part discrim_costs c
863   = vcat [
864       hcat [text "if (", pp_pred, text ") {"],
865       nest 8 (pprAbsC then_part         (c + discrim_costs +
866                                         (Cost (0, 2, 0, 0, 0)) +
867                                         costs then_part)),
868       (case nonemptyAbsC else_part of Nothing -> empty; Just _ -> text "} else {"),
869       nest 8 (pprAbsC else_part  (c + discrim_costs +
870                                         (Cost (0, 1, 0, 0, 0)) +
871                                         costs else_part)),
872       char '}' ]
873     {- Total costs = inherited costs (before if) + costs for accessing discrim
874                      + costs for cond branch ( = (0, 1, 0, 0, 0) )
875                      + costs for that alternative
876     -}
877 \end{code}
878
879 Historical note: this used to be two separate cases -- one for `ccall'
880 and one for `casm'.  To get round a potential limitation to only 10
881 arguments, the numbering of arguments in @process_casm@ was beefed up a
882 bit. ADR
883
884 Some rough notes on generating code for @CCallOp@:
885
886 1) Evaluate all arguments and stuff them into registers. (done elsewhere)
887 2) Save any essential registers (heap, stack, etc).
888
889    ToDo: If stable pointers are in use, these must be saved in a place
890    where the runtime system can get at them so that the Stg world can
891    be restarted during the call.
892
893 3) Save any temporary registers that are currently in use.
894 4) Do the call, putting result into a local variable
895 5) Restore essential registers
896 6) Restore temporaries
897
898    (This happens after restoration of essential registers because we
899    might need the @Base@ register to access all the others correctly.)
900
901    Otherwise, copy local variable into result register.
902
903 8) If ccall (not casm), declare the function being called as extern so
904    that C knows if it returns anything other than an int.
905
906 \begin{pseudocode}
907 { ResultType _ccall_result;
908   basic_saves;
909   saves;
910   _ccall_result = f( args );
911   basic_restores;
912   restores;
913
914   return_reg = _ccall_result;
915 }
916 \end{pseudocode}
917
918 Amendment to the above: if we can GC, we have to:
919
920 * make sure we save all our registers away where the garbage collector
921   can get at them.
922 * be sure that there are no live registers or we're in trouble.
923   (This can cause problems if you try something foolish like passing
924    an array or a foreign obj to a _ccall_GC_ thing.)
925 * increment/decrement the @inCCallGC@ counter before/after the call so
926   that the runtime check that PerformGC is being used sensibly will work.
927
928 \begin{code}
929 pprFCall call@(CCall (CCallSpec target cconv safety)) uniq args results vol_regs
930   = vcat [
931       char '{',
932       declare_local_vars,   -- local var for *result*
933       vcat local_arg_decls,
934       pp_save_context,
935         process_casm local_vars pp_non_void_args call_str,
936       pp_restore_context,
937       assign_results,
938       char '}'
939     ]
940   where
941     (pp_saves, pp_restores) = ppr_vol_regs vol_regs
942
943     thread_macro_args = ppr_uniq_token <> comma <+> 
944                         text "rts" <> ppr (playThreadSafe safety)
945     ppr_uniq_token = text "tok_" <> ppr uniq
946     (pp_save_context, pp_restore_context)
947         | playSafe safety = ( text "{ I_" <+> ppr_uniq_token <> 
948                                 text "; SUSPEND_THREAD" <> parens thread_macro_args <> semi
949                             , text "RESUME_THREAD" <> parens thread_macro_args <> text ";}"
950                             )
951         | otherwise = ( pp_basic_saves $$ pp_saves,
952                         pp_basic_restores $$ pp_restores)
953
954     non_void_args = 
955         let nvas = init args
956         in ASSERT2 ( all non_void nvas, ppr call <+> hsep (map pprAmode args) )
957         nvas
958     -- the last argument will be the "I/O world" token (a VoidRep)
959     -- all others should be non-void
960
961     non_void_results =
962         let nvrs = grab_non_void_amodes results
963         in ASSERT (listLengthCmp nvrs 1 /= GT) nvrs
964     -- there will usually be two results: a (void) state which we
965     -- should ignore and a (possibly void) result.
966
967     (local_arg_decls, pp_non_void_args)
968       = unzip [ ppr_casm_arg a i | (a,i) <- non_void_args `zip` [1..] ]
969
970     (declare_local_vars, local_vars, assign_results)
971       = ppr_casm_results non_void_results
972
973     call_str = case target of
974                   CasmTarget str  -> _UNPK_ str
975                   StaticTarget fn -> mk_ccall_str (pprCLabelString fn) ccall_args
976                   DynamicTarget   -> mk_ccall_str dyn_fun              (tail ccall_args)
977
978     ccall_args = zipWith (\ _ i -> char '%' <> int i) non_void_args [0..]
979     dyn_fun    = parens (parens (ptext SLIT("_ccall_fun_ty") <> ppr uniq) <> text "%0")
980                                                  
981
982     -- Remainder only used for ccall
983     mk_ccall_str fun_name ccall_fun_args = showSDoc
984         (hcat [
985                 if null non_void_results
986                   then empty
987                   else text "%r = ",
988                 lparen, fun_name, lparen,
989                   hcat (punctuate comma ccall_fun_args),
990                 text "));"
991         ])
992 \end{code}
993
994 If the argument is a heap object, we need to reach inside and pull out
995 the bit the C world wants to see.  The only heap objects which can be
996 passed are @Array@s and @ByteArray@s.
997
998 \begin{code}
999 ppr_casm_arg :: CAddrMode -> Int -> (SDoc, SDoc)
1000     -- (a) decl and assignment, (b) local var to be used later
1001
1002 ppr_casm_arg amode a_num
1003   = let
1004         a_kind   = getAmodeRep amode
1005         pp_amode = pprAmode amode
1006         pp_kind  = pprPrimKind a_kind
1007
1008         local_var  = (<>) (ptext SLIT("_ccall_arg")) (int a_num)
1009
1010         (arg_type, pp_amode2)
1011           = case a_kind of
1012
1013               -- for array arguments, pass a pointer to the body of the array
1014               -- (PTRS_ARR_CTS skips over all the header nonsense)
1015               ArrayRep      -> (pp_kind,
1016                                 hcat [ptext SLIT("PTRS_ARR_CTS"),char '(', pp_amode, rparen])
1017               ByteArrayRep -> (pp_kind,
1018                                 hcat [ptext SLIT("BYTE_ARR_CTS"),char '(', pp_amode, rparen])
1019
1020               -- for ForeignObj, use FOREIGN_OBJ_DATA to fish out the contents.
1021               ForeignObjRep -> (pp_kind,
1022                                 hcat [ptext SLIT("ForeignObj_CLOSURE_DATA"),
1023                                       char '(', pp_amode, char ')'])
1024
1025               other         -> (pp_kind, pp_amode)
1026
1027         declare_local_var
1028           = hcat [ arg_type, space, local_var, equals, pp_amode2, semi ]
1029     in
1030     (declare_local_var, local_var)
1031 \end{code}
1032
1033 For l-values, the critical questions are:
1034
1035 1) Are there any results at all?
1036
1037    We only allow zero or one results.
1038
1039 \begin{code}
1040 ppr_casm_results
1041         :: [CAddrMode]  -- list of results (length <= 1)
1042         ->
1043         ( SDoc,         -- declaration of any local vars
1044           [SDoc],       -- list of result vars (same length as results)
1045           SDoc )        -- assignment (if any) of results in local var to registers
1046
1047 ppr_casm_results []
1048   = (empty, [], empty)  -- no results
1049
1050 ppr_casm_results [r]
1051   = let
1052         result_reg = ppr_amode r
1053         r_kind     = getAmodeRep r
1054
1055         local_var  = ptext SLIT("_ccall_result")
1056
1057         (result_type, assign_result)
1058           = (pprPrimKind r_kind,
1059              hcat [ result_reg, equals, local_var, semi ])
1060
1061         declare_local_var = hcat [ result_type, space, local_var, semi ]
1062     in
1063     (declare_local_var, [local_var], assign_result)
1064
1065 ppr_casm_results rs
1066   = panic "ppr_casm_results: ccall/casm with many results"
1067 \end{code}
1068
1069
1070 Note the sneaky way _the_ result is represented by a list so that we
1071 can complain if it's used twice.
1072
1073 ToDo: Any chance of giving line numbers when process-casm fails?
1074       Or maybe we should do a check _much earlier_ in compiler. ADR
1075
1076 \begin{code}
1077 process_casm :: [SDoc]          -- results (length <= 1)
1078              -> [SDoc]          -- arguments
1079              -> String          -- format string (with embedded %'s)
1080              -> SDoc            -- code being generated
1081
1082 process_casm results args string = process results args string
1083  where
1084   process []    _ "" = empty
1085   process (_:_) _ "" = error ("process_casm: non-void result not assigned while processing _casm_ \"" ++ 
1086                               string ++ 
1087                               "\"\n(Try changing result type to IO ()\n")
1088
1089   process ress args ('%':cs)
1090     = case cs of
1091         [] ->
1092             error ("process_casm: lonely % while processing _casm_ \"" ++ string ++ "\".\n")
1093
1094         ('%':css) ->
1095             char '%' <> process ress args css
1096
1097         ('r':css)  ->
1098           case ress of
1099             []  -> error ("process_casm: no result to match %r while processing _casm_ \"" ++ string ++ "\".\nTry deleting %r or changing result type from PrimIO ()\n")
1100             [r] -> r <> (process [] args css)
1101             _   -> panic ("process_casm: casm with many results while processing _casm_ \"" ++ string ++ "\".\n")
1102
1103         other ->
1104           let
1105                 read_int :: ReadS Int
1106                 read_int = reads
1107           in
1108           case (read_int other) of
1109             [(num,css)] ->
1110                   if num >= 0 && args `lengthExceeds` num
1111                   then parens (args !! num) <> process ress args css
1112                   else error ("process_casm: no such arg #:"++(show num)++" while processing \"" ++ string ++ "\".\n")
1113             _ -> error ("process_casm: not %<num> while processing _casm_ \"" ++ string ++ "\".\n")
1114
1115   process ress args (other_c:cs)
1116     = char other_c <> process ress args cs
1117 \end{code}
1118
1119 %************************************************************************
1120 %*                                                                      *
1121 \subsection[a2r-assignments]{Assignments}
1122 %*                                                                      *
1123 %************************************************************************
1124
1125 Printing assignments is a little tricky because of type coercion.
1126
1127 First of all, the kind of the thing being assigned can be gotten from
1128 the destination addressing mode.  (It should be the same as the kind
1129 of the source addressing mode.)  If the kind of the assignment is of
1130 @VoidRep@, then don't generate any code at all.
1131
1132 \begin{code}
1133 pprAssign :: PrimRep -> CAddrMode -> CAddrMode -> SDoc
1134
1135 pprAssign VoidRep dest src = empty
1136 \end{code}
1137
1138 Special treatment for floats and doubles, to avoid unwanted conversions.
1139
1140 \begin{code}
1141 pprAssign FloatRep dest@(CVal reg_rel _) src
1142   = hcat [ ptext SLIT("ASSIGN_FLT((W_*)"), parens (ppr_amode (CAddr reg_rel)), comma, pprAmode src, pp_paren_semi ]
1143
1144 pprAssign DoubleRep dest@(CVal reg_rel _) src
1145   = hcat [ ptext SLIT("ASSIGN_DBL((W_*)"), parens (ppr_amode (CAddr reg_rel)), comma, pprAmode src, pp_paren_semi ]
1146
1147 pprAssign Int64Rep dest@(CVal reg_rel _) src
1148   = hcat [ ptext SLIT("ASSIGN_Int64((W_*)"), parens (ppr_amode (CAddr reg_rel)), comma, pprAmode src, pp_paren_semi ]
1149 pprAssign Word64Rep dest@(CVal reg_rel _) src
1150   = hcat [ ptext SLIT("ASSIGN_Word64((W_*)"), parens (ppr_amode (CAddr reg_rel)), comma, pprAmode src, pp_paren_semi ]
1151 \end{code}
1152
1153 Lastly, the question is: will the C compiler think the types of the
1154 two sides of the assignment match?
1155
1156         We assume that the types will match if neither side is a
1157         @CVal@ addressing mode for any register which can point into
1158         the heap or stack.
1159
1160 Why?  Because the heap and stack are used to store miscellaneous
1161 things, whereas the temporaries, registers, etc., are only used for
1162 things of fixed type.
1163
1164 \begin{code}
1165 pprAssign kind (CReg (VanillaReg _ dest)) (CReg (VanillaReg _ src))
1166   = hcat [ pprVanillaReg dest, equals,
1167                 pprVanillaReg src, semi ]
1168
1169 pprAssign kind dest src
1170   | mixedTypeLocn dest
1171     -- Add in a cast to StgWord (a.k.a. W_) iff the destination is mixed
1172   = hcat [ ppr_amode dest, equals,
1173                 text "(W_)(",   -- Here is the cast
1174                 ppr_amode src, pp_paren_semi ]
1175
1176 pprAssign kind dest src
1177   | mixedPtrLocn dest && getAmodeRep src /= PtrRep
1178     -- Add in a cast to StgPtr (a.k.a. P_) iff the destination is mixed
1179   = hcat [ ppr_amode dest, equals,
1180                 text "(P_)(",   -- Here is the cast
1181                 ppr_amode src, pp_paren_semi ]
1182
1183 pprAssign ByteArrayRep dest src
1184   | mixedPtrLocn src
1185     -- Add in a cast iff the source is mixed
1186   = hcat [ ppr_amode dest, equals,
1187                 text "(StgByteArray)(", -- Here is the cast
1188                 ppr_amode src, pp_paren_semi ]
1189
1190 pprAssign kind other_dest src
1191   = hcat [ ppr_amode other_dest, equals,
1192                 pprAmode  src, semi ]
1193 \end{code}
1194
1195
1196 %************************************************************************
1197 %*                                                                      *
1198 \subsection[a2r-CAddrModes]{Addressing modes}
1199 %*                                                                      *
1200 %************************************************************************
1201
1202 @pprAmode@ is used to print r-values (which may need casts), whereas
1203 @ppr_amode@ is used for l-values {\em and} as a help function for
1204 @pprAmode@.
1205
1206 \begin{code}
1207 pprAmode, ppr_amode :: CAddrMode -> SDoc
1208 \end{code}
1209
1210 For reasons discussed above under assignments, @CVal@ modes need
1211 to be treated carefully.  First come special cases for floats and doubles,
1212 similar to those in @pprAssign@:
1213
1214 (NB: @PK_FLT@ and @PK_DBL@ require the {\em address} of the value in
1215 question.)
1216
1217 \begin{code}
1218 pprAmode (CVal reg_rel FloatRep)
1219   = hcat [ text "PK_FLT((W_*)", parens (ppr_amode (CAddr reg_rel)), rparen ]
1220 pprAmode (CVal reg_rel DoubleRep)
1221   = hcat [ text "PK_DBL((W_*)", parens (ppr_amode (CAddr reg_rel)), rparen ]
1222 pprAmode (CVal reg_rel Int64Rep)
1223   = hcat [ text "PK_Int64((W_*)", parens (ppr_amode (CAddr reg_rel)), rparen ]
1224 pprAmode (CVal reg_rel Word64Rep)
1225   = hcat [ text "PK_Word64((W_*)", parens (ppr_amode (CAddr reg_rel)), rparen ]
1226 \end{code}
1227
1228 Next comes the case where there is some other cast need, and the
1229 no-cast case:
1230
1231 \begin{code}
1232 pprAmode amode
1233   | mixedTypeLocn amode
1234   = parens (hcat [ pprPrimKind (getAmodeRep amode), ptext SLIT(")("),
1235                 ppr_amode amode ])
1236   | otherwise   -- No cast needed
1237   = ppr_amode amode
1238 \end{code}
1239
1240 When we have an indirection through a CIndex, we have to be careful to
1241 get the type casts right.  
1242
1243 this amode:
1244
1245         CVal (CIndex kind1 base offset) kind2
1246
1247 means (in C speak): 
1248         
1249         *(kind2 *)((kind1 *)base + offset)
1250
1251 That is, the indexing is done in units of kind1, but the resulting
1252 amode has kind2.
1253
1254 \begin{code}
1255 ppr_amode CBytesPerWord
1256   = text "(sizeof(void*))"
1257
1258 ppr_amode (CVal reg_rel@(CIndex _ _ _) kind)
1259   = case (pprRegRelative False{-no sign wanted-} reg_rel) of
1260         (pp_reg, Nothing)     -> panic "ppr_amode: CIndex"
1261         (pp_reg, Just offset) -> 
1262            hcat [ char '*', parens (pprPrimKind kind <> char '*'),
1263                   parens (pp_reg <> char '+' <> offset) ]
1264 \end{code}
1265
1266 Now the rest of the cases for ``workhorse'' @ppr_amode@:
1267
1268 \begin{code}
1269 ppr_amode (CVal reg_rel _)
1270   = case (pprRegRelative False{-no sign wanted-} reg_rel) of
1271         (pp_reg, Nothing)     -> (<>)  (char '*') pp_reg
1272         (pp_reg, Just offset) -> hcat [ pp_reg, brackets offset ]
1273
1274 ppr_amode (CAddr reg_rel)
1275   = case (pprRegRelative True{-sign wanted-} reg_rel) of
1276         (pp_reg, Nothing)     -> pp_reg
1277         (pp_reg, Just offset) -> (<>) pp_reg offset
1278
1279 ppr_amode (CReg magic_id) = pprMagicId magic_id
1280
1281 ppr_amode (CTemp uniq kind) = char '_' <> pprUnique uniq <> char '_'
1282
1283 ppr_amode (CLbl lbl kind) = pprCLabelAddr lbl 
1284
1285 ppr_amode (CCharLike ch)
1286   = hcat [ptext SLIT("CHARLIKE_CLOSURE"), char '(', pprAmode ch, rparen ]
1287 ppr_amode (CIntLike int)
1288   = hcat [ptext SLIT("INTLIKE_CLOSURE"), char '(', pprAmode int, rparen ]
1289
1290 ppr_amode (CLit lit) = pprBasicLit lit
1291
1292 ppr_amode (CJoinPoint _)
1293   = panic "ppr_amode: CJoinPoint"
1294
1295 ppr_amode (CMacroExpr pk macro as)
1296   = parens (ptext (cExprMacroText macro) <> 
1297             parens (hcat (punctuate comma (map pprAmode as))))
1298 \end{code}
1299
1300 \begin{code}
1301 cExprMacroText ENTRY_CODE               = SLIT("ENTRY_CODE")
1302 cExprMacroText ARG_TAG                  = SLIT("ARG_TAG")
1303 cExprMacroText GET_TAG                  = SLIT("GET_TAG")
1304 cExprMacroText UPD_FRAME_UPDATEE        = SLIT("UPD_FRAME_UPDATEE")
1305 cExprMacroText CCS_HDR                  = SLIT("CCS_HDR")
1306
1307 cStmtMacroText ARGS_CHK                 = SLIT("ARGS_CHK")
1308 cStmtMacroText ARGS_CHK_LOAD_NODE       = SLIT("ARGS_CHK_LOAD_NODE")
1309 cStmtMacroText UPD_CAF                  = SLIT("UPD_CAF")
1310 cStmtMacroText UPD_BH_UPDATABLE         = SLIT("UPD_BH_UPDATABLE")
1311 cStmtMacroText UPD_BH_SINGLE_ENTRY      = SLIT("UPD_BH_SINGLE_ENTRY")
1312 cStmtMacroText PUSH_UPD_FRAME           = SLIT("PUSH_UPD_FRAME")
1313 cStmtMacroText PUSH_SEQ_FRAME           = SLIT("PUSH_SEQ_FRAME")
1314 cStmtMacroText UPDATE_SU_FROM_UPD_FRAME = SLIT("UPDATE_SU_FROM_UPD_FRAME")
1315 cStmtMacroText SET_TAG                  = SLIT("SET_TAG")
1316 cStmtMacroText DATA_TO_TAGZH            = SLIT("dataToTagzh")
1317 cStmtMacroText REGISTER_FOREIGN_EXPORT  = SLIT("REGISTER_FOREIGN_EXPORT")
1318 cStmtMacroText REGISTER_IMPORT          = SLIT("REGISTER_IMPORT")
1319 cStmtMacroText REGISTER_DIMPORT         = SLIT("REGISTER_DIMPORT")
1320 cStmtMacroText GRAN_FETCH               = SLIT("GRAN_FETCH")
1321 cStmtMacroText GRAN_RESCHEDULE          = SLIT("GRAN_RESCHEDULE")
1322 cStmtMacroText GRAN_FETCH_AND_RESCHEDULE= SLIT("GRAN_FETCH_AND_RESCHEDULE")
1323 cStmtMacroText THREAD_CONTEXT_SWITCH    = SLIT("THREAD_CONTEXT_SWITCH")
1324 cStmtMacroText GRAN_YIELD               = SLIT("GRAN_YIELD")
1325
1326 cCheckMacroText HP_CHK_NP               = SLIT("HP_CHK_NP")
1327 cCheckMacroText STK_CHK_NP              = SLIT("STK_CHK_NP")
1328 cCheckMacroText HP_STK_CHK_NP           = SLIT("HP_STK_CHK_NP")
1329 cCheckMacroText HP_CHK_SEQ_NP           = SLIT("HP_CHK_SEQ_NP")
1330 cCheckMacroText HP_CHK                  = SLIT("HP_CHK")
1331 cCheckMacroText STK_CHK                 = SLIT("STK_CHK")
1332 cCheckMacroText HP_STK_CHK              = SLIT("HP_STK_CHK")
1333 cCheckMacroText HP_CHK_NOREGS           = SLIT("HP_CHK_NOREGS")
1334 cCheckMacroText HP_CHK_UNPT_R1          = SLIT("HP_CHK_UNPT_R1")
1335 cCheckMacroText HP_CHK_UNBX_R1          = SLIT("HP_CHK_UNBX_R1")
1336 cCheckMacroText HP_CHK_F1               = SLIT("HP_CHK_F1")
1337 cCheckMacroText HP_CHK_D1               = SLIT("HP_CHK_D1")
1338 cCheckMacroText HP_CHK_L1               = SLIT("HP_CHK_L1")
1339 cCheckMacroText HP_CHK_UT_ALT           = SLIT("HP_CHK_UT_ALT")
1340 cCheckMacroText HP_CHK_GEN              = SLIT("HP_CHK_GEN")
1341 \end{code}
1342
1343 \begin{code}
1344 \end{code}
1345
1346 %************************************************************************
1347 %*                                                                      *
1348 \subsection[ppr-liveness-masks]{Liveness Masks}
1349 %*                                                                      *
1350 %************************************************************************
1351
1352 \begin{code}
1353 pp_bitmap_switch :: [BitSet] -> SDoc -> SDoc -> SDoc
1354 pp_bitmap_switch ([   ]) small large = small
1355 pp_bitmap_switch ([_  ]) small large = small
1356 pp_bitmap_switch ([_,_]) small large = hcat
1357     [ptext SLIT("BITMAP_SWITCH64"), lparen, small, comma, large, rparen]
1358 pp_bitmap_switch (_    ) small large = large
1359
1360 pp_liveness_switch :: Liveness -> SDoc -> SDoc -> SDoc
1361 pp_liveness_switch (Liveness lbl mask) = pp_bitmap_switch mask
1362
1363 pp_bitset :: BitSet -> SDoc
1364 pp_bitset s
1365     | i < -1    = int (i + 1) <> text "-1"
1366     | otherwise = int i
1367     where i = intBS s
1368
1369 pp_bitmap :: [BitSet] -> SDoc
1370 pp_bitmap [] = int 0
1371 pp_bitmap ss = hcat (punctuate delayed_comma (bundle ss)) where
1372   delayed_comma         = hcat [space, ptext SLIT("COMMA"), space]
1373   bundle []         = []
1374   bundle [s]        = [hcat bitmap32]
1375      where bitmap32 = [ptext SLIT("BITMAP32"), lparen,
1376                        pp_bitset s, rparen]
1377   bundle (s1:s2:ss) = hcat bitmap64 : bundle ss
1378      where bitmap64 = [ptext SLIT("BITMAP64"), lparen,
1379                        pp_bitset s1, comma, pp_bitset s2, rparen]
1380
1381 pp_liveness :: Liveness -> SDoc
1382 pp_liveness (Liveness lbl mask)
1383  = pp_bitmap_switch mask (pp_bitmap mask) (char '&' <> pprCLabel lbl)
1384 \end{code}
1385
1386 %************************************************************************
1387 %*                                                                      *
1388 \subsection[a2r-MagicIds]{Magic ids}
1389 %*                                                                      *
1390 %************************************************************************
1391
1392 @pprRegRelative@ returns a pair of the @Doc@ for the register
1393 (some casting may be required), and a @Maybe Doc@ for the offset
1394 (zero offset gives a @Nothing@).
1395
1396 \begin{code}
1397 addPlusSign :: Bool -> SDoc -> SDoc
1398 addPlusSign False p = p
1399 addPlusSign True  p = (<>) (char '+') p
1400
1401 pprSignedInt :: Bool -> Int -> Maybe SDoc       -- Nothing => 0
1402 pprSignedInt sign_wanted n
1403  = if n == 0 then Nothing else
1404    if n > 0  then Just (addPlusSign sign_wanted (int n))
1405    else           Just (int n)
1406
1407 pprRegRelative :: Bool          -- True <=> Print leading plus sign (if +ve)
1408                -> RegRelative
1409                -> (SDoc, Maybe SDoc)
1410
1411 pprRegRelative sign_wanted (SpRel off)
1412   = (pprMagicId Sp, pprSignedInt sign_wanted (I# off))
1413
1414 pprRegRelative sign_wanted r@(HpRel o)
1415   = let pp_Hp    = pprMagicId Hp; off = I# o
1416     in
1417     if off == 0 then
1418         (pp_Hp, Nothing)
1419     else
1420         (pp_Hp, Just ((<>) (char '-') (int off)))
1421
1422 pprRegRelative sign_wanted (NodeRel o)
1423   = let pp_Node = pprMagicId node; off = I# o
1424     in
1425     if off == 0 then
1426         (pp_Node, Nothing)
1427     else
1428         (pp_Node, Just (addPlusSign sign_wanted (int off)))
1429
1430 pprRegRelative sign_wanted (CIndex base offset kind)
1431   = ( hcat [text "((", pprPrimKind kind, text " *)(", ppr_amode base, text "))"]
1432     , Just (hcat [if sign_wanted then char '+' else empty,
1433             text "(I_)(", ppr_amode offset, ptext SLIT(")")])
1434     )
1435 \end{code}
1436
1437 @pprMagicId@ just prints the register name.  @VanillaReg@ registers are
1438 represented by a discriminated union (@StgUnion@), so we use the @PrimRep@
1439 to select the union tag.
1440
1441 \begin{code}
1442 pprMagicId :: MagicId -> SDoc
1443
1444 pprMagicId BaseReg                  = ptext SLIT("BaseReg")
1445 pprMagicId (VanillaReg pk n)
1446                                     = hcat [ pprVanillaReg n, char '.',
1447                                                   pprUnionTag pk ]
1448 pprMagicId (FloatReg  n)            = ptext SLIT("F") <> int (I# n)
1449 pprMagicId (DoubleReg n)            = ptext SLIT("D") <> int (I# n)
1450 pprMagicId (LongReg _ n)            = ptext SLIT("L") <> int (I# n)
1451 pprMagicId Sp                       = ptext SLIT("Sp")
1452 pprMagicId Su                       = ptext SLIT("Su")
1453 pprMagicId SpLim                    = ptext SLIT("SpLim")
1454 pprMagicId Hp                       = ptext SLIT("Hp")
1455 pprMagicId HpLim                    = ptext SLIT("HpLim")
1456 pprMagicId CurCostCentre            = ptext SLIT("CCCS")
1457 pprMagicId VoidReg                  = panic "pprMagicId:VoidReg!"
1458
1459 pprVanillaReg :: Int# -> SDoc
1460 pprVanillaReg n = char 'R' <> int (I# n)
1461
1462 pprUnionTag :: PrimRep -> SDoc
1463
1464 pprUnionTag PtrRep              = char 'p'
1465 pprUnionTag CodePtrRep          = ptext SLIT("fp")
1466 pprUnionTag DataPtrRep          = char 'd'
1467 pprUnionTag RetRep              = char 'p'
1468 pprUnionTag CostCentreRep       = panic "pprUnionTag:CostCentre?"
1469
1470 pprUnionTag CharRep             = char 'c'
1471 pprUnionTag Int8Rep             = ptext SLIT("i8")
1472 pprUnionTag IntRep              = char 'i'
1473 pprUnionTag WordRep             = char 'w'
1474 pprUnionTag Int32Rep            = char 'i'
1475 pprUnionTag Word32Rep           = char 'w'
1476 pprUnionTag AddrRep             = char 'a'
1477 pprUnionTag FloatRep            = char 'f'
1478 pprUnionTag DoubleRep           = panic "pprUnionTag:Double?"
1479
1480 pprUnionTag StablePtrRep        = char 'p'
1481 pprUnionTag StableNameRep       = char 'p'
1482 pprUnionTag WeakPtrRep          = char 'p'
1483 pprUnionTag ForeignObjRep       = char 'p'
1484 pprUnionTag PrimPtrRep          = char 'p'
1485
1486 pprUnionTag ThreadIdRep         = char 't'
1487
1488 pprUnionTag ArrayRep            = char 'p'
1489 pprUnionTag ByteArrayRep        = char 'b'
1490 pprUnionTag BCORep              = char 'p'
1491
1492 pprUnionTag _                   = panic "pprUnionTag:Odd kind"
1493 \end{code}
1494
1495
1496 Find and print local and external declarations for a list of
1497 Abstract~C statements.
1498 \begin{code}
1499 pprTempAndExternDecls :: AbstractC -> (SDoc{-temps-}, SDoc{-externs-})
1500 pprTempAndExternDecls AbsCNop = (empty, empty)
1501
1502 pprTempAndExternDecls (AbsCStmts stmt1 stmt2)
1503   = initTE (ppr_decls_AbsC stmt1        `thenTE` \ (t_p1, e_p1) ->
1504             ppr_decls_AbsC stmt2        `thenTE` \ (t_p2, e_p2) ->
1505             case (catMaybes [t_p1, t_p2])        of { real_temps ->
1506             case (catMaybes [e_p1, e_p2])        of { real_exts ->
1507             returnTE (vcat real_temps, vcat real_exts) }}
1508            )
1509
1510 pprTempAndExternDecls other_stmt
1511   = initTE (ppr_decls_AbsC other_stmt `thenTE` \ (maybe_t, maybe_e) ->
1512             returnTE (
1513                 case maybe_t of
1514                   Nothing -> empty
1515                   Just pp -> pp,
1516
1517                 case maybe_e of
1518                   Nothing -> empty
1519                   Just pp -> pp )
1520            )
1521
1522 pprBasicLit :: Literal -> SDoc
1523 pprPrimKind :: PrimRep -> SDoc
1524
1525 pprBasicLit  lit = ppr lit
1526 pprPrimKind  k   = ppr k
1527 \end{code}
1528
1529
1530 %************************************************************************
1531 %*                                                                      *
1532 \subsection[a2r-monad]{Monadery}
1533 %*                                                                      *
1534 %************************************************************************
1535
1536 We need some monadery to keep track of temps and externs we have already
1537 printed.  This info must be threaded right through the Abstract~C, so
1538 it's most convenient to hide it in this monad.
1539
1540 WDP 95/02: Switched from \tr{([Unique], [CLabel])} to
1541 \tr{(UniqSet, CLabelSet)}.  Allegedly for efficiency.
1542
1543 \begin{code}
1544 type CLabelSet = FiniteMap CLabel (){-any type will do-}
1545 emptyCLabelSet = emptyFM
1546 x `elementOfCLabelSet` labs
1547   = case (lookupFM labs x) of { Just _ -> True; Nothing -> False }
1548
1549 addToCLabelSet set x = addToFM set x ()
1550
1551 type TEenv = (UniqSet Unique, CLabelSet)
1552
1553 type TeM result =  TEenv -> (TEenv, result)
1554
1555 initTE :: TeM a -> a
1556 initTE sa
1557   = case sa (emptyUniqSet, emptyCLabelSet) of { (_, result) ->
1558     result }
1559
1560 {-# INLINE thenTE #-}
1561 {-# INLINE returnTE #-}
1562
1563 thenTE :: TeM a -> (a -> TeM b) -> TeM b
1564 thenTE a b u
1565   = case a u        of { (u_1, result_of_a) ->
1566     b result_of_a u_1 }
1567
1568 mapTE :: (a -> TeM b) -> [a] -> TeM [b]
1569 mapTE f []     = returnTE []
1570 mapTE f (x:xs)
1571   = f x         `thenTE` \ r  ->
1572     mapTE f xs  `thenTE` \ rs ->
1573     returnTE (r : rs)
1574
1575 returnTE :: a -> TeM a
1576 returnTE result env = (env, result)
1577
1578 -- these next two check whether the thing is already
1579 -- recorded, and THEN THEY RECORD IT
1580 -- (subsequent calls will return False for the same uniq/label)
1581
1582 tempSeenTE :: Unique -> TeM Bool
1583 tempSeenTE uniq env@(seen_uniqs, seen_labels)
1584   = if (uniq `elementOfUniqSet` seen_uniqs)
1585     then (env, True)
1586     else ((addOneToUniqSet seen_uniqs uniq,
1587           seen_labels),
1588           False)
1589
1590 labelSeenTE :: CLabel -> TeM Bool
1591 labelSeenTE lbl env@(seen_uniqs, seen_labels)
1592   = if (lbl `elementOfCLabelSet` seen_labels)
1593     then (env, True)
1594     else ((seen_uniqs,
1595           addToCLabelSet seen_labels lbl),
1596           False)
1597 \end{code}
1598
1599 \begin{code}
1600 pprTempDecl :: Unique -> PrimRep -> SDoc
1601 pprTempDecl uniq kind
1602   = hcat [ pprPrimKind kind, space, char '_', pprUnique uniq, ptext SLIT("_;") ]
1603
1604 pprExternDecl :: Bool -> CLabel -> SDoc
1605 pprExternDecl in_srt clabel
1606   | not (needsCDecl clabel) = empty -- do not print anything for "known external" things
1607   | otherwise               = 
1608         hcat [ ppLocalnessMacro (not in_srt) clabel, 
1609                lparen, dyn_wrapper (pprCLabel clabel), pp_paren_semi ]
1610  where
1611   dyn_wrapper d
1612     | in_srt && labelDynamic clabel = text "DLL_IMPORT_DATA_VAR" <> parens d
1613     | otherwise                     = d
1614
1615 \end{code}
1616
1617 \begin{code}
1618 ppr_decls_AbsC :: AbstractC -> TeM (Maybe SDoc{-temps-}, Maybe SDoc{-externs-})
1619
1620 ppr_decls_AbsC AbsCNop          = returnTE (Nothing, Nothing)
1621
1622 ppr_decls_AbsC (AbsCStmts stmts_1 stmts_2)
1623   = ppr_decls_AbsC stmts_1  `thenTE` \ p1 ->
1624     ppr_decls_AbsC stmts_2  `thenTE` \ p2 ->
1625     returnTE (maybe_vcat [p1, p2])
1626
1627 ppr_decls_AbsC (CSplitMarker) = returnTE (Nothing, Nothing)
1628
1629 ppr_decls_AbsC (CAssign dest source)
1630   = ppr_decls_Amode dest    `thenTE` \ p1 ->
1631     ppr_decls_Amode source  `thenTE` \ p2 ->
1632     returnTE (maybe_vcat [p1, p2])
1633
1634 ppr_decls_AbsC (CJump target) = ppr_decls_Amode target
1635
1636 ppr_decls_AbsC (CFallThrough target) = ppr_decls_Amode target
1637
1638 ppr_decls_AbsC (CReturn target _) = ppr_decls_Amode target
1639
1640 ppr_decls_AbsC (CSwitch discrim alts deflt)
1641   = ppr_decls_Amode discrim     `thenTE` \ pdisc ->
1642     mapTE ppr_alt_stuff alts    `thenTE` \ palts  ->
1643     ppr_decls_AbsC deflt        `thenTE` \ pdeflt ->
1644     returnTE (maybe_vcat (pdisc:pdeflt:palts))
1645   where
1646     ppr_alt_stuff (_, absC) = ppr_decls_AbsC absC
1647
1648 ppr_decls_AbsC (CCodeBlock lbl absC)
1649   = ppr_decls_AbsC absC
1650
1651 ppr_decls_AbsC (CInitHdr cl_info reg_rel cost_centre _)
1652         -- ToDo: strictly speaking, should chk "cost_centre" amode
1653   = labelSeenTE info_lbl     `thenTE` \  label_seen ->
1654     returnTE (Nothing,
1655               if label_seen then
1656                   Nothing
1657               else
1658                   Just (pprExternDecl False{-not in an SRT decl-} info_lbl))
1659   where
1660     info_lbl = infoTableLabelFromCI cl_info
1661
1662 ppr_decls_AbsC (CMachOpStmt res _ args _) = ppr_decls_Amodes (res : args)
1663 ppr_decls_AbsC (COpStmt results _ args _) = ppr_decls_Amodes (results ++ args)
1664
1665 ppr_decls_AbsC (CSimultaneous abc)        = ppr_decls_AbsC abc
1666
1667 ppr_decls_AbsC (CSequential abcs) 
1668   = mapTE ppr_decls_AbsC abcs   `thenTE` \ t_and_e_s ->
1669     returnTE (maybe_vcat t_and_e_s)
1670
1671 ppr_decls_AbsC (CCheck              _ amodes code) = 
1672      ppr_decls_Amodes amodes `thenTE` \p1 ->
1673      ppr_decls_AbsC code     `thenTE` \p2 ->
1674      returnTE (maybe_vcat [p1,p2])
1675
1676 ppr_decls_AbsC (CMacroStmt          _ amodes)   = ppr_decls_Amodes amodes
1677
1678 ppr_decls_AbsC (CCallProfCtrMacro   _ amodes)   = ppr_decls_Amodes [] -- *****!!!
1679   -- you get some nasty re-decls of stdio.h if you compile
1680   -- the prelude while looking inside those amodes;
1681   -- no real reason to, anyway.
1682 ppr_decls_AbsC (CCallProfCCMacro    _ amodes)   = ppr_decls_Amodes amodes
1683
1684 ppr_decls_AbsC (CStaticClosure closure_info cost_centre amodes)
1685         -- ToDo: strictly speaking, should chk "cost_centre" amode
1686   = ppr_decls_Amodes amodes
1687
1688 ppr_decls_AbsC (CClosureInfoAndCode cl_info slow maybe_fast _)
1689   = ppr_decls_Amodes [entry_lbl]                `thenTE` \ p1 ->
1690     ppr_decls_AbsC slow                         `thenTE` \ p2 ->
1691     (case maybe_fast of
1692         Nothing   -> returnTE (Nothing, Nothing)
1693         Just fast -> ppr_decls_AbsC fast)       `thenTE` \ p3 ->
1694     returnTE (maybe_vcat [p1, p2, p3])
1695   where
1696     entry_lbl = CLbl slow_lbl CodePtrRep
1697     slow_lbl    = case (nonemptyAbsC slow) of
1698                     Nothing -> mkErrorStdEntryLabel
1699                     Just _  -> entryLabelFromCI cl_info
1700
1701 ppr_decls_AbsC (CSRT _ closure_lbls)
1702   = mapTE labelSeenTE closure_lbls              `thenTE` \ seen ->
1703     returnTE (Nothing, 
1704               if and seen then Nothing
1705                 else Just (vcat [ pprExternDecl True{-in SRT decl-} l
1706                                 | (l,False) <- zip closure_lbls seen ]))
1707
1708 ppr_decls_AbsC (CRetDirect     _ code _ _)   = ppr_decls_AbsC code
1709 ppr_decls_AbsC (CRetVector _ amodes _ _)     = ppr_decls_Amodes amodes
1710 ppr_decls_AbsC (CModuleInitBlock _ code)     = ppr_decls_AbsC code
1711
1712 ppr_decls_AbsC (_) = returnTE (Nothing, Nothing)
1713 \end{code}
1714
1715 \begin{code}
1716 ppr_decls_Amode :: CAddrMode -> TeM (Maybe SDoc, Maybe SDoc)
1717 ppr_decls_Amode (CVal  (CIndex base offset _) _) = ppr_decls_Amodes [base,offset]
1718 ppr_decls_Amode (CAddr (CIndex base offset _))   = ppr_decls_Amodes [base,offset]
1719 ppr_decls_Amode (CVal _ _)      = returnTE (Nothing, Nothing)
1720 ppr_decls_Amode (CAddr _)       = returnTE (Nothing, Nothing)
1721 ppr_decls_Amode (CReg _)        = returnTE (Nothing, Nothing)
1722 ppr_decls_Amode (CLit _)        = returnTE (Nothing, Nothing)
1723
1724 -- CIntLike must be a literal -- no decls
1725 ppr_decls_Amode (CIntLike int)  = returnTE (Nothing, Nothing)
1726
1727 -- CCharLike too
1728 ppr_decls_Amode (CCharLike char) = returnTE (Nothing, Nothing)
1729
1730 -- now, the only place where we actually print temps/externs...
1731 ppr_decls_Amode (CTemp uniq kind)
1732   = case kind of
1733       VoidRep -> returnTE (Nothing, Nothing)
1734       other ->
1735         tempSeenTE uniq `thenTE` \ temp_seen ->
1736         returnTE
1737           (if temp_seen then Nothing else Just (pprTempDecl uniq kind), Nothing)
1738
1739 ppr_decls_Amode (CLbl lbl VoidRep)
1740   = returnTE (Nothing, Nothing)
1741
1742 ppr_decls_Amode (CLbl lbl kind)
1743   = labelSeenTE lbl `thenTE` \ label_seen ->
1744     returnTE (Nothing,
1745               if label_seen then Nothing else Just (pprExternDecl False{-not in an SRT decl-} lbl))
1746
1747 ppr_decls_Amode (CMacroExpr _ _ amodes)
1748   = ppr_decls_Amodes amodes
1749
1750 ppr_decls_Amode other = returnTE (Nothing, Nothing)
1751
1752
1753 maybe_vcat :: [(Maybe SDoc, Maybe SDoc)] -> (Maybe SDoc, Maybe SDoc)
1754 maybe_vcat ps
1755   = case (unzip ps)     of { (ts, es) ->
1756     case (catMaybes ts) of { real_ts  ->
1757     case (catMaybes es) of { real_es  ->
1758     (if (null real_ts) then Nothing else Just (vcat real_ts),
1759      if (null real_es) then Nothing else Just (vcat real_es))
1760     } } }
1761 \end{code}
1762
1763 \begin{code}
1764 ppr_decls_Amodes :: [CAddrMode] -> TeM (Maybe SDoc, Maybe SDoc)
1765 ppr_decls_Amodes amodes
1766   = mapTE ppr_decls_Amode amodes `thenTE` \ ps ->
1767     returnTE ( maybe_vcat ps )
1768 \end{code}
1769
1770 Print out a C Label where you want the *address* of the label, not the
1771 object it refers to.  The distinction is important when the label may
1772 refer to a C structure (info tables and closures, for instance).
1773
1774 When just generating a declaration for the label, use pprCLabel.
1775
1776 \begin{code}
1777 pprCLabelAddr :: CLabel -> SDoc
1778 pprCLabelAddr clabel =
1779   case labelType clabel of
1780      InfoTblType -> addr_of_label
1781      ClosureType -> addr_of_label
1782      VecTblType  -> addr_of_label
1783      _           -> pp_label
1784   where
1785     addr_of_label = ptext SLIT("(P_)&") <> pp_label
1786     pp_label = pprCLabel clabel
1787
1788 \end{code}
1789
1790 -----------------------------------------------------------------------------
1791 Initialising static objects with floating-point numbers.  We can't
1792 just emit the floating point number, because C will cast it to an int
1793 by rounding it.  We want the actual bit-representation of the float.
1794
1795 This is a hack to turn the floating point numbers into ints that we
1796 can safely initialise to static locations.
1797
1798 \begin{code}
1799 big_doubles = (getPrimRepSize DoubleRep) /= 1
1800
1801 -- floatss are always 1 word
1802 floatToWord :: CAddrMode -> CAddrMode
1803 floatToWord (CLit (MachFloat r))
1804   = runST (do
1805         arr <- newFloatArray ((0::Int),0)
1806         writeFloatArray arr 0 (fromRational r)
1807         i <- readIntArray arr 0
1808         return (CLit (MachInt (toInteger i)))
1809     )
1810
1811 doubleToWords :: CAddrMode -> [CAddrMode]
1812 doubleToWords (CLit (MachDouble r))
1813   | big_doubles                         -- doubles are 2 words
1814   = runST (do
1815         arr <- newDoubleArray ((0::Int),1)
1816         writeDoubleArray arr 0 (fromRational r)
1817         i1 <- readIntArray arr 0
1818         i2 <- readIntArray arr 1
1819         return [ CLit (MachInt (toInteger i1))
1820                , CLit (MachInt (toInteger i2))
1821                ]
1822     )
1823   | otherwise                           -- doubles are 1 word
1824   = runST (do
1825         arr <- newDoubleArray ((0::Int),0)
1826         writeDoubleArray arr 0 (fromRational r)
1827         i <- readIntArray arr 0
1828         return [ CLit (MachInt (toInteger i)) ]
1829     )
1830 \end{code}