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