1 -----------------------------------------------------------------------------
3 -- Pretty-printing of Cmm as C, suitable for feeding gcc
5 -- (c) The University of Glasgow 2004-2006
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.
20 -- The above warning supression flag is a temporary kludge.
21 -- While working on this module you are encouraged to remove it and fix
22 -- any warnings in the module. See
23 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
31 #include "HsVersions.h"
58 import PprCmm () -- instances only
63 import Control.Monad.ST
65 #if x86_64_TARGET_ARCH
66 import StaticFlags ( opt_Unregisterised )
69 #if defined(alpha_TARGET_ARCH) || defined(mips_TARGET_ARCH) || defined(mipsel_TARGET_ARCH) || defined(arm_TARGET_ARCH)
70 #define BEWARE_LOAD_STORE_ALIGNMENT
73 -- --------------------------------------------------------------------------
76 pprCs :: DynFlags -> [RawCmm] -> SDoc
78 = pprCode CStyle (vcat $ map (\c -> split_marker $$ pprC c) cmms)
81 | dopt Opt_SplitObjs dflags = ptext SLIT("__STG_SPLIT_MARKER")
84 writeCs :: DynFlags -> Handle -> [RawCmm] -> IO ()
85 writeCs dflags handle cmms
86 = printForC handle (pprCs dflags cmms)
88 -- --------------------------------------------------------------------------
89 -- Now do some real work
91 -- for fun, we could call cmmToCmm over the tops...
94 pprC :: RawCmm -> SDoc
95 pprC (Cmm tops) = vcat $ intersperse (text "") $ map pprTop tops
100 pprTop :: RawCmmTop -> SDoc
101 pprTop (CmmProc info clbl _params (ListGraph blocks)) =
103 then pprDataExterns info $$
104 pprWordArray (entryLblToInfoLbl clbl) info
108 -- the first block doesn't get a label:
109 (BasicBlock _ stmts : rest) -> vcat [
112 (if (externallyVisibleCLabel clbl)
113 then mkFN_ else mkIF_) (pprCLabel clbl) <+> lbrace,
116 nest 8 (vcat (map pprStmt stmts)) $$
117 vcat (map pprBBlock rest),
122 (temp_decls, extern_decls) = pprTempAndExternDecls blocks
125 -- Chunks of static data.
127 -- We only handle (a) arrays of word-sized things and (b) strings.
129 pprTop (CmmData _section _ds@[CmmDataLabel lbl, CmmString str]) =
131 pprLocalness lbl, ptext SLIT("char "), pprCLabel lbl,
132 ptext SLIT("[] = "), pprStringInCStyle str, semi
135 pprTop (CmmData _section _ds@[CmmDataLabel lbl, CmmUninitialised size]) =
137 pprLocalness lbl, ptext SLIT("char "), pprCLabel lbl,
138 brackets (int size), semi
141 pprTop top@(CmmData _section (CmmDataLabel lbl : lits)) =
142 pprDataExterns lits $$
143 pprWordArray lbl lits
145 -- these shouldn't appear?
146 pprTop (CmmData _ _) = panic "PprC.pprTop: can't handle this data"
149 -- --------------------------------------------------------------------------
150 -- BasicBlocks are self-contained entities: they always end in a jump.
152 -- Like nativeGen/AsmCodeGen, we could probably reorder blocks to turn
153 -- as many jumps as possible into fall throughs.
156 pprBBlock :: CmmBasicBlock -> SDoc
157 pprBBlock (BasicBlock lbl stmts) =
159 pprTrace "pprC.pprBBlock: curious empty code block for"
160 (pprBlockId lbl) empty
162 nest 4 (pprBlockId lbl <> colon) $$
163 nest 8 (vcat (map pprStmt stmts))
165 -- --------------------------------------------------------------------------
166 -- Info tables. Just arrays of words.
167 -- See codeGen/ClosureInfo, and nativeGen/PprMach
169 pprWordArray :: CLabel -> [CmmStatic] -> SDoc
171 = hcat [ pprLocalness lbl, ptext SLIT("StgWord")
172 , space, pprCLabel lbl, ptext SLIT("[] = {") ]
173 $$ nest 8 (commafy (pprStatics ds))
177 -- has to be static, if it isn't globally visible
179 pprLocalness :: CLabel -> SDoc
180 pprLocalness lbl | not $ externallyVisibleCLabel lbl = ptext SLIT("static ")
183 -- --------------------------------------------------------------------------
187 pprStmt :: CmmStmt -> SDoc
189 pprStmt stmt = case stmt of
191 CmmComment s -> (hang (ptext SLIT("/*")) 3 (ftext s)) $$ ptext SLIT("*/")
193 CmmAssign dest src -> pprAssign dest src
196 | rep == I64 && wordRep /= I64
197 -> ptext SLIT("ASSIGN_Word64") <>
198 parens (mkP_ <> pprExpr1 dest <> comma <> pprExpr src) <> semi
200 | rep == F64 && wordRep /= I64
201 -> ptext SLIT("ASSIGN_DBL") <>
202 parens (mkP_ <> pprExpr1 dest <> comma <> pprExpr src) <> semi
205 -> hsep [ pprExpr (CmmLoad dest rep), equals, pprExpr src <> semi ]
209 CmmCall (CmmCallee fn cconv) results args safety _ret ->
210 -- Controversial: leave this out for now.
213 pprCall ppr_fn cconv results args safety
216 CmmLit (CmmLabel lbl) -> pprCLabel lbl
217 _ -> parens (cCast (pprCFunType cconv results args) fn)
218 -- for a dynamic call, cast the expression to
219 -- a function of the right type (we hope).
221 -- we #undef a function before calling it: the FFI is supposed to be
222 -- an interface specifically to C, not to C+CPP. For one thing, this
223 -- makes the via-C route more compatible with the NCG. If macros
224 -- are being used for optimisation, then inline functions are probably
226 pprUndef (CmmLit (CmmLabel lbl)) =
227 ptext SLIT("#undef") <+> pprCLabel lbl
230 CmmCall (CmmPrim op) results args safety _ret ->
231 pprCall ppr_fn CCallConv results args safety
233 ppr_fn = pprCallishMachOp_for_C op
235 CmmBranch ident -> pprBranch ident
236 CmmCondBranch expr ident -> pprCondBranch expr ident
237 CmmJump lbl _params -> mkJMP_(pprExpr lbl) <> semi
238 CmmSwitch arg ids -> pprSwitch arg ids
240 pprCFunType :: CCallConv -> CmmFormals -> CmmActuals -> SDoc
241 pprCFunType cconv ress args
244 parens (text (ccallConvAttribute cconv) <> char '*'),
245 parens (commafy (map arg_type args))
248 res_type [] = ptext SLIT("void")
249 res_type [(one,hint)] = machRepHintCType (localRegRep one) hint
251 arg_type (expr,hint) = machRepHintCType (cmmExprRep expr) hint
253 -- ---------------------------------------------------------------------
254 -- unconditional branches
255 pprBranch :: BlockId -> SDoc
256 pprBranch ident = ptext SLIT("goto") <+> pprBlockId ident <> semi
259 -- ---------------------------------------------------------------------
260 -- conditional branches to local labels
261 pprCondBranch :: CmmExpr -> BlockId -> SDoc
262 pprCondBranch expr ident
263 = hsep [ ptext SLIT("if") , parens(pprExpr expr) ,
264 ptext SLIT("goto") , (pprBlockId ident) <> semi ]
267 -- ---------------------------------------------------------------------
268 -- a local table branch
270 -- we find the fall-through cases
272 -- N.B. we remove Nothing's from the list of branches, as they are
273 -- 'undefined'. However, they may be defined one day, so we better
274 -- document this behaviour.
276 pprSwitch :: CmmExpr -> [ Maybe BlockId ] -> SDoc
277 pprSwitch e maybe_ids
278 = let pairs = [ (ix, ident) | (ix,Just ident) <- zip [0..] maybe_ids ]
279 pairs2 = [ (map fst as, snd (head as)) | as <- groupBy sndEq pairs ]
281 (hang (ptext SLIT("switch") <+> parens ( pprExpr e ) <+> lbrace)
282 4 (vcat ( map caseify pairs2 )))
286 sndEq (_,x) (_,y) = x == y
289 caseify (ix:ixs, ident) = vcat (map do_fallthrough ixs) $$ final_branch ix
292 hsep [ ptext SLIT("case") , pprHexVal ix wordRep <> colon ,
293 ptext SLIT("/* fall through */") ]
296 hsep [ ptext SLIT("case") , pprHexVal ix wordRep <> colon ,
297 ptext SLIT("goto") , (pprBlockId ident) <> semi ]
299 -- ---------------------------------------------------------------------
303 -- C Types: the invariant is that the C expression generated by
307 -- has a type in C which is also given by
309 -- machRepCType (cmmExprRep e)
311 -- (similar invariants apply to the rest of the pretty printer).
313 pprExpr :: CmmExpr -> SDoc
314 pprExpr e = case e of
315 CmmLit lit -> pprLit lit
317 CmmLoad e I64 | wordRep /= I64
318 -> ptext SLIT("PK_Word64") <> parens (mkP_ <> pprExpr1 e)
320 CmmLoad e F64 | wordRep /= I64
321 -> ptext SLIT("PK_DBL") <> parens (mkP_ <> pprExpr1 e)
323 CmmLoad (CmmReg r) rep
324 | isPtrReg r && rep == wordRep
325 -> char '*' <> pprAsPtrReg r
327 CmmLoad (CmmRegOff r 0) rep
328 | isPtrReg r && rep == wordRep
329 -> char '*' <> pprAsPtrReg r
331 CmmLoad (CmmRegOff r off) rep
332 | isPtrReg r && rep == wordRep && (off `rem` wORD_SIZE == 0)
333 -- ToDo: check that the offset is a word multiple?
334 -- (For tagging to work, I had to avoid unaligned loads. --ARY)
335 -> pprAsPtrReg r <> brackets (ppr (off `shiftR` wordShift))
341 CmmReg reg -> pprCastReg reg
342 CmmRegOff reg 0 -> pprCastReg reg
345 | i > 0 -> pprRegOff (char '+') i
346 | otherwise -> pprRegOff (char '-') (-i)
348 pprRegOff op i' = pprCastReg reg <> op <> int i'
350 CmmMachOp mop args -> pprMachOpApp mop args
352 pprExpr1 :: CmmExpr -> SDoc
353 pprExpr1 (CmmLit lit) = pprLit1 lit
354 pprExpr1 e@(CmmReg _reg) = pprExpr e
355 pprExpr1 other = parens (pprExpr other)
357 -- --------------------------------------------------------------------------
358 -- MachOp applications
360 pprMachOpApp :: MachOp -> [CmmExpr] -> SDoc
364 = ptext SLIT("mulIntMayOflo") <> parens (commafy (map pprExpr args))
365 where isMulMayOfloOp (MO_U_MulMayOflo _) = True
366 isMulMayOfloOp (MO_S_MulMayOflo _) = True
367 isMulMayOfloOp _ = False
369 pprMachOpApp mop args
370 | Just ty <- machOpNeedsCast mop
371 = ty <> parens (pprMachOpApp' mop args)
373 = pprMachOpApp' mop args
375 -- Comparisons in C have type 'int', but we want type W_ (this is what
376 -- resultRepOfMachOp says). The other C operations inherit their type
377 -- from their operands, so no casting is required.
378 machOpNeedsCast :: MachOp -> Maybe SDoc
380 | isComparisonMachOp mop = Just mkW_
381 | otherwise = Nothing
383 pprMachOpApp' mop args
386 [x,y] -> pprArg x <+> pprMachOp_for_C mop <+> pprArg y
389 [x] -> pprMachOp_for_C mop <> parens (pprArg x)
391 _ -> panic "PprC.pprMachOp : machop with wrong number of args"
394 pprArg e | signedOp mop = cCast (machRepSignedCType (cmmExprRep e)) e
395 | otherwise = pprExpr1 e
397 -- --------------------------------------------------------------------------
400 pprLit :: CmmLit -> SDoc
401 pprLit lit = case lit of
402 CmmInt i rep -> pprHexVal i rep
403 CmmFloat f rep -> parens (machRepCType rep) <> (rational f)
404 CmmLabel clbl -> mkW_ <> pprCLabelAddr clbl
405 CmmLabelOff clbl i -> mkW_ <> pprCLabelAddr clbl <> char '+' <> int i
406 CmmLabelDiffOff clbl1 clbl2 i
408 -- * the lit must occur in the info table clbl2
409 -- * clbl1 must be an SRT, a slow entry point or a large bitmap
410 -- The Mangler is expected to convert any reference to an SRT,
411 -- a slow entry point or a large bitmap
412 -- from an info table to an offset.
413 -> mkW_ <> pprCLabelAddr clbl1 <> char '+' <> int i
415 pprCLabelAddr lbl = char '&' <> pprCLabel lbl
417 pprLit1 :: CmmLit -> SDoc
418 pprLit1 lit@(CmmLabelOff _ _) = parens (pprLit lit)
419 pprLit1 lit@(CmmLabelDiffOff _ _ _) = parens (pprLit lit)
420 pprLit1 lit@(CmmFloat _ _) = parens (pprLit lit)
421 pprLit1 other = pprLit other
423 -- ---------------------------------------------------------------------------
426 pprStatics :: [CmmStatic] -> [SDoc]
428 pprStatics (CmmStaticLit (CmmFloat f F32) : rest)
429 = pprLit1 (floatToWord f) : pprStatics rest
430 pprStatics (CmmStaticLit (CmmFloat f F64) : rest)
431 = map pprLit1 (doubleToWords f) ++ pprStatics rest
432 pprStatics (CmmStaticLit (CmmInt i I64) : rest)
433 | machRepByteWidth I32 == wORD_SIZE
434 #ifdef WORDS_BIGENDIAN
435 = pprStatics (CmmStaticLit (CmmInt q I32) :
436 CmmStaticLit (CmmInt r I32) : rest)
438 = pprStatics (CmmStaticLit (CmmInt r I32) :
439 CmmStaticLit (CmmInt q I32) : rest)
441 where r = i .&. 0xffffffff
443 pprStatics (CmmStaticLit (CmmInt i rep) : rest)
444 | machRepByteWidth rep /= wORD_SIZE
445 = panic "pprStatics: cannot emit a non-word-sized static literal"
446 pprStatics (CmmStaticLit lit : rest)
447 = pprLit1 lit : pprStatics rest
448 pprStatics (other : rest)
449 = pprPanic "pprWord" (pprStatic other)
451 pprStatic :: CmmStatic -> SDoc
452 pprStatic s = case s of
454 CmmStaticLit lit -> nest 4 (pprLit lit)
455 CmmAlign i -> nest 4 (ptext SLIT("/* align */") <+> int i)
456 CmmDataLabel clbl -> pprCLabel clbl <> colon
457 CmmUninitialised i -> nest 4 (mkC_ <> brackets (int i))
459 -- these should be inlined, like the old .hc
460 CmmString s' -> nest 4 (mkW_ <> parens(pprStringInCStyle s'))
463 -- ---------------------------------------------------------------------------
466 pprBlockId :: BlockId -> SDoc
467 pprBlockId b = char '_' <> ppr (getUnique b)
469 -- --------------------------------------------------------------------------
470 -- Print a MachOp in a way suitable for emitting via C.
473 pprMachOp_for_C :: MachOp -> SDoc
475 pprMachOp_for_C mop = case mop of
477 -- Integer operations
480 MO_Eq _ -> ptext SLIT("==")
481 MO_Ne _ -> ptext SLIT("!=")
484 MO_S_Quot _ -> char '/'
485 MO_S_Rem _ -> char '%'
486 MO_S_Neg _ -> char '-'
488 MO_U_Quot _ -> char '/'
489 MO_U_Rem _ -> char '%'
491 -- Signed comparisons (floating-point comparisons also use these)
492 -- & Unsigned comparisons
493 MO_S_Ge _ -> ptext SLIT(">=")
494 MO_S_Le _ -> ptext SLIT("<=")
495 MO_S_Gt _ -> char '>'
496 MO_S_Lt _ -> char '<'
498 MO_U_Ge _ -> ptext SLIT(">=")
499 MO_U_Le _ -> ptext SLIT("<=")
500 MO_U_Gt _ -> char '>'
501 MO_U_Lt _ -> char '<'
503 -- Bitwise operations. Not all of these may be supported at all
504 -- sizes, and only integral MachReps are valid.
509 MO_Shl _ -> ptext SLIT("<<")
510 MO_U_Shr _ -> ptext SLIT(">>") -- unsigned shift right
511 MO_S_Shr _ -> ptext SLIT(">>") -- signed shift right
513 -- Conversions. Some of these will be NOPs.
514 -- Floating-point conversions use the signed variant.
515 -- We won't know to generate (void*) casts here, but maybe from
519 MO_U_Conv I8 I8 -> empty
520 MO_U_Conv I16 I16 -> empty
521 MO_U_Conv I32 I32 -> empty
522 MO_U_Conv I64 I64 -> empty
523 MO_U_Conv I128 I128 -> empty
524 MO_S_Conv I8 I8 -> empty
525 MO_S_Conv I16 I16 -> empty
526 MO_S_Conv I32 I32 -> empty
527 MO_S_Conv I64 I64 -> empty
528 MO_S_Conv I128 I128 -> empty
530 MO_U_Conv _from to -> parens (machRepCType to)
531 MO_S_Conv _from to -> parens (machRepSignedCType to)
533 _ -> panic "PprC.pprMachOp_for_C: unknown machop"
535 signedOp :: MachOp -> Bool
536 signedOp (MO_S_Quot _) = True
537 signedOp (MO_S_Rem _) = True
538 signedOp (MO_S_Neg _) = True
539 signedOp (MO_S_Ge _) = True
540 signedOp (MO_S_Le _) = True
541 signedOp (MO_S_Gt _) = True
542 signedOp (MO_S_Lt _) = True
543 signedOp (MO_S_Shr _) = True
544 signedOp (MO_S_Conv _ _) = True
547 -- ---------------------------------------------------------------------
548 -- tend to be implemented by foreign calls
550 pprCallishMachOp_for_C :: CallishMachOp -> SDoc
552 pprCallishMachOp_for_C mop
554 MO_F64_Pwr -> ptext SLIT("pow")
555 MO_F64_Sin -> ptext SLIT("sin")
556 MO_F64_Cos -> ptext SLIT("cos")
557 MO_F64_Tan -> ptext SLIT("tan")
558 MO_F64_Sinh -> ptext SLIT("sinh")
559 MO_F64_Cosh -> ptext SLIT("cosh")
560 MO_F64_Tanh -> ptext SLIT("tanh")
561 MO_F64_Asin -> ptext SLIT("asin")
562 MO_F64_Acos -> ptext SLIT("acos")
563 MO_F64_Atan -> ptext SLIT("atan")
564 MO_F64_Log -> ptext SLIT("log")
565 MO_F64_Exp -> ptext SLIT("exp")
566 MO_F64_Sqrt -> ptext SLIT("sqrt")
567 MO_F32_Pwr -> ptext SLIT("powf")
568 MO_F32_Sin -> ptext SLIT("sinf")
569 MO_F32_Cos -> ptext SLIT("cosf")
570 MO_F32_Tan -> ptext SLIT("tanf")
571 MO_F32_Sinh -> ptext SLIT("sinhf")
572 MO_F32_Cosh -> ptext SLIT("coshf")
573 MO_F32_Tanh -> ptext SLIT("tanhf")
574 MO_F32_Asin -> ptext SLIT("asinf")
575 MO_F32_Acos -> ptext SLIT("acosf")
576 MO_F32_Atan -> ptext SLIT("atanf")
577 MO_F32_Log -> ptext SLIT("logf")
578 MO_F32_Exp -> ptext SLIT("expf")
579 MO_F32_Sqrt -> ptext SLIT("sqrtf")
580 MO_WriteBarrier -> ptext SLIT("write_barrier")
582 -- ---------------------------------------------------------------------
586 mkJMP_, mkFN_, mkIF_ :: SDoc -> SDoc
588 mkJMP_ i = ptext SLIT("JMP_") <> parens i
589 mkFN_ i = ptext SLIT("FN_") <> parens i -- externally visible function
590 mkIF_ i = ptext SLIT("IF_") <> parens i -- locally visible
594 mkFB_ = ptext SLIT("FB_") -- function code begin
595 mkFE_ = ptext SLIT("FE_") -- function code end
597 -- from includes/Stg.h
599 mkC_,mkW_,mkP_,mkPP_,mkI_,mkA_,mkD_,mkF_,mkB_,mkL_,mkLI_,mkLW_ :: SDoc
601 mkC_ = ptext SLIT("(C_)") -- StgChar
602 mkW_ = ptext SLIT("(W_)") -- StgWord
603 mkP_ = ptext SLIT("(P_)") -- StgWord*
604 mkPP_ = ptext SLIT("(PP_)") -- P_*
605 mkI_ = ptext SLIT("(I_)") -- StgInt
606 mkA_ = ptext SLIT("(A_)") -- StgAddr
607 mkD_ = ptext SLIT("(D_)") -- const StgWord*
608 mkF_ = ptext SLIT("(F_)") -- StgFunPtr
609 mkB_ = ptext SLIT("(B_)") -- StgByteArray
610 mkL_ = ptext SLIT("(L_)") -- StgClosurePtr
612 mkLI_ = ptext SLIT("(LI_)") -- StgInt64
613 mkLW_ = ptext SLIT("(LW_)") -- StgWord64
616 -- ---------------------------------------------------------------------
620 -- Generating assignments is what we're all about, here
622 pprAssign :: CmmReg -> CmmExpr -> SDoc
624 -- dest is a reg, rhs is a reg
625 pprAssign r1 (CmmReg r2)
626 | isPtrReg r1 && isPtrReg r2
627 = hcat [ pprAsPtrReg r1, equals, pprAsPtrReg r2, semi ]
629 -- dest is a reg, rhs is a CmmRegOff
630 pprAssign r1 (CmmRegOff r2 off)
631 | isPtrReg r1 && isPtrReg r2 && (off `rem` wORD_SIZE == 0)
632 = hcat [ pprAsPtrReg r1, equals, pprAsPtrReg r2, op, int off', semi ]
634 off1 = off `shiftR` wordShift
636 (op,off') | off >= 0 = (char '+', off1)
637 | otherwise = (char '-', -off1)
639 -- dest is a reg, rhs is anything.
640 -- We can't cast the lvalue, so we have to cast the rhs if necessary. Casting
641 -- the lvalue elicits a warning from new GCC versions (3.4+).
643 | isFixedPtrReg r1 = mkAssign (mkP_ <> pprExpr1 r2)
644 | Just ty <- strangeRegType r1 = mkAssign (parens ty <> pprExpr1 r2)
645 | otherwise = mkAssign (pprExpr r2)
646 where mkAssign x = if r1 == CmmGlobal BaseReg
647 then ptext SLIT("ASSIGN_BaseReg") <> parens x <> semi
648 else pprReg r1 <> ptext SLIT(" = ") <> x <> semi
650 -- ---------------------------------------------------------------------
654 | isStrangeTypeReg reg = mkW_ <> pprReg reg
655 | otherwise = pprReg reg
657 -- True if (pprReg reg) will give an expression with type StgPtr. We
658 -- need to take care with pointer arithmetic on registers with type
660 isFixedPtrReg :: CmmReg -> Bool
661 isFixedPtrReg (CmmLocal _) = False
662 isFixedPtrReg (CmmGlobal r) = isFixedPtrGlobalReg r
664 -- True if (pprAsPtrReg reg) will give an expression with type StgPtr
665 isPtrReg :: CmmReg -> Bool
666 isPtrReg (CmmLocal _) = False
667 isPtrReg (CmmGlobal (VanillaReg n)) = True -- if we print via pprAsPtrReg
668 isPtrReg (CmmGlobal reg) = isFixedPtrGlobalReg reg
670 -- True if this global reg has type StgPtr
671 isFixedPtrGlobalReg :: GlobalReg -> Bool
672 isFixedPtrGlobalReg Sp = True
673 isFixedPtrGlobalReg Hp = True
674 isFixedPtrGlobalReg HpLim = True
675 isFixedPtrGlobalReg SpLim = True
676 isFixedPtrGlobalReg _ = False
678 -- True if in C this register doesn't have the type given by
679 -- (machRepCType (cmmRegRep reg)), so it has to be cast.
680 isStrangeTypeReg :: CmmReg -> Bool
681 isStrangeTypeReg (CmmLocal _) = False
682 isStrangeTypeReg (CmmGlobal g) = isStrangeTypeGlobal g
684 isStrangeTypeGlobal :: GlobalReg -> Bool
685 isStrangeTypeGlobal CurrentTSO = True
686 isStrangeTypeGlobal CurrentNursery = True
687 isStrangeTypeGlobal BaseReg = True
688 isStrangeTypeGlobal r = isFixedPtrGlobalReg r
690 strangeRegType :: CmmReg -> Maybe SDoc
691 strangeRegType (CmmGlobal CurrentTSO) = Just (ptext SLIT("struct StgTSO_ *"))
692 strangeRegType (CmmGlobal CurrentNursery) = Just (ptext SLIT("struct bdescr_ *"))
693 strangeRegType (CmmGlobal BaseReg) = Just (ptext SLIT("struct StgRegTable_ *"))
694 strangeRegType _ = Nothing
696 -- pprReg just prints the register name.
698 pprReg :: CmmReg -> SDoc
700 CmmLocal local -> pprLocalReg local
701 CmmGlobal global -> pprGlobalReg global
703 pprAsPtrReg :: CmmReg -> SDoc
704 pprAsPtrReg (CmmGlobal (VanillaReg n)) = char 'R' <> int n <> ptext SLIT(".p")
705 pprAsPtrReg other_reg = pprReg other_reg
707 pprGlobalReg :: GlobalReg -> SDoc
708 pprGlobalReg gr = case gr of
709 VanillaReg n -> char 'R' <> int n <> ptext SLIT(".w")
710 FloatReg n -> char 'F' <> int n
711 DoubleReg n -> char 'D' <> int n
712 LongReg n -> char 'L' <> int n
713 Sp -> ptext SLIT("Sp")
714 SpLim -> ptext SLIT("SpLim")
715 Hp -> ptext SLIT("Hp")
716 HpLim -> ptext SLIT("HpLim")
717 CurrentTSO -> ptext SLIT("CurrentTSO")
718 CurrentNursery -> ptext SLIT("CurrentNursery")
719 HpAlloc -> ptext SLIT("HpAlloc")
720 BaseReg -> ptext SLIT("BaseReg")
721 GCEnter1 -> ptext SLIT("stg_gc_enter_1")
722 GCFun -> ptext SLIT("stg_gc_fun")
724 pprLocalReg :: LocalReg -> SDoc
725 pprLocalReg (LocalReg uniq _ _) = char '_' <> ppr uniq
727 -- -----------------------------------------------------------------------------
730 pprCall :: SDoc -> CCallConv -> CmmFormals -> CmmActuals -> CmmSafety
733 pprCall ppr_fn cconv results args _
734 | not (is_cish cconv)
735 = panic "pprCall: unknown calling convention"
739 #if x86_64_TARGET_ARCH
740 -- HACK around gcc optimisations.
741 -- x86_64 needs a __DISCARD__() here, to create a barrier between
742 -- putting the arguments into temporaries and passing the arguments
743 -- to the callee, because the argument expressions may refer to
744 -- machine registers that are also used for passing arguments in the
745 -- C calling convention.
746 (if (not opt_Unregisterised)
747 then ptext SLIT("__DISCARD__();")
750 ppr_assign results (ppr_fn <> parens (commafy (map pprArg args))) <> semi
752 ppr_assign [] rhs = rhs
753 ppr_assign [(one,hint)] rhs
754 = pprLocalReg one <> ptext SLIT(" = ")
755 <> pprUnHint hint (localRegRep one) <> rhs
756 ppr_assign _other _rhs = panic "pprCall: multiple results"
758 pprArg (expr, PtrHint)
759 = cCast (ptext SLIT("void *")) expr
760 -- see comment by machRepHintCType below
761 pprArg (expr, SignedHint)
762 = cCast (machRepSignedCType (cmmExprRep expr)) expr
763 pprArg (expr, _other)
766 pprUnHint PtrHint rep = parens (machRepCType rep)
767 pprUnHint SignedHint rep = parens (machRepCType rep)
768 pprUnHint _ _ = empty
770 pprGlobalRegName :: GlobalReg -> SDoc
771 pprGlobalRegName gr = case gr of
772 VanillaReg n -> char 'R' <> int n -- without the .w suffix
775 -- Currently we only have these two calling conventions, but this might
776 -- change in the future...
777 is_cish CCallConv = True
778 is_cish StdCallConv = True
780 -- ---------------------------------------------------------------------
781 -- Find and print local and external declarations for a list of
784 pprTempAndExternDecls :: [CmmBasicBlock] -> (SDoc{-temps-}, SDoc{-externs-})
785 pprTempAndExternDecls stmts
786 = (vcat (map pprTempDecl (eltsUFM temps)),
787 vcat (map (pprExternDecl False{-ToDo-}) (keysFM lbls)))
788 where (temps, lbls) = runTE (mapM_ te_BB stmts)
790 pprDataExterns :: [CmmStatic] -> SDoc
791 pprDataExterns statics
792 = vcat (map (pprExternDecl False{-ToDo-}) (keysFM lbls))
793 where (_, lbls) = runTE (mapM_ te_Static statics)
795 pprTempDecl :: LocalReg -> SDoc
796 pprTempDecl l@(LocalReg _ rep _)
797 = hcat [ machRepCType rep, space, pprLocalReg l, semi ]
799 pprExternDecl :: Bool -> CLabel -> SDoc
800 pprExternDecl in_srt lbl
801 -- do not print anything for "known external" things
802 | not (needsCDecl lbl) = empty
804 hcat [ visibility, label_type (labelType lbl),
805 lparen, pprCLabel lbl, text ");" ]
807 label_type CodeLabel = ptext SLIT("F_")
808 label_type DataLabel = ptext SLIT("I_")
811 | externallyVisibleCLabel lbl = char 'E'
812 | otherwise = char 'I'
815 type TEState = (UniqSet LocalReg, FiniteMap CLabel ())
816 newtype TE a = TE { unTE :: TEState -> (a, TEState) }
818 instance Monad TE where
819 TE m >>= k = TE $ \s -> case m s of (a, s') -> unTE (k a) s'
820 return a = TE $ \s -> (a, s)
822 te_lbl :: CLabel -> TE ()
823 te_lbl lbl = TE $ \(temps,lbls) -> ((), (temps, addToFM lbls lbl ()))
825 te_temp :: LocalReg -> TE ()
826 te_temp r = TE $ \(temps,lbls) -> ((), (addOneToUniqSet temps r, lbls))
828 runTE :: TE () -> TEState
829 runTE (TE m) = snd (m (emptyUniqSet, emptyFM))
831 te_Static :: CmmStatic -> TE ()
832 te_Static (CmmStaticLit lit) = te_Lit lit
833 te_Static _ = return ()
835 te_BB :: CmmBasicBlock -> TE ()
836 te_BB (BasicBlock _ ss) = mapM_ te_Stmt ss
838 te_Lit :: CmmLit -> TE ()
839 te_Lit (CmmLabel l) = te_lbl l
840 te_Lit (CmmLabelOff l _) = te_lbl l
841 te_Lit (CmmLabelDiffOff l1 l2 _) = te_lbl l1
844 te_Stmt :: CmmStmt -> TE ()
845 te_Stmt (CmmAssign r e) = te_Reg r >> te_Expr e
846 te_Stmt (CmmStore l r) = te_Expr l >> te_Expr r
847 te_Stmt (CmmCall _ rs es _ _) = mapM_ (te_temp.fst) rs >>
848 mapM_ (te_Expr.fst) es
849 te_Stmt (CmmCondBranch e _) = te_Expr e
850 te_Stmt (CmmSwitch e _) = te_Expr e
851 te_Stmt (CmmJump e _) = te_Expr e
852 te_Stmt _ = return ()
854 te_Expr :: CmmExpr -> TE ()
855 te_Expr (CmmLit lit) = te_Lit lit
856 te_Expr (CmmLoad e _) = te_Expr e
857 te_Expr (CmmReg r) = te_Reg r
858 te_Expr (CmmMachOp _ es) = mapM_ te_Expr es
859 te_Expr (CmmRegOff r _) = te_Reg r
861 te_Reg :: CmmReg -> TE ()
862 te_Reg (CmmLocal l) = te_temp l
866 -- ---------------------------------------------------------------------
867 -- C types for MachReps
869 cCast :: SDoc -> CmmExpr -> SDoc
870 cCast ty expr = parens ty <> pprExpr1 expr
872 cLoad :: CmmExpr -> MachRep -> SDoc
873 #ifdef BEWARE_LOAD_STORE_ALIGNMENT
875 let decl = machRepCType rep <+> ptext SLIT("x") <> semi
876 struct = ptext SLIT("struct") <+> braces (decl)
877 packed_attr = ptext SLIT("__attribute__((packed))")
878 cast = parens (struct <+> packed_attr <> char '*')
879 in parens (cast <+> pprExpr1 expr) <> ptext SLIT("->x")
881 cLoad expr rep = char '*' <> parens (cCast (machRepPtrCType rep) expr)
884 -- This is for finding the types of foreign call arguments. For a pointer
885 -- argument, we always cast the argument to (void *), to avoid warnings from
887 machRepHintCType :: MachRep -> MachHint -> SDoc
888 machRepHintCType rep PtrHint = ptext SLIT("void *")
889 machRepHintCType rep SignedHint = machRepSignedCType rep
890 machRepHintCType rep _other = machRepCType rep
892 machRepPtrCType :: MachRep -> SDoc
893 machRepPtrCType r | r == wordRep = ptext SLIT("P_")
894 | otherwise = machRepCType r <> char '*'
896 machRepCType :: MachRep -> SDoc
897 machRepCType r | r == wordRep = ptext SLIT("W_")
898 | otherwise = sized_type
899 where sized_type = case r of
900 I8 -> ptext SLIT("StgWord8")
901 I16 -> ptext SLIT("StgWord16")
902 I32 -> ptext SLIT("StgWord32")
903 I64 -> ptext SLIT("StgWord64")
904 F32 -> ptext SLIT("StgFloat") -- ToDo: correct?
905 F64 -> ptext SLIT("StgDouble")
906 _ -> panic "machRepCType"
908 machRepSignedCType :: MachRep -> SDoc
909 machRepSignedCType r | r == wordRep = ptext SLIT("I_")
910 | otherwise = sized_type
911 where sized_type = case r of
912 I8 -> ptext SLIT("StgInt8")
913 I16 -> ptext SLIT("StgInt16")
914 I32 -> ptext SLIT("StgInt32")
915 I64 -> ptext SLIT("StgInt64")
916 F32 -> ptext SLIT("StgFloat") -- ToDo: correct?
917 F64 -> ptext SLIT("StgDouble")
918 _ -> panic "machRepCType"
920 -- ---------------------------------------------------------------------
921 -- print strings as valid C strings
923 pprStringInCStyle :: [Word8] -> SDoc
924 pprStringInCStyle s = doubleQuotes (text (concatMap charToC s))
926 charToC :: Word8 -> String
928 case chr (fromIntegral w) of
932 c | c >= ' ' && c <= '~' -> [c]
933 | otherwise -> ['\\',
934 chr (ord '0' + ord c `div` 64),
935 chr (ord '0' + ord c `div` 8 `mod` 8),
936 chr (ord '0' + ord c `mod` 8)]
938 -- ---------------------------------------------------------------------------
939 -- Initialising static objects with floating-point numbers. We can't
940 -- just emit the floating point number, because C will cast it to an int
941 -- by rounding it. We want the actual bit-representation of the float.
943 -- This is a hack to turn the floating point numbers into ints that we
944 -- can safely initialise to static locations.
947 | machRepByteWidth F64 == 2 * wORD_SIZE = True
948 | machRepByteWidth F64 == wORD_SIZE = False
949 | otherwise = panic "big_doubles"
951 castFloatToIntArray :: STUArray s Int Float -> ST s (STUArray s Int Int)
952 castFloatToIntArray = castSTUArray
954 castDoubleToIntArray :: STUArray s Int Double -> ST s (STUArray s Int Int)
955 castDoubleToIntArray = castSTUArray
957 -- floats are always 1 word
958 floatToWord :: Rational -> CmmLit
961 arr <- newArray_ ((0::Int),0)
962 writeArray arr 0 (fromRational r)
963 arr' <- castFloatToIntArray arr
964 i <- readArray arr' 0
965 return (CmmInt (toInteger i) wordRep)
968 doubleToWords :: Rational -> [CmmLit]
970 | big_doubles -- doubles are 2 words
972 arr <- newArray_ ((0::Int),1)
973 writeArray arr 0 (fromRational r)
974 arr' <- castDoubleToIntArray arr
975 i1 <- readArray arr' 0
976 i2 <- readArray arr' 1
977 return [ CmmInt (toInteger i1) wordRep
978 , CmmInt (toInteger i2) wordRep
981 | otherwise -- doubles are 1 word
983 arr <- newArray_ ((0::Int),0)
984 writeArray arr 0 (fromRational r)
985 arr' <- castDoubleToIntArray arr
986 i <- readArray arr' 0
987 return [ CmmInt (toInteger i) wordRep ]
990 -- ---------------------------------------------------------------------------
994 wordShift = machRepLogWidth wordRep
996 commafy :: [SDoc] -> SDoc
997 commafy xs = hsep $ punctuate comma xs
999 -- Print in C hex format: 0x13fa
1000 pprHexVal :: Integer -> MachRep -> SDoc
1001 pprHexVal 0 _ = ptext SLIT("0x0")
1003 | w < 0 = parens (char '-' <> ptext SLIT("0x") <> go (-w) <> repsuffix rep)
1004 | otherwise = ptext SLIT("0x") <> go w <> repsuffix rep
1006 -- type suffix for literals:
1007 -- Integer literals are unsigned in Cmm/C. We explicitly cast to
1008 -- signed values for doing signed operations, but at all other
1009 -- times values are unsigned. This also helps eliminate occasional
1010 -- warnings about integer overflow from gcc.
1012 -- on 32-bit platforms, add "ULL" to 64-bit literals
1013 repsuffix I64 | wORD_SIZE == 4 = ptext SLIT("ULL")
1014 -- on 64-bit platforms with 32-bit int, add "L" to 64-bit literals
1015 repsuffix I64 | cINT_SIZE == 4 = ptext SLIT("UL")
1016 repsuffix _ = char 'U'
1021 (q,r) = w' `quotRem` 16
1022 dig | r < 10 = char (chr (fromInteger r + ord '0'))
1023 | otherwise = char (chr (fromInteger r - 10 + ord 'a'))