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 )
41 import StaticFlags ( opt_Unregisterised )
44 import Data.List ( intersperse, groupBy )
45 import Data.Bits ( shiftR )
46 import Char ( ord, chr )
49 import Data.Word ( Word8 )
52 import PprCmm () -- instances only
56 #if __GLASGOW_HASKELL__ >= 504
61 -- --------------------------------------------------------------------------
64 pprCs :: DynFlags -> [Cmm] -> SDoc
66 = pprCode CStyle (vcat $ map (\c -> split_marker $$ pprC c) cmms)
69 | dopt Opt_SplitObjs dflags = ptext SLIT("__STG_SPLIT_MARKER")
72 writeCs :: DynFlags -> Handle -> [Cmm] -> IO ()
73 writeCs dflags handle cmms
74 = printForC handle (pprCs dflags cmms)
76 -- --------------------------------------------------------------------------
77 -- Now do some real work
79 -- for fun, we could call cmmToCmm over the tops...
83 pprC (Cmm tops) = vcat $ intersperse (text "") $ map pprTop tops
88 pprTop :: CmmTop -> SDoc
89 pprTop (CmmProc info clbl _params blocks) =
91 then pprDataExterns info $$
92 pprWordArray (entryLblToInfoLbl clbl) info
96 -- the first block doesn't get a label:
97 (BasicBlock _ stmts : rest) -> vcat [
100 (if (externallyVisibleCLabel clbl)
101 then mkFN_ else mkIF_) (pprCLabel clbl) <+> lbrace,
104 nest 8 (vcat (map pprStmt stmts)) $$
105 vcat (map pprBBlock rest),
110 (temp_decls, extern_decls) = pprTempAndExternDecls blocks
113 -- Chunks of static data.
115 -- We only handle (a) arrays of word-sized things and (b) strings.
117 pprTop (CmmData _section _ds@[CmmDataLabel lbl, CmmString str]) =
119 pprLocalness lbl, ptext SLIT("char "), pprCLabel lbl,
120 ptext SLIT("[] = "), pprStringInCStyle str, semi
123 pprTop (CmmData _section _ds@[CmmDataLabel lbl, CmmUninitialised size]) =
125 pprLocalness lbl, ptext SLIT("char "), pprCLabel lbl,
126 brackets (int size), semi
129 pprTop top@(CmmData _section (CmmDataLabel lbl : lits)) =
130 pprDataExterns lits $$
131 pprWordArray lbl lits
133 -- these shouldn't appear?
134 pprTop (CmmData _ _) = panic "PprC.pprTop: can't handle this data"
137 -- --------------------------------------------------------------------------
138 -- BasicBlocks are self-contained entities: they always end in a jump.
140 -- Like nativeGen/AsmCodeGen, we could probably reorder blocks to turn
141 -- as many jumps as possible into fall throughs.
144 pprBBlock :: CmmBasicBlock -> SDoc
145 pprBBlock (BasicBlock lbl stmts) =
147 pprTrace "pprC.pprBBlock: curious empty code block for"
148 (pprBlockId lbl) empty
150 nest 4 (pprBlockId lbl <> colon) $$
151 nest 8 (vcat (map pprStmt stmts))
153 -- --------------------------------------------------------------------------
154 -- Info tables. Just arrays of words.
155 -- See codeGen/ClosureInfo, and nativeGen/PprMach
157 pprWordArray :: CLabel -> [CmmStatic] -> SDoc
159 = hcat [ pprLocalness lbl, ptext SLIT("StgWord")
160 , space, pprCLabel lbl, ptext SLIT("[] = {") ]
161 $$ nest 8 (commafy (pprStatics ds))
165 -- has to be static, if it isn't globally visible
167 pprLocalness :: CLabel -> SDoc
168 pprLocalness lbl | not $ externallyVisibleCLabel lbl = ptext SLIT("static ")
171 -- --------------------------------------------------------------------------
175 pprStmt :: CmmStmt -> SDoc
177 pprStmt stmt = case stmt of
179 CmmComment s -> (hang (ptext SLIT("/*")) 3 (ftext s)) $$ ptext SLIT("*/")
181 CmmAssign dest src -> pprAssign dest src
184 | rep == I64 && wordRep /= I64
185 -> ptext SLIT("ASSIGN_Word64") <>
186 parens (mkP_ <> pprExpr1 dest <> comma <> pprExpr src) <> semi
188 | rep == F64 && wordRep /= I64
189 -> ptext SLIT("ASSIGN_DBL") <>
190 parens (mkP_ <> pprExpr1 dest <> comma <> pprExpr src) <> semi
193 -> hsep [ pprExpr (CmmLoad dest rep), equals, pprExpr src <> semi ]
197 CmmCall (CmmForeignCall fn cconv) results args volatile ->
198 -- Controversial: leave this out for now.
201 pprCall ppr_fn cconv results args volatile
204 CmmLit (CmmLabel lbl) -> pprCLabel lbl
205 _other -> parens (cCast (pprCFunType cconv results args) fn)
206 -- for a dynamic call, cast the expression to
207 -- a function of the right type (we hope).
209 -- we #undef a function before calling it: the FFI is supposed to be
210 -- an interface specifically to C, not to C+CPP. For one thing, this
211 -- makes the via-C route more compatible with the NCG. If macros
212 -- are being used for optimisation, then inline functions are probably
214 pprUndef (CmmLit (CmmLabel lbl)) =
215 ptext SLIT("#undef") <+> pprCLabel lbl
218 CmmCall (CmmPrim op) results args volatile ->
219 pprCall ppr_fn CCallConv results args volatile
221 ppr_fn = pprCallishMachOp_for_C op
223 CmmBranch ident -> pprBranch ident
224 CmmCondBranch expr ident -> pprCondBranch expr ident
225 CmmJump lbl _params -> mkJMP_(pprExpr lbl) <> semi
226 CmmSwitch arg ids -> pprSwitch arg ids
228 pprCFunType :: CCallConv -> [(CmmReg,MachHint)] -> [(CmmExpr,MachHint)] -> SDoc
229 pprCFunType cconv ress args
232 parens (text (ccallConvAttribute cconv) <> char '*'),
233 parens (commafy (map arg_type args))
236 res_type [] = ptext SLIT("void")
237 res_type [(one,hint)] = machRepHintCType (cmmRegRep one) hint
239 arg_type (expr,hint) = machRepHintCType (cmmExprRep expr) hint
241 -- ---------------------------------------------------------------------
242 -- unconditional branches
243 pprBranch :: BlockId -> SDoc
244 pprBranch ident = ptext SLIT("goto") <+> pprBlockId ident <> semi
247 -- ---------------------------------------------------------------------
248 -- conditional branches to local labels
249 pprCondBranch :: CmmExpr -> BlockId -> SDoc
250 pprCondBranch expr ident
251 = hsep [ ptext SLIT("if") , parens(pprExpr expr) ,
252 ptext SLIT("goto") , (pprBlockId ident) <> semi ]
255 -- ---------------------------------------------------------------------
256 -- a local table branch
258 -- we find the fall-through cases
260 -- N.B. we remove Nothing's from the list of branches, as they are
261 -- 'undefined'. However, they may be defined one day, so we better
262 -- document this behaviour.
264 pprSwitch :: CmmExpr -> [ Maybe BlockId ] -> SDoc
265 pprSwitch e maybe_ids
266 = let pairs = [ (ix, ident) | (ix,Just ident) <- zip [0..] maybe_ids ]
267 pairs2 = [ (map fst as, snd (head as)) | as <- groupBy sndEq pairs ]
269 (hang (ptext SLIT("switch") <+> parens ( pprExpr e ) <+> lbrace)
270 4 (vcat ( map caseify pairs2 )))
274 sndEq (_,x) (_,y) = x == y
277 caseify (ix:ixs, ident) = vcat (map do_fallthrough ixs) $$ final_branch ix
280 hsep [ ptext SLIT("case") , pprHexVal ix wordRep <> colon ,
281 ptext SLIT("/* fall through */") ]
284 hsep [ ptext SLIT("case") , pprHexVal ix wordRep <> colon ,
285 ptext SLIT("goto") , (pprBlockId ident) <> semi ]
287 -- ---------------------------------------------------------------------
291 -- C Types: the invariant is that the C expression generated by
295 -- has a type in C which is also given by
297 -- machRepCType (cmmExprRep e)
299 -- (similar invariants apply to the rest of the pretty printer).
301 pprExpr :: CmmExpr -> SDoc
302 pprExpr e = case e of
303 CmmLit lit -> pprLit lit
305 CmmLoad e I64 | wordRep /= I64
306 -> ptext SLIT("PK_Word64") <> parens (mkP_ <> pprExpr1 e)
308 CmmLoad e F64 | wordRep /= I64
309 -> ptext SLIT("PK_DBL") <> parens (mkP_ <> pprExpr1 e)
311 CmmLoad (CmmReg r) rep
312 | isPtrReg r && rep == wordRep
313 -> char '*' <> pprAsPtrReg r
315 CmmLoad (CmmRegOff r 0) rep
316 | isPtrReg r && rep == wordRep
317 -> char '*' <> pprAsPtrReg r
319 CmmLoad (CmmRegOff r off) rep
320 | isPtrReg r && rep == wordRep
321 -- ToDo: check that the offset is a word multiple?
322 -> pprAsPtrReg r <> brackets (ppr (off `shiftR` wordShift))
326 char '*' <> parens (cCast (machRepPtrCType rep) expr)
328 CmmReg reg -> pprCastReg reg
329 CmmRegOff reg 0 -> pprCastReg reg
332 | i > 0 -> pprRegOff (char '+') i
333 | otherwise -> pprRegOff (char '-') (-i)
335 pprRegOff op i' = pprCastReg reg <> op <> int i'
337 CmmMachOp mop args -> pprMachOpApp mop args
339 pprExpr1 :: CmmExpr -> SDoc
340 pprExpr1 (CmmLit lit) = pprLit1 lit
341 pprExpr1 e@(CmmReg _reg) = pprExpr e
342 pprExpr1 other = parens (pprExpr other)
344 -- --------------------------------------------------------------------------
345 -- MachOp applications
347 pprMachOpApp :: MachOp -> [CmmExpr] -> SDoc
351 = ptext SLIT("mulIntMayOflo") <> parens (commafy (map pprExpr args))
352 where isMulMayOfloOp (MO_U_MulMayOflo _) = True
353 isMulMayOfloOp (MO_S_MulMayOflo _) = True
354 isMulMayOfloOp _ = False
356 pprMachOpApp mop args
359 [x,y] -> pprArg x <+> pprMachOp_for_C mop <+> pprArg y
362 [x] -> pprMachOp_for_C mop <> parens (pprArg x)
364 _ -> panic "PprC.pprMachOp : machop with wrong number of args"
367 pprArg e | signedOp mop = cCast (machRepSignedCType (cmmExprRep e)) e
368 | otherwise = pprExpr1 e
370 -- --------------------------------------------------------------------------
373 pprLit :: CmmLit -> SDoc
374 pprLit lit = case lit of
375 CmmInt i rep -> pprHexVal i rep
376 CmmFloat f rep -> parens (machRepCType rep) <> (rational f)
377 CmmLabel clbl -> mkW_ <> pprCLabelAddr clbl
378 CmmLabelOff clbl i -> mkW_ <> pprCLabelAddr clbl <> char '+' <> int i
379 CmmLabelDiffOff clbl1 clbl2 i
381 -- * the lit must occur in the info table clbl2
382 -- * clbl1 must be an SRT, a slow entry point or a large bitmap
383 -- The Mangler is expected to convert any reference to an SRT,
384 -- a slow entry point or a large bitmap
385 -- from an info table to an offset.
386 -> mkW_ <> pprCLabelAddr clbl1 <> char '+' <> int i
388 pprCLabelAddr lbl = char '&' <> pprCLabel lbl
390 pprLit1 :: CmmLit -> SDoc
391 pprLit1 lit@(CmmLabelOff _ _) = parens (pprLit lit)
392 pprLit1 lit@(CmmLabelDiffOff _ _ _) = parens (pprLit lit)
393 pprLit1 lit@(CmmFloat _ _) = parens (pprLit lit)
394 pprLit1 other = pprLit other
396 -- ---------------------------------------------------------------------------
399 pprStatics :: [CmmStatic] -> [SDoc]
401 pprStatics (CmmStaticLit (CmmFloat f F32) : rest)
402 = pprLit1 (floatToWord f) : pprStatics rest
403 pprStatics (CmmStaticLit (CmmFloat f F64) : rest)
404 = map pprLit1 (doubleToWords f) ++ pprStatics rest
405 pprStatics (CmmStaticLit (CmmInt i I64) : rest)
406 | machRepByteWidth I32 == wORD_SIZE
407 #ifdef WORDS_BIGENDIAN
408 = pprStatics (CmmStaticLit (CmmInt q I32) :
409 CmmStaticLit (CmmInt r I32) : rest)
411 = pprStatics (CmmStaticLit (CmmInt r I32) :
412 CmmStaticLit (CmmInt q I32) : rest)
414 where r = i .&. 0xffffffff
416 pprStatics (CmmStaticLit lit : rest)
417 = pprLit1 lit : pprStatics rest
418 pprStatics (other : rest)
419 = pprPanic "pprWord" (pprStatic other)
421 pprStatic :: CmmStatic -> SDoc
422 pprStatic s = case s of
424 CmmStaticLit lit -> nest 4 (pprLit lit)
425 CmmAlign i -> nest 4 (ptext SLIT("/* align */") <+> int i)
426 CmmDataLabel clbl -> pprCLabel clbl <> colon
427 CmmUninitialised i -> nest 4 (mkC_ <> brackets (int i))
429 -- these should be inlined, like the old .hc
430 CmmString s' -> nest 4 (mkW_ <> parens(pprStringInCStyle s'))
433 -- ---------------------------------------------------------------------------
436 pprBlockId :: BlockId -> SDoc
437 pprBlockId b = char '_' <> ppr (getUnique b)
439 -- --------------------------------------------------------------------------
440 -- Print a MachOp in a way suitable for emitting via C.
443 pprMachOp_for_C :: MachOp -> SDoc
445 pprMachOp_for_C mop = case mop of
447 -- Integer operations
450 MO_Eq _ -> ptext SLIT("==")
451 MO_Ne _ -> ptext SLIT("!=")
454 MO_S_Quot _ -> char '/'
455 MO_S_Rem _ -> char '%'
456 MO_S_Neg _ -> char '-'
458 MO_U_Quot _ -> char '/'
459 MO_U_Rem _ -> char '%'
461 -- Signed comparisons (floating-point comparisons also use these)
462 -- & Unsigned comparisons
463 MO_S_Ge _ -> ptext SLIT(">=")
464 MO_S_Le _ -> ptext SLIT("<=")
465 MO_S_Gt _ -> char '>'
466 MO_S_Lt _ -> char '<'
468 MO_U_Ge _ -> ptext SLIT(">=")
469 MO_U_Le _ -> ptext SLIT("<=")
470 MO_U_Gt _ -> char '>'
471 MO_U_Lt _ -> char '<'
473 -- Bitwise operations. Not all of these may be supported at all
474 -- sizes, and only integral MachReps are valid.
479 MO_Shl _ -> ptext SLIT("<<")
480 MO_U_Shr _ -> ptext SLIT(">>") -- unsigned shift right
481 MO_S_Shr _ -> ptext SLIT(">>") -- signed shift right
483 -- Conversions. Some of these will be NOPs.
484 -- Floating-point conversions use the signed variant.
485 -- We won't know to generate (void*) casts here, but maybe from
489 MO_U_Conv I8 I8 -> empty
490 MO_U_Conv I16 I16 -> empty
491 MO_U_Conv I32 I32 -> empty
492 MO_U_Conv I64 I64 -> empty
493 MO_U_Conv I128 I128 -> empty
494 MO_S_Conv I8 I8 -> empty
495 MO_S_Conv I16 I16 -> empty
496 MO_S_Conv I32 I32 -> empty
497 MO_S_Conv I64 I64 -> empty
498 MO_S_Conv I128 I128 -> empty
500 MO_U_Conv _from to -> parens (machRepCType to)
501 MO_S_Conv _from to -> parens (machRepSignedCType to)
503 _ -> panic "PprC.pprMachOp_for_C: unknown machop"
505 signedOp :: MachOp -> Bool
506 signedOp (MO_S_Quot _) = True
507 signedOp (MO_S_Rem _) = True
508 signedOp (MO_S_Neg _) = True
509 signedOp (MO_S_Ge _) = True
510 signedOp (MO_S_Le _) = True
511 signedOp (MO_S_Gt _) = True
512 signedOp (MO_S_Lt _) = True
513 signedOp (MO_S_Shr _) = True
514 signedOp (MO_S_Conv _ _) = True
517 -- ---------------------------------------------------------------------
518 -- tend to be implemented by foreign calls
520 pprCallishMachOp_for_C :: CallishMachOp -> SDoc
522 pprCallishMachOp_for_C mop
524 MO_F64_Pwr -> ptext SLIT("pow")
525 MO_F64_Sin -> ptext SLIT("sin")
526 MO_F64_Cos -> ptext SLIT("cos")
527 MO_F64_Tan -> ptext SLIT("tan")
528 MO_F64_Sinh -> ptext SLIT("sinh")
529 MO_F64_Cosh -> ptext SLIT("cosh")
530 MO_F64_Tanh -> ptext SLIT("tanh")
531 MO_F64_Asin -> ptext SLIT("asin")
532 MO_F64_Acos -> ptext SLIT("acos")
533 MO_F64_Atan -> ptext SLIT("atan")
534 MO_F64_Log -> ptext SLIT("log")
535 MO_F64_Exp -> ptext SLIT("exp")
536 MO_F64_Sqrt -> ptext SLIT("sqrt")
537 MO_F32_Pwr -> ptext SLIT("powf")
538 MO_F32_Sin -> ptext SLIT("sinf")
539 MO_F32_Cos -> ptext SLIT("cosf")
540 MO_F32_Tan -> ptext SLIT("tanf")
541 MO_F32_Sinh -> ptext SLIT("sinhf")
542 MO_F32_Cosh -> ptext SLIT("coshf")
543 MO_F32_Tanh -> ptext SLIT("tanhf")
544 MO_F32_Asin -> ptext SLIT("asinf")
545 MO_F32_Acos -> ptext SLIT("acosf")
546 MO_F32_Atan -> ptext SLIT("atanf")
547 MO_F32_Log -> ptext SLIT("logf")
548 MO_F32_Exp -> ptext SLIT("expf")
549 MO_F32_Sqrt -> ptext SLIT("sqrtf")
551 -- ---------------------------------------------------------------------
555 mkJMP_, mkFN_, mkIF_ :: SDoc -> SDoc
557 mkJMP_ i = ptext SLIT("JMP_") <> parens i
558 mkFN_ i = ptext SLIT("FN_") <> parens i -- externally visible function
559 mkIF_ i = ptext SLIT("IF_") <> parens i -- locally visible
563 mkFB_ = ptext SLIT("FB_") -- function code begin
564 mkFE_ = ptext SLIT("FE_") -- function code end
566 -- from includes/Stg.h
568 mkC_,mkW_,mkP_,mkPP_,mkI_,mkA_,mkD_,mkF_,mkB_,mkL_,mkLI_,mkLW_ :: SDoc
570 mkC_ = ptext SLIT("(C_)") -- StgChar
571 mkW_ = ptext SLIT("(W_)") -- StgWord
572 mkP_ = ptext SLIT("(P_)") -- StgWord*
573 mkPP_ = ptext SLIT("(PP_)") -- P_*
574 mkI_ = ptext SLIT("(I_)") -- StgInt
575 mkA_ = ptext SLIT("(A_)") -- StgAddr
576 mkD_ = ptext SLIT("(D_)") -- const StgWord*
577 mkF_ = ptext SLIT("(F_)") -- StgFunPtr
578 mkB_ = ptext SLIT("(B_)") -- StgByteArray
579 mkL_ = ptext SLIT("(L_)") -- StgClosurePtr
581 mkLI_ = ptext SLIT("(LI_)") -- StgInt64
582 mkLW_ = ptext SLIT("(LW_)") -- StgWord64
585 -- ---------------------------------------------------------------------
589 -- Generating assignments is what we're all about, here
591 pprAssign :: CmmReg -> CmmExpr -> SDoc
593 -- dest is a reg, rhs is a reg
594 pprAssign r1 (CmmReg r2)
595 | not (isStrangeTypeReg r1) && not (isStrangeTypeReg r2)
596 || isPtrReg r1 && isPtrReg r2
597 = hcat [ pprAsPtrReg r1, equals, pprAsPtrReg r2, semi ]
599 -- dest is a reg, rhs is a CmmRegOff
600 pprAssign r1 (CmmRegOff r2 off)
601 | not (isStrangeTypeReg r1) && not (isStrangeTypeReg r2)
602 || isPtrReg r1 && isPtrReg r2
603 = hcat [ pprAsPtrReg r1, equals, pprAsPtrReg r2, op, int off', semi ]
605 off1 | isPtrReg r2 = off `shiftR` wordShift
608 (op,off') | off >= 0 = (char '+', off1)
609 | otherwise = (char '-', -off1)
611 -- dest is a reg, rhs is anything.
612 -- We can't cast the lvalue, so we have to cast the rhs if necessary. Casting
613 -- the lvalue elicits a warning from new GCC versions (3.4+).
616 = pprAsPtrReg r1 <> ptext SLIT(" = ") <> mkP_ <> pprExpr1 r2 <> semi
617 | Just ty <- strangeRegType r1
618 = pprReg r1 <> ptext SLIT(" = ") <> parens ty <> pprExpr1 r2 <> semi
620 = pprReg r1 <> ptext SLIT(" = ") <> pprExpr r2 <> semi
622 -- ---------------------------------------------------------------------
626 | isStrangeTypeReg reg = mkW_ <> pprReg reg
627 | otherwise = pprReg reg
629 -- True if the register has type StgPtr in C, otherwise it has an
630 -- integer type. We need to take care with pointer arithmetic on registers
632 isPtrReg :: CmmReg -> Bool
633 isPtrReg (CmmLocal _) = False
634 isPtrReg (CmmGlobal r) = isPtrGlobalReg r
636 isPtrGlobalReg :: GlobalReg -> Bool
637 isPtrGlobalReg (VanillaReg n) = True
638 isPtrGlobalReg Sp = True
639 isPtrGlobalReg Hp = True
640 isPtrGlobalReg HpLim = True
641 isPtrGlobalReg SpLim = True
642 isPtrGlobalReg _ = False
644 -- True if in C this register doesn't have the type given by
645 -- (machRepCType (cmmRegRep reg)), so it has to be cast.
646 isStrangeTypeReg :: CmmReg -> Bool
647 isStrangeTypeReg (CmmLocal _) = False
648 isStrangeTypeReg (CmmGlobal g) = isStrangeTypeGlobal g
650 isStrangeTypeGlobal :: GlobalReg -> Bool
651 isStrangeTypeGlobal CurrentTSO = True
652 isStrangeTypeGlobal CurrentNursery = True
653 isStrangeTypeGlobal BaseReg = True
654 isStrangeTypeGlobal r = isPtrGlobalReg r
656 strangeRegType :: CmmReg -> Maybe SDoc
657 strangeRegType (CmmGlobal CurrentTSO) = Just (ptext SLIT("struct StgTSO_ *"))
658 strangeRegType (CmmGlobal CurrentNursery) = Just (ptext SLIT("struct bdescr_ *"))
659 strangeRegType (CmmGlobal BaseReg) = Just (ptext SLIT("struct StgRegTable_ *"))
660 strangeRegType _ = Nothing
662 -- pprReg just prints the register name.
664 pprReg :: CmmReg -> SDoc
666 CmmLocal local -> pprLocalReg local
667 CmmGlobal global -> pprGlobalReg global
669 pprAsPtrReg :: CmmReg -> SDoc
670 pprAsPtrReg (CmmGlobal (VanillaReg n)) = char 'R' <> int n <> ptext SLIT(".p")
671 pprAsPtrReg other_reg = pprReg other_reg
673 pprGlobalReg :: GlobalReg -> SDoc
674 pprGlobalReg gr = case gr of
675 VanillaReg n -> char 'R' <> int n <> ptext SLIT(".w")
676 FloatReg n -> char 'F' <> int n
677 DoubleReg n -> char 'D' <> int n
678 LongReg n -> char 'L' <> int n
679 Sp -> ptext SLIT("Sp")
680 SpLim -> ptext SLIT("SpLim")
681 Hp -> ptext SLIT("Hp")
682 HpLim -> ptext SLIT("HpLim")
683 CurrentTSO -> ptext SLIT("CurrentTSO")
684 CurrentNursery -> ptext SLIT("CurrentNursery")
685 HpAlloc -> ptext SLIT("HpAlloc")
686 BaseReg -> ptext SLIT("BaseReg")
687 GCEnter1 -> ptext SLIT("stg_gc_enter_1")
688 GCFun -> ptext SLIT("stg_gc_fun")
690 pprLocalReg :: LocalReg -> SDoc
691 pprLocalReg (LocalReg uniq _rep) = char '_' <> ppr uniq
693 -- -----------------------------------------------------------------------------
696 pprCall :: SDoc -> CCallConv -> [(CmmReg,MachHint)] -> [(CmmExpr,MachHint)]
697 -> Maybe [GlobalReg] -> SDoc
699 pprCall ppr_fn cconv results args vols
700 | not (is_cish cconv)
701 = panic "pprCall: unknown calling convention"
705 ptext SLIT("CALLER_SAVE_SYSTEM") $$
706 #if x86_64_TARGET_ARCH
707 -- HACK around gcc optimisations.
708 -- x86_64 needs a __DISCARD__() here, to create a barrier between
709 -- putting the arguments into temporaries and passing the arguments
710 -- to the callee, because the argument expressions may refer to
711 -- machine registers that are also used for passing arguments in the
712 -- C calling convention.
713 (if (not opt_Unregisterised)
714 then ptext SLIT("__DISCARD__();")
717 ppr_assign results (ppr_fn <> parens (commafy (map pprArg args))) <> semi $$
718 ptext SLIT("CALLER_RESTORE_SYSTEM") $$
721 ppr_assign [] rhs = rhs
722 ppr_assign [(reg@(CmmGlobal BaseReg), hint)] rhs
723 | Just ty <- strangeRegType reg
724 = ptext SLIT("ASSIGN_BaseReg") <> parens (parens ty <> rhs)
725 -- BaseReg is special, sometimes it isn't an lvalue and we
726 -- can't assign to it.
727 ppr_assign [(one,hint)] rhs
728 | Just ty <- strangeRegType one
729 = pprReg one <> ptext SLIT(" = ") <> parens ty <> rhs
731 = pprReg one <> ptext SLIT(" = ")
732 <> pprUnHint hint (cmmRegRep one) <> rhs
733 ppr_assign _other _rhs = panic "pprCall: multiple results"
735 pprArg (expr, PtrHint)
736 = cCast (ptext SLIT("void *")) expr
737 -- see comment by machRepHintCType below
738 pprArg (expr, SignedHint)
739 = cCast (machRepSignedCType (cmmExprRep expr)) expr
740 pprArg (expr, _other)
743 pprUnHint PtrHint rep = parens (machRepCType rep)
744 pprUnHint SignedHint rep = parens (machRepCType rep)
745 pprUnHint _ _ = empty
747 save = save_restore SLIT("CALLER_SAVE")
748 restore = save_restore SLIT("CALLER_RESTORE")
750 -- Nothing says "I don't know what's live; save everything"
751 -- CALLER_SAVE_USER is defined in ghc/includes/Regs.h
752 save_restore txt Nothing = ptext txt <> ptext SLIT("_USER")
753 save_restore txt (Just these) = vcat (map saveRestoreGlobal these)
754 where saveRestoreGlobal r = ptext txt <> char '_' <> pprGlobalRegName r
756 pprGlobalRegName :: GlobalReg -> SDoc
757 pprGlobalRegName gr = case gr of
758 VanillaReg n -> char 'R' <> int n -- without the .w suffix
761 -- Currently we only have these two calling conventions, but this might
762 -- change in the future...
763 is_cish CCallConv = True
764 is_cish StdCallConv = True
766 -- ---------------------------------------------------------------------
767 -- Find and print local and external declarations for a list of
770 pprTempAndExternDecls :: [CmmBasicBlock] -> (SDoc{-temps-}, SDoc{-externs-})
771 pprTempAndExternDecls stmts
772 = (vcat (map pprTempDecl (eltsUFM temps)),
773 vcat (map (pprExternDecl False{-ToDo-}) (keysFM lbls)))
774 where (temps, lbls) = runTE (mapM_ te_BB stmts)
776 pprDataExterns :: [CmmStatic] -> SDoc
777 pprDataExterns statics
778 = vcat (map (pprExternDecl False{-ToDo-}) (keysFM lbls))
779 where (_, lbls) = runTE (mapM_ te_Static statics)
781 pprTempDecl :: LocalReg -> SDoc
782 pprTempDecl l@(LocalReg _uniq rep)
783 = hcat [ machRepCType rep, space, pprLocalReg l, semi ]
785 pprExternDecl :: Bool -> CLabel -> SDoc
786 pprExternDecl in_srt lbl
787 -- do not print anything for "known external" things
788 | not (needsCDecl lbl) = empty
790 hcat [ visibility, label_type (labelType lbl),
791 lparen, dyn_wrapper (pprCLabel lbl), text ");" ]
794 | in_srt && labelDynamic lbl = text "DLL_IMPORT_DATA_VAR" <> parens d
797 label_type CodeLabel = ptext SLIT("F_")
798 label_type DataLabel = ptext SLIT("I_")
801 | externallyVisibleCLabel lbl = char 'E'
802 | otherwise = char 'I'
805 type TEState = (UniqSet LocalReg, FiniteMap CLabel ())
806 newtype TE a = TE { unTE :: TEState -> (a, TEState) }
808 instance Monad TE where
809 TE m >>= k = TE $ \s -> case m s of (a, s') -> unTE (k a) s'
810 return a = TE $ \s -> (a, s)
812 te_lbl :: CLabel -> TE ()
813 te_lbl lbl = TE $ \(temps,lbls) -> ((), (temps, addToFM lbls lbl ()))
815 te_temp :: LocalReg -> TE ()
816 te_temp r = TE $ \(temps,lbls) -> ((), (addOneToUniqSet temps r, lbls))
818 runTE :: TE () -> TEState
819 runTE (TE m) = snd (m (emptyUniqSet, emptyFM))
821 te_Static :: CmmStatic -> TE ()
822 te_Static (CmmStaticLit lit) = te_Lit lit
823 te_Static _ = return ()
825 te_BB :: CmmBasicBlock -> TE ()
826 te_BB (BasicBlock _ ss) = mapM_ te_Stmt ss
828 te_Lit :: CmmLit -> TE ()
829 te_Lit (CmmLabel l) = te_lbl l
830 te_Lit (CmmLabelOff l _) = te_lbl l
831 te_Lit (CmmLabelDiffOff l1 l2 _) = te_lbl l1
834 te_Stmt :: CmmStmt -> TE ()
835 te_Stmt (CmmAssign r e) = te_Reg r >> te_Expr e
836 te_Stmt (CmmStore l r) = te_Expr l >> te_Expr r
837 te_Stmt (CmmCall _ rs es _) = mapM_ (te_Reg.fst) rs >>
838 mapM_ (te_Expr.fst) es
839 te_Stmt (CmmCondBranch e _) = te_Expr e
840 te_Stmt (CmmSwitch e _) = te_Expr e
841 te_Stmt (CmmJump e _) = te_Expr e
842 te_Stmt _ = return ()
844 te_Expr :: CmmExpr -> TE ()
845 te_Expr (CmmLit lit) = te_Lit lit
846 te_Expr (CmmLoad e _) = te_Expr e
847 te_Expr (CmmReg r) = te_Reg r
848 te_Expr (CmmMachOp _ es) = mapM_ te_Expr es
849 te_Expr (CmmRegOff r _) = te_Reg r
851 te_Reg :: CmmReg -> TE ()
852 te_Reg (CmmLocal l) = te_temp l
856 -- ---------------------------------------------------------------------
857 -- C types for MachReps
859 cCast :: SDoc -> CmmExpr -> SDoc
860 cCast ty expr = parens ty <> pprExpr1 expr
862 -- This is for finding the types of foreign call arguments. For a pointer
863 -- argument, we always cast the argument to (void *), to avoid warnings from
865 machRepHintCType :: MachRep -> MachHint -> SDoc
866 machRepHintCType rep PtrHint = ptext SLIT("void *")
867 machRepHintCType rep SignedHint = machRepSignedCType rep
868 machRepHintCType rep _other = machRepCType rep
870 machRepPtrCType :: MachRep -> SDoc
871 machRepPtrCType r | r == wordRep = ptext SLIT("P_")
872 | otherwise = machRepCType r <> char '*'
874 machRepCType :: MachRep -> SDoc
875 machRepCType r | r == wordRep = ptext SLIT("W_")
876 | otherwise = sized_type
877 where sized_type = case r of
878 I8 -> ptext SLIT("StgWord8")
879 I16 -> ptext SLIT("StgWord16")
880 I32 -> ptext SLIT("StgWord32")
881 I64 -> ptext SLIT("StgWord64")
882 F32 -> ptext SLIT("StgFloat") -- ToDo: correct?
883 F64 -> ptext SLIT("StgDouble")
884 _ -> panic "machRepCType"
886 machRepSignedCType :: MachRep -> SDoc
887 machRepSignedCType r | r == wordRep = ptext SLIT("I_")
888 | otherwise = sized_type
889 where sized_type = case r of
890 I8 -> ptext SLIT("StgInt8")
891 I16 -> ptext SLIT("StgInt16")
892 I32 -> ptext SLIT("StgInt32")
893 I64 -> ptext SLIT("StgInt64")
894 F32 -> ptext SLIT("StgFloat") -- ToDo: correct?
895 F64 -> ptext SLIT("StgDouble")
896 _ -> panic "machRepCType"
898 -- ---------------------------------------------------------------------
899 -- print strings as valid C strings
901 pprStringInCStyle :: [Word8] -> SDoc
902 pprStringInCStyle s = doubleQuotes (text (concatMap charToC s))
904 charToC :: Word8 -> String
906 case chr (fromIntegral w) of
910 c | c >= ' ' && c <= '~' -> [c]
911 | otherwise -> ['\\',
912 chr (ord '0' + ord c `div` 64),
913 chr (ord '0' + ord c `div` 8 `mod` 8),
914 chr (ord '0' + ord c `mod` 8)]
916 -- ---------------------------------------------------------------------------
917 -- Initialising static objects with floating-point numbers. We can't
918 -- just emit the floating point number, because C will cast it to an int
919 -- by rounding it. We want the actual bit-representation of the float.
921 -- This is a hack to turn the floating point numbers into ints that we
922 -- can safely initialise to static locations.
925 | machRepByteWidth F64 == 2 * wORD_SIZE = True
926 | machRepByteWidth F64 == wORD_SIZE = False
927 | otherwise = panic "big_doubles"
929 #if __GLASGOW_HASKELL__ >= 504
930 newFloatArray :: (Int,Int) -> ST s (STUArray s Int Float)
931 newFloatArray = newArray_
933 newDoubleArray :: (Int,Int) -> ST s (STUArray s Int Double)
934 newDoubleArray = newArray_
936 castFloatToIntArray :: STUArray s Int Float -> ST s (STUArray s Int Int)
937 castFloatToIntArray = castSTUArray
939 castDoubleToIntArray :: STUArray s Int Double -> ST s (STUArray s Int Int)
940 castDoubleToIntArray = castSTUArray
942 writeFloatArray :: STUArray s Int Float -> Int -> Float -> ST s ()
943 writeFloatArray = writeArray
945 writeDoubleArray :: STUArray s Int Double -> Int -> Double -> ST s ()
946 writeDoubleArray = writeArray
948 readIntArray :: STUArray s Int Int -> Int -> ST s Int
949 readIntArray = readArray
953 castFloatToIntArray :: MutableByteArray s t -> ST s (MutableByteArray s t)
954 castFloatToIntArray = return
956 castDoubleToIntArray :: MutableByteArray s t -> ST s (MutableByteArray s t)
957 castDoubleToIntArray = return
961 -- floats are always 1 word
962 floatToWord :: Rational -> CmmLit
965 arr <- newFloatArray ((0::Int),0)
966 writeFloatArray arr 0 (fromRational r)
967 arr' <- castFloatToIntArray arr
968 i <- readIntArray arr' 0
969 return (CmmInt (toInteger i) wordRep)
972 doubleToWords :: Rational -> [CmmLit]
974 | big_doubles -- doubles are 2 words
976 arr <- newDoubleArray ((0::Int),1)
977 writeDoubleArray arr 0 (fromRational r)
978 arr' <- castDoubleToIntArray arr
979 i1 <- readIntArray arr' 0
980 i2 <- readIntArray arr' 1
981 return [ CmmInt (toInteger i1) wordRep
982 , CmmInt (toInteger i2) wordRep
985 | otherwise -- doubles are 1 word
987 arr <- newDoubleArray ((0::Int),0)
988 writeDoubleArray arr 0 (fromRational r)
989 arr' <- castDoubleToIntArray arr
990 i <- readIntArray arr' 0
991 return [ CmmInt (toInteger i) wordRep ]
994 -- ---------------------------------------------------------------------------
998 wordShift = machRepLogWidth wordRep
1000 commafy :: [SDoc] -> SDoc
1001 commafy xs = hsep $ punctuate comma xs
1003 -- Print in C hex format: 0x13fa
1004 pprHexVal :: Integer -> MachRep -> SDoc
1005 pprHexVal 0 _ = ptext SLIT("0x0")
1007 | w < 0 = parens (char '-' <> ptext SLIT("0x") <> go (-w) <> repsuffix rep)
1008 | otherwise = ptext SLIT("0x") <> go w <> repsuffix rep
1010 -- type suffix for literals:
1011 -- Integer literals are unsigned in Cmm/C. We explicitly cast to
1012 -- signed values for doing signed operations, but at all other
1013 -- times values are unsigned. This also helps eliminate occasional
1014 -- warnings about integer overflow from gcc.
1016 -- on 32-bit platforms, add "ULL" to 64-bit literals
1017 repsuffix I64 | wORD_SIZE == 4 = ptext SLIT("ULL")
1018 -- on 64-bit platforms with 32-bit int, add "L" to 64-bit literals
1019 repsuffix I64 | cINT_SIZE == 4 = ptext SLIT("UL")
1020 repsuffix _ = char 'U'
1025 (q,r) = w' `quotRem` 16
1026 dig | r < 10 = char (chr (fromInteger r + ord '0'))
1027 | otherwise = char (chr (fromInteger r - 10 + ord 'a'))