1 -----------------------------------------------------------------------------
3 -- Pretty-printing of Cmm as C, suitable for feeding gcc
5 -- (c) The University of Glasgow 2004
7 -----------------------------------------------------------------------------
10 -- Print Cmm as real C, for -fvia-C
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.
17 -- ToDo: save/restore volatile registers around calls.
24 #include "HsVersions.h"
33 import Unique ( getUnique )
36 import UniqFM ( eltsUFM )
40 import CmdLineOpts ( opt_EnsureSplittableC )
43 import Data.List ( intersperse, groupBy )
44 import Data.Bits ( shiftR )
45 import Char ( ord, chr )
50 import PprCmm () -- instances only
54 #if __GLASGOW_HASKELL__ >= 504
59 -- --------------------------------------------------------------------------
62 pprCs :: [Cmm] -> SDoc
63 pprCs cmms = pprCode CStyle (vcat $ map (\c -> split_marker $$ pprC c) cmms)
65 writeCs :: Handle -> [Cmm] -> IO ()
66 writeCs handle cmms = printForUser handle alwaysQualify (pprCs cmms)
67 -- ToDo: should be printForC
70 | opt_EnsureSplittableC = ptext SLIT("__STG_SPLIT_MARKER")
73 -- --------------------------------------------------------------------------
74 -- Now do some real work
76 -- for fun, we could call cmmToCmm over the tops...
80 pprC (Cmm tops) = vcat $ intersperse (text "") $ map pprTop tops
85 pprTop :: CmmTop -> SDoc
86 pprTop (CmmProc info clbl _params blocks) =
88 then pprDataExterns info $$
89 pprWordArray (entryLblToInfoLbl clbl) info
93 -- the first block doesn't get a label:
94 (BasicBlock _ stmts : rest) -> vcat [
97 (if (externallyVisibleCLabel clbl)
98 then mkFN_ else mkIF_) (pprCLabel clbl) <+> lbrace,
101 nest 8 (vcat (map pprStmt stmts)) $$
102 vcat (map pprBBlock rest),
107 (temp_decls, extern_decls) = pprTempAndExternDecls blocks
110 -- Chunks of static data.
112 -- We only handle (a) arrays of word-sized things and (b) strings.
114 pprTop (CmmData _section _ds@[CmmDataLabel lbl, CmmString str]) =
116 pprLocalness lbl, ptext SLIT("char "), pprCLabel lbl,
117 ptext SLIT("[] = "), pprStringInCStyle str, semi
120 pprTop (CmmData _section _ds@[CmmDataLabel lbl, CmmUninitialised size]) =
122 pprLocalness lbl, ptext SLIT("char "), pprCLabel lbl,
123 brackets (int size), semi
126 pprTop top@(CmmData _section (CmmDataLabel lbl : lits)) =
127 pprDataExterns lits $$
128 pprWordArray lbl lits
130 -- these shouldn't appear?
131 pprTop (CmmData _ _) = panic "PprC.pprTop: can't handle this data"
134 -- --------------------------------------------------------------------------
135 -- BasicBlocks are self-contained entities: they always end in a jump.
137 -- Like nativeGen/AsmCodeGen, we could probably reorder blocks to turn
138 -- as many jumps as possible into fall throughs.
141 pprBBlock :: CmmBasicBlock -> SDoc
142 pprBBlock (BasicBlock lbl stmts) =
144 pprTrace "pprC.pprBBlock: curious empty code block for"
145 (pprBlockId lbl) empty
147 nest 4 (pprBlockId lbl <> colon) $$
148 nest 8 (vcat (map pprStmt stmts))
150 -- --------------------------------------------------------------------------
151 -- Info tables. Just arrays of words.
152 -- See codeGen/ClosureInfo, and nativeGen/PprMach
154 pprWordArray :: CLabel -> [CmmStatic] -> SDoc
156 = hcat [ pprLocalness lbl, ptext SLIT("StgWord")
157 , space, pprCLabel lbl, ptext SLIT("[] = {") ]
158 $$ nest 8 (commafy (pprStatics ds))
162 -- has to be static, if it isn't globally visible
164 pprLocalness :: CLabel -> SDoc
165 pprLocalness lbl | not $ externallyVisibleCLabel lbl = ptext SLIT("static ")
168 -- --------------------------------------------------------------------------
172 pprStmt :: CmmStmt -> SDoc
174 pprStmt stmt = case stmt of
176 CmmComment s -> (hang (ptext SLIT("/*")) 3 (ftext s)) $$ ptext SLIT("*/")
178 CmmAssign dest src -> pprAssign dest src
181 | rep == I64 && wordRep /= I64
182 -> ptext SLIT("ASSIGN_Word64") <>
183 parens (mkP_ <> pprExpr1 dest <> comma <> pprExpr src) <> semi
186 -> hsep [ pprExpr (CmmLoad dest rep), equals, pprExpr src <> semi ]
190 CmmCall (CmmForeignCall fn cconv) results args volatile ->
191 -- Controversial: leave this out for now.
194 pprCall ppr_fn cconv results args volatile
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).
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
207 pprUndef (CmmLit (CmmLabel lbl)) =
208 ptext SLIT("#undef") <+> pprCLabel lbl
211 CmmCall (CmmPrim op) results args volatile ->
212 pprCall ppr_fn CCallConv results args volatile
214 ppr_fn = pprCallishMachOp_for_C op
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
221 pprCFunType :: CCallConv -> [(CmmReg,MachHint)] -> [(CmmExpr,MachHint)] -> SDoc
222 pprCFunType cconv ress args
225 parens (text (ccallConvAttribute cconv) <> char '*'),
226 parens (commafy (map arg_type args))
229 res_type [] = ptext SLIT("void")
230 res_type [(one,hint)] = machRepHintCType (cmmRegRep one) hint
232 arg_type (expr,hint) = machRepHintCType (cmmExprRep expr) hint
234 -- ---------------------------------------------------------------------
235 -- unconditional branches
236 pprBranch :: BlockId -> SDoc
237 pprBranch ident = ptext SLIT("goto") <+> pprBlockId ident <> semi
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 ]
248 -- ---------------------------------------------------------------------
249 -- a local table branch
251 -- we find the fall-through cases
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.
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 ]
262 (hang (ptext SLIT("switch") <+> parens ( pprExpr e ) <+> lbrace)
263 4 (vcat ( map caseify pairs2 )))
267 sndEq (_,x) (_,y) = x == y
270 caseify (ix:ixs, ident) = vcat (map do_fallthrough ixs) $$ final_branch ix
273 hsep [ ptext SLIT("case") , pprHexVal ix wordRep <> colon ,
274 ptext SLIT("/* fall through */") ]
277 hsep [ ptext SLIT("case") , pprHexVal ix wordRep <> colon ,
278 ptext SLIT("goto") , (pprBlockId ident) <> semi ]
280 -- ---------------------------------------------------------------------
284 -- C Types: the invariant is that the C expression generated by
288 -- has a type in C which is also given by
290 -- machRepCType (cmmExprRep e)
292 -- (similar invariants apply to the rest of the pretty printer).
294 pprExpr :: CmmExpr -> SDoc
295 pprExpr e = case e of
296 CmmLit lit -> pprLit lit
298 CmmLoad e I64 | wordRep /= I64
299 -> ptext SLIT("PK_Word64") <> parens (mkP_ <> pprExpr1 e)
301 CmmLoad (CmmReg r) rep
302 | isPtrReg r && rep == wordRep
303 -> char '*' <> pprAsPtrReg r
305 CmmLoad (CmmRegOff r 0) rep
306 | isPtrReg r && rep == wordRep
307 -> char '*' <> pprAsPtrReg r
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))
316 char '*' <> parens (cCast (machRepPtrCType rep) expr)
318 CmmReg reg -> pprCastReg reg
319 CmmRegOff reg 0 -> pprCastReg reg
322 | i > 0 -> pprRegOff (char '+') i
323 | otherwise -> pprRegOff (char '-') (-i)
325 pprRegOff op i' = pprCastReg reg <> op <> int i'
327 CmmMachOp mop args -> pprMachOpApp mop args
329 pprExpr1 :: CmmExpr -> SDoc
330 pprExpr1 (CmmLit lit) = pprLit1 lit
331 pprExpr1 e@(CmmReg _reg) = pprExpr e
332 pprExpr1 other = parens (pprExpr other)
334 -- --------------------------------------------------------------------------
335 -- MachOp applications
337 pprMachOpApp :: MachOp -> [CmmExpr] -> SDoc
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
346 pprMachOpApp mop args
349 [x,y] -> pprArg x <+> pprMachOp_for_C mop <+> pprArg y
352 [x] -> pprMachOp_for_C mop <> parens (pprArg x)
354 _ -> panic "PprC.pprMachOp : machop with wrong number of args"
357 pprArg e | signedOp mop = cCast (machRepSignedCType (cmmExprRep e)) e
358 | otherwise = pprExpr1 e
360 -- --------------------------------------------------------------------------
363 pprLit :: CmmLit -> SDoc
364 pprLit lit = case lit of
365 CmmInt i rep -> pprHexVal i rep
366 CmmFloat f rep -> parens (machRepCType rep) <> (rational f)
367 CmmLabel clbl -> mkW_ <> pprCLabel clbl
368 CmmLabelOff clbl i -> mkW_ <> pprCLabel clbl <> char '+' <> int i
369 CmmLabelDiffOff clbl1 clbl2 i
371 -- * the lit must occur in the info table clbl2
372 -- * clbl1 must be an SRT, a slow entry point or a large bitmap
373 -- The Mangler is expected to convert any reference to an SRT,
374 -- a slow entry point or a large bitmap
375 -- from an info table to an offset.
376 -> mkW_ <> pprCLabel clbl1 <> char '+' <> int i
378 pprLit1 :: CmmLit -> SDoc
379 pprLit1 lit@(CmmLabelOff _ _) = parens (pprLit lit)
380 pprLit1 lit@(CmmLabelDiffOff _ _ _) = parens (pprLit lit)
381 pprLit1 lit@(CmmFloat _ _) = parens (pprLit lit)
382 pprLit1 other = pprLit other
384 -- ---------------------------------------------------------------------------
387 pprStatics :: [CmmStatic] -> [SDoc]
389 pprStatics (CmmStaticLit (CmmFloat f F32) : rest)
390 = pprLit1 (floatToWord f) : pprStatics rest
391 pprStatics (CmmStaticLit (CmmFloat f F64) : rest)
392 = map pprLit1 (doubleToWords f) ++ pprStatics rest
393 pprStatics (CmmStaticLit (CmmInt i I64) : rest)
394 | machRepByteWidth I32 == wORD_SIZE
395 #ifdef WORDS_BIGENDIAN
396 = pprStatics (CmmStaticLit (CmmInt q I32) :
397 CmmStaticLit (CmmInt r I32) : rest)
399 = pprStatics (CmmStaticLit (CmmInt r I32) :
400 CmmStaticLit (CmmInt q I32) : rest)
402 where r = i .&. 0xffffffff
404 pprStatics (CmmStaticLit lit : rest)
405 = pprLit1 lit : pprStatics rest
406 pprStatics (other : rest)
407 = pprPanic "pprWord" (pprStatic other)
409 pprStatic :: CmmStatic -> SDoc
410 pprStatic s = case s of
412 CmmStaticLit lit -> nest 4 (pprLit lit)
413 CmmAlign i -> nest 4 (ptext SLIT("/* align */") <+> int i)
414 CmmDataLabel clbl -> pprCLabel clbl <> colon
415 CmmUninitialised i -> nest 4 (mkC_ <> brackets (int i))
417 -- these should be inlined, like the old .hc
418 CmmString s' -> nest 4 (mkW_ <> parens(pprStringInCStyle s'))
421 -- ---------------------------------------------------------------------------
424 pprBlockId :: BlockId -> SDoc
425 pprBlockId b = char '_' <> ppr (getUnique b)
427 -- --------------------------------------------------------------------------
428 -- Print a MachOp in a way suitable for emitting via C.
431 pprMachOp_for_C :: MachOp -> SDoc
433 pprMachOp_for_C mop = case mop of
435 -- Integer operations
438 MO_Eq _ -> ptext SLIT("==")
439 MO_Ne _ -> ptext SLIT("!=")
442 MO_S_Quot _ -> char '/'
443 MO_S_Rem _ -> char '%'
444 MO_S_Neg _ -> char '-'
446 MO_U_Quot _ -> char '/'
447 MO_U_Rem _ -> char '%'
449 -- Signed comparisons (floating-point comparisons also use these)
450 -- & Unsigned comparisons
451 MO_S_Ge _ -> ptext SLIT(">=")
452 MO_S_Le _ -> ptext SLIT("<=")
453 MO_S_Gt _ -> char '>'
454 MO_S_Lt _ -> char '<'
456 MO_U_Ge _ -> ptext SLIT(">=")
457 MO_U_Le _ -> ptext SLIT("<=")
458 MO_U_Gt _ -> char '>'
459 MO_U_Lt _ -> char '<'
461 -- Bitwise operations. Not all of these may be supported at all
462 -- sizes, and only integral MachReps are valid.
467 MO_Shl _ -> ptext SLIT("<<")
468 MO_U_Shr _ -> ptext SLIT(">>") -- unsigned shift right
469 MO_S_Shr _ -> ptext SLIT(">>") -- signed shift right
471 -- Conversions. Some of these will be NOPs.
472 -- Floating-point conversions use the signed variant.
473 -- We won't know to generate (void*) casts here, but maybe from
477 MO_U_Conv I8 I8 -> empty
478 MO_U_Conv I16 I16 -> empty
479 MO_U_Conv I32 I32 -> empty
480 MO_U_Conv I64 I64 -> empty
481 MO_U_Conv I128 I128 -> empty
482 MO_S_Conv I8 I8 -> empty
483 MO_S_Conv I16 I16 -> empty
484 MO_S_Conv I32 I32 -> empty
485 MO_S_Conv I64 I64 -> empty
486 MO_S_Conv I128 I128 -> empty
488 MO_U_Conv _from to -> parens (machRepCType to)
489 MO_S_Conv _from to -> parens (machRepSignedCType to)
491 _ -> panic "PprC.pprMachOp_for_C: unknown machop"
493 signedOp :: MachOp -> Bool
494 signedOp (MO_S_Quot _) = True
495 signedOp (MO_S_Rem _) = True
496 signedOp (MO_S_Neg _) = True
497 signedOp (MO_S_Ge _) = True
498 signedOp (MO_S_Le _) = True
499 signedOp (MO_S_Gt _) = True
500 signedOp (MO_S_Lt _) = True
501 signedOp (MO_S_Shr _) = True
502 signedOp (MO_S_Conv _ _) = True
505 -- ---------------------------------------------------------------------
506 -- tend to be implemented by foreign calls
508 pprCallishMachOp_for_C :: CallishMachOp -> SDoc
510 pprCallishMachOp_for_C mop
512 MO_F64_Pwr -> ptext SLIT("pow")
513 MO_F64_Sin -> ptext SLIT("sin")
514 MO_F64_Cos -> ptext SLIT("cos")
515 MO_F64_Tan -> ptext SLIT("tan")
516 MO_F64_Sinh -> ptext SLIT("sinh")
517 MO_F64_Cosh -> ptext SLIT("cosh")
518 MO_F64_Tanh -> ptext SLIT("tanh")
519 MO_F64_Asin -> ptext SLIT("asin")
520 MO_F64_Acos -> ptext SLIT("acos")
521 MO_F64_Atan -> ptext SLIT("atan")
522 MO_F64_Log -> ptext SLIT("log")
523 MO_F64_Exp -> ptext SLIT("exp")
524 MO_F64_Sqrt -> ptext SLIT("sqrt")
525 MO_F32_Pwr -> ptext SLIT("pow")
526 MO_F32_Sin -> ptext SLIT("sin")
527 MO_F32_Cos -> ptext SLIT("cos")
528 MO_F32_Tan -> ptext SLIT("tan")
529 MO_F32_Sinh -> ptext SLIT("sinh")
530 MO_F32_Cosh -> ptext SLIT("cosh")
531 MO_F32_Tanh -> ptext SLIT("tanh")
532 MO_F32_Asin -> ptext SLIT("asin")
533 MO_F32_Acos -> ptext SLIT("acos")
534 MO_F32_Atan -> ptext SLIT("atan")
535 MO_F32_Log -> ptext SLIT("log")
536 MO_F32_Exp -> ptext SLIT("exp")
537 MO_F32_Sqrt -> ptext SLIT("sqrt")
539 -- ---------------------------------------------------------------------
543 mkJMP_, mkFN_, mkIF_ :: SDoc -> SDoc
545 mkJMP_ i = ptext SLIT("JMP_") <> parens i
546 mkFN_ i = ptext SLIT("FN_") <> parens i -- externally visible function
547 mkIF_ i = ptext SLIT("IF_") <> parens i -- locally visible
551 mkFB_ = ptext SLIT("FB_") -- function code begin
552 mkFE_ = ptext SLIT("FE_") -- function code end
554 -- from includes/Stg.h
556 mkC_,mkW_,mkP_,mkPP_,mkI_,mkA_,mkD_,mkF_,mkB_,mkL_,mkLI_,mkLW_ :: SDoc
558 mkC_ = ptext SLIT("(C_)") -- StgChar
559 mkW_ = ptext SLIT("(W_)") -- StgWord
560 mkP_ = ptext SLIT("(P_)") -- StgWord*
561 mkPP_ = ptext SLIT("(PP_)") -- P_*
562 mkI_ = ptext SLIT("(I_)") -- StgInt
563 mkA_ = ptext SLIT("(A_)") -- StgAddr
564 mkD_ = ptext SLIT("(D_)") -- const StgWord*
565 mkF_ = ptext SLIT("(F_)") -- StgFunPtr
566 mkB_ = ptext SLIT("(B_)") -- StgByteArray
567 mkL_ = ptext SLIT("(L_)") -- StgClosurePtr
569 mkLI_ = ptext SLIT("(LI_)") -- StgInt64
570 mkLW_ = ptext SLIT("(LW_)") -- StgWord64
573 -- ---------------------------------------------------------------------
577 -- Generating assignments is what we're all about, here
579 pprAssign :: CmmReg -> CmmExpr -> SDoc
581 -- dest is a reg, rhs is a reg
582 pprAssign r1 (CmmReg r2)
583 | not (isStrangeTypeReg r1) && not (isStrangeTypeReg r2)
584 || isPtrReg r1 && isPtrReg r2
585 = hcat [ pprAsPtrReg r1, equals, pprAsPtrReg r2, semi ]
587 -- dest is a reg, rhs is a CmmRegOff
588 pprAssign r1 (CmmRegOff r2 off)
589 | not (isStrangeTypeReg r1) && not (isStrangeTypeReg r2)
590 || isPtrReg r1 && isPtrReg r2
591 = hcat [ pprAsPtrReg r1, equals, pprAsPtrReg r2, op, int off', semi ]
593 off1 | isPtrReg r2 = off `shiftR` wordShift
596 (op,off') | off >= 0 = (char '+', off1)
597 | otherwise = (char '-', -off1)
599 -- dest is a reg, rhs is anything.
600 -- We can't cast the lvalue, so we have to cast the rhs if necessary. Casting
601 -- the lvalue elicits a warning from new GCC versions (3.4+).
604 = pprAsPtrReg r1 <> ptext SLIT(" = ") <> mkP_ <> pprExpr1 r2 <> semi
605 | Just ty <- strangeRegType r1
606 = pprReg r1 <> ptext SLIT(" = ") <> parens ty <> pprExpr1 r2 <> semi
608 = pprReg r1 <> ptext SLIT(" = ") <> pprExpr r2 <> semi
610 -- ---------------------------------------------------------------------
614 | isStrangeTypeReg reg = mkW_ <> pprReg reg
615 | otherwise = pprReg reg
617 -- True if the register has type StgPtr in C, otherwise it has an
618 -- integer type. We need to take care with pointer arithmetic on registers
620 isPtrReg :: CmmReg -> Bool
621 isPtrReg (CmmLocal _) = False
622 isPtrReg (CmmGlobal r) = isPtrGlobalReg r
624 isPtrGlobalReg :: GlobalReg -> Bool
625 isPtrGlobalReg (VanillaReg n) = True
626 isPtrGlobalReg Sp = True
627 isPtrGlobalReg Hp = True
628 isPtrGlobalReg HpLim = True
629 isPtrGlobalReg SpLim = True
630 isPtrGlobalReg _ = False
632 -- True if in C this register doesn't have the type given by
633 -- (machRepCType (cmmRegRep reg)), so it has to be cast.
634 isStrangeTypeReg :: CmmReg -> Bool
635 isStrangeTypeReg (CmmLocal _) = False
636 isStrangeTypeReg (CmmGlobal g) = isStrangeTypeGlobal g
638 isStrangeTypeGlobal :: GlobalReg -> Bool
639 isStrangeTypeGlobal CurrentTSO = True
640 isStrangeTypeGlobal CurrentNursery = True
641 isStrangeTypeGlobal r = isPtrGlobalReg r
643 strangeRegType :: CmmReg -> Maybe SDoc
644 strangeRegType (CmmGlobal CurrentTSO) = Just (ptext SLIT("struct StgTSO_ *"))
645 strangeRegType (CmmGlobal CurrentNursery) = Just (ptext SLIT("struct bdescr_ *"))
646 strangeRegType _ = Nothing
648 -- pprReg just prints the register name.
650 pprReg :: CmmReg -> SDoc
652 CmmLocal local -> pprLocalReg local
653 CmmGlobal global -> pprGlobalReg global
655 pprAsPtrReg :: CmmReg -> SDoc
656 pprAsPtrReg (CmmGlobal (VanillaReg n)) = char 'R' <> int n <> ptext SLIT(".p")
657 pprAsPtrReg other_reg = pprReg other_reg
659 pprGlobalReg :: GlobalReg -> SDoc
660 pprGlobalReg gr = case gr of
661 VanillaReg n -> char 'R' <> int n <> ptext SLIT(".w")
662 FloatReg n -> char 'F' <> int n
663 DoubleReg n -> char 'D' <> int n
664 LongReg n -> char 'L' <> int n
665 Sp -> ptext SLIT("Sp")
666 SpLim -> ptext SLIT("SpLim")
667 Hp -> ptext SLIT("Hp")
668 HpLim -> ptext SLIT("HpLim")
669 CurrentTSO -> ptext SLIT("CurrentTSO")
670 CurrentNursery -> ptext SLIT("CurrentNursery")
671 HpAlloc -> ptext SLIT("HpAlloc")
672 BaseReg -> ptext SLIT("BaseReg")
673 GCEnter1 -> ptext SLIT("stg_gc_enter_1")
674 GCFun -> ptext SLIT("stg_gc_fun")
676 pprLocalReg :: LocalReg -> SDoc
677 pprLocalReg (LocalReg uniq _rep) = char '_' <> ppr uniq
679 -- -----------------------------------------------------------------------------
682 pprCall :: SDoc -> CCallConv -> [(CmmReg,MachHint)] -> [(CmmExpr,MachHint)]
683 -> Maybe [GlobalReg] -> SDoc
685 pprCall ppr_fn cconv results args vols
686 | not (is_cish cconv)
687 = panic "pprForeignCall: unknown calling convention"
691 ptext SLIT("CALLER_SAVE_SYSTEM") $$
692 hcat [ ppr_results results, ppr_fn,
693 parens (commafy (map pprArg args)), semi ] $$
694 ptext SLIT("CALLER_RESTORE_SYSTEM") $$
697 ppr_results [] = empty
698 ppr_results [(one,hint)]
699 = pprExpr (CmmReg one) <> ptext SLIT(" = ")
700 <> pprUnHint hint (cmmRegRep one)
701 ppr_results _other = panic "pprCall: multiple results"
703 pprArg (expr, PtrHint)
704 = cCast (ptext SLIT("void *")) expr
705 -- see comment by machRepHintCType below
706 pprArg (expr, SignedHint)
707 = cCast (machRepSignedCType (cmmExprRep expr)) expr
708 pprArg (expr, _other)
711 pprUnHint PtrHint rep = parens (machRepCType rep)
712 pprUnHint SignedHint rep = parens (machRepCType rep)
713 pprUnHint _ _ = empty
715 save = save_restore SLIT("CALLER_SAVE")
716 restore = save_restore SLIT("CALLER_RESTORE")
718 -- Nothing says "I don't know what's live; save everything"
719 -- CALLER_SAVE_USER is defined in ghc/includes/Regs.h
720 save_restore txt Nothing = ptext txt <> ptext SLIT("_USER")
721 save_restore txt (Just these) = vcat (map saveRestoreGlobal these)
722 where saveRestoreGlobal r = ptext txt <> char '_' <> pprGlobalRegName r
724 pprGlobalRegName :: GlobalReg -> SDoc
725 pprGlobalRegName gr = case gr of
726 VanillaReg n -> char 'R' <> int n -- without the .w suffix
729 is_cish CCallConv = True
730 is_cish StdCallConv = True
733 -- ---------------------------------------------------------------------
734 -- Find and print local and external declarations for a list of
737 pprTempAndExternDecls :: [CmmBasicBlock] -> (SDoc{-temps-}, SDoc{-externs-})
738 pprTempAndExternDecls stmts
739 = (vcat (map pprTempDecl (eltsUFM temps)),
740 vcat (map (pprExternDecl False{-ToDo-}) (keysFM lbls)))
741 where (temps, lbls) = runTE (mapM_ te_BB stmts)
743 pprDataExterns :: [CmmStatic] -> SDoc
744 pprDataExterns statics
745 = vcat (map (pprExternDecl False{-ToDo-}) (keysFM lbls))
746 where (_, lbls) = runTE (mapM_ te_Static statics)
748 pprTempDecl :: LocalReg -> SDoc
749 pprTempDecl l@(LocalReg _uniq rep)
750 = hcat [ machRepCType rep, space, pprLocalReg l, semi ]
752 pprExternDecl :: Bool -> CLabel -> SDoc
753 pprExternDecl in_srt lbl
754 -- do not print anything for "known external" things
755 | not (needsCDecl lbl) = empty
757 hcat [ visibility, label_type (labelType lbl),
758 lparen, dyn_wrapper (pprCLabel lbl), text ");" ]
761 | in_srt && labelDynamic lbl = text "DLL_IMPORT_DATA_VAR" <> parens d
764 label_type CodeLabel = ptext SLIT("F_")
765 label_type DataLabel = ptext SLIT("I_")
768 | externallyVisibleCLabel lbl = char 'E'
769 | otherwise = char 'I'
772 type TEState = (UniqSet LocalReg, FiniteMap CLabel ())
773 newtype TE a = TE { unTE :: TEState -> (a, TEState) }
775 instance Monad TE where
776 TE m >>= k = TE $ \s -> case m s of (a, s') -> unTE (k a) s'
777 return a = TE $ \s -> (a, s)
779 te_lbl :: CLabel -> TE ()
780 te_lbl lbl = TE $ \(temps,lbls) -> ((), (temps, addToFM lbls lbl ()))
782 te_temp :: LocalReg -> TE ()
783 te_temp r = TE $ \(temps,lbls) -> ((), (addOneToUniqSet temps r, lbls))
785 runTE :: TE () -> TEState
786 runTE (TE m) = snd (m (emptyUniqSet, emptyFM))
788 te_Static :: CmmStatic -> TE ()
789 te_Static (CmmStaticLit lit) = te_Lit lit
790 te_Static _ = return ()
792 te_BB :: CmmBasicBlock -> TE ()
793 te_BB (BasicBlock _ ss) = mapM_ te_Stmt ss
795 te_Lit :: CmmLit -> TE ()
796 te_Lit (CmmLabel l) = te_lbl l
797 te_Lit (CmmLabelOff l _) = te_lbl l
798 te_Lit (CmmLabelDiffOff l1 l2 _) = te_lbl l1
801 te_Stmt :: CmmStmt -> TE ()
802 te_Stmt (CmmAssign r e) = te_Reg r >> te_Expr e
803 te_Stmt (CmmStore l r) = te_Expr l >> te_Expr r
804 te_Stmt (CmmCall _ rs es _) = mapM_ (te_Reg.fst) rs >>
805 mapM_ (te_Expr.fst) es
806 te_Stmt (CmmCondBranch e _) = te_Expr e
807 te_Stmt (CmmSwitch e _) = te_Expr e
808 te_Stmt (CmmJump e _) = te_Expr e
809 te_Stmt _ = return ()
811 te_Expr :: CmmExpr -> TE ()
812 te_Expr (CmmLit lit) = te_Lit lit
813 te_Expr (CmmReg r) = te_Reg r
814 te_Expr (CmmLoad e _) = te_Expr e
815 te_Expr (CmmMachOp _ es) = mapM_ te_Expr es
816 te_Expr (CmmRegOff r _) = te_Reg r
817 te_Expr _ = return ()
819 te_Reg :: CmmReg -> TE ()
820 te_Reg (CmmLocal l) = te_temp l
824 -- ---------------------------------------------------------------------
825 -- C types for MachReps
827 cCast :: SDoc -> CmmExpr -> SDoc
828 cCast ty expr = parens ty <> pprExpr1 expr
830 -- This is for finding the types of foreign call arguments. For a pointer
831 -- argument, we always cast the argument to (void *), to avoid warnings from
833 machRepHintCType :: MachRep -> MachHint -> SDoc
834 machRepHintCType rep PtrHint = ptext SLIT("void *")
835 machRepHintCType rep SignedHint = machRepSignedCType rep
836 machRepHintCType rep _other = machRepCType rep
838 machRepPtrCType :: MachRep -> SDoc
839 machRepPtrCType r | r == wordRep = ptext SLIT("P_")
840 | otherwise = machRepCType r <> char '*'
842 machRepCType :: MachRep -> SDoc
843 machRepCType r | r == wordRep = ptext SLIT("W_")
844 | otherwise = sized_type
845 where sized_type = case r of
846 I8 -> ptext SLIT("StgWord8")
847 I16 -> ptext SLIT("StgWord16")
848 I32 -> ptext SLIT("StgWord32")
849 I64 -> ptext SLIT("StgWord64")
850 F32 -> ptext SLIT("StgFloat") -- ToDo: correct?
851 F64 -> ptext SLIT("StgDouble")
852 _ -> panic "machRepCType"
854 machRepSignedCType :: MachRep -> SDoc
855 machRepSignedCType r | r == wordRep = ptext SLIT("I_")
856 | otherwise = sized_type
857 where sized_type = case r of
858 I8 -> ptext SLIT("StgInt8")
859 I16 -> ptext SLIT("StgInt16")
860 I32 -> ptext SLIT("StgInt32")
861 I64 -> ptext SLIT("StgInt64")
862 F32 -> ptext SLIT("StgFloat") -- ToDo: correct?
863 F64 -> ptext SLIT("StgDouble")
864 _ -> panic "machRepCType"
866 -- ---------------------------------------------------------------------
867 -- print strings as valid C strings
869 -- Assumes it contains only characters '\0'..'\xFF'!
870 pprFSInCStyle :: FastString -> SDoc
871 pprFSInCStyle fs = pprStringInCStyle (unpackFS fs)
873 pprStringInCStyle :: String -> SDoc
874 pprStringInCStyle s = doubleQuotes (text (concatMap charToC s))
876 charToC :: Char -> String
877 charToC '\"' = "\\\""
878 charToC '\'' = "\\\'"
879 charToC '\\' = "\\\\"
880 charToC c | c >= ' ' && c <= '~' = [c]
881 | c > '\xFF' = panic ("charToC "++show c)
883 chr (ord '0' + ord c `div` 64),
884 chr (ord '0' + ord c `div` 8 `mod` 8),
885 chr (ord '0' + ord c `mod` 8)]
888 -- ---------------------------------------------------------------------------
889 -- Initialising static objects with floating-point numbers. We can't
890 -- just emit the floating point number, because C will cast it to an int
891 -- by rounding it. We want the actual bit-representation of the float.
893 -- This is a hack to turn the floating point numbers into ints that we
894 -- can safely initialise to static locations.
897 | machRepByteWidth F64 == 2 * wORD_SIZE = True
898 | machRepByteWidth F64 == wORD_SIZE = False
899 | otherwise = panic "big_doubles"
901 #if __GLASGOW_HASKELL__ >= 504
902 newFloatArray :: (Int,Int) -> ST s (STUArray s Int Float)
903 newFloatArray = newArray_
905 newDoubleArray :: (Int,Int) -> ST s (STUArray s Int Double)
906 newDoubleArray = newArray_
908 castFloatToIntArray :: STUArray s Int Float -> ST s (STUArray s Int Int)
909 castFloatToIntArray = castSTUArray
911 castDoubleToIntArray :: STUArray s Int Double -> ST s (STUArray s Int Int)
912 castDoubleToIntArray = castSTUArray
914 writeFloatArray :: STUArray s Int Float -> Int -> Float -> ST s ()
915 writeFloatArray = writeArray
917 writeDoubleArray :: STUArray s Int Double -> Int -> Double -> ST s ()
918 writeDoubleArray = writeArray
920 readIntArray :: STUArray s Int Int -> Int -> ST s Int
921 readIntArray = readArray
925 castFloatToIntArray :: MutableByteArray s t -> ST s (MutableByteArray s t)
926 castFloatToIntArray = return
928 castDoubleToIntArray :: MutableByteArray s t -> ST s (MutableByteArray s t)
929 castDoubleToIntArray = return
933 -- floats are always 1 word
934 floatToWord :: Rational -> CmmLit
937 arr <- newFloatArray ((0::Int),0)
938 writeFloatArray arr 0 (fromRational r)
939 arr' <- castFloatToIntArray arr
940 i <- readIntArray arr' 0
941 return (CmmInt (toInteger i) wordRep)
944 doubleToWords :: Rational -> [CmmLit]
946 | big_doubles -- doubles are 2 words
948 arr <- newDoubleArray ((0::Int),1)
949 writeDoubleArray arr 0 (fromRational r)
950 arr' <- castDoubleToIntArray arr
951 i1 <- readIntArray arr' 0
952 i2 <- readIntArray arr' 1
953 return [ CmmInt (toInteger i1) wordRep
954 , CmmInt (toInteger i2) wordRep
957 | otherwise -- doubles are 1 word
959 arr <- newDoubleArray ((0::Int),0)
960 writeDoubleArray arr 0 (fromRational r)
961 arr' <- castDoubleToIntArray arr
962 i <- readIntArray arr' 0
963 return [ CmmInt (toInteger i) wordRep ]
966 -- ---------------------------------------------------------------------------
970 wordShift = machRepLogWidth wordRep
972 commafy :: [SDoc] -> SDoc
973 commafy xs = hsep $ punctuate comma xs
975 -- Print in C hex format: 0x13fa
976 pprHexVal :: Integer -> MachRep -> SDoc
977 pprHexVal 0 _ = ptext SLIT("0x0")
979 | w < 0 = parens (char '-' <> ptext SLIT("0x") <> go (-w) <> repsuffix rep)
980 | otherwise = ptext SLIT("0x") <> go w <> repsuffix rep
982 -- type suffix for literals:
983 -- on 32-bit platforms, add "LL" to 64-bit literals
984 repsuffix I64 | wORD_SIZE == 4 = ptext SLIT("LL")
985 -- on 64-bit platforms with 32-bit int, add "L" to 64-bit literals
986 repsuffix I64 | cINT_SIZE == 4 = ptext SLIT("L")
992 (q,r) = w' `quotRem` 16
993 dig | r < 10 = char (chr (fromInteger r + ord '0'))
994 | otherwise = char (chr (fromInteger r - 10 + ord 'a'))