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 DynFlags ( DynFlags, DynFlag(..), dopt )
34 import Unique ( getUnique )
37 import UniqFM ( eltsUFM )
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 :: DynFlags -> [Cmm] -> SDoc
64 = pprCode CStyle (vcat $ map (\c -> split_marker $$ pprC c) cmms)
67 | dopt Opt_SplitObjs dflags = ptext SLIT("__STG_SPLIT_MARKER")
70 writeCs :: DynFlags -> Handle -> [Cmm] -> IO ()
71 writeCs dflags handle cmms
72 = printForUser handle alwaysQualify (pprCs dflags cmms)
73 -- ToDo: should be printForC
75 -- --------------------------------------------------------------------------
76 -- Now do some real work
78 -- for fun, we could call cmmToCmm over the tops...
82 pprC (Cmm tops) = vcat $ intersperse (text "") $ map pprTop tops
87 pprTop :: CmmTop -> SDoc
88 pprTop (CmmProc info clbl _params blocks) =
90 then pprDataExterns info $$
91 pprWordArray (entryLblToInfoLbl clbl) info
95 -- the first block doesn't get a label:
96 (BasicBlock _ stmts : rest) -> vcat [
99 (if (externallyVisibleCLabel clbl)
100 then mkFN_ else mkIF_) (pprCLabel clbl) <+> lbrace,
103 nest 8 (vcat (map pprStmt stmts)) $$
104 vcat (map pprBBlock rest),
109 (temp_decls, extern_decls) = pprTempAndExternDecls blocks
112 -- Chunks of static data.
114 -- We only handle (a) arrays of word-sized things and (b) strings.
116 pprTop (CmmData _section _ds@[CmmDataLabel lbl, CmmString str]) =
118 pprLocalness lbl, ptext SLIT("char "), pprCLabel lbl,
119 ptext SLIT("[] = "), pprStringInCStyle str, semi
122 pprTop (CmmData _section _ds@[CmmDataLabel lbl, CmmUninitialised size]) =
124 pprLocalness lbl, ptext SLIT("char "), pprCLabel lbl,
125 brackets (int size), semi
128 pprTop top@(CmmData _section (CmmDataLabel lbl : lits)) =
129 pprDataExterns lits $$
130 pprWordArray lbl lits
132 -- these shouldn't appear?
133 pprTop (CmmData _ _) = panic "PprC.pprTop: can't handle this data"
136 -- --------------------------------------------------------------------------
137 -- BasicBlocks are self-contained entities: they always end in a jump.
139 -- Like nativeGen/AsmCodeGen, we could probably reorder blocks to turn
140 -- as many jumps as possible into fall throughs.
143 pprBBlock :: CmmBasicBlock -> SDoc
144 pprBBlock (BasicBlock lbl stmts) =
146 pprTrace "pprC.pprBBlock: curious empty code block for"
147 (pprBlockId lbl) empty
149 nest 4 (pprBlockId lbl <> colon) $$
150 nest 8 (vcat (map pprStmt stmts))
152 -- --------------------------------------------------------------------------
153 -- Info tables. Just arrays of words.
154 -- See codeGen/ClosureInfo, and nativeGen/PprMach
156 pprWordArray :: CLabel -> [CmmStatic] -> SDoc
158 = hcat [ pprLocalness lbl, ptext SLIT("StgWord")
159 , space, pprCLabel lbl, ptext SLIT("[] = {") ]
160 $$ nest 8 (commafy (pprStatics ds))
164 -- has to be static, if it isn't globally visible
166 pprLocalness :: CLabel -> SDoc
167 pprLocalness lbl | not $ externallyVisibleCLabel lbl = ptext SLIT("static ")
170 -- --------------------------------------------------------------------------
174 pprStmt :: CmmStmt -> SDoc
176 pprStmt stmt = case stmt of
178 CmmComment s -> (hang (ptext SLIT("/*")) 3 (ftext s)) $$ ptext SLIT("*/")
180 CmmAssign dest src -> pprAssign dest src
183 | rep == I64 && wordRep /= I64
184 -> ptext SLIT("ASSIGN_Word64") <>
185 parens (mkP_ <> pprExpr1 dest <> comma <> pprExpr src) <> semi
188 -> hsep [ pprExpr (CmmLoad dest rep), equals, pprExpr src <> semi ]
192 CmmCall (CmmForeignCall fn cconv) results args volatile ->
193 -- Controversial: leave this out for now.
196 pprCall ppr_fn cconv results args volatile
199 CmmLit (CmmLabel lbl) -> pprCLabel lbl
200 _other -> parens (cCast (pprCFunType cconv results args) fn)
201 -- for a dynamic call, cast the expression to
202 -- a function of the right type (we hope).
204 -- we #undef a function before calling it: the FFI is supposed to be
205 -- an interface specifically to C, not to C+CPP. For one thing, this
206 -- makes the via-C route more compatible with the NCG. If macros
207 -- are being used for optimisation, then inline functions are probably
209 pprUndef (CmmLit (CmmLabel lbl)) =
210 ptext SLIT("#undef") <+> pprCLabel lbl
213 CmmCall (CmmPrim op) results args volatile ->
214 pprCall ppr_fn CCallConv results args volatile
216 ppr_fn = pprCallishMachOp_for_C op
218 CmmBranch ident -> pprBranch ident
219 CmmCondBranch expr ident -> pprCondBranch expr ident
220 CmmJump lbl _params -> mkJMP_(pprExpr lbl) <> semi
221 CmmSwitch arg ids -> pprSwitch arg ids
223 pprCFunType :: CCallConv -> [(CmmReg,MachHint)] -> [(CmmExpr,MachHint)] -> SDoc
224 pprCFunType cconv ress args
227 parens (text (ccallConvAttribute cconv) <> char '*'),
228 parens (commafy (map arg_type args))
231 res_type [] = ptext SLIT("void")
232 res_type [(one,hint)] = machRepHintCType (cmmRegRep one) hint
234 arg_type (expr,hint) = machRepHintCType (cmmExprRep expr) hint
236 -- ---------------------------------------------------------------------
237 -- unconditional branches
238 pprBranch :: BlockId -> SDoc
239 pprBranch ident = ptext SLIT("goto") <+> pprBlockId ident <> semi
242 -- ---------------------------------------------------------------------
243 -- conditional branches to local labels
244 pprCondBranch :: CmmExpr -> BlockId -> SDoc
245 pprCondBranch expr ident
246 = hsep [ ptext SLIT("if") , parens(pprExpr expr) ,
247 ptext SLIT("goto") , (pprBlockId ident) <> semi ]
250 -- ---------------------------------------------------------------------
251 -- a local table branch
253 -- we find the fall-through cases
255 -- N.B. we remove Nothing's from the list of branches, as they are
256 -- 'undefined'. However, they may be defined one day, so we better
257 -- document this behaviour.
259 pprSwitch :: CmmExpr -> [ Maybe BlockId ] -> SDoc
260 pprSwitch e maybe_ids
261 = let pairs = [ (ix, ident) | (ix,Just ident) <- zip [0..] maybe_ids ]
262 pairs2 = [ (map fst as, snd (head as)) | as <- groupBy sndEq pairs ]
264 (hang (ptext SLIT("switch") <+> parens ( pprExpr e ) <+> lbrace)
265 4 (vcat ( map caseify pairs2 )))
269 sndEq (_,x) (_,y) = x == y
272 caseify (ix:ixs, ident) = vcat (map do_fallthrough ixs) $$ final_branch ix
275 hsep [ ptext SLIT("case") , pprHexVal ix wordRep <> colon ,
276 ptext SLIT("/* fall through */") ]
279 hsep [ ptext SLIT("case") , pprHexVal ix wordRep <> colon ,
280 ptext SLIT("goto") , (pprBlockId ident) <> semi ]
282 -- ---------------------------------------------------------------------
286 -- C Types: the invariant is that the C expression generated by
290 -- has a type in C which is also given by
292 -- machRepCType (cmmExprRep e)
294 -- (similar invariants apply to the rest of the pretty printer).
296 pprExpr :: CmmExpr -> SDoc
297 pprExpr e = case e of
298 CmmLit lit -> pprLit lit
300 CmmLoad e I64 | wordRep /= I64
301 -> ptext SLIT("PK_Word64") <> parens (mkP_ <> pprExpr1 e)
303 CmmLoad (CmmReg r) rep
304 | isPtrReg r && rep == wordRep
305 -> char '*' <> pprAsPtrReg r
307 CmmLoad (CmmRegOff r 0) rep
308 | isPtrReg r && rep == wordRep
309 -> char '*' <> pprAsPtrReg r
311 CmmLoad (CmmRegOff r off) rep
312 | isPtrReg r && rep == wordRep
313 -- ToDo: check that the offset is a word multiple?
314 -> pprAsPtrReg r <> brackets (ppr (off `shiftR` wordShift))
318 char '*' <> parens (cCast (machRepPtrCType rep) expr)
320 CmmReg reg -> pprCastReg reg
321 CmmRegOff reg 0 -> pprCastReg reg
324 | i > 0 -> pprRegOff (char '+') i
325 | otherwise -> pprRegOff (char '-') (-i)
327 pprRegOff op i' = pprCastReg reg <> op <> int i'
329 CmmMachOp mop args -> pprMachOpApp mop args
331 pprExpr1 :: CmmExpr -> SDoc
332 pprExpr1 (CmmLit lit) = pprLit1 lit
333 pprExpr1 e@(CmmReg _reg) = pprExpr e
334 pprExpr1 other = parens (pprExpr other)
336 -- --------------------------------------------------------------------------
337 -- MachOp applications
339 pprMachOpApp :: MachOp -> [CmmExpr] -> SDoc
343 = ptext SLIT("mulIntMayOflo") <> parens (commafy (map pprExpr args))
344 where isMulMayOfloOp (MO_U_MulMayOflo _) = True
345 isMulMayOfloOp (MO_S_MulMayOflo _) = True
346 isMulMayOfloOp _ = False
348 pprMachOpApp mop args
351 [x,y] -> pprArg x <+> pprMachOp_for_C mop <+> pprArg y
354 [x] -> pprMachOp_for_C mop <> parens (pprArg x)
356 _ -> panic "PprC.pprMachOp : machop with wrong number of args"
359 pprArg e | signedOp mop = cCast (machRepSignedCType (cmmExprRep e)) e
360 | otherwise = pprExpr1 e
362 -- --------------------------------------------------------------------------
365 pprLit :: CmmLit -> SDoc
366 pprLit lit = case lit of
367 CmmInt i rep -> pprHexVal i rep
368 CmmFloat f rep -> parens (machRepCType rep) <> (rational f)
369 CmmLabel clbl -> mkW_ <> pprCLabel clbl
370 CmmLabelOff clbl i -> mkW_ <> pprCLabel clbl <> char '+' <> int i
371 CmmLabelDiffOff clbl1 clbl2 i
373 -- * the lit must occur in the info table clbl2
374 -- * clbl1 must be an SRT, a slow entry point or a large bitmap
375 -- The Mangler is expected to convert any reference to an SRT,
376 -- a slow entry point or a large bitmap
377 -- from an info table to an offset.
378 -> mkW_ <> pprCLabel clbl1 <> char '+' <> int i
380 pprLit1 :: CmmLit -> SDoc
381 pprLit1 lit@(CmmLabelOff _ _) = parens (pprLit lit)
382 pprLit1 lit@(CmmLabelDiffOff _ _ _) = parens (pprLit lit)
383 pprLit1 lit@(CmmFloat _ _) = parens (pprLit lit)
384 pprLit1 other = pprLit other
386 -- ---------------------------------------------------------------------------
389 pprStatics :: [CmmStatic] -> [SDoc]
391 pprStatics (CmmStaticLit (CmmFloat f F32) : rest)
392 = pprLit1 (floatToWord f) : pprStatics rest
393 pprStatics (CmmStaticLit (CmmFloat f F64) : rest)
394 = map pprLit1 (doubleToWords f) ++ pprStatics rest
395 pprStatics (CmmStaticLit (CmmInt i I64) : rest)
396 | machRepByteWidth I32 == wORD_SIZE
397 #ifdef WORDS_BIGENDIAN
398 = pprStatics (CmmStaticLit (CmmInt q I32) :
399 CmmStaticLit (CmmInt r I32) : rest)
401 = pprStatics (CmmStaticLit (CmmInt r I32) :
402 CmmStaticLit (CmmInt q I32) : rest)
404 where r = i .&. 0xffffffff
406 pprStatics (CmmStaticLit lit : rest)
407 = pprLit1 lit : pprStatics rest
408 pprStatics (other : rest)
409 = pprPanic "pprWord" (pprStatic other)
411 pprStatic :: CmmStatic -> SDoc
412 pprStatic s = case s of
414 CmmStaticLit lit -> nest 4 (pprLit lit)
415 CmmAlign i -> nest 4 (ptext SLIT("/* align */") <+> int i)
416 CmmDataLabel clbl -> pprCLabel clbl <> colon
417 CmmUninitialised i -> nest 4 (mkC_ <> brackets (int i))
419 -- these should be inlined, like the old .hc
420 CmmString s' -> nest 4 (mkW_ <> parens(pprStringInCStyle s'))
423 -- ---------------------------------------------------------------------------
426 pprBlockId :: BlockId -> SDoc
427 pprBlockId b = char '_' <> ppr (getUnique b)
429 -- --------------------------------------------------------------------------
430 -- Print a MachOp in a way suitable for emitting via C.
433 pprMachOp_for_C :: MachOp -> SDoc
435 pprMachOp_for_C mop = case mop of
437 -- Integer operations
440 MO_Eq _ -> ptext SLIT("==")
441 MO_Ne _ -> ptext SLIT("!=")
444 MO_S_Quot _ -> char '/'
445 MO_S_Rem _ -> char '%'
446 MO_S_Neg _ -> char '-'
448 MO_U_Quot _ -> char '/'
449 MO_U_Rem _ -> char '%'
451 -- Signed comparisons (floating-point comparisons also use these)
452 -- & Unsigned comparisons
453 MO_S_Ge _ -> ptext SLIT(">=")
454 MO_S_Le _ -> ptext SLIT("<=")
455 MO_S_Gt _ -> char '>'
456 MO_S_Lt _ -> char '<'
458 MO_U_Ge _ -> ptext SLIT(">=")
459 MO_U_Le _ -> ptext SLIT("<=")
460 MO_U_Gt _ -> char '>'
461 MO_U_Lt _ -> char '<'
463 -- Bitwise operations. Not all of these may be supported at all
464 -- sizes, and only integral MachReps are valid.
469 MO_Shl _ -> ptext SLIT("<<")
470 MO_U_Shr _ -> ptext SLIT(">>") -- unsigned shift right
471 MO_S_Shr _ -> ptext SLIT(">>") -- signed shift right
473 -- Conversions. Some of these will be NOPs.
474 -- Floating-point conversions use the signed variant.
475 -- We won't know to generate (void*) casts here, but maybe from
479 MO_U_Conv I8 I8 -> empty
480 MO_U_Conv I16 I16 -> empty
481 MO_U_Conv I32 I32 -> empty
482 MO_U_Conv I64 I64 -> empty
483 MO_U_Conv I128 I128 -> empty
484 MO_S_Conv I8 I8 -> empty
485 MO_S_Conv I16 I16 -> empty
486 MO_S_Conv I32 I32 -> empty
487 MO_S_Conv I64 I64 -> empty
488 MO_S_Conv I128 I128 -> empty
490 MO_U_Conv _from to -> parens (machRepCType to)
491 MO_S_Conv _from to -> parens (machRepSignedCType to)
493 _ -> panic "PprC.pprMachOp_for_C: unknown machop"
495 signedOp :: MachOp -> Bool
496 signedOp (MO_S_Quot _) = True
497 signedOp (MO_S_Rem _) = True
498 signedOp (MO_S_Neg _) = True
499 signedOp (MO_S_Ge _) = True
500 signedOp (MO_S_Le _) = True
501 signedOp (MO_S_Gt _) = True
502 signedOp (MO_S_Lt _) = True
503 signedOp (MO_S_Shr _) = True
504 signedOp (MO_S_Conv _ _) = True
507 -- ---------------------------------------------------------------------
508 -- tend to be implemented by foreign calls
510 pprCallishMachOp_for_C :: CallishMachOp -> SDoc
512 pprCallishMachOp_for_C mop
514 MO_F64_Pwr -> ptext SLIT("pow")
515 MO_F64_Sin -> ptext SLIT("sin")
516 MO_F64_Cos -> ptext SLIT("cos")
517 MO_F64_Tan -> ptext SLIT("tan")
518 MO_F64_Sinh -> ptext SLIT("sinh")
519 MO_F64_Cosh -> ptext SLIT("cosh")
520 MO_F64_Tanh -> ptext SLIT("tanh")
521 MO_F64_Asin -> ptext SLIT("asin")
522 MO_F64_Acos -> ptext SLIT("acos")
523 MO_F64_Atan -> ptext SLIT("atan")
524 MO_F64_Log -> ptext SLIT("log")
525 MO_F64_Exp -> ptext SLIT("exp")
526 MO_F64_Sqrt -> ptext SLIT("sqrt")
527 MO_F32_Pwr -> ptext SLIT("pow")
528 MO_F32_Sin -> ptext SLIT("sin")
529 MO_F32_Cos -> ptext SLIT("cos")
530 MO_F32_Tan -> ptext SLIT("tan")
531 MO_F32_Sinh -> ptext SLIT("sinh")
532 MO_F32_Cosh -> ptext SLIT("cosh")
533 MO_F32_Tanh -> ptext SLIT("tanh")
534 MO_F32_Asin -> ptext SLIT("asin")
535 MO_F32_Acos -> ptext SLIT("acos")
536 MO_F32_Atan -> ptext SLIT("atan")
537 MO_F32_Log -> ptext SLIT("log")
538 MO_F32_Exp -> ptext SLIT("exp")
539 MO_F32_Sqrt -> ptext SLIT("sqrt")
541 -- ---------------------------------------------------------------------
545 mkJMP_, mkFN_, mkIF_ :: SDoc -> SDoc
547 mkJMP_ i = ptext SLIT("JMP_") <> parens i
548 mkFN_ i = ptext SLIT("FN_") <> parens i -- externally visible function
549 mkIF_ i = ptext SLIT("IF_") <> parens i -- locally visible
553 mkFB_ = ptext SLIT("FB_") -- function code begin
554 mkFE_ = ptext SLIT("FE_") -- function code end
556 -- from includes/Stg.h
558 mkC_,mkW_,mkP_,mkPP_,mkI_,mkA_,mkD_,mkF_,mkB_,mkL_,mkLI_,mkLW_ :: SDoc
560 mkC_ = ptext SLIT("(C_)") -- StgChar
561 mkW_ = ptext SLIT("(W_)") -- StgWord
562 mkP_ = ptext SLIT("(P_)") -- StgWord*
563 mkPP_ = ptext SLIT("(PP_)") -- P_*
564 mkI_ = ptext SLIT("(I_)") -- StgInt
565 mkA_ = ptext SLIT("(A_)") -- StgAddr
566 mkD_ = ptext SLIT("(D_)") -- const StgWord*
567 mkF_ = ptext SLIT("(F_)") -- StgFunPtr
568 mkB_ = ptext SLIT("(B_)") -- StgByteArray
569 mkL_ = ptext SLIT("(L_)") -- StgClosurePtr
571 mkLI_ = ptext SLIT("(LI_)") -- StgInt64
572 mkLW_ = ptext SLIT("(LW_)") -- StgWord64
575 -- ---------------------------------------------------------------------
579 -- Generating assignments is what we're all about, here
581 pprAssign :: CmmReg -> CmmExpr -> SDoc
583 -- dest is a reg, rhs is a reg
584 pprAssign r1 (CmmReg r2)
585 | not (isStrangeTypeReg r1) && not (isStrangeTypeReg r2)
586 || isPtrReg r1 && isPtrReg r2
587 = hcat [ pprAsPtrReg r1, equals, pprAsPtrReg r2, semi ]
589 -- dest is a reg, rhs is a CmmRegOff
590 pprAssign r1 (CmmRegOff r2 off)
591 | not (isStrangeTypeReg r1) && not (isStrangeTypeReg r2)
592 || isPtrReg r1 && isPtrReg r2
593 = hcat [ pprAsPtrReg r1, equals, pprAsPtrReg r2, op, int off', semi ]
595 off1 | isPtrReg r2 = off `shiftR` wordShift
598 (op,off') | off >= 0 = (char '+', off1)
599 | otherwise = (char '-', -off1)
601 -- dest is a reg, rhs is anything.
602 -- We can't cast the lvalue, so we have to cast the rhs if necessary. Casting
603 -- the lvalue elicits a warning from new GCC versions (3.4+).
606 = pprAsPtrReg r1 <> ptext SLIT(" = ") <> mkP_ <> pprExpr1 r2 <> semi
607 | Just ty <- strangeRegType r1
608 = pprReg r1 <> ptext SLIT(" = ") <> parens ty <> pprExpr1 r2 <> semi
610 = pprReg r1 <> ptext SLIT(" = ") <> pprExpr r2 <> semi
612 -- ---------------------------------------------------------------------
616 | isStrangeTypeReg reg = mkW_ <> pprReg reg
617 | otherwise = pprReg reg
619 -- True if the register has type StgPtr in C, otherwise it has an
620 -- integer type. We need to take care with pointer arithmetic on registers
622 isPtrReg :: CmmReg -> Bool
623 isPtrReg (CmmLocal _) = False
624 isPtrReg (CmmGlobal r) = isPtrGlobalReg r
626 isPtrGlobalReg :: GlobalReg -> Bool
627 isPtrGlobalReg (VanillaReg n) = True
628 isPtrGlobalReg Sp = True
629 isPtrGlobalReg Hp = True
630 isPtrGlobalReg HpLim = True
631 isPtrGlobalReg SpLim = True
632 isPtrGlobalReg _ = False
634 -- True if in C this register doesn't have the type given by
635 -- (machRepCType (cmmRegRep reg)), so it has to be cast.
636 isStrangeTypeReg :: CmmReg -> Bool
637 isStrangeTypeReg (CmmLocal _) = False
638 isStrangeTypeReg (CmmGlobal g) = isStrangeTypeGlobal g
640 isStrangeTypeGlobal :: GlobalReg -> Bool
641 isStrangeTypeGlobal CurrentTSO = True
642 isStrangeTypeGlobal CurrentNursery = True
643 isStrangeTypeGlobal r = isPtrGlobalReg r
645 strangeRegType :: CmmReg -> Maybe SDoc
646 strangeRegType (CmmGlobal CurrentTSO) = Just (ptext SLIT("struct StgTSO_ *"))
647 strangeRegType (CmmGlobal CurrentNursery) = Just (ptext SLIT("struct bdescr_ *"))
648 strangeRegType _ = Nothing
650 -- pprReg just prints the register name.
652 pprReg :: CmmReg -> SDoc
654 CmmLocal local -> pprLocalReg local
655 CmmGlobal global -> pprGlobalReg global
657 pprAsPtrReg :: CmmReg -> SDoc
658 pprAsPtrReg (CmmGlobal (VanillaReg n)) = char 'R' <> int n <> ptext SLIT(".p")
659 pprAsPtrReg other_reg = pprReg other_reg
661 pprGlobalReg :: GlobalReg -> SDoc
662 pprGlobalReg gr = case gr of
663 VanillaReg n -> char 'R' <> int n <> ptext SLIT(".w")
664 FloatReg n -> char 'F' <> int n
665 DoubleReg n -> char 'D' <> int n
666 LongReg n -> char 'L' <> int n
667 Sp -> ptext SLIT("Sp")
668 SpLim -> ptext SLIT("SpLim")
669 Hp -> ptext SLIT("Hp")
670 HpLim -> ptext SLIT("HpLim")
671 CurrentTSO -> ptext SLIT("CurrentTSO")
672 CurrentNursery -> ptext SLIT("CurrentNursery")
673 HpAlloc -> ptext SLIT("HpAlloc")
674 BaseReg -> ptext SLIT("BaseReg")
675 GCEnter1 -> ptext SLIT("stg_gc_enter_1")
676 GCFun -> ptext SLIT("stg_gc_fun")
678 pprLocalReg :: LocalReg -> SDoc
679 pprLocalReg (LocalReg uniq _rep) = char '_' <> ppr uniq
681 -- -----------------------------------------------------------------------------
684 pprCall :: SDoc -> CCallConv -> [(CmmReg,MachHint)] -> [(CmmExpr,MachHint)]
685 -> Maybe [GlobalReg] -> SDoc
687 pprCall ppr_fn cconv results args vols
688 | not (is_cish cconv)
689 = panic "pprForeignCall: unknown calling convention"
693 ptext SLIT("CALLER_SAVE_SYSTEM") $$
694 hcat [ ppr_results results, ppr_fn,
695 parens (commafy (map pprArg args)), semi ] $$
696 ptext SLIT("CALLER_RESTORE_SYSTEM") $$
699 ppr_results [] = empty
700 ppr_results [(one,hint)]
701 = pprExpr (CmmReg one) <> ptext SLIT(" = ")
702 <> pprUnHint hint (cmmRegRep one)
703 ppr_results _other = panic "pprCall: multiple results"
705 pprArg (expr, PtrHint)
706 = cCast (ptext SLIT("void *")) expr
707 -- see comment by machRepHintCType below
708 pprArg (expr, SignedHint)
709 = cCast (machRepSignedCType (cmmExprRep expr)) expr
710 pprArg (expr, _other)
713 pprUnHint PtrHint rep = parens (machRepCType rep)
714 pprUnHint SignedHint rep = parens (machRepCType rep)
715 pprUnHint _ _ = empty
717 save = save_restore SLIT("CALLER_SAVE")
718 restore = save_restore SLIT("CALLER_RESTORE")
720 -- Nothing says "I don't know what's live; save everything"
721 -- CALLER_SAVE_USER is defined in ghc/includes/Regs.h
722 save_restore txt Nothing = ptext txt <> ptext SLIT("_USER")
723 save_restore txt (Just these) = vcat (map saveRestoreGlobal these)
724 where saveRestoreGlobal r = ptext txt <> char '_' <> pprGlobalRegName r
726 pprGlobalRegName :: GlobalReg -> SDoc
727 pprGlobalRegName gr = case gr of
728 VanillaReg n -> char 'R' <> int n -- without the .w suffix
731 is_cish CCallConv = True
732 is_cish StdCallConv = True
735 -- ---------------------------------------------------------------------
736 -- Find and print local and external declarations for a list of
739 pprTempAndExternDecls :: [CmmBasicBlock] -> (SDoc{-temps-}, SDoc{-externs-})
740 pprTempAndExternDecls stmts
741 = (vcat (map pprTempDecl (eltsUFM temps)),
742 vcat (map (pprExternDecl False{-ToDo-}) (keysFM lbls)))
743 where (temps, lbls) = runTE (mapM_ te_BB stmts)
745 pprDataExterns :: [CmmStatic] -> SDoc
746 pprDataExterns statics
747 = vcat (map (pprExternDecl False{-ToDo-}) (keysFM lbls))
748 where (_, lbls) = runTE (mapM_ te_Static statics)
750 pprTempDecl :: LocalReg -> SDoc
751 pprTempDecl l@(LocalReg _uniq rep)
752 = hcat [ machRepCType rep, space, pprLocalReg l, semi ]
754 pprExternDecl :: Bool -> CLabel -> SDoc
755 pprExternDecl in_srt lbl
756 -- do not print anything for "known external" things
757 | not (needsCDecl lbl) = empty
759 hcat [ visibility, label_type (labelType lbl),
760 lparen, dyn_wrapper (pprCLabel lbl), text ");" ]
763 | in_srt && labelDynamic lbl = text "DLL_IMPORT_DATA_VAR" <> parens d
766 label_type CodeLabel = ptext SLIT("F_")
767 label_type DataLabel = ptext SLIT("I_")
770 | externallyVisibleCLabel lbl = char 'E'
771 | otherwise = char 'I'
774 type TEState = (UniqSet LocalReg, FiniteMap CLabel ())
775 newtype TE a = TE { unTE :: TEState -> (a, TEState) }
777 instance Monad TE where
778 TE m >>= k = TE $ \s -> case m s of (a, s') -> unTE (k a) s'
779 return a = TE $ \s -> (a, s)
781 te_lbl :: CLabel -> TE ()
782 te_lbl lbl = TE $ \(temps,lbls) -> ((), (temps, addToFM lbls lbl ()))
784 te_temp :: LocalReg -> TE ()
785 te_temp r = TE $ \(temps,lbls) -> ((), (addOneToUniqSet temps r, lbls))
787 runTE :: TE () -> TEState
788 runTE (TE m) = snd (m (emptyUniqSet, emptyFM))
790 te_Static :: CmmStatic -> TE ()
791 te_Static (CmmStaticLit lit) = te_Lit lit
792 te_Static _ = return ()
794 te_BB :: CmmBasicBlock -> TE ()
795 te_BB (BasicBlock _ ss) = mapM_ te_Stmt ss
797 te_Lit :: CmmLit -> TE ()
798 te_Lit (CmmLabel l) = te_lbl l
799 te_Lit (CmmLabelOff l _) = te_lbl l
800 te_Lit (CmmLabelDiffOff l1 l2 _) = te_lbl l1
803 te_Stmt :: CmmStmt -> TE ()
804 te_Stmt (CmmAssign r e) = te_Reg r >> te_Expr e
805 te_Stmt (CmmStore l r) = te_Expr l >> te_Expr r
806 te_Stmt (CmmCall _ rs es _) = mapM_ (te_Reg.fst) rs >>
807 mapM_ (te_Expr.fst) es
808 te_Stmt (CmmCondBranch e _) = te_Expr e
809 te_Stmt (CmmSwitch e _) = te_Expr e
810 te_Stmt (CmmJump e _) = te_Expr e
811 te_Stmt _ = return ()
813 te_Expr :: CmmExpr -> TE ()
814 te_Expr (CmmLit lit) = te_Lit lit
815 te_Expr (CmmReg r) = te_Reg r
816 te_Expr (CmmLoad e _) = te_Expr e
817 te_Expr (CmmMachOp _ es) = mapM_ te_Expr es
818 te_Expr (CmmRegOff r _) = te_Reg r
819 te_Expr _ = return ()
821 te_Reg :: CmmReg -> TE ()
822 te_Reg (CmmLocal l) = te_temp l
826 -- ---------------------------------------------------------------------
827 -- C types for MachReps
829 cCast :: SDoc -> CmmExpr -> SDoc
830 cCast ty expr = parens ty <> pprExpr1 expr
832 -- This is for finding the types of foreign call arguments. For a pointer
833 -- argument, we always cast the argument to (void *), to avoid warnings from
835 machRepHintCType :: MachRep -> MachHint -> SDoc
836 machRepHintCType rep PtrHint = ptext SLIT("void *")
837 machRepHintCType rep SignedHint = machRepSignedCType rep
838 machRepHintCType rep _other = machRepCType rep
840 machRepPtrCType :: MachRep -> SDoc
841 machRepPtrCType r | r == wordRep = ptext SLIT("P_")
842 | otherwise = machRepCType r <> char '*'
844 machRepCType :: MachRep -> SDoc
845 machRepCType r | r == wordRep = ptext SLIT("W_")
846 | otherwise = sized_type
847 where sized_type = case r of
848 I8 -> ptext SLIT("StgWord8")
849 I16 -> ptext SLIT("StgWord16")
850 I32 -> ptext SLIT("StgWord32")
851 I64 -> ptext SLIT("StgWord64")
852 F32 -> ptext SLIT("StgFloat") -- ToDo: correct?
853 F64 -> ptext SLIT("StgDouble")
854 _ -> panic "machRepCType"
856 machRepSignedCType :: MachRep -> SDoc
857 machRepSignedCType r | r == wordRep = ptext SLIT("I_")
858 | otherwise = sized_type
859 where sized_type = case r of
860 I8 -> ptext SLIT("StgInt8")
861 I16 -> ptext SLIT("StgInt16")
862 I32 -> ptext SLIT("StgInt32")
863 I64 -> ptext SLIT("StgInt64")
864 F32 -> ptext SLIT("StgFloat") -- ToDo: correct?
865 F64 -> ptext SLIT("StgDouble")
866 _ -> panic "machRepCType"
868 -- ---------------------------------------------------------------------
869 -- print strings as valid C strings
871 -- Assumes it contains only characters '\0'..'\xFF'!
872 pprFSInCStyle :: FastString -> SDoc
873 pprFSInCStyle fs = pprStringInCStyle (unpackFS fs)
875 pprStringInCStyle :: String -> SDoc
876 pprStringInCStyle s = doubleQuotes (text (concatMap charToC s))
878 charToC :: Char -> String
879 charToC '\"' = "\\\""
880 charToC '\'' = "\\\'"
881 charToC '\\' = "\\\\"
882 charToC c | c >= ' ' && c <= '~' = [c]
883 | c > '\xFF' = panic ("charToC "++show c)
885 chr (ord '0' + ord c `div` 64),
886 chr (ord '0' + ord c `div` 8 `mod` 8),
887 chr (ord '0' + ord c `mod` 8)]
890 -- ---------------------------------------------------------------------------
891 -- Initialising static objects with floating-point numbers. We can't
892 -- just emit the floating point number, because C will cast it to an int
893 -- by rounding it. We want the actual bit-representation of the float.
895 -- This is a hack to turn the floating point numbers into ints that we
896 -- can safely initialise to static locations.
899 | machRepByteWidth F64 == 2 * wORD_SIZE = True
900 | machRepByteWidth F64 == wORD_SIZE = False
901 | otherwise = panic "big_doubles"
903 #if __GLASGOW_HASKELL__ >= 504
904 newFloatArray :: (Int,Int) -> ST s (STUArray s Int Float)
905 newFloatArray = newArray_
907 newDoubleArray :: (Int,Int) -> ST s (STUArray s Int Double)
908 newDoubleArray = newArray_
910 castFloatToIntArray :: STUArray s Int Float -> ST s (STUArray s Int Int)
911 castFloatToIntArray = castSTUArray
913 castDoubleToIntArray :: STUArray s Int Double -> ST s (STUArray s Int Int)
914 castDoubleToIntArray = castSTUArray
916 writeFloatArray :: STUArray s Int Float -> Int -> Float -> ST s ()
917 writeFloatArray = writeArray
919 writeDoubleArray :: STUArray s Int Double -> Int -> Double -> ST s ()
920 writeDoubleArray = writeArray
922 readIntArray :: STUArray s Int Int -> Int -> ST s Int
923 readIntArray = readArray
927 castFloatToIntArray :: MutableByteArray s t -> ST s (MutableByteArray s t)
928 castFloatToIntArray = return
930 castDoubleToIntArray :: MutableByteArray s t -> ST s (MutableByteArray s t)
931 castDoubleToIntArray = return
935 -- floats are always 1 word
936 floatToWord :: Rational -> CmmLit
939 arr <- newFloatArray ((0::Int),0)
940 writeFloatArray arr 0 (fromRational r)
941 arr' <- castFloatToIntArray arr
942 i <- readIntArray arr' 0
943 return (CmmInt (toInteger i) wordRep)
946 doubleToWords :: Rational -> [CmmLit]
948 | big_doubles -- doubles are 2 words
950 arr <- newDoubleArray ((0::Int),1)
951 writeDoubleArray arr 0 (fromRational r)
952 arr' <- castDoubleToIntArray arr
953 i1 <- readIntArray arr' 0
954 i2 <- readIntArray arr' 1
955 return [ CmmInt (toInteger i1) wordRep
956 , CmmInt (toInteger i2) wordRep
959 | otherwise -- doubles are 1 word
961 arr <- newDoubleArray ((0::Int),0)
962 writeDoubleArray arr 0 (fromRational r)
963 arr' <- castDoubleToIntArray arr
964 i <- readIntArray arr' 0
965 return [ CmmInt (toInteger i) wordRep ]
968 -- ---------------------------------------------------------------------------
972 wordShift = machRepLogWidth wordRep
974 commafy :: [SDoc] -> SDoc
975 commafy xs = hsep $ punctuate comma xs
977 -- Print in C hex format: 0x13fa
978 pprHexVal :: Integer -> MachRep -> SDoc
979 pprHexVal 0 _ = ptext SLIT("0x0")
981 | w < 0 = parens (char '-' <> ptext SLIT("0x") <> go (-w) <> repsuffix rep)
982 | otherwise = ptext SLIT("0x") <> go w <> repsuffix rep
984 -- type suffix for literals:
985 -- on 32-bit platforms, add "LL" to 64-bit literals
986 repsuffix I64 | wORD_SIZE == 4 = ptext SLIT("LL")
987 -- on 64-bit platforms with 32-bit int, add "L" to 64-bit literals
988 repsuffix I64 | cINT_SIZE == 4 = ptext SLIT("L")
994 (q,r) = w' `quotRem` 16
995 dig | r < 10 = char (chr (fromInteger r + ord '0'))
996 | otherwise = char (chr (fromInteger r - 10 + ord 'a'))