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