2 -- The above warning supression flag is a temporary kludge.
3 -- While working on this module you are encouraged to remove it and fix
4 -- any warnings in the module. See
5 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
8 -----------------------------------------------------------------------------
10 -- Pretty-printing of Cmm as C, suitable for feeding gcc
12 -- (c) The University of Glasgow 2004-2006
14 -----------------------------------------------------------------------------
17 -- Print Cmm as real C, for -fvia-C
19 -- See wiki:Commentary/Compiler/Backends/PprC
21 -- This is simpler than the old PprAbsC, because Cmm is "macro-expanded"
22 -- relative to the old AbstractC, and many oddities/decorations have
23 -- disappeared from the data type.
26 -- ToDo: save/restore volatile registers around calls.
33 #include "HsVersions.h"
38 import PprCmm () -- Instances only
61 import Control.Monad.ST
63 #if x86_64_TARGET_ARCH
64 import StaticFlags ( opt_Unregisterised )
67 #if defined(alpha_TARGET_ARCH) || defined(mips_TARGET_ARCH) || defined(mipsel_TARGET_ARCH) || defined(arm_TARGET_ARCH)
68 #define BEWARE_LOAD_STORE_ALIGNMENT
71 -- --------------------------------------------------------------------------
74 pprCs :: DynFlags -> [RawCmm] -> SDoc
76 = pprCode CStyle (vcat $ map (\c -> split_marker $$ pprC c) cmms)
79 | dopt Opt_SplitObjs dflags = ptext (sLit "__STG_SPLIT_MARKER")
82 writeCs :: DynFlags -> Handle -> [RawCmm] -> IO ()
83 writeCs dflags handle cmms
84 = printForC handle (pprCs dflags cmms)
86 -- --------------------------------------------------------------------------
87 -- Now do some real work
89 -- for fun, we could call cmmToCmm over the tops...
92 pprC :: RawCmm -> SDoc
93 pprC (Cmm tops) = vcat $ intersperse (text "") $ map pprTop tops
98 pprTop :: RawCmmTop -> SDoc
99 pprTop (CmmProc info clbl _params (ListGraph blocks)) =
101 then pprDataExterns info $$
102 pprWordArray (entryLblToInfoLbl clbl) info
106 -- the first block doesn't get a label:
107 (BasicBlock _ stmts : rest) -> vcat [
110 (if (externallyVisibleCLabel clbl)
111 then mkFN_ else mkIF_) (pprCLabel clbl) <+> lbrace,
114 nest 8 (vcat (map pprStmt stmts)) $$
115 vcat (map pprBBlock rest),
120 (temp_decls, extern_decls) = pprTempAndExternDecls blocks
123 -- Chunks of static data.
125 -- We only handle (a) arrays of word-sized things and (b) strings.
127 pprTop (CmmData _section _ds@[CmmDataLabel lbl, CmmString str]) =
129 pprLocalness lbl, ptext (sLit "char "), pprCLabel lbl,
130 ptext (sLit "[] = "), pprStringInCStyle str, semi
133 pprTop (CmmData _section _ds@[CmmDataLabel lbl, CmmUninitialised size]) =
135 pprLocalness lbl, ptext (sLit "char "), pprCLabel lbl,
136 brackets (int size), semi
139 pprTop top@(CmmData _section (CmmDataLabel lbl : lits)) =
140 pprDataExterns lits $$
141 pprWordArray lbl lits
143 -- Floating info table for safe a foreign call.
144 pprTop top@(CmmData _section d@(_ : _))
145 | CmmDataLabel lbl : lits <- reverse d =
146 pprDataExterns lits $$
147 pprWordArray lbl lits
149 -- these shouldn't appear?
150 pprTop (CmmData _ _) = panic "PprC.pprTop: can't handle this data"
152 -- --------------------------------------------------------------------------
153 -- BasicBlocks are self-contained entities: they always end in a jump.
155 -- Like nativeGen/AsmCodeGen, we could probably reorder blocks to turn
156 -- as many jumps as possible into fall throughs.
159 pprBBlock :: CmmBasicBlock -> SDoc
160 pprBBlock (BasicBlock lbl stmts) =
162 pprTrace "pprC.pprBBlock: curious empty code block for"
163 (pprBlockId lbl) empty
165 nest 4 (pprBlockId lbl <> colon) $$
166 nest 8 (vcat (map pprStmt stmts))
168 -- --------------------------------------------------------------------------
169 -- Info tables. Just arrays of words.
170 -- See codeGen/ClosureInfo, and nativeGen/PprMach
172 pprWordArray :: CLabel -> [CmmStatic] -> SDoc
174 = hcat [ pprLocalness lbl, ptext (sLit "StgWord")
175 , space, pprCLabel lbl, ptext (sLit "[] = {") ]
176 $$ nest 8 (commafy (pprStatics ds))
180 -- has to be static, if it isn't globally visible
182 pprLocalness :: CLabel -> SDoc
183 pprLocalness lbl | not $ externallyVisibleCLabel lbl = ptext (sLit "static ")
186 -- --------------------------------------------------------------------------
190 pprStmt :: CmmStmt -> SDoc
192 pprStmt stmt = case stmt of
194 CmmComment s -> (hang (ptext (sLit "/*")) 3 (ftext s)) $$ ptext (sLit "*/")
196 CmmAssign dest src -> pprAssign dest src
199 | typeWidth rep == W64 && wordWidth /= W64
200 -> (if isFloatType rep then ptext (sLit "ASSIGN_DBL")
201 else ptext (sLit ("ASSIGN_Word64"))) <>
202 parens (mkP_ <> pprExpr1 dest <> comma <> pprExpr src) <> semi
205 -> hsep [ pprExpr (CmmLoad dest rep), equals, pprExpr src <> semi ]
207 rep = cmmExprType src
209 CmmCall (CmmCallee fn cconv) results args safety ret ->
211 pprCall ppr_fn cconv results args safety
213 cast_fn = parens (cCast (pprCFunType (char '*') cconv results args) fn)
215 real_fun_proto lbl = char ';' <>
216 pprCFunType (pprCLabel lbl) cconv results args <>
217 noreturn_attr <> semi
219 data_proto lbl = ptext (sLit ";EI_(") <>
220 pprCLabel lbl <> char ')' <> semi
222 noreturn_attr = case ret of
223 CmmNeverReturns -> text "__attribute__ ((noreturn))"
224 CmmMayReturn -> empty
226 -- See wiki:Commentary/Compiler/Backends/PprC#Prototypes
227 (maybe_proto, ppr_fn) =
229 CmmLit (CmmLabel lbl)
230 | StdCallConv <- cconv -> (real_fun_proto lbl, pprCLabel lbl)
231 -- stdcall functions must be declared with
232 -- a function type, otherwise the C compiler
233 -- doesn't add the @n suffix to the label. We
234 -- can't add the @n suffix ourselves, because
236 | CmmNeverReturns <- ret -> (real_fun_proto lbl, pprCLabel lbl)
237 | not (isMathFun lbl) -> (data_proto lbl, cast_fn)
238 -- we declare all other called functions as
239 -- data labels, and then cast them to the
240 -- right type when calling. This is because
241 -- the label might already have a declaration
242 -- as a data label in the same file,
243 -- e.g. Foreign.Marshal.Alloc declares 'free'
244 -- as both a data label and a function label.
246 (empty {- no proto -}, cast_fn)
247 -- for a dynamic call, no declaration is necessary.
249 CmmCall (CmmPrim op) results args safety _ret ->
250 pprCall ppr_fn CCallConv results args safety
252 ppr_fn = pprCallishMachOp_for_C op
254 CmmBranch ident -> pprBranch ident
255 CmmCondBranch expr ident -> pprCondBranch expr ident
256 CmmJump lbl _params -> mkJMP_(pprExpr lbl) <> semi
257 CmmSwitch arg ids -> pprSwitch arg ids
259 pprCFunType :: SDoc -> CCallConv -> HintedCmmFormals -> HintedCmmActuals -> SDoc
260 pprCFunType ppr_fn cconv ress args
262 parens (text (ccallConvAttribute cconv) <> ppr_fn) <>
263 parens (commafy (map arg_type args))
265 res_type [] = ptext (sLit "void")
266 res_type [CmmHinted one hint] = machRepHintCType (localRegType one) hint
268 arg_type (CmmHinted expr hint) = machRepHintCType (cmmExprType expr) hint
270 -- ---------------------------------------------------------------------
271 -- unconditional branches
272 pprBranch :: BlockId -> SDoc
273 pprBranch ident = ptext (sLit "goto") <+> pprBlockId ident <> semi
276 -- ---------------------------------------------------------------------
277 -- conditional branches to local labels
278 pprCondBranch :: CmmExpr -> BlockId -> SDoc
279 pprCondBranch expr ident
280 = hsep [ ptext (sLit "if") , parens(pprExpr expr) ,
281 ptext (sLit "goto") , (pprBlockId ident) <> semi ]
284 -- ---------------------------------------------------------------------
285 -- a local table branch
287 -- we find the fall-through cases
289 -- N.B. we remove Nothing's from the list of branches, as they are
290 -- 'undefined'. However, they may be defined one day, so we better
291 -- document this behaviour.
293 pprSwitch :: CmmExpr -> [ Maybe BlockId ] -> SDoc
294 pprSwitch e maybe_ids
295 = let pairs = [ (ix, ident) | (ix,Just ident) <- zip [0..] maybe_ids ]
296 pairs2 = [ (map fst as, snd (head as)) | as <- groupBy sndEq pairs ]
298 (hang (ptext (sLit "switch") <+> parens ( pprExpr e ) <+> lbrace)
299 4 (vcat ( map caseify pairs2 )))
303 sndEq (_,x) (_,y) = x == y
306 caseify (ix:ixs, ident) = vcat (map do_fallthrough ixs) $$ final_branch ix
309 hsep [ ptext (sLit "case") , pprHexVal ix wordWidth <> colon ,
310 ptext (sLit "/* fall through */") ]
313 hsep [ ptext (sLit "case") , pprHexVal ix wordWidth <> colon ,
314 ptext (sLit "goto") , (pprBlockId ident) <> semi ]
316 -- ---------------------------------------------------------------------
320 -- C Types: the invariant is that the C expression generated by
324 -- has a type in C which is also given by
326 -- machRepCType (cmmExprType e)
328 -- (similar invariants apply to the rest of the pretty printer).
330 pprExpr :: CmmExpr -> SDoc
331 pprExpr e = case e of
332 CmmLit lit -> pprLit lit
335 CmmLoad e ty -> pprLoad e ty
336 CmmReg reg -> pprCastReg reg
337 CmmRegOff reg 0 -> pprCastReg reg
340 | i > 0 -> pprRegOff (char '+') i
341 | otherwise -> pprRegOff (char '-') (-i)
343 pprRegOff op i' = pprCastReg reg <> op <> int i'
345 CmmMachOp mop args -> pprMachOpApp mop args
348 pprLoad :: CmmExpr -> CmmType -> SDoc
350 | width == W64, wordWidth /= W64
351 = (if isFloatType ty then ptext (sLit "PK_DBL")
352 else ptext (sLit "PK_Word64"))
353 <> parens (mkP_ <> pprExpr1 e)
357 CmmReg r | isPtrReg r && width == wordWidth && not (isFloatType ty)
358 -> char '*' <> pprAsPtrReg r
360 CmmRegOff r 0 | isPtrReg r && width == wordWidth && not (isFloatType ty)
361 -> char '*' <> pprAsPtrReg r
363 CmmRegOff r off | isPtrReg r && width == wordWidth
364 , off `rem` wORD_SIZE == 0 && not (isFloatType ty)
365 -- ToDo: check that the offset is a word multiple?
366 -- (For tagging to work, I had to avoid unaligned loads. --ARY)
367 -> pprAsPtrReg r <> brackets (ppr (off `shiftR` wordShift))
373 pprExpr1 :: CmmExpr -> SDoc
374 pprExpr1 (CmmLit lit) = pprLit1 lit
375 pprExpr1 e@(CmmReg _reg) = pprExpr e
376 pprExpr1 other = parens (pprExpr other)
378 -- --------------------------------------------------------------------------
379 -- MachOp applications
381 pprMachOpApp :: MachOp -> [CmmExpr] -> SDoc
385 = ptext (sLit "mulIntMayOflo") <> parens (commafy (map pprExpr args))
386 where isMulMayOfloOp (MO_U_MulMayOflo _) = True
387 isMulMayOfloOp (MO_S_MulMayOflo _) = True
388 isMulMayOfloOp _ = False
390 pprMachOpApp mop args
391 | Just ty <- machOpNeedsCast mop
392 = ty <> parens (pprMachOpApp' mop args)
394 = pprMachOpApp' mop args
396 -- Comparisons in C have type 'int', but we want type W_ (this is what
397 -- resultRepOfMachOp says). The other C operations inherit their type
398 -- from their operands, so no casting is required.
399 machOpNeedsCast :: MachOp -> Maybe SDoc
401 | isComparisonMachOp mop = Just mkW_
402 | otherwise = Nothing
404 pprMachOpApp' mop args
407 [x,y] -> pprArg x <+> pprMachOp_for_C mop <+> pprArg y
410 [x] -> pprMachOp_for_C mop <> parens (pprArg x)
412 _ -> panic "PprC.pprMachOp : machop with wrong number of args"
415 -- Cast needed for signed integer ops
416 pprArg e | signedOp mop = cCast (machRep_S_CType (typeWidth (cmmExprType e))) e
417 | needsFCasts mop = cCast (machRep_F_CType (typeWidth (cmmExprType e))) e
418 | otherwise = pprExpr1 e
419 needsFCasts (MO_F_Eq _) = False
420 needsFCasts (MO_F_Ne _) = False
421 needsFCasts (MO_F_Neg _) = True
422 needsFCasts (MO_F_Quot _) = True
423 needsFCasts mop = floatComparison mop
425 -- --------------------------------------------------------------------------
428 pprLit :: CmmLit -> SDoc
429 pprLit lit = case lit of
430 CmmInt i rep -> pprHexVal i rep
432 CmmFloat f w -> parens (machRep_F_CType w) <> str
433 where d = fromRational f :: Double
434 str | isInfinite d && d < 0 = ptext (sLit "-INFINITY")
435 | isInfinite d = ptext (sLit "INFINITY")
436 | isNaN d = ptext (sLit "NAN")
437 | otherwise = text (show d)
438 -- these constants come from <math.h>
441 CmmBlock bid -> mkW_ <> pprCLabelAddr (infoTblLbl bid)
442 CmmHighStackMark -> panic "PprC printing high stack mark"
443 CmmLabel clbl -> mkW_ <> pprCLabelAddr clbl
444 CmmLabelOff clbl i -> mkW_ <> pprCLabelAddr clbl <> char '+' <> int i
445 CmmLabelDiffOff clbl1 clbl2 i
447 -- * the lit must occur in the info table clbl2
448 -- * clbl1 must be an SRT, a slow entry point or a large bitmap
449 -- The Mangler is expected to convert any reference to an SRT,
450 -- a slow entry point or a large bitmap
451 -- from an info table to an offset.
452 -> mkW_ <> pprCLabelAddr clbl1 <> char '+' <> int i
454 pprCLabelAddr lbl = char '&' <> pprCLabel lbl
456 pprLit1 :: CmmLit -> SDoc
457 pprLit1 lit@(CmmLabelOff _ _) = parens (pprLit lit)
458 pprLit1 lit@(CmmLabelDiffOff _ _ _) = parens (pprLit lit)
459 pprLit1 lit@(CmmFloat _ _) = parens (pprLit lit)
460 pprLit1 other = pprLit other
462 -- ---------------------------------------------------------------------------
465 pprStatics :: [CmmStatic] -> [SDoc]
467 pprStatics (CmmStaticLit (CmmFloat f W32) : rest)
468 -- floats are padded to a word, see #1852
469 | wORD_SIZE == 8, CmmStaticLit (CmmInt 0 W32) : rest' <- rest
470 = pprLit1 (floatToWord f) : pprStatics rest'
472 = pprLit1 (floatToWord f) : pprStatics rest
474 = pprPanic "pprStatics: float" (vcat (map (\(CmmStaticLit l) -> ppr (cmmLitType l)) rest))
475 pprStatics (CmmStaticLit (CmmFloat f W64) : rest)
476 = map pprLit1 (doubleToWords f) ++ pprStatics rest
477 pprStatics (CmmStaticLit (CmmInt i W64) : rest)
479 #ifdef WORDS_BIGENDIAN
480 = pprStatics (CmmStaticLit (CmmInt q W32) :
481 CmmStaticLit (CmmInt r W32) : rest)
483 = pprStatics (CmmStaticLit (CmmInt r W32) :
484 CmmStaticLit (CmmInt q W32) : rest)
486 where r = i .&. 0xffffffff
488 pprStatics (CmmStaticLit (CmmInt i w) : rest)
490 = panic "pprStatics: cannot emit a non-word-sized static literal"
491 pprStatics (CmmStaticLit lit : rest)
492 = pprLit1 lit : pprStatics rest
493 pprStatics (other : rest)
494 = pprPanic "pprWord" (pprStatic other)
496 pprStatic :: CmmStatic -> SDoc
497 pprStatic s = case s of
499 CmmStaticLit lit -> nest 4 (pprLit lit)
500 CmmAlign i -> nest 4 (ptext (sLit "/* align */") <+> int i)
501 CmmDataLabel clbl -> pprCLabel clbl <> colon
502 CmmUninitialised i -> nest 4 (mkC_ <> brackets (int i))
504 -- these should be inlined, like the old .hc
505 CmmString s' -> nest 4 (mkW_ <> parens(pprStringInCStyle s'))
508 -- ---------------------------------------------------------------------------
511 pprBlockId :: BlockId -> SDoc
512 pprBlockId b = char '_' <> ppr (getUnique b)
514 -- --------------------------------------------------------------------------
515 -- Print a MachOp in a way suitable for emitting via C.
518 pprMachOp_for_C :: MachOp -> SDoc
520 pprMachOp_for_C mop = case mop of
522 -- Integer operations
525 MO_Eq _ -> ptext (sLit "==")
526 MO_Ne _ -> ptext (sLit "!=")
529 MO_S_Quot _ -> char '/'
530 MO_S_Rem _ -> char '%'
531 MO_S_Neg _ -> char '-'
533 MO_U_Quot _ -> char '/'
534 MO_U_Rem _ -> char '%'
536 -- & Floating-point operations
537 MO_F_Add _ -> char '+'
538 MO_F_Sub _ -> char '-'
539 MO_F_Neg _ -> char '-'
540 MO_F_Mul _ -> char '*'
541 MO_F_Quot _ -> char '/'
543 -- Signed comparisons
544 MO_S_Ge _ -> ptext (sLit ">=")
545 MO_S_Le _ -> ptext (sLit "<=")
546 MO_S_Gt _ -> char '>'
547 MO_S_Lt _ -> char '<'
549 -- & Unsigned comparisons
550 MO_U_Ge _ -> ptext (sLit ">=")
551 MO_U_Le _ -> ptext (sLit "<=")
552 MO_U_Gt _ -> char '>'
553 MO_U_Lt _ -> char '<'
555 -- & Floating-point comparisons
556 MO_F_Eq _ -> ptext (sLit "==")
557 MO_F_Ne _ -> ptext (sLit "!=")
558 MO_F_Ge _ -> ptext (sLit ">=")
559 MO_F_Le _ -> ptext (sLit "<=")
560 MO_F_Gt _ -> char '>'
561 MO_F_Lt _ -> char '<'
563 -- Bitwise operations. Not all of these may be supported at all
564 -- sizes, and only integral MachReps are valid.
569 MO_Shl _ -> ptext (sLit "<<")
570 MO_U_Shr _ -> ptext (sLit ">>") -- unsigned shift right
571 MO_S_Shr _ -> ptext (sLit ">>") -- signed shift right
573 -- Conversions. Some of these will be NOPs, but never those that convert
574 -- between ints and floats.
575 -- Floating-point conversions use the signed variant.
576 -- We won't know to generate (void*) casts here, but maybe from
580 MO_UU_Conv from to | from == to -> empty
581 MO_UU_Conv _from to -> parens (machRep_U_CType to)
583 MO_SS_Conv from to | from == to -> empty
584 MO_SS_Conv _from to -> parens (machRep_S_CType to)
586 -- TEMPORARY: the old code didn't check this case, so let's leave it out
587 -- to facilitate comparisons against the old output code.
588 --MO_FF_Conv from to | from == to -> empty
589 MO_FF_Conv _from to -> parens (machRep_F_CType to)
591 MO_SF_Conv _from to -> parens (machRep_F_CType to)
592 MO_FS_Conv _from to -> parens (machRep_S_CType to)
594 _ -> pprTrace "offending mop" (ptext $ sLit $ show mop) $
595 panic "PprC.pprMachOp_for_C: unknown machop"
597 signedOp :: MachOp -> Bool -- Argument type(s) are signed ints
598 signedOp (MO_S_Quot _) = True
599 signedOp (MO_S_Rem _) = True
600 signedOp (MO_S_Neg _) = True
601 signedOp (MO_S_Ge _) = True
602 signedOp (MO_S_Le _) = True
603 signedOp (MO_S_Gt _) = True
604 signedOp (MO_S_Lt _) = True
605 signedOp (MO_S_Shr _) = True
606 signedOp (MO_SS_Conv _ _) = True
607 signedOp (MO_SF_Conv _ _) = True
610 floatComparison :: MachOp -> Bool -- comparison between float args
611 floatComparison (MO_F_Eq _) = True
612 floatComparison (MO_F_Ne _) = True
613 floatComparison (MO_F_Ge _) = True
614 floatComparison (MO_F_Le _) = True
615 floatComparison (MO_F_Gt _) = True
616 floatComparison (MO_F_Lt _) = True
617 floatComparison _ = False
619 -- ---------------------------------------------------------------------
620 -- tend to be implemented by foreign calls
622 pprCallishMachOp_for_C :: CallishMachOp -> SDoc
624 pprCallishMachOp_for_C mop
626 MO_F64_Pwr -> ptext (sLit "pow")
627 MO_F64_Sin -> ptext (sLit "sin")
628 MO_F64_Cos -> ptext (sLit "cos")
629 MO_F64_Tan -> ptext (sLit "tan")
630 MO_F64_Sinh -> ptext (sLit "sinh")
631 MO_F64_Cosh -> ptext (sLit "cosh")
632 MO_F64_Tanh -> ptext (sLit "tanh")
633 MO_F64_Asin -> ptext (sLit "asin")
634 MO_F64_Acos -> ptext (sLit "acos")
635 MO_F64_Atan -> ptext (sLit "atan")
636 MO_F64_Log -> ptext (sLit "log")
637 MO_F64_Exp -> ptext (sLit "exp")
638 MO_F64_Sqrt -> ptext (sLit "sqrt")
639 MO_F32_Pwr -> ptext (sLit "powf")
640 MO_F32_Sin -> ptext (sLit "sinf")
641 MO_F32_Cos -> ptext (sLit "cosf")
642 MO_F32_Tan -> ptext (sLit "tanf")
643 MO_F32_Sinh -> ptext (sLit "sinhf")
644 MO_F32_Cosh -> ptext (sLit "coshf")
645 MO_F32_Tanh -> ptext (sLit "tanhf")
646 MO_F32_Asin -> ptext (sLit "asinf")
647 MO_F32_Acos -> ptext (sLit "acosf")
648 MO_F32_Atan -> ptext (sLit "atanf")
649 MO_F32_Log -> ptext (sLit "logf")
650 MO_F32_Exp -> ptext (sLit "expf")
651 MO_F32_Sqrt -> ptext (sLit "sqrtf")
652 MO_WriteBarrier -> ptext (sLit "write_barrier")
654 -- ---------------------------------------------------------------------
658 mkJMP_, mkFN_, mkIF_ :: SDoc -> SDoc
660 mkJMP_ i = ptext (sLit "JMP_") <> parens i
661 mkFN_ i = ptext (sLit "FN_") <> parens i -- externally visible function
662 mkIF_ i = ptext (sLit "IF_") <> parens i -- locally visible
666 mkFB_ = ptext (sLit "FB_") -- function code begin
667 mkFE_ = ptext (sLit "FE_") -- function code end
669 -- from includes/Stg.h
671 mkC_,mkW_,mkP_,mkPP_,mkI_,mkA_,mkD_,mkF_,mkB_,mkL_,mkLI_,mkLW_ :: SDoc
673 mkC_ = ptext (sLit "(C_)") -- StgChar
674 mkW_ = ptext (sLit "(W_)") -- StgWord
675 mkP_ = ptext (sLit "(P_)") -- StgWord*
676 mkPP_ = ptext (sLit "(PP_)") -- P_*
677 mkI_ = ptext (sLit "(I_)") -- StgInt
678 mkA_ = ptext (sLit "(A_)") -- StgAddr
679 mkD_ = ptext (sLit "(D_)") -- const StgWord*
680 mkF_ = ptext (sLit "(F_)") -- StgFunPtr
681 mkB_ = ptext (sLit "(B_)") -- StgByteArray
682 mkL_ = ptext (sLit "(L_)") -- StgClosurePtr
684 mkLI_ = ptext (sLit "(LI_)") -- StgInt64
685 mkLW_ = ptext (sLit "(LW_)") -- StgWord64
688 -- ---------------------------------------------------------------------
692 -- Generating assignments is what we're all about, here
694 pprAssign :: CmmReg -> CmmExpr -> SDoc
696 -- dest is a reg, rhs is a reg
697 pprAssign r1 (CmmReg r2)
698 | isPtrReg r1 && isPtrReg r2
699 = hcat [ pprAsPtrReg r1, equals, pprAsPtrReg r2, semi ]
701 -- dest is a reg, rhs is a CmmRegOff
702 pprAssign r1 (CmmRegOff r2 off)
703 | isPtrReg r1 && isPtrReg r2 && (off `rem` wORD_SIZE == 0)
704 = hcat [ pprAsPtrReg r1, equals, pprAsPtrReg r2, op, int off', semi ]
706 off1 = off `shiftR` wordShift
708 (op,off') | off >= 0 = (char '+', off1)
709 | otherwise = (char '-', -off1)
711 -- dest is a reg, rhs is anything.
712 -- We can't cast the lvalue, so we have to cast the rhs if necessary. Casting
713 -- the lvalue elicits a warning from new GCC versions (3.4+).
715 | isFixedPtrReg r1 = mkAssign (mkP_ <> pprExpr1 r2)
716 | Just ty <- strangeRegType r1 = mkAssign (parens ty <> pprExpr1 r2)
717 | otherwise = mkAssign (pprExpr r2)
718 where mkAssign x = if r1 == CmmGlobal BaseReg
719 then ptext (sLit "ASSIGN_BaseReg") <> parens x <> semi
720 else pprReg r1 <> ptext (sLit " = ") <> x <> semi
722 -- ---------------------------------------------------------------------
726 | isStrangeTypeReg reg = mkW_ <> pprReg reg
727 | otherwise = pprReg reg
729 -- True if (pprReg reg) will give an expression with type StgPtr. We
730 -- need to take care with pointer arithmetic on registers with type
732 isFixedPtrReg :: CmmReg -> Bool
733 isFixedPtrReg (CmmLocal _) = False
734 isFixedPtrReg (CmmGlobal r) = isFixedPtrGlobalReg r
736 -- True if (pprAsPtrReg reg) will give an expression with type StgPtr
737 -- JD: THIS IS HORRIBLE AND SHOULD BE RENAMED, AT THE VERY LEAST.
738 -- THE GARBAGE WITH THE VNonGcPtr HELPS MATCH THE OLD CODE GENERATOR'S OUTPUT;
739 -- I'M NOT SURE IF IT SHOULD REALLY STAY THAT WAY.
740 isPtrReg :: CmmReg -> Bool
741 isPtrReg (CmmLocal _) = False
742 isPtrReg (CmmGlobal (VanillaReg n VGcPtr)) = True -- if we print via pprAsPtrReg
743 isPtrReg (CmmGlobal (VanillaReg n VNonGcPtr)) = False --if we print via pprAsPtrReg
744 isPtrReg (CmmGlobal reg) = isFixedPtrGlobalReg reg
746 -- True if this global reg has type StgPtr
747 isFixedPtrGlobalReg :: GlobalReg -> Bool
748 isFixedPtrGlobalReg Sp = True
749 isFixedPtrGlobalReg Hp = True
750 isFixedPtrGlobalReg HpLim = True
751 isFixedPtrGlobalReg SpLim = True
752 isFixedPtrGlobalReg _ = False
754 -- True if in C this register doesn't have the type given by
755 -- (machRepCType (cmmRegType reg)), so it has to be cast.
756 isStrangeTypeReg :: CmmReg -> Bool
757 isStrangeTypeReg (CmmLocal _) = False
758 isStrangeTypeReg (CmmGlobal g) = isStrangeTypeGlobal g
760 isStrangeTypeGlobal :: GlobalReg -> Bool
761 isStrangeTypeGlobal CurrentTSO = True
762 isStrangeTypeGlobal CurrentNursery = True
763 isStrangeTypeGlobal BaseReg = True
764 isStrangeTypeGlobal r = isFixedPtrGlobalReg r
766 strangeRegType :: CmmReg -> Maybe SDoc
767 strangeRegType (CmmGlobal CurrentTSO) = Just (ptext (sLit "struct StgTSO_ *"))
768 strangeRegType (CmmGlobal CurrentNursery) = Just (ptext (sLit "struct bdescr_ *"))
769 strangeRegType (CmmGlobal BaseReg) = Just (ptext (sLit "struct StgRegTable_ *"))
770 strangeRegType _ = Nothing
772 -- pprReg just prints the register name.
774 pprReg :: CmmReg -> SDoc
776 CmmLocal local -> pprLocalReg local
777 CmmGlobal global -> pprGlobalReg global
779 pprAsPtrReg :: CmmReg -> SDoc
780 pprAsPtrReg (CmmGlobal (VanillaReg n gcp))
781 = WARN( gcp /= VGcPtr, ppr n ) char 'R' <> int n <> ptext (sLit ".p")
782 pprAsPtrReg other_reg = pprReg other_reg
784 pprGlobalReg :: GlobalReg -> SDoc
785 pprGlobalReg gr = case gr of
786 VanillaReg n _ -> char 'R' <> int n <> ptext (sLit ".w")
787 -- pprGlobalReg prints a VanillaReg as a .w regardless
788 -- Example: R1.w = R1.w & (-0x8UL);
790 FloatReg n -> char 'F' <> int n
791 DoubleReg n -> char 'D' <> int n
792 LongReg n -> char 'L' <> int n
793 Sp -> ptext (sLit "Sp")
794 SpLim -> ptext (sLit "SpLim")
795 Hp -> ptext (sLit "Hp")
796 HpLim -> ptext (sLit "HpLim")
797 CurrentTSO -> ptext (sLit "CurrentTSO")
798 CurrentNursery -> ptext (sLit "CurrentNursery")
799 HpAlloc -> ptext (sLit "HpAlloc")
800 BaseReg -> ptext (sLit "BaseReg")
801 EagerBlackholeInfo -> ptext (sLit "stg_EAGER_BLACKHOLE_info")
802 GCEnter1 -> ptext (sLit "stg_gc_enter_1")
803 GCFun -> ptext (sLit "stg_gc_fun")
805 pprLocalReg :: LocalReg -> SDoc
806 pprLocalReg (LocalReg uniq _) = char '_' <> ppr uniq
808 -- -----------------------------------------------------------------------------
811 pprCall :: SDoc -> CCallConv -> HintedCmmFormals -> HintedCmmActuals -> CmmSafety
814 pprCall ppr_fn cconv results args _
815 | not (is_cish cconv)
816 = panic "pprCall: unknown calling convention"
820 #if x86_64_TARGET_ARCH
821 -- HACK around gcc optimisations.
822 -- x86_64 needs a __DISCARD__() here, to create a barrier between
823 -- putting the arguments into temporaries and passing the arguments
824 -- to the callee, because the argument expressions may refer to
825 -- machine registers that are also used for passing arguments in the
826 -- C calling convention.
827 (if (not opt_Unregisterised)
828 then ptext (sLit "__DISCARD__();")
831 ppr_assign results (ppr_fn <> parens (commafy (map pprArg args))) <> semi
833 ppr_assign [] rhs = rhs
834 ppr_assign [CmmHinted one hint] rhs
835 = pprLocalReg one <> ptext (sLit " = ")
836 <> pprUnHint hint (localRegType one) <> rhs
837 ppr_assign _other _rhs = panic "pprCall: multiple results"
839 pprArg (CmmHinted expr AddrHint)
840 = cCast (ptext (sLit "void *")) expr
841 -- see comment by machRepHintCType below
842 pprArg (CmmHinted expr SignedHint)
843 = cCast (machRep_S_CType $ typeWidth $ cmmExprType expr) expr
844 pprArg (CmmHinted expr _other)
847 pprUnHint AddrHint rep = parens (machRepCType rep)
848 pprUnHint SignedHint rep = parens (machRepCType rep)
849 pprUnHint _ _ = empty
851 pprGlobalRegName :: GlobalReg -> SDoc
852 pprGlobalRegName gr = case gr of
853 VanillaReg n _ -> char 'R' <> int n -- without the .w suffix
856 -- Currently we only have these two calling conventions, but this might
857 -- change in the future...
858 is_cish CCallConv = True
859 is_cish StdCallConv = True
861 -- ---------------------------------------------------------------------
862 -- Find and print local and external declarations for a list of
865 pprTempAndExternDecls :: [CmmBasicBlock] -> (SDoc{-temps-}, SDoc{-externs-})
866 pprTempAndExternDecls stmts
867 = (vcat (map pprTempDecl (uniqSetToList temps)),
868 vcat (map (pprExternDecl False{-ToDo-}) (keysFM lbls)))
869 where (temps, lbls) = runTE (mapM_ te_BB stmts)
871 pprDataExterns :: [CmmStatic] -> SDoc
872 pprDataExterns statics
873 = vcat (map (pprExternDecl False{-ToDo-}) (keysFM lbls))
874 where (_, lbls) = runTE (mapM_ te_Static statics)
876 pprTempDecl :: LocalReg -> SDoc
877 pprTempDecl l@(LocalReg _ rep)
878 = hcat [ machRepCType rep, space, pprLocalReg l, semi ]
880 pprExternDecl :: Bool -> CLabel -> SDoc
881 pprExternDecl in_srt lbl
882 -- do not print anything for "known external" things
883 | not (needsCDecl lbl) = empty
884 | Just sz <- foreignLabelStdcallInfo lbl = stdcall_decl sz
886 hcat [ visibility, label_type lbl,
887 lparen, pprCLabel lbl, text ");" ]
889 label_type lbl | isCFunctionLabel lbl = ptext (sLit "F_")
890 | otherwise = ptext (sLit "I_")
893 | externallyVisibleCLabel lbl = char 'E'
894 | otherwise = char 'I'
896 -- If the label we want to refer to is a stdcall function (on Windows) then
897 -- we must generate an appropriate prototype for it, so that the C compiler will
898 -- add the @n suffix to the label (#2276)
900 ptext (sLit "extern __attribute__((stdcall)) void ") <> pprCLabel lbl
901 <> parens (commafy (replicate (sz `quot` wORD_SIZE) (machRep_U_CType wordWidth)))
904 type TEState = (UniqSet LocalReg, FiniteMap CLabel ())
905 newtype TE a = TE { unTE :: TEState -> (a, TEState) }
907 instance Monad TE where
908 TE m >>= k = TE $ \s -> case m s of (a, s') -> unTE (k a) s'
909 return a = TE $ \s -> (a, s)
911 te_lbl :: CLabel -> TE ()
912 te_lbl lbl = TE $ \(temps,lbls) -> ((), (temps, addToFM lbls lbl ()))
914 te_temp :: LocalReg -> TE ()
915 te_temp r = TE $ \(temps,lbls) -> ((), (addOneToUniqSet temps r, lbls))
917 runTE :: TE () -> TEState
918 runTE (TE m) = snd (m (emptyUniqSet, emptyFM))
920 te_Static :: CmmStatic -> TE ()
921 te_Static (CmmStaticLit lit) = te_Lit lit
922 te_Static _ = return ()
924 te_BB :: CmmBasicBlock -> TE ()
925 te_BB (BasicBlock _ ss) = mapM_ te_Stmt ss
927 te_Lit :: CmmLit -> TE ()
928 te_Lit (CmmLabel l) = te_lbl l
929 te_Lit (CmmLabelOff l _) = te_lbl l
930 te_Lit (CmmLabelDiffOff l1 l2 _) = te_lbl l1
933 te_Stmt :: CmmStmt -> TE ()
934 te_Stmt (CmmAssign r e) = te_Reg r >> te_Expr e
935 te_Stmt (CmmStore l r) = te_Expr l >> te_Expr r
936 te_Stmt (CmmCall _ rs es _ _) = mapM_ (te_temp.hintlessCmm) rs >>
937 mapM_ (te_Expr.hintlessCmm) es
938 te_Stmt (CmmCondBranch e _) = te_Expr e
939 te_Stmt (CmmSwitch e _) = te_Expr e
940 te_Stmt (CmmJump e _) = te_Expr e
941 te_Stmt _ = return ()
943 te_Expr :: CmmExpr -> TE ()
944 te_Expr (CmmLit lit) = te_Lit lit
945 te_Expr (CmmLoad e _) = te_Expr e
946 te_Expr (CmmReg r) = te_Reg r
947 te_Expr (CmmMachOp _ es) = mapM_ te_Expr es
948 te_Expr (CmmRegOff r _) = te_Reg r
950 te_Reg :: CmmReg -> TE ()
951 te_Reg (CmmLocal l) = te_temp l
955 -- ---------------------------------------------------------------------
956 -- C types for MachReps
958 cCast :: SDoc -> CmmExpr -> SDoc
959 cCast ty expr = parens ty <> pprExpr1 expr
961 cLoad :: CmmExpr -> CmmType -> SDoc
962 #ifdef BEWARE_LOAD_STORE_ALIGNMENT
964 let decl = machRepCType rep <+> ptext (sLit "x") <> semi
965 struct = ptext (sLit "struct") <+> braces (decl)
966 packed_attr = ptext (sLit "__attribute__((packed))")
967 cast = parens (struct <+> packed_attr <> char '*')
968 in parens (cast <+> pprExpr1 expr) <> ptext (sLit "->x")
970 cLoad expr rep = char '*' <> parens (cCast (machRepPtrCType rep) expr)
973 isCmmWordType :: CmmType -> Bool
974 -- True of GcPtrReg/NonGcReg of native word size
975 isCmmWordType ty = not (isFloatType ty)
976 && typeWidth ty == wordWidth
978 -- This is for finding the types of foreign call arguments. For a pointer
979 -- argument, we always cast the argument to (void *), to avoid warnings from
981 machRepHintCType :: CmmType -> ForeignHint -> SDoc
982 machRepHintCType rep AddrHint = ptext (sLit "void *")
983 machRepHintCType rep SignedHint = machRep_S_CType (typeWidth rep)
984 machRepHintCType rep _other = machRepCType rep
986 machRepPtrCType :: CmmType -> SDoc
987 machRepPtrCType r | isCmmWordType r = ptext (sLit "P_")
988 | otherwise = machRepCType r <> char '*'
990 machRepCType :: CmmType -> SDoc
991 machRepCType ty | isFloatType ty = machRep_F_CType w
992 | otherwise = machRep_U_CType w
996 machRep_F_CType :: Width -> SDoc
997 machRep_F_CType W32 = ptext (sLit "StgFloat") -- ToDo: correct?
998 machRep_F_CType W64 = ptext (sLit "StgDouble")
999 machRep_F_CType _ = panic "machRep_F_CType"
1001 machRep_U_CType :: Width -> SDoc
1002 machRep_U_CType w | w == wordWidth = ptext (sLit "W_")
1003 machRep_U_CType W8 = ptext (sLit "StgWord8")
1004 machRep_U_CType W16 = ptext (sLit "StgWord16")
1005 machRep_U_CType W32 = ptext (sLit "StgWord32")
1006 machRep_U_CType W64 = ptext (sLit "StgWord64")
1007 machRep_U_CType _ = panic "machRep_U_CType"
1009 machRep_S_CType :: Width -> SDoc
1010 machRep_S_CType w | w == wordWidth = ptext (sLit "I_")
1011 machRep_S_CType W8 = ptext (sLit "StgInt8")
1012 machRep_S_CType W16 = ptext (sLit "StgInt16")
1013 machRep_S_CType W32 = ptext (sLit "StgInt32")
1014 machRep_S_CType W64 = ptext (sLit "StgInt64")
1015 machRep_S_CType _ = panic "machRep_S_CType"
1018 -- ---------------------------------------------------------------------
1019 -- print strings as valid C strings
1021 pprStringInCStyle :: [Word8] -> SDoc
1022 pprStringInCStyle s = doubleQuotes (text (concatMap charToC s))
1024 charToC :: Word8 -> String
1026 case chr (fromIntegral w) of
1030 c | c >= ' ' && c <= '~' -> [c]
1031 | otherwise -> ['\\',
1032 chr (ord '0' + ord c `div` 64),
1033 chr (ord '0' + ord c `div` 8 `mod` 8),
1034 chr (ord '0' + ord c `mod` 8)]
1036 -- ---------------------------------------------------------------------------
1037 -- Initialising static objects with floating-point numbers. We can't
1038 -- just emit the floating point number, because C will cast it to an int
1039 -- by rounding it. We want the actual bit-representation of the float.
1041 -- This is a hack to turn the floating point numbers into ints that we
1042 -- can safely initialise to static locations.
1045 | widthInBytes W64 == 2 * wORD_SIZE = True
1046 | widthInBytes W64 == wORD_SIZE = False
1047 | otherwise = panic "big_doubles"
1049 castFloatToIntArray :: STUArray s Int Float -> ST s (STUArray s Int Int)
1050 castFloatToIntArray = castSTUArray
1052 castDoubleToIntArray :: STUArray s Int Double -> ST s (STUArray s Int Int)
1053 castDoubleToIntArray = castSTUArray
1055 -- floats are always 1 word
1056 floatToWord :: Rational -> CmmLit
1059 arr <- newArray_ ((0::Int),0)
1060 writeArray arr 0 (fromRational r)
1061 arr' <- castFloatToIntArray arr
1062 i <- readArray arr' 0
1063 return (CmmInt (toInteger i) wordWidth)
1066 doubleToWords :: Rational -> [CmmLit]
1068 | big_doubles -- doubles are 2 words
1070 arr <- newArray_ ((0::Int),1)
1071 writeArray arr 0 (fromRational r)
1072 arr' <- castDoubleToIntArray arr
1073 i1 <- readArray arr' 0
1074 i2 <- readArray arr' 1
1075 return [ CmmInt (toInteger i1) wordWidth
1076 , CmmInt (toInteger i2) wordWidth
1079 | otherwise -- doubles are 1 word
1081 arr <- newArray_ ((0::Int),0)
1082 writeArray arr 0 (fromRational r)
1083 arr' <- castDoubleToIntArray arr
1084 i <- readArray arr' 0
1085 return [ CmmInt (toInteger i) wordWidth ]
1088 -- ---------------------------------------------------------------------------
1092 wordShift = widthInLog wordWidth
1094 commafy :: [SDoc] -> SDoc
1095 commafy xs = hsep $ punctuate comma xs
1097 -- Print in C hex format: 0x13fa
1098 pprHexVal :: Integer -> Width -> SDoc
1099 pprHexVal 0 _ = ptext (sLit "0x0")
1101 | w < 0 = parens (char '-' <> ptext (sLit "0x") <> go (-w) <> repsuffix rep)
1102 | otherwise = ptext (sLit "0x") <> go w <> repsuffix rep
1104 -- type suffix for literals:
1105 -- Integer literals are unsigned in Cmm/C. We explicitly cast to
1106 -- signed values for doing signed operations, but at all other
1107 -- times values are unsigned. This also helps eliminate occasional
1108 -- warnings about integer overflow from gcc.
1110 -- on 32-bit platforms, add "ULL" to 64-bit literals
1111 repsuffix W64 | wORD_SIZE == 4 = ptext (sLit "ULL")
1112 -- on 64-bit platforms with 32-bit int, add "L" to 64-bit literals
1113 repsuffix W64 | cINT_SIZE == 4 = ptext (sLit "UL")
1114 repsuffix _ = char 'U'
1119 (q,r) = w' `quotRem` 16
1120 dig | r < 10 = char (chr (fromInteger r + ord '0'))
1121 | otherwise = char (chr (fromInteger r - 10 + ord 'a'))