[project @ 2004-10-26 17:48:39 by ross]
[ghc-hetmet.git] / ghc / compiler / cmm / PprC.hs
1 -----------------------------------------------------------------------------
2 --
3 -- Pretty-printing of Cmm as C, suitable for feeding gcc
4 --
5 -- (c) The University of Glasgow 2004
6 --
7 -----------------------------------------------------------------------------
8
9 --
10 -- Print Cmm as real C, for -fvia-C
11 --
12 -- This is simpler than the old PprAbsC, because Cmm is "macro-expanded"
13 -- relative to the old AbstractC, and many oddities/decorations have
14 -- disappeared from the data type.
15 --
16
17 -- ToDo: save/restore volatile registers around calls.
18
19 module PprC (
20         writeCs,
21         pprStringInCStyle 
22   ) where
23
24 #include "HsVersions.h"
25
26 -- Cmm stuff
27 import Cmm
28 import CLabel
29 import MachOp
30 import ForeignCall
31
32 -- Utils
33 import Unique           ( getUnique )
34 import UniqSet
35 import FiniteMap
36 import UniqFM           ( eltsUFM )
37 import FastString
38 import Outputable
39 import Constants
40 import CmdLineOpts      ( opt_EnsureSplittableC )
41
42 -- The rest
43 import Data.List        ( intersperse, groupBy )
44 import Data.Bits        ( shiftR )
45 import Char             ( ord, chr )
46 import IO               ( Handle )
47 import DATA_BITS
48
49 #ifdef DEBUG
50 import PprCmm           () -- instances only
51 -- import Debug.Trace
52 #endif
53
54 #if __GLASGOW_HASKELL__ >= 504
55 import Data.Array.ST
56 #endif
57 import MONAD_ST
58
59 -- --------------------------------------------------------------------------
60 -- Top level
61
62 pprCs :: [Cmm] -> SDoc
63 pprCs cmms = pprCode CStyle (vcat $ map (\c -> split_marker $$ pprC c) cmms)
64
65 writeCs :: Handle -> [Cmm] -> IO ()
66 writeCs handle cmms = printForUser handle alwaysQualify (pprCs cmms)
67                         -- ToDo: should be printForC
68
69 split_marker
70   | opt_EnsureSplittableC = ptext SLIT("__STG_SPLIT_MARKER")
71   | otherwise             = empty
72
73 -- --------------------------------------------------------------------------
74 -- Now do some real work
75 --
76 -- for fun, we could call cmmToCmm over the tops...
77 --
78
79 pprC :: Cmm -> SDoc
80 pprC (Cmm tops) = vcat $ intersperse (text "") $ map pprTop tops
81
82 --
83 -- top level procs
84 -- 
85 pprTop :: CmmTop -> SDoc
86 pprTop (CmmProc info clbl _params blocks) =
87     (if not (null info)
88         then pprDataExterns info $$
89              pprWordArray (entryLblToInfoLbl clbl) info
90         else empty) $$
91     (case blocks of
92         [] -> empty
93          -- the first block doesn't get a label:
94         (BasicBlock _ stmts : rest) -> vcat [
95            text "",
96            extern_decls,
97            (if (externallyVisibleCLabel clbl)
98                     then mkFN_ else mkIF_) (pprCLabel clbl) <+> lbrace,
99            nest 8 temp_decls,
100            nest 8 mkFB_,
101            nest 8 (vcat (map pprStmt stmts)) $$
102               vcat (map pprBBlock rest),
103            nest 8 mkFE_,
104            rbrace ]
105     )
106   where
107         (temp_decls, extern_decls) = pprTempAndExternDecls blocks 
108
109
110 -- Chunks of static data.
111
112 -- We only handle (a) arrays of word-sized things and (b) strings.
113
114 pprTop (CmmData _section _ds@[CmmDataLabel lbl, CmmString str]) = 
115   hcat [
116     pprLocalness lbl, ptext SLIT("char "), pprCLabel lbl,
117     ptext SLIT("[] = "), pprStringInCStyle str, semi
118   ]
119
120 pprTop (CmmData _section _ds@[CmmDataLabel lbl, CmmUninitialised size]) = 
121   hcat [
122     pprLocalness lbl, ptext SLIT("char "), pprCLabel lbl,
123     brackets (int size), semi
124   ]
125
126 pprTop top@(CmmData _section (CmmDataLabel lbl : lits)) = 
127   pprDataExterns lits $$
128   pprWordArray lbl lits  
129
130 -- these shouldn't appear?
131 pprTop (CmmData _ _) = panic "PprC.pprTop: can't handle this data"
132
133
134 -- --------------------------------------------------------------------------
135 -- BasicBlocks are self-contained entities: they always end in a jump.
136 --
137 -- Like nativeGen/AsmCodeGen, we could probably reorder blocks to turn
138 -- as many jumps as possible into fall throughs.
139 --
140
141 pprBBlock :: CmmBasicBlock -> SDoc
142 pprBBlock (BasicBlock lbl stmts) = 
143     if null stmts then
144         pprTrace "pprC.pprBBlock: curious empty code block for" 
145                         (pprBlockId lbl) empty
146     else 
147         nest 4 (pprBlockId lbl <> colon) $$
148         nest 8 (vcat (map pprStmt stmts))
149
150 -- --------------------------------------------------------------------------
151 -- Info tables. Just arrays of words. 
152 -- See codeGen/ClosureInfo, and nativeGen/PprMach
153
154 pprWordArray :: CLabel -> [CmmStatic] -> SDoc
155 pprWordArray lbl ds
156   = hcat [ pprLocalness lbl, ptext SLIT("StgWord")
157          , space, pprCLabel lbl, ptext SLIT("[] = {") ] 
158     $$ nest 8 (commafy (pprStatics ds))
159     $$ ptext SLIT("};")
160
161 --
162 -- has to be static, if it isn't globally visible
163 --
164 pprLocalness :: CLabel -> SDoc
165 pprLocalness lbl | not $ externallyVisibleCLabel lbl = ptext SLIT("static ")
166                  | otherwise = empty
167
168 -- --------------------------------------------------------------------------
169 -- Statements.
170 --
171
172 pprStmt :: CmmStmt -> SDoc
173
174 pprStmt stmt = case stmt of
175     CmmNop       -> empty
176     CmmComment s -> (hang (ptext SLIT("/*")) 3 (ftext s)) $$ ptext SLIT("*/")
177
178     CmmAssign dest src -> pprAssign dest src
179
180     CmmStore  dest src
181         | rep == I64
182         -> ptext SLIT("ASSIGN_Word64") <> 
183                 parens (mkP_ <> pprExpr1 dest <> comma <> pprExpr src) <> semi
184
185         | otherwise
186         -> hsep [ pprExpr (CmmLoad dest rep), equals, pprExpr src <> semi ]
187         where
188           rep = cmmExprRep src
189
190     CmmCall (CmmForeignCall fn cconv) results args volatile -> 
191         -- Controversial: leave this out for now.
192         -- pprUndef fn $$
193
194         pprCall ppr_fn cconv results args volatile
195         where
196         ppr_fn = case fn of
197                    CmmLit (CmmLabel lbl) -> pprCLabel lbl
198                    _other -> parens (cCast (pprCFunType cconv results args) fn)
199                         -- for a dynamic call, cast the expression to
200                         -- a function of the right type (we hope).
201
202         -- we #undef a function before calling it: the FFI is supposed to be
203         -- an interface specifically to C, not to C+CPP.  For one thing, this
204         -- makes the via-C route more compatible with the NCG.  If macros
205         -- are being used for optimisation, then inline functions are probably
206         -- better anyway.
207         pprUndef (CmmLit (CmmLabel lbl)) = 
208            ptext SLIT("#undef") <+> pprCLabel lbl
209         pprUndef _ = empty
210
211     CmmCall (CmmPrim op) results args volatile -> 
212         pprCall ppr_fn CCallConv results args volatile
213         where
214         ppr_fn = pprCallishMachOp_for_C op
215
216     CmmBranch ident          -> pprBranch ident
217     CmmCondBranch expr ident -> pprCondBranch expr ident
218     CmmJump lbl _params      -> mkJMP_(pprExpr lbl) <> semi
219     CmmSwitch arg ids        -> pprSwitch arg ids
220
221 pprCFunType :: CCallConv -> [(CmmReg,MachHint)] -> [(CmmExpr,MachHint)] -> SDoc
222 pprCFunType cconv ress args
223   = hcat [
224         res_type ress,
225         parens (text (ccallConvAttribute cconv) <>  char '*'),
226         parens (commafy (map arg_type args))
227    ]
228   where
229         res_type [] = ptext SLIT("void")
230         res_type [(one,hint)] = machRepHintCType (cmmRegRep one) hint
231
232         arg_type (expr,hint) = machRepHintCType (cmmExprRep expr) hint
233
234 -- ---------------------------------------------------------------------
235 -- unconditional branches
236 pprBranch :: BlockId -> SDoc
237 pprBranch ident = ptext SLIT("goto") <+> pprBlockId ident <> semi
238
239
240 -- ---------------------------------------------------------------------
241 -- conditional branches to local labels
242 pprCondBranch :: CmmExpr -> BlockId -> SDoc
243 pprCondBranch expr ident 
244         = hsep [ ptext SLIT("if") , parens(pprExpr expr) ,
245                         ptext SLIT("goto") , (pprBlockId ident) <> semi ]
246
247
248 -- ---------------------------------------------------------------------
249 -- a local table branch
250 --
251 -- we find the fall-through cases
252 --
253 -- N.B. we remove Nothing's from the list of branches, as they are
254 -- 'undefined'. However, they may be defined one day, so we better
255 -- document this behaviour.
256 --
257 pprSwitch :: CmmExpr -> [ Maybe BlockId ] -> SDoc
258 pprSwitch e maybe_ids 
259   = let pairs  = [ (ix, ident) | (ix,Just ident) <- zip [0..] maybe_ids ]
260         pairs2 = [ (map fst as, snd (head as)) | as <- groupBy sndEq pairs ]
261     in 
262         (hang (ptext SLIT("switch") <+> parens ( pprExpr e ) <+> lbrace)
263                 4 (vcat ( map caseify pairs2 )))
264         $$ rbrace
265
266   where
267     sndEq (_,x) (_,y) = x == y
268
269     -- fall through case
270     caseify (ix:ixs, ident) = vcat (map do_fallthrough ixs) $$ final_branch ix
271         where 
272         do_fallthrough ix =
273                  hsep [ ptext SLIT("case") , pprHexVal ix <> colon ,
274                         ptext SLIT("/* fall through */") ]
275
276         final_branch ix = 
277                 hsep [ ptext SLIT("case") , pprHexVal ix <> colon ,
278                        ptext SLIT("goto") , (pprBlockId ident) <> semi ]
279
280 -- ---------------------------------------------------------------------
281 -- Expressions.
282 --
283
284 -- C Types: the invariant is that the C expression generated by
285 --
286 --      pprExpr e
287 --
288 -- has a type in C which is also given by
289 --
290 --      machRepCType (cmmExprRep e)
291 --
292 -- (similar invariants apply to the rest of the pretty printer).
293
294 pprExpr :: CmmExpr -> SDoc
295 pprExpr e = case e of
296     CmmLit lit -> pprLit lit
297
298     CmmLoad e I64
299         -> ptext SLIT("PK_Word64") <> parens (mkP_ <> pprExpr1 e)
300
301     CmmLoad (CmmReg r) rep 
302         | isPtrReg r && rep == wordRep
303         -> char '*' <> pprAsPtrReg r
304
305     CmmLoad (CmmRegOff r 0) rep 
306         | isPtrReg r && rep == wordRep
307         -> char '*' <> pprAsPtrReg r
308
309     CmmLoad (CmmRegOff r off) rep
310         | isPtrReg r && rep == wordRep 
311         -- ToDo: check that the offset is a word multiple?
312         -> pprAsPtrReg r <> brackets (ppr (off `shiftR` wordShift))
313
314     CmmLoad expr rep ->
315         -- the general case:
316         char '*' <> parens (cCast (machRepPtrCType rep) expr)
317
318     CmmReg reg      -> pprCastReg reg
319     CmmRegOff reg 0 -> pprCastReg reg
320
321     CmmRegOff reg i
322         | i >  0    -> pprRegOff (char '+') i
323         | otherwise -> pprRegOff (char '-') (-i)
324       where
325         pprRegOff op i' = pprCastReg reg <> op <> int i'
326
327     CmmMachOp mop args -> pprMachOpApp mop args
328
329 pprExpr1 :: CmmExpr -> SDoc
330 pprExpr1 (CmmLit lit)     = pprLit1 lit
331 pprExpr1 e@(CmmReg _reg)  = pprExpr e
332 pprExpr1 other            = parens (pprExpr other)
333
334 -- --------------------------------------------------------------------------
335 -- MachOp applications
336
337 pprMachOpApp :: MachOp -> [CmmExpr] -> SDoc
338
339 pprMachOpApp op args
340   | isMulMayOfloOp op
341   = ptext SLIT("mulIntMayOflo") <> parens (commafy (map pprExpr args))
342   where isMulMayOfloOp (MO_U_MulMayOflo _) = True
343         isMulMayOfloOp (MO_S_MulMayOflo _) = True
344         isMulMayOfloOp _ = False
345
346 pprMachOpApp mop args
347  = case args of
348     -- dyadic
349     [x,y] -> pprArg x <+> pprMachOp_for_C mop <+> pprArg y
350
351     -- unary
352     [x]   -> pprMachOp_for_C mop <> parens (pprArg x)
353
354     _     -> panic "PprC.pprMachOp : machop with wrong number of args"
355
356   where
357     pprArg e | signedOp mop = cCast (machRepSignedCType (cmmExprRep e)) e
358              | otherwise    = pprExpr1 e
359
360 -- --------------------------------------------------------------------------
361 -- Literals
362
363 pprLit :: CmmLit -> SDoc
364 pprLit lit = case lit of
365     CmmInt i I64 | machRepByteWidth I32 == wORD_SIZE 
366                        -> pprHexVal i <> ptext SLIT("LL")
367         -- Append an 'LL' suffix to 64-bit integers on a 32-bit
368         -- platform.  This might not be strictly necessary (the
369         -- type will always be apparent from the context), but
370         -- it avoids some warnings from gcc.
371     CmmInt i _rep      -> pprHexVal i
372     CmmFloat f rep     -> parens (machRepCType rep) <> (rational f)
373     CmmLabel clbl      -> mkW_ <> pprCLabel clbl
374     CmmLabelOff clbl i -> mkW_ <> pprCLabel clbl <> char '+' <> int i
375     CmmLabelDiffOff clbl1 clbl2 i
376         -- WARNING:
377         -- * the lit must occur in the info table clbl2
378         -- * clbl1 must be an SRT, a slow entry point or a large bitmap
379         -- The Mangler is expected to convert any reference to an SRT,
380         -- a slow entry point or a large bitmap
381         -- from an info table to an offset.
382         -> mkW_ <> pprCLabel clbl1 <> char '+' <> int i
383
384 pprLit1 :: CmmLit -> SDoc
385 pprLit1 lit@(CmmLabelOff _ _) = parens (pprLit lit)
386 pprLit1 lit@(CmmLabelDiffOff _ _ _) = parens (pprLit lit)
387 pprLit1 lit@(CmmFloat _ _)    = parens (pprLit lit)
388 pprLit1 other = pprLit other
389
390 -- ---------------------------------------------------------------------------
391 -- Static data
392
393 pprStatics :: [CmmStatic] -> [SDoc]
394 pprStatics [] = []
395 pprStatics (CmmStaticLit (CmmFloat f F32) : rest) 
396   = pprLit1 (floatToWord f) : pprStatics rest
397 pprStatics (CmmStaticLit (CmmFloat f F64) : rest)
398   = map pprLit1 (doubleToWords f) ++ pprStatics rest
399 pprStatics (CmmStaticLit (CmmInt i I64) : rest)
400   | machRepByteWidth I32 == wORD_SIZE
401 #ifdef WORDS_BIGENDIAN
402   = pprStatics (CmmStaticLit (CmmInt q I32) : 
403                 CmmStaticLit (CmmInt r I32) : rest)
404 #else
405   = pprStatics (CmmStaticLit (CmmInt r I32) : 
406                 CmmStaticLit (CmmInt q I32) : rest)
407 #endif
408   where r = i .&. 0xffffffff
409         q = i `shiftR` 32
410 pprStatics (CmmStaticLit lit : rest)
411   = pprLit1 lit : pprStatics rest
412 pprStatics (other : rest)
413   = pprPanic "pprWord" (pprStatic other)
414
415 pprStatic :: CmmStatic -> SDoc
416 pprStatic s = case s of
417
418     CmmStaticLit lit   -> nest 4 (pprLit lit)
419     CmmAlign i         -> nest 4 (ptext SLIT("/* align */") <+> int i)
420     CmmDataLabel clbl  -> pprCLabel clbl <> colon
421     CmmUninitialised i -> nest 4 (mkC_ <> brackets (int i))
422
423     -- these should be inlined, like the old .hc
424     CmmString s'       -> nest 4 (mkW_ <> parens(pprStringInCStyle s'))
425
426
427 -- ---------------------------------------------------------------------------
428 -- Block Ids
429
430 pprBlockId :: BlockId -> SDoc
431 pprBlockId b = char '_' <> ppr (getUnique b)
432
433 -- --------------------------------------------------------------------------
434 -- Print a MachOp in a way suitable for emitting via C.
435 --
436
437 pprMachOp_for_C :: MachOp -> SDoc
438
439 pprMachOp_for_C mop = case mop of 
440
441         -- Integer operations
442         MO_Add          _ -> char '+'
443         MO_Sub          _ -> char '-'
444         MO_Eq           _ -> ptext SLIT("==")
445         MO_Ne           _ -> ptext SLIT("!=")
446         MO_Mul          _ -> char '*'
447
448         MO_S_Quot       _ -> char '/'
449         MO_S_Rem        _ -> char '%'
450         MO_S_Neg        _ -> char '-'
451
452         MO_U_Quot       _ -> char '/'
453         MO_U_Rem        _ -> char '%'
454
455         -- Signed comparisons (floating-point comparisons also use these)
456         -- & Unsigned comparisons
457         MO_S_Ge         _ -> ptext SLIT(">=")
458         MO_S_Le         _ -> ptext SLIT("<=")
459         MO_S_Gt         _ -> char '>'
460         MO_S_Lt         _ -> char '<'
461
462         MO_U_Ge         _ -> ptext SLIT(">=")
463         MO_U_Le         _ -> ptext SLIT("<=")
464         MO_U_Gt         _ -> char '>'
465         MO_U_Lt         _ -> char '<'
466
467         -- Bitwise operations.  Not all of these may be supported at all
468         -- sizes, and only integral MachReps are valid.
469         MO_And          _ -> char '&'
470         MO_Or           _ -> char '|'
471         MO_Xor          _ -> char '^'
472         MO_Not          _ -> char '~'
473         MO_Shl          _ -> ptext SLIT("<<")
474         MO_U_Shr        _ -> ptext SLIT(">>") -- unsigned shift right
475         MO_S_Shr        _ -> ptext SLIT(">>") -- signed shift right
476
477 -- Conversions.  Some of these will be NOPs.
478 -- Floating-point conversions use the signed variant.
479 -- We won't know to generate (void*) casts here, but maybe from
480 -- context elsewhere
481
482 -- noop casts
483         MO_U_Conv I8 I8     -> empty
484         MO_U_Conv I16 I16   -> empty
485         MO_U_Conv I32 I32   -> empty
486         MO_U_Conv I64 I64   -> empty
487         MO_U_Conv I128 I128 -> empty
488         MO_S_Conv I8 I8     -> empty
489         MO_S_Conv I16 I16   -> empty
490         MO_S_Conv I32 I32   -> empty
491         MO_S_Conv I64 I64   -> empty
492         MO_S_Conv I128 I128 -> empty
493
494         MO_U_Conv _from to  -> parens (machRepCType to)
495         MO_S_Conv _from to  -> parens (machRepSignedCType to)
496
497         _ -> panic "PprC.pprMachOp_for_C: unknown machop"
498
499 signedOp :: MachOp -> Bool
500 signedOp (MO_S_Quot _)   = True
501 signedOp (MO_S_Rem  _)   = True
502 signedOp (MO_S_Neg  _)   = True
503 signedOp (MO_S_Ge   _)   = True
504 signedOp (MO_S_Le   _)   = True
505 signedOp (MO_S_Gt   _)   = True
506 signedOp (MO_S_Lt   _)   = True
507 signedOp (MO_S_Shr  _)   = True
508 signedOp (MO_S_Conv _ _) = True
509 signedOp _ = False
510
511 -- ---------------------------------------------------------------------
512 -- tend to be implemented by foreign calls
513
514 pprCallishMachOp_for_C :: CallishMachOp -> SDoc
515
516 pprCallishMachOp_for_C mop 
517     = case mop of
518         MO_F64_Pwr  -> ptext SLIT("pow")
519         MO_F64_Sin  -> ptext SLIT("sin")
520         MO_F64_Cos  -> ptext SLIT("cos")
521         MO_F64_Tan  -> ptext SLIT("tan")
522         MO_F64_Sinh -> ptext SLIT("sinh")
523         MO_F64_Cosh -> ptext SLIT("cosh")
524         MO_F64_Tanh -> ptext SLIT("tanh")
525         MO_F64_Asin -> ptext SLIT("asin")
526         MO_F64_Acos -> ptext SLIT("acos")
527         MO_F64_Atan -> ptext SLIT("atan")
528         MO_F64_Log  -> ptext SLIT("log")
529         MO_F64_Exp  -> ptext SLIT("exp")
530         MO_F64_Sqrt -> ptext SLIT("sqrt")
531         MO_F32_Pwr  -> ptext SLIT("pow")
532         MO_F32_Sin  -> ptext SLIT("sin")
533         MO_F32_Cos  -> ptext SLIT("cos")
534         MO_F32_Tan  -> ptext SLIT("tan")
535         MO_F32_Sinh -> ptext SLIT("sinh")
536         MO_F32_Cosh -> ptext SLIT("cosh")
537         MO_F32_Tanh -> ptext SLIT("tanh")
538         MO_F32_Asin -> ptext SLIT("asin")
539         MO_F32_Acos -> ptext SLIT("acos")
540         MO_F32_Atan -> ptext SLIT("atan")
541         MO_F32_Log  -> ptext SLIT("log")
542         MO_F32_Exp  -> ptext SLIT("exp")
543         MO_F32_Sqrt -> ptext SLIT("sqrt")
544
545 -- ---------------------------------------------------------------------
546 -- Useful #defines
547 --
548
549 mkJMP_, mkFN_, mkIF_ :: SDoc -> SDoc
550
551 mkJMP_ i = ptext SLIT("JMP_") <> parens i
552 mkFN_  i = ptext SLIT("FN_")  <> parens i -- externally visible function
553 mkIF_  i = ptext SLIT("IF_")  <> parens i -- locally visible
554
555
556 mkFB_, mkFE_ :: SDoc
557 mkFB_ = ptext SLIT("FB_") -- function code begin
558 mkFE_ = ptext SLIT("FE_") -- function code end
559
560 -- from includes/Stg.h
561 --
562 mkC_,mkW_,mkP_,mkPP_,mkI_,mkA_,mkD_,mkF_,mkB_,mkL_,mkLI_,mkLW_ :: SDoc
563
564 mkC_  = ptext SLIT("(C_)")        -- StgChar
565 mkW_  = ptext SLIT("(W_)")        -- StgWord
566 mkP_  = ptext SLIT("(P_)")        -- StgWord*
567 mkPP_ = ptext SLIT("(PP_)")       -- P_*
568 mkI_  = ptext SLIT("(I_)")        -- StgInt
569 mkA_  = ptext SLIT("(A_)")        -- StgAddr
570 mkD_  = ptext SLIT("(D_)")        -- const StgWord*
571 mkF_  = ptext SLIT("(F_)")        -- StgFunPtr
572 mkB_  = ptext SLIT("(B_)")        -- StgByteArray
573 mkL_  = ptext SLIT("(L_)")        -- StgClosurePtr
574
575 mkLI_ = ptext SLIT("(LI_)")       -- StgInt64
576 mkLW_ = ptext SLIT("(LW_)")       -- StgWord64
577
578
579 -- ---------------------------------------------------------------------
580 --
581 -- Assignments
582 --
583 -- Generating assignments is what we're all about, here
584 --
585 pprAssign :: CmmReg -> CmmExpr -> SDoc
586
587 -- dest is a reg, rhs is a reg
588 pprAssign r1 (CmmReg r2)
589    | not (isStrangeTypeReg r1) && not (isStrangeTypeReg r2)
590    || isPtrReg r1 && isPtrReg r2
591    = hcat [ pprAsPtrReg r1, equals, pprAsPtrReg r2, semi ]
592
593 -- dest is a reg, rhs is a CmmRegOff
594 pprAssign r1 (CmmRegOff r2 off)
595    | not (isStrangeTypeReg r1) && not (isStrangeTypeReg r2)
596    || isPtrReg r1 && isPtrReg r2
597    = hcat [ pprAsPtrReg r1, equals, pprAsPtrReg r2, op, int off', semi ]
598   where
599         off1 | isPtrReg r2 = off `shiftR` wordShift
600              | otherwise   = off
601
602         (op,off') | off >= 0  = (char '+', off1)
603                   | otherwise = (char '-', -off1)
604
605 -- dest is a reg, rhs is anything.
606 -- We can't cast the lvalue, so we have to cast the rhs if necessary.  Casting
607 -- the lvalue elicits a warning from new GCC versions (3.4+).
608 pprAssign r1 r2
609   | isPtrReg r1
610   = pprAsPtrReg r1 <> ptext SLIT(" = ") <> mkP_ <> pprExpr1 r2 <> semi
611   | Just ty <- strangeRegType r1
612   = pprReg r1 <> ptext SLIT(" = ") <> parens ty <> pprExpr1 r2 <> semi
613   | otherwise
614   = pprReg r1 <> ptext SLIT(" = ") <> pprExpr r2 <> semi
615
616 -- ---------------------------------------------------------------------
617 -- Registers
618
619 pprCastReg reg
620    | isStrangeTypeReg reg = mkW_ <> pprReg reg
621    | otherwise            = pprReg reg
622
623 -- True if the register has type StgPtr in C, otherwise it has an
624 -- integer type.  We need to take care with pointer arithmetic on registers
625 -- with type StgPtr.
626 isPtrReg :: CmmReg -> Bool
627 isPtrReg (CmmLocal _) = False
628 isPtrReg (CmmGlobal r) = isPtrGlobalReg r
629
630 isPtrGlobalReg :: GlobalReg -> Bool
631 isPtrGlobalReg (VanillaReg n)   = True
632 isPtrGlobalReg Sp               = True
633 isPtrGlobalReg Hp               = True
634 isPtrGlobalReg HpLim            = True
635 isPtrGlobalReg SpLim            = True
636 isPtrGlobalReg _                = False
637
638 -- True if in C this register doesn't have the type given by 
639 -- (machRepCType (cmmRegRep reg)), so it has to be cast.
640 isStrangeTypeReg :: CmmReg -> Bool
641 isStrangeTypeReg (CmmLocal _)   = False
642 isStrangeTypeReg (CmmGlobal g)  = isStrangeTypeGlobal g
643
644 isStrangeTypeGlobal :: GlobalReg -> Bool
645 isStrangeTypeGlobal CurrentTSO          = True
646 isStrangeTypeGlobal CurrentNursery      = True
647 isStrangeTypeGlobal r                   = isPtrGlobalReg r
648
649 strangeRegType :: CmmReg -> Maybe SDoc
650 strangeRegType (CmmGlobal CurrentTSO) = Just (ptext SLIT("struct StgTSO_ *"))
651 strangeRegType (CmmGlobal CurrentNursery) = Just (ptext SLIT("struct bdescr_ *"))
652 strangeRegType _ = Nothing
653
654 -- pprReg just prints the register name.
655 --
656 pprReg :: CmmReg -> SDoc
657 pprReg r = case r of
658         CmmLocal  local  -> pprLocalReg local
659         CmmGlobal global -> pprGlobalReg global
660                 
661 pprAsPtrReg :: CmmReg -> SDoc
662 pprAsPtrReg (CmmGlobal (VanillaReg n)) = char 'R' <> int n <> ptext SLIT(".p")
663 pprAsPtrReg other_reg = pprReg other_reg
664
665 pprGlobalReg :: GlobalReg -> SDoc
666 pprGlobalReg gr = case gr of
667     VanillaReg n   -> char 'R' <> int n  <> ptext SLIT(".w")
668     FloatReg   n   -> char 'F' <> int n
669     DoubleReg  n   -> char 'D' <> int n
670     LongReg    n   -> char 'L' <> int n
671     Sp             -> ptext SLIT("Sp")
672     SpLim          -> ptext SLIT("SpLim")
673     Hp             -> ptext SLIT("Hp")
674     HpLim          -> ptext SLIT("HpLim")
675     CurrentTSO     -> ptext SLIT("CurrentTSO")
676     CurrentNursery -> ptext SLIT("CurrentNursery")
677     HpAlloc        -> ptext SLIT("HpAlloc")
678     BaseReg        -> ptext SLIT("BaseReg")
679     GCEnter1       -> ptext SLIT("stg_gc_enter_1")
680     GCFun          -> ptext SLIT("stg_gc_fun")
681
682 pprLocalReg :: LocalReg -> SDoc
683 pprLocalReg (LocalReg uniq _rep) = char '_' <> ppr uniq
684
685 -- -----------------------------------------------------------------------------
686 -- Foreign Calls
687
688 pprCall :: SDoc -> CCallConv -> [(CmmReg,MachHint)] -> [(CmmExpr,MachHint)]
689         -> Maybe [GlobalReg] -> SDoc
690
691 pprCall ppr_fn cconv results args vols
692   | not (is_cish cconv)
693   = panic "pprForeignCall: unknown calling convention"
694
695   | otherwise
696   = save vols $$
697     ptext SLIT("CALLER_SAVE_SYSTEM") $$
698     hcat [ ppr_results results, ppr_fn, 
699            parens (commafy (map pprArg args)), semi ] $$
700     ptext SLIT("CALLER_RESTORE_SYSTEM") $$
701     restore vols
702   where 
703      ppr_results []     = empty
704      ppr_results [(one,hint)] 
705          = pprExpr (CmmReg one) <> ptext SLIT(" = ")
706                  <> pprUnHint hint (cmmRegRep one)
707      ppr_results _other = panic "pprCall: multiple results"
708
709      pprArg (expr, PtrHint)
710         = cCast (ptext SLIT("void *")) expr
711         -- see comment by machRepHintCType below
712      pprArg (expr, SignedHint)
713         = cCast (machRepSignedCType (cmmExprRep expr)) expr
714      pprArg (expr, _other)
715         = pprExpr expr
716
717      pprUnHint PtrHint    rep = parens (machRepCType rep)
718      pprUnHint SignedHint rep = parens (machRepCType rep)
719      pprUnHint _          _   = empty
720
721      save    = save_restore SLIT("CALLER_SAVE")
722      restore = save_restore SLIT("CALLER_RESTORE")
723
724         -- Nothing says "I don't know what's live; save everything"
725         -- CALLER_SAVE_USER is defined in ghc/includes/Regs.h
726      save_restore txt Nothing     = ptext txt <> ptext SLIT("_USER")
727      save_restore txt (Just these) = vcat (map saveRestoreGlobal these)
728         where saveRestoreGlobal r = ptext txt <> char '_' <> pprGlobalRegName r
729
730 pprGlobalRegName :: GlobalReg -> SDoc
731 pprGlobalRegName gr = case gr of
732     VanillaReg n   -> char 'R' <> int n  -- without the .w suffix
733     _              -> pprGlobalReg gr
734
735 is_cish CCallConv   = True
736 is_cish StdCallConv = True
737 is_cish _           = False
738
739 -- ---------------------------------------------------------------------
740 -- Find and print local and external declarations for a list of
741 -- Cmm statements.
742 -- 
743 pprTempAndExternDecls :: [CmmBasicBlock] -> (SDoc{-temps-}, SDoc{-externs-})
744 pprTempAndExternDecls stmts 
745   = (vcat (map pprTempDecl (eltsUFM temps)), 
746      vcat (map (pprExternDecl False{-ToDo-}) (keysFM lbls)))
747   where (temps, lbls) = runTE (mapM_ te_BB stmts)
748
749 pprDataExterns :: [CmmStatic] -> SDoc
750 pprDataExterns statics
751   = vcat (map (pprExternDecl False{-ToDo-}) (keysFM lbls))
752   where (_, lbls) = runTE (mapM_ te_Static statics)
753
754 pprTempDecl :: LocalReg -> SDoc
755 pprTempDecl l@(LocalReg _uniq rep)
756   = hcat [ machRepCType rep, space, pprLocalReg l, semi ]
757
758 pprExternDecl :: Bool -> CLabel -> SDoc
759 pprExternDecl in_srt lbl
760   -- do not print anything for "known external" things
761   | not (needsCDecl lbl) = empty
762   | otherwise               = 
763         hcat [ visibility, label_type (labelType lbl), 
764                lparen, dyn_wrapper (pprCLabel lbl), text ");" ]
765  where
766   dyn_wrapper d
767     | in_srt && labelDynamic lbl = text "DLL_IMPORT_DATA_VAR" <> parens d
768     | otherwise                  = d
769
770   label_type CodeLabel = ptext SLIT("F_")
771   label_type DataLabel = ptext SLIT("I_")
772
773   visibility
774      | externallyVisibleCLabel lbl = char 'E'
775      | otherwise                   = char 'I'
776
777
778 type TEState = (UniqSet LocalReg, FiniteMap CLabel ())
779 newtype TE a = TE { unTE :: TEState -> (a, TEState) }
780
781 instance Monad TE where
782    TE m >>= k  = TE $ \s -> case m s of (a, s') -> unTE (k a) s'
783    return a    = TE $ \s -> (a, s)
784
785 te_lbl :: CLabel -> TE ()
786 te_lbl lbl = TE $ \(temps,lbls) -> ((), (temps, addToFM lbls lbl ()))
787
788 te_temp :: LocalReg -> TE ()
789 te_temp r = TE $ \(temps,lbls) -> ((), (addOneToUniqSet temps r, lbls))
790
791 runTE :: TE () -> TEState
792 runTE (TE m) = snd (m (emptyUniqSet, emptyFM))
793
794 te_Static :: CmmStatic -> TE ()
795 te_Static (CmmStaticLit lit) = te_Lit lit
796 te_Static _ = return ()
797
798 te_BB :: CmmBasicBlock -> TE ()
799 te_BB (BasicBlock _ ss)         = mapM_ te_Stmt ss
800
801 te_Lit :: CmmLit -> TE ()
802 te_Lit (CmmLabel l) = te_lbl l
803 te_Lit (CmmLabelOff l _) = te_lbl l
804 te_Lit (CmmLabelDiffOff l1 l2 _) = te_lbl l1
805 te_Lit _ = return ()
806
807 te_Stmt :: CmmStmt -> TE ()
808 te_Stmt (CmmAssign r e)         = te_Reg r >> te_Expr e
809 te_Stmt (CmmStore l r)          = te_Expr l >> te_Expr r
810 te_Stmt (CmmCall _ rs es _)     = mapM_ (te_Reg.fst) rs >>
811                                   mapM_ (te_Expr.fst) es
812 te_Stmt (CmmCondBranch e _)     = te_Expr e
813 te_Stmt (CmmSwitch e _)         = te_Expr e
814 te_Stmt (CmmJump e _)           = te_Expr e
815 te_Stmt _                       = return ()
816
817 te_Expr :: CmmExpr -> TE ()
818 te_Expr (CmmLit lit)            = te_Lit lit
819 te_Expr (CmmReg r)              = te_Reg r
820 te_Expr (CmmLoad e _)           = te_Expr e
821 te_Expr (CmmMachOp _ es)        = mapM_ te_Expr es
822 te_Expr (CmmRegOff r _)         = te_Reg r
823 te_Expr _                       = return ()
824
825 te_Reg :: CmmReg -> TE ()
826 te_Reg (CmmLocal l) = te_temp l
827 te_Reg _            = return ()
828
829
830 -- ---------------------------------------------------------------------
831 -- C types for MachReps
832
833 cCast :: SDoc -> CmmExpr -> SDoc
834 cCast ty expr = parens ty <> pprExpr1 expr
835
836 -- This is for finding the types of foreign call arguments.  For a pointer
837 -- argument, we always cast the argument to (void *), to avoid warnings from
838 -- the C compiler.
839 machRepHintCType :: MachRep -> MachHint -> SDoc
840 machRepHintCType rep PtrHint    = ptext SLIT("void *")
841 machRepHintCType rep SignedHint = machRepSignedCType rep
842 machRepHintCType rep _other     = machRepCType rep
843
844 machRepPtrCType :: MachRep -> SDoc
845 machRepPtrCType r | r == wordRep = ptext SLIT("P_")
846                   | otherwise    = machRepCType r <> char '*'
847
848 machRepCType :: MachRep -> SDoc
849 machRepCType r | r == wordRep = ptext SLIT("W_")
850                | otherwise    = sized_type
851   where sized_type = case r of
852                         I8      -> ptext SLIT("StgWord8")
853                         I16     -> ptext SLIT("StgWord16")
854                         I32     -> ptext SLIT("StgWord32")
855                         I64     -> ptext SLIT("StgWord64")
856                         F32     -> ptext SLIT("StgFloat") -- ToDo: correct?
857                         F64     -> ptext SLIT("StgDouble")
858                         _  -> panic "machRepCType"
859
860 machRepSignedCType :: MachRep -> SDoc
861 machRepSignedCType r | r == wordRep = ptext SLIT("I_")
862                      | otherwise    = sized_type
863   where sized_type = case r of
864                         I8      -> ptext SLIT("StgInt8")
865                         I16     -> ptext SLIT("StgInt16")
866                         I32     -> ptext SLIT("StgInt32")
867                         I64     -> ptext SLIT("StgInt64")
868                         F32     -> ptext SLIT("StgFloat") -- ToDo: correct?
869                         F64     -> ptext SLIT("StgDouble")
870                         _ -> panic "machRepCType"
871
872 -- ---------------------------------------------------------------------
873 -- print strings as valid C strings
874
875 -- Assumes it contains only characters '\0'..'\xFF'!
876 pprFSInCStyle :: FastString -> SDoc
877 pprFSInCStyle fs = pprStringInCStyle (unpackFS fs)
878
879 pprStringInCStyle :: String -> SDoc
880 pprStringInCStyle s = doubleQuotes (text (concatMap charToC s))
881
882 charToC :: Char -> String
883 charToC '\"' = "\\\""
884 charToC '\'' = "\\\'"
885 charToC '\\' = "\\\\"
886 charToC c | c >= ' ' && c <= '~' = [c]
887           | c > '\xFF' = panic ("charToC "++show c)
888           | otherwise = ['\\',
889                          chr (ord '0' + ord c `div` 64),
890                          chr (ord '0' + ord c `div` 8 `mod` 8),
891                          chr (ord '0' + ord c         `mod` 8)]
892
893
894 -- ---------------------------------------------------------------------------
895 -- Initialising static objects with floating-point numbers.  We can't
896 -- just emit the floating point number, because C will cast it to an int
897 -- by rounding it.  We want the actual bit-representation of the float.
898
899 -- This is a hack to turn the floating point numbers into ints that we
900 -- can safely initialise to static locations.
901
902 big_doubles 
903   | machRepByteWidth F64 == 2 * wORD_SIZE  = True
904   | machRepByteWidth F64 == wORD_SIZE      = False
905   | otherwise = panic "big_doubles"
906
907 #if __GLASGOW_HASKELL__ >= 504
908 newFloatArray :: (Int,Int) -> ST s (STUArray s Int Float)
909 newFloatArray = newArray_
910
911 newDoubleArray :: (Int,Int) -> ST s (STUArray s Int Double)
912 newDoubleArray = newArray_
913
914 castFloatToIntArray :: STUArray s Int Float -> ST s (STUArray s Int Int)
915 castFloatToIntArray = castSTUArray
916
917 castDoubleToIntArray :: STUArray s Int Double -> ST s (STUArray s Int Int)
918 castDoubleToIntArray = castSTUArray
919
920 writeFloatArray :: STUArray s Int Float -> Int -> Float -> ST s ()
921 writeFloatArray = writeArray
922
923 writeDoubleArray :: STUArray s Int Double -> Int -> Double -> ST s ()
924 writeDoubleArray = writeArray
925
926 readIntArray :: STUArray s Int Int -> Int -> ST s Int
927 readIntArray = readArray
928
929 #else
930
931 castFloatToIntArray :: MutableByteArray s t -> ST s (MutableByteArray s t)
932 castFloatToIntArray = return
933
934 castDoubleToIntArray :: MutableByteArray s t -> ST s (MutableByteArray s t)
935 castDoubleToIntArray = return
936
937 #endif
938
939 -- floats are always 1 word
940 floatToWord :: Rational -> CmmLit
941 floatToWord r
942   = runST (do
943         arr <- newFloatArray ((0::Int),0)
944         writeFloatArray arr 0 (fromRational r)
945         arr' <- castFloatToIntArray arr
946         i <- readIntArray arr' 0
947         return (CmmInt (toInteger i) wordRep)
948     )
949
950 doubleToWords :: Rational -> [CmmLit]
951 doubleToWords r
952   | big_doubles                         -- doubles are 2 words
953   = runST (do
954         arr <- newDoubleArray ((0::Int),1)
955         writeDoubleArray arr 0 (fromRational r)
956         arr' <- castDoubleToIntArray arr
957         i1 <- readIntArray arr' 0
958         i2 <- readIntArray arr' 1
959         return [ CmmInt (toInteger i1) wordRep
960                , CmmInt (toInteger i2) wordRep
961                ]
962     )
963   | otherwise                           -- doubles are 1 word
964   = runST (do
965         arr <- newDoubleArray ((0::Int),0)
966         writeDoubleArray arr 0 (fromRational r)
967         arr' <- castDoubleToIntArray arr
968         i <- readIntArray arr' 0
969         return [ CmmInt (toInteger i) wordRep ]
970     )
971
972 -- ---------------------------------------------------------------------------
973 -- Utils
974
975 wordShift :: Int
976 wordShift = machRepLogWidth wordRep
977
978 commafy :: [SDoc] -> SDoc
979 commafy xs = hsep $ punctuate comma xs
980
981 -- Print in C hex format: 0x13fa
982 pprHexVal :: Integer -> SDoc
983 pprHexVal 0 = ptext SLIT("0x0")
984 pprHexVal w 
985   | w < 0     = parens (char '-' <> ptext SLIT("0x") <> go (-w))
986   | otherwise = ptext SLIT("0x") <> go w
987   where
988       go 0 = empty
989       go w' = go q <> dig
990            where
991              (q,r) = w' `quotRem` 16
992              dig | r < 10    = char (chr (fromInteger r + ord '0'))
993                  | otherwise = char (chr (fromInteger r - 10 + ord 'a'))
994