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_ <> pprCLabelAddr clbl
370 CmmLabelOff clbl i -> mkW_ <> pprCLabelAddr 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_ <> pprCLabelAddr clbl1 <> char '+' <> int i
380 pprCLabelAddr lbl = char '&' <> pprCLabel lbl
382 pprLit1 :: CmmLit -> SDoc
383 pprLit1 lit@(CmmLabelOff _ _) = parens (pprLit lit)
384 pprLit1 lit@(CmmLabelDiffOff _ _ _) = parens (pprLit lit)
385 pprLit1 lit@(CmmFloat _ _) = parens (pprLit lit)
386 pprLit1 other = pprLit other
388 -- ---------------------------------------------------------------------------
391 pprStatics :: [CmmStatic] -> [SDoc]
393 pprStatics (CmmStaticLit (CmmFloat f F32) : rest)
394 = pprLit1 (floatToWord f) : pprStatics rest
395 pprStatics (CmmStaticLit (CmmFloat f F64) : rest)
396 = map pprLit1 (doubleToWords f) ++ pprStatics rest
397 pprStatics (CmmStaticLit (CmmInt i I64) : rest)
398 | machRepByteWidth I32 == wORD_SIZE
399 #ifdef WORDS_BIGENDIAN
400 = pprStatics (CmmStaticLit (CmmInt q I32) :
401 CmmStaticLit (CmmInt r I32) : rest)
403 = pprStatics (CmmStaticLit (CmmInt r I32) :
404 CmmStaticLit (CmmInt q I32) : rest)
406 where r = i .&. 0xffffffff
408 pprStatics (CmmStaticLit lit : rest)
409 = pprLit1 lit : pprStatics rest
410 pprStatics (other : rest)
411 = pprPanic "pprWord" (pprStatic other)
413 pprStatic :: CmmStatic -> SDoc
414 pprStatic s = case s of
416 CmmStaticLit lit -> nest 4 (pprLit lit)
417 CmmAlign i -> nest 4 (ptext SLIT("/* align */") <+> int i)
418 CmmDataLabel clbl -> pprCLabel clbl <> colon
419 CmmUninitialised i -> nest 4 (mkC_ <> brackets (int i))
421 -- these should be inlined, like the old .hc
422 CmmString s' -> nest 4 (mkW_ <> parens(pprStringInCStyle s'))
425 -- ---------------------------------------------------------------------------
428 pprBlockId :: BlockId -> SDoc
429 pprBlockId b = char '_' <> ppr (getUnique b)
431 -- --------------------------------------------------------------------------
432 -- Print a MachOp in a way suitable for emitting via C.
435 pprMachOp_for_C :: MachOp -> SDoc
437 pprMachOp_for_C mop = case mop of
439 -- Integer operations
442 MO_Eq _ -> ptext SLIT("==")
443 MO_Ne _ -> ptext SLIT("!=")
446 MO_S_Quot _ -> char '/'
447 MO_S_Rem _ -> char '%'
448 MO_S_Neg _ -> char '-'
450 MO_U_Quot _ -> char '/'
451 MO_U_Rem _ -> char '%'
453 -- Signed comparisons (floating-point comparisons also use these)
454 -- & Unsigned comparisons
455 MO_S_Ge _ -> ptext SLIT(">=")
456 MO_S_Le _ -> ptext SLIT("<=")
457 MO_S_Gt _ -> char '>'
458 MO_S_Lt _ -> char '<'
460 MO_U_Ge _ -> ptext SLIT(">=")
461 MO_U_Le _ -> ptext SLIT("<=")
462 MO_U_Gt _ -> char '>'
463 MO_U_Lt _ -> char '<'
465 -- Bitwise operations. Not all of these may be supported at all
466 -- sizes, and only integral MachReps are valid.
471 MO_Shl _ -> ptext SLIT("<<")
472 MO_U_Shr _ -> ptext SLIT(">>") -- unsigned shift right
473 MO_S_Shr _ -> ptext SLIT(">>") -- signed shift right
475 -- Conversions. Some of these will be NOPs.
476 -- Floating-point conversions use the signed variant.
477 -- We won't know to generate (void*) casts here, but maybe from
481 MO_U_Conv I8 I8 -> empty
482 MO_U_Conv I16 I16 -> empty
483 MO_U_Conv I32 I32 -> empty
484 MO_U_Conv I64 I64 -> empty
485 MO_U_Conv I128 I128 -> empty
486 MO_S_Conv I8 I8 -> empty
487 MO_S_Conv I16 I16 -> empty
488 MO_S_Conv I32 I32 -> empty
489 MO_S_Conv I64 I64 -> empty
490 MO_S_Conv I128 I128 -> empty
492 MO_U_Conv _from to -> parens (machRepCType to)
493 MO_S_Conv _from to -> parens (machRepSignedCType to)
495 _ -> panic "PprC.pprMachOp_for_C: unknown machop"
497 signedOp :: MachOp -> Bool
498 signedOp (MO_S_Quot _) = True
499 signedOp (MO_S_Rem _) = True
500 signedOp (MO_S_Neg _) = True
501 signedOp (MO_S_Ge _) = True
502 signedOp (MO_S_Le _) = True
503 signedOp (MO_S_Gt _) = True
504 signedOp (MO_S_Lt _) = True
505 signedOp (MO_S_Shr _) = True
506 signedOp (MO_S_Conv _ _) = True
509 -- ---------------------------------------------------------------------
510 -- tend to be implemented by foreign calls
512 pprCallishMachOp_for_C :: CallishMachOp -> SDoc
514 pprCallishMachOp_for_C mop
516 MO_F64_Pwr -> ptext SLIT("pow")
517 MO_F64_Sin -> ptext SLIT("sin")
518 MO_F64_Cos -> ptext SLIT("cos")
519 MO_F64_Tan -> ptext SLIT("tan")
520 MO_F64_Sinh -> ptext SLIT("sinh")
521 MO_F64_Cosh -> ptext SLIT("cosh")
522 MO_F64_Tanh -> ptext SLIT("tanh")
523 MO_F64_Asin -> ptext SLIT("asin")
524 MO_F64_Acos -> ptext SLIT("acos")
525 MO_F64_Atan -> ptext SLIT("atan")
526 MO_F64_Log -> ptext SLIT("log")
527 MO_F64_Exp -> ptext SLIT("exp")
528 MO_F64_Sqrt -> ptext SLIT("sqrt")
529 MO_F32_Pwr -> ptext SLIT("pow")
530 MO_F32_Sin -> ptext SLIT("sin")
531 MO_F32_Cos -> ptext SLIT("cos")
532 MO_F32_Tan -> ptext SLIT("tan")
533 MO_F32_Sinh -> ptext SLIT("sinh")
534 MO_F32_Cosh -> ptext SLIT("cosh")
535 MO_F32_Tanh -> ptext SLIT("tanh")
536 MO_F32_Asin -> ptext SLIT("asin")
537 MO_F32_Acos -> ptext SLIT("acos")
538 MO_F32_Atan -> ptext SLIT("atan")
539 MO_F32_Log -> ptext SLIT("log")
540 MO_F32_Exp -> ptext SLIT("exp")
541 MO_F32_Sqrt -> ptext SLIT("sqrt")
543 -- ---------------------------------------------------------------------
547 mkJMP_, mkFN_, mkIF_ :: SDoc -> SDoc
549 mkJMP_ i = ptext SLIT("JMP_") <> parens i
550 mkFN_ i = ptext SLIT("FN_") <> parens i -- externally visible function
551 mkIF_ i = ptext SLIT("IF_") <> parens i -- locally visible
555 mkFB_ = ptext SLIT("FB_") -- function code begin
556 mkFE_ = ptext SLIT("FE_") -- function code end
558 -- from includes/Stg.h
560 mkC_,mkW_,mkP_,mkPP_,mkI_,mkA_,mkD_,mkF_,mkB_,mkL_,mkLI_,mkLW_ :: SDoc
562 mkC_ = ptext SLIT("(C_)") -- StgChar
563 mkW_ = ptext SLIT("(W_)") -- StgWord
564 mkP_ = ptext SLIT("(P_)") -- StgWord*
565 mkPP_ = ptext SLIT("(PP_)") -- P_*
566 mkI_ = ptext SLIT("(I_)") -- StgInt
567 mkA_ = ptext SLIT("(A_)") -- StgAddr
568 mkD_ = ptext SLIT("(D_)") -- const StgWord*
569 mkF_ = ptext SLIT("(F_)") -- StgFunPtr
570 mkB_ = ptext SLIT("(B_)") -- StgByteArray
571 mkL_ = ptext SLIT("(L_)") -- StgClosurePtr
573 mkLI_ = ptext SLIT("(LI_)") -- StgInt64
574 mkLW_ = ptext SLIT("(LW_)") -- StgWord64
577 -- ---------------------------------------------------------------------
581 -- Generating assignments is what we're all about, here
583 pprAssign :: CmmReg -> CmmExpr -> SDoc
585 -- dest is a reg, rhs is a reg
586 pprAssign r1 (CmmReg r2)
587 | not (isStrangeTypeReg r1) && not (isStrangeTypeReg r2)
588 || isPtrReg r1 && isPtrReg r2
589 = hcat [ pprAsPtrReg r1, equals, pprAsPtrReg r2, semi ]
591 -- dest is a reg, rhs is a CmmRegOff
592 pprAssign r1 (CmmRegOff r2 off)
593 | not (isStrangeTypeReg r1) && not (isStrangeTypeReg r2)
594 || isPtrReg r1 && isPtrReg r2
595 = hcat [ pprAsPtrReg r1, equals, pprAsPtrReg r2, op, int off', semi ]
597 off1 | isPtrReg r2 = off `shiftR` wordShift
600 (op,off') | off >= 0 = (char '+', off1)
601 | otherwise = (char '-', -off1)
603 -- dest is a reg, rhs is anything.
604 -- We can't cast the lvalue, so we have to cast the rhs if necessary. Casting
605 -- the lvalue elicits a warning from new GCC versions (3.4+).
608 = pprAsPtrReg r1 <> ptext SLIT(" = ") <> mkP_ <> pprExpr1 r2 <> semi
609 | Just ty <- strangeRegType r1
610 = pprReg r1 <> ptext SLIT(" = ") <> parens ty <> pprExpr1 r2 <> semi
612 = pprReg r1 <> ptext SLIT(" = ") <> pprExpr r2 <> semi
614 -- ---------------------------------------------------------------------
618 | isStrangeTypeReg reg = mkW_ <> pprReg reg
619 | otherwise = pprReg reg
621 -- True if the register has type StgPtr in C, otherwise it has an
622 -- integer type. We need to take care with pointer arithmetic on registers
624 isPtrReg :: CmmReg -> Bool
625 isPtrReg (CmmLocal _) = False
626 isPtrReg (CmmGlobal r) = isPtrGlobalReg r
628 isPtrGlobalReg :: GlobalReg -> Bool
629 isPtrGlobalReg (VanillaReg n) = True
630 isPtrGlobalReg Sp = True
631 isPtrGlobalReg Hp = True
632 isPtrGlobalReg HpLim = True
633 isPtrGlobalReg SpLim = True
634 isPtrGlobalReg _ = False
636 -- True if in C this register doesn't have the type given by
637 -- (machRepCType (cmmRegRep reg)), so it has to be cast.
638 isStrangeTypeReg :: CmmReg -> Bool
639 isStrangeTypeReg (CmmLocal _) = False
640 isStrangeTypeReg (CmmGlobal g) = isStrangeTypeGlobal g
642 isStrangeTypeGlobal :: GlobalReg -> Bool
643 isStrangeTypeGlobal CurrentTSO = True
644 isStrangeTypeGlobal CurrentNursery = True
645 isStrangeTypeGlobal BaseReg = True
646 isStrangeTypeGlobal r = isPtrGlobalReg r
648 strangeRegType :: CmmReg -> Maybe SDoc
649 strangeRegType (CmmGlobal CurrentTSO) = Just (ptext SLIT("struct StgTSO_ *"))
650 strangeRegType (CmmGlobal CurrentNursery) = Just (ptext SLIT("struct bdescr_ *"))
651 strangeRegType _ = Nothing
653 -- pprReg just prints the register name.
655 pprReg :: CmmReg -> SDoc
657 CmmLocal local -> pprLocalReg local
658 CmmGlobal global -> pprGlobalReg global
660 pprAsPtrReg :: CmmReg -> SDoc
661 pprAsPtrReg (CmmGlobal (VanillaReg n)) = char 'R' <> int n <> ptext SLIT(".p")
662 pprAsPtrReg other_reg = pprReg other_reg
664 pprGlobalReg :: GlobalReg -> SDoc
665 pprGlobalReg gr = case gr of
666 VanillaReg n -> char 'R' <> int n <> ptext SLIT(".w")
667 FloatReg n -> char 'F' <> int n
668 DoubleReg n -> char 'D' <> int n
669 LongReg n -> char 'L' <> int n
670 Sp -> ptext SLIT("Sp")
671 SpLim -> ptext SLIT("SpLim")
672 Hp -> ptext SLIT("Hp")
673 HpLim -> ptext SLIT("HpLim")
674 CurrentTSO -> ptext SLIT("CurrentTSO")
675 CurrentNursery -> ptext SLIT("CurrentNursery")
676 HpAlloc -> ptext SLIT("HpAlloc")
677 BaseReg -> ptext SLIT("BaseReg")
678 GCEnter1 -> ptext SLIT("stg_gc_enter_1")
679 GCFun -> ptext SLIT("stg_gc_fun")
681 pprLocalReg :: LocalReg -> SDoc
682 pprLocalReg (LocalReg uniq _rep) = char '_' <> ppr uniq
684 -- -----------------------------------------------------------------------------
687 pprCall :: SDoc -> CCallConv -> [(CmmReg,MachHint)] -> [(CmmExpr,MachHint)]
688 -> Maybe [GlobalReg] -> SDoc
690 pprCall ppr_fn cconv results args vols
691 | not (is_cish cconv)
692 = panic "pprForeignCall: unknown calling convention"
696 ptext SLIT("CALLER_SAVE_SYSTEM") $$
697 hcat [ ppr_results results, ppr_fn,
698 parens (commafy (map pprArg args)), semi ] $$
699 ptext SLIT("CALLER_RESTORE_SYSTEM") $$
702 ppr_results [] = empty
703 ppr_results [(one,hint)]
704 = pprExpr (CmmReg one) <> ptext SLIT(" = ")
705 <> pprUnHint hint (cmmRegRep one)
706 ppr_results _other = panic "pprCall: multiple results"
708 pprArg (expr, PtrHint)
709 = cCast (ptext SLIT("void *")) expr
710 -- see comment by machRepHintCType below
711 pprArg (expr, SignedHint)
712 = cCast (machRepSignedCType (cmmExprRep expr)) expr
713 pprArg (expr, _other)
716 pprUnHint PtrHint rep = parens (machRepCType rep)
717 pprUnHint SignedHint rep = parens (machRepCType rep)
718 pprUnHint _ _ = empty
720 save = save_restore SLIT("CALLER_SAVE")
721 restore = save_restore SLIT("CALLER_RESTORE")
723 -- Nothing says "I don't know what's live; save everything"
724 -- CALLER_SAVE_USER is defined in ghc/includes/Regs.h
725 save_restore txt Nothing = ptext txt <> ptext SLIT("_USER")
726 save_restore txt (Just these) = vcat (map saveRestoreGlobal these)
727 where saveRestoreGlobal r = ptext txt <> char '_' <> pprGlobalRegName r
729 pprGlobalRegName :: GlobalReg -> SDoc
730 pprGlobalRegName gr = case gr of
731 VanillaReg n -> char 'R' <> int n -- without the .w suffix
734 is_cish CCallConv = True
735 is_cish StdCallConv = True
738 -- ---------------------------------------------------------------------
739 -- Find and print local and external declarations for a list of
742 pprTempAndExternDecls :: [CmmBasicBlock] -> (SDoc{-temps-}, SDoc{-externs-})
743 pprTempAndExternDecls stmts
744 = (vcat (map pprTempDecl (eltsUFM temps)),
745 vcat (map (pprExternDecl False{-ToDo-}) (keysFM lbls)))
746 where (temps, lbls) = runTE (mapM_ te_BB stmts)
748 pprDataExterns :: [CmmStatic] -> SDoc
749 pprDataExterns statics
750 = vcat (map (pprExternDecl False{-ToDo-}) (keysFM lbls))
751 where (_, lbls) = runTE (mapM_ te_Static statics)
753 pprTempDecl :: LocalReg -> SDoc
754 pprTempDecl l@(LocalReg _uniq rep)
755 = hcat [ machRepCType rep, space, pprLocalReg l, semi ]
757 pprExternDecl :: Bool -> CLabel -> SDoc
758 pprExternDecl in_srt lbl
759 -- do not print anything for "known external" things
760 | not (needsCDecl lbl) = empty
762 hcat [ visibility, label_type (labelType lbl),
763 lparen, dyn_wrapper (pprCLabel lbl), text ");" ]
766 | in_srt && labelDynamic lbl = text "DLL_IMPORT_DATA_VAR" <> parens d
769 label_type CodeLabel = ptext SLIT("F_")
770 label_type DataLabel = ptext SLIT("I_")
773 | externallyVisibleCLabel lbl = char 'E'
774 | otherwise = char 'I'
777 type TEState = (UniqSet LocalReg, FiniteMap CLabel ())
778 newtype TE a = TE { unTE :: TEState -> (a, TEState) }
780 instance Monad TE where
781 TE m >>= k = TE $ \s -> case m s of (a, s') -> unTE (k a) s'
782 return a = TE $ \s -> (a, s)
784 te_lbl :: CLabel -> TE ()
785 te_lbl lbl = TE $ \(temps,lbls) -> ((), (temps, addToFM lbls lbl ()))
787 te_temp :: LocalReg -> TE ()
788 te_temp r = TE $ \(temps,lbls) -> ((), (addOneToUniqSet temps r, lbls))
790 runTE :: TE () -> TEState
791 runTE (TE m) = snd (m (emptyUniqSet, emptyFM))
793 te_Static :: CmmStatic -> TE ()
794 te_Static (CmmStaticLit lit) = te_Lit lit
795 te_Static _ = return ()
797 te_BB :: CmmBasicBlock -> TE ()
798 te_BB (BasicBlock _ ss) = mapM_ te_Stmt ss
800 te_Lit :: CmmLit -> TE ()
801 te_Lit (CmmLabel l) = te_lbl l
802 te_Lit (CmmLabelOff l _) = te_lbl l
803 te_Lit (CmmLabelDiffOff l1 l2 _) = te_lbl l1
806 te_Stmt :: CmmStmt -> TE ()
807 te_Stmt (CmmAssign r e) = te_Reg r >> te_Expr e
808 te_Stmt (CmmStore l r) = te_Expr l >> te_Expr r
809 te_Stmt (CmmCall _ rs es _) = mapM_ (te_Reg.fst) rs >>
810 mapM_ (te_Expr.fst) es
811 te_Stmt (CmmCondBranch e _) = te_Expr e
812 te_Stmt (CmmSwitch e _) = te_Expr e
813 te_Stmt (CmmJump e _) = te_Expr e
814 te_Stmt _ = return ()
816 te_Expr :: CmmExpr -> TE ()
817 te_Expr (CmmLit lit) = te_Lit lit
818 te_Expr (CmmReg r) = te_Reg r
819 te_Expr (CmmLoad e _) = te_Expr e
820 te_Expr (CmmMachOp _ es) = mapM_ te_Expr es
821 te_Expr (CmmRegOff r _) = te_Reg r
822 te_Expr _ = return ()
824 te_Reg :: CmmReg -> TE ()
825 te_Reg (CmmLocal l) = te_temp l
829 -- ---------------------------------------------------------------------
830 -- C types for MachReps
832 cCast :: SDoc -> CmmExpr -> SDoc
833 cCast ty expr = parens ty <> pprExpr1 expr
835 -- This is for finding the types of foreign call arguments. For a pointer
836 -- argument, we always cast the argument to (void *), to avoid warnings from
838 machRepHintCType :: MachRep -> MachHint -> SDoc
839 machRepHintCType rep PtrHint = ptext SLIT("void *")
840 machRepHintCType rep SignedHint = machRepSignedCType rep
841 machRepHintCType rep _other = machRepCType rep
843 machRepPtrCType :: MachRep -> SDoc
844 machRepPtrCType r | r == wordRep = ptext SLIT("P_")
845 | otherwise = machRepCType r <> char '*'
847 machRepCType :: MachRep -> SDoc
848 machRepCType r | r == wordRep = ptext SLIT("W_")
849 | otherwise = sized_type
850 where sized_type = case r of
851 I8 -> ptext SLIT("StgWord8")
852 I16 -> ptext SLIT("StgWord16")
853 I32 -> ptext SLIT("StgWord32")
854 I64 -> ptext SLIT("StgWord64")
855 F32 -> ptext SLIT("StgFloat") -- ToDo: correct?
856 F64 -> ptext SLIT("StgDouble")
857 _ -> panic "machRepCType"
859 machRepSignedCType :: MachRep -> SDoc
860 machRepSignedCType r | r == wordRep = ptext SLIT("I_")
861 | otherwise = sized_type
862 where sized_type = case r of
863 I8 -> ptext SLIT("StgInt8")
864 I16 -> ptext SLIT("StgInt16")
865 I32 -> ptext SLIT("StgInt32")
866 I64 -> ptext SLIT("StgInt64")
867 F32 -> ptext SLIT("StgFloat") -- ToDo: correct?
868 F64 -> ptext SLIT("StgDouble")
869 _ -> panic "machRepCType"
871 -- ---------------------------------------------------------------------
872 -- print strings as valid C strings
874 -- Assumes it contains only characters '\0'..'\xFF'!
875 pprFSInCStyle :: FastString -> SDoc
876 pprFSInCStyle fs = pprStringInCStyle (unpackFS fs)
878 pprStringInCStyle :: String -> SDoc
879 pprStringInCStyle s = doubleQuotes (text (concatMap charToC s))
881 charToC :: Char -> String
882 charToC '\"' = "\\\""
883 charToC '\'' = "\\\'"
884 charToC '\\' = "\\\\"
885 charToC c | c >= ' ' && c <= '~' = [c]
886 | c > '\xFF' = panic ("charToC "++show c)
888 chr (ord '0' + ord c `div` 64),
889 chr (ord '0' + ord c `div` 8 `mod` 8),
890 chr (ord '0' + ord c `mod` 8)]
893 -- ---------------------------------------------------------------------------
894 -- Initialising static objects with floating-point numbers. We can't
895 -- just emit the floating point number, because C will cast it to an int
896 -- by rounding it. We want the actual bit-representation of the float.
898 -- This is a hack to turn the floating point numbers into ints that we
899 -- can safely initialise to static locations.
902 | machRepByteWidth F64 == 2 * wORD_SIZE = True
903 | machRepByteWidth F64 == wORD_SIZE = False
904 | otherwise = panic "big_doubles"
906 #if __GLASGOW_HASKELL__ >= 504
907 newFloatArray :: (Int,Int) -> ST s (STUArray s Int Float)
908 newFloatArray = newArray_
910 newDoubleArray :: (Int,Int) -> ST s (STUArray s Int Double)
911 newDoubleArray = newArray_
913 castFloatToIntArray :: STUArray s Int Float -> ST s (STUArray s Int Int)
914 castFloatToIntArray = castSTUArray
916 castDoubleToIntArray :: STUArray s Int Double -> ST s (STUArray s Int Int)
917 castDoubleToIntArray = castSTUArray
919 writeFloatArray :: STUArray s Int Float -> Int -> Float -> ST s ()
920 writeFloatArray = writeArray
922 writeDoubleArray :: STUArray s Int Double -> Int -> Double -> ST s ()
923 writeDoubleArray = writeArray
925 readIntArray :: STUArray s Int Int -> Int -> ST s Int
926 readIntArray = readArray
930 castFloatToIntArray :: MutableByteArray s t -> ST s (MutableByteArray s t)
931 castFloatToIntArray = return
933 castDoubleToIntArray :: MutableByteArray s t -> ST s (MutableByteArray s t)
934 castDoubleToIntArray = return
938 -- floats are always 1 word
939 floatToWord :: Rational -> CmmLit
942 arr <- newFloatArray ((0::Int),0)
943 writeFloatArray arr 0 (fromRational r)
944 arr' <- castFloatToIntArray arr
945 i <- readIntArray arr' 0
946 return (CmmInt (toInteger i) wordRep)
949 doubleToWords :: Rational -> [CmmLit]
951 | big_doubles -- doubles are 2 words
953 arr <- newDoubleArray ((0::Int),1)
954 writeDoubleArray arr 0 (fromRational r)
955 arr' <- castDoubleToIntArray arr
956 i1 <- readIntArray arr' 0
957 i2 <- readIntArray arr' 1
958 return [ CmmInt (toInteger i1) wordRep
959 , CmmInt (toInteger i2) wordRep
962 | otherwise -- doubles are 1 word
964 arr <- newDoubleArray ((0::Int),0)
965 writeDoubleArray arr 0 (fromRational r)
966 arr' <- castDoubleToIntArray arr
967 i <- readIntArray arr' 0
968 return [ CmmInt (toInteger i) wordRep ]
971 -- ---------------------------------------------------------------------------
975 wordShift = machRepLogWidth wordRep
977 commafy :: [SDoc] -> SDoc
978 commafy xs = hsep $ punctuate comma xs
980 -- Print in C hex format: 0x13fa
981 pprHexVal :: Integer -> MachRep -> SDoc
982 pprHexVal 0 _ = ptext SLIT("0x0")
984 | w < 0 = parens (char '-' <> ptext SLIT("0x") <> go (-w) <> repsuffix rep)
985 | otherwise = ptext SLIT("0x") <> go w <> repsuffix rep
987 -- type suffix for literals:
988 -- on 32-bit platforms, add "LL" to 64-bit literals
989 repsuffix I64 | wORD_SIZE == 4 = ptext SLIT("LL")
990 -- on 64-bit platforms with 32-bit int, add "L" to 64-bit literals
991 repsuffix I64 | cINT_SIZE == 4 = ptext SLIT("L")
997 (q,r) = w' `quotRem` 16
998 dig | r < 10 = char (chr (fromInteger r + ord '0'))
999 | otherwise = char (chr (fromInteger r - 10 + ord 'a'))