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 -- these shouldn't appear?
144 pprTop (CmmData _ _) = panic "PprC.pprTop: can't handle this data"
146 -- --------------------------------------------------------------------------
147 -- BasicBlocks are self-contained entities: they always end in a jump.
149 -- Like nativeGen/AsmCodeGen, we could probably reorder blocks to turn
150 -- as many jumps as possible into fall throughs.
153 pprBBlock :: CmmBasicBlock -> SDoc
154 pprBBlock (BasicBlock lbl stmts) =
156 pprTrace "pprC.pprBBlock: curious empty code block for"
157 (pprBlockId lbl) empty
159 nest 4 (pprBlockId lbl <> colon) $$
160 nest 8 (vcat (map pprStmt stmts))
162 -- --------------------------------------------------------------------------
163 -- Info tables. Just arrays of words.
164 -- See codeGen/ClosureInfo, and nativeGen/PprMach
166 pprWordArray :: CLabel -> [CmmStatic] -> SDoc
168 = hcat [ pprLocalness lbl, ptext (sLit "StgWord")
169 , space, pprCLabel lbl, ptext (sLit "[] = {") ]
170 $$ nest 8 (commafy (pprStatics ds))
174 -- has to be static, if it isn't globally visible
176 pprLocalness :: CLabel -> SDoc
177 pprLocalness lbl | not $ externallyVisibleCLabel lbl = ptext (sLit "static ")
180 -- --------------------------------------------------------------------------
184 pprStmt :: CmmStmt -> SDoc
186 pprStmt stmt = case stmt of
188 CmmComment s -> (hang (ptext (sLit "/*")) 3 (ftext s)) $$ ptext (sLit "*/")
190 CmmAssign dest src -> pprAssign dest src
193 | typeWidth rep == W64 && wordWidth /= W64
194 -> (if isFloatType rep then ptext (sLit "ASSIGN_DBL")
195 else ptext (sLit ("ASSIGN_Word64"))) <>
196 parens (mkP_ <> pprExpr1 dest <> comma <> pprExpr src) <> semi
199 -> hsep [ pprExpr (CmmLoad dest rep), equals, pprExpr src <> semi ]
201 rep = cmmExprType src
203 CmmCall (CmmCallee fn cconv) results args safety ret ->
205 pprCall ppr_fn cconv results args safety
207 cast_fn = parens (cCast (pprCFunType (char '*') cconv results args) fn)
209 real_fun_proto lbl = char ';' <>
210 pprCFunType (pprCLabel lbl) cconv results args <>
211 noreturn_attr <> semi
213 data_proto lbl = ptext (sLit ";EI_(") <>
214 pprCLabel lbl <> char ')' <> semi
216 noreturn_attr = case ret of
217 CmmNeverReturns -> text "__attribute__ ((noreturn))"
218 CmmMayReturn -> empty
220 -- See wiki:Commentary/Compiler/Backends/PprC#Prototypes
221 (maybe_proto, ppr_fn) =
223 CmmLit (CmmLabel lbl)
224 | StdCallConv <- cconv -> (real_fun_proto lbl, pprCLabel lbl)
225 -- stdcall functions must be declared with
226 -- a function type, otherwise the C compiler
227 -- doesn't add the @n suffix to the label. We
228 -- can't add the @n suffix ourselves, because
230 | CmmNeverReturns <- ret -> (real_fun_proto lbl, pprCLabel lbl)
231 | not (isMathFun lbl) -> (data_proto lbl, cast_fn)
232 -- we declare all other called functions as
233 -- data labels, and then cast them to the
234 -- right type when calling. This is because
235 -- the label might already have a declaration
236 -- as a data label in the same file,
237 -- e.g. Foreign.Marshal.Alloc declares 'free'
238 -- as both a data label and a function label.
240 (empty {- no proto -}, cast_fn)
241 -- for a dynamic call, no declaration is necessary.
243 CmmCall (CmmPrim op) results args safety _ret ->
244 pprCall ppr_fn CCallConv results args safety
246 ppr_fn = pprCallishMachOp_for_C op
248 CmmBranch ident -> pprBranch ident
249 CmmCondBranch expr ident -> pprCondBranch expr ident
250 CmmJump lbl _params -> mkJMP_(pprExpr lbl) <> semi
251 CmmSwitch arg ids -> pprSwitch arg ids
253 pprCFunType :: SDoc -> CCallConv -> HintedCmmFormals -> HintedCmmActuals -> SDoc
254 pprCFunType ppr_fn cconv ress args
256 parens (text (ccallConvAttribute cconv) <> ppr_fn) <>
257 parens (commafy (map arg_type args))
259 res_type [] = ptext (sLit "void")
260 res_type [CmmHinted one hint] = machRepHintCType (localRegType one) hint
262 arg_type (CmmHinted expr hint) = machRepHintCType (cmmExprType expr) hint
264 -- ---------------------------------------------------------------------
265 -- unconditional branches
266 pprBranch :: BlockId -> SDoc
267 pprBranch ident = ptext (sLit "goto") <+> pprBlockId ident <> semi
270 -- ---------------------------------------------------------------------
271 -- conditional branches to local labels
272 pprCondBranch :: CmmExpr -> BlockId -> SDoc
273 pprCondBranch expr ident
274 = hsep [ ptext (sLit "if") , parens(pprExpr expr) ,
275 ptext (sLit "goto") , (pprBlockId ident) <> semi ]
278 -- ---------------------------------------------------------------------
279 -- a local table branch
281 -- we find the fall-through cases
283 -- N.B. we remove Nothing's from the list of branches, as they are
284 -- 'undefined'. However, they may be defined one day, so we better
285 -- document this behaviour.
287 pprSwitch :: CmmExpr -> [ Maybe BlockId ] -> SDoc
288 pprSwitch e maybe_ids
289 = let pairs = [ (ix, ident) | (ix,Just ident) <- zip [0..] maybe_ids ]
290 pairs2 = [ (map fst as, snd (head as)) | as <- groupBy sndEq pairs ]
292 (hang (ptext (sLit "switch") <+> parens ( pprExpr e ) <+> lbrace)
293 4 (vcat ( map caseify pairs2 )))
297 sndEq (_,x) (_,y) = x == y
300 caseify (ix:ixs, ident) = vcat (map do_fallthrough ixs) $$ final_branch ix
303 hsep [ ptext (sLit "case") , pprHexVal ix wordWidth <> colon ,
304 ptext (sLit "/* fall through */") ]
307 hsep [ ptext (sLit "case") , pprHexVal ix wordWidth <> colon ,
308 ptext (sLit "goto") , (pprBlockId ident) <> semi ]
310 -- ---------------------------------------------------------------------
314 -- C Types: the invariant is that the C expression generated by
318 -- has a type in C which is also given by
320 -- machRepCType (cmmExprType e)
322 -- (similar invariants apply to the rest of the pretty printer).
324 pprExpr :: CmmExpr -> SDoc
325 pprExpr e = case e of
326 CmmLit lit -> pprLit lit
329 CmmLoad e ty -> pprLoad e ty
330 CmmReg reg -> pprCastReg reg
331 CmmRegOff reg 0 -> pprCastReg reg
334 | i > 0 -> pprRegOff (char '+') i
335 | otherwise -> pprRegOff (char '-') (-i)
337 pprRegOff op i' = pprCastReg reg <> op <> int i'
339 CmmMachOp mop args -> pprMachOpApp mop args
342 pprLoad :: CmmExpr -> CmmType -> SDoc
344 | width == W64, wordWidth /= W64
345 = (if isFloatType ty then ptext (sLit "PK_DBL")
346 else ptext (sLit "PK_Word64"))
347 <> parens (mkP_ <> pprExpr1 e)
351 CmmReg r | isPtrReg r && width == wordWidth && not (isFloatType ty)
352 -> char '*' <> pprAsPtrReg r
354 CmmRegOff r 0 | isPtrReg r && width == wordWidth && not (isFloatType ty)
355 -> char '*' <> pprAsPtrReg r
357 CmmRegOff r off | isPtrReg r && width == wordWidth
358 , off `rem` wORD_SIZE == 0 && not (isFloatType ty)
359 -- ToDo: check that the offset is a word multiple?
360 -- (For tagging to work, I had to avoid unaligned loads. --ARY)
361 -> pprAsPtrReg r <> brackets (ppr (off `shiftR` wordShift))
367 pprExpr1 :: CmmExpr -> SDoc
368 pprExpr1 (CmmLit lit) = pprLit1 lit
369 pprExpr1 e@(CmmReg _reg) = pprExpr e
370 pprExpr1 other = parens (pprExpr other)
372 -- --------------------------------------------------------------------------
373 -- MachOp applications
375 pprMachOpApp :: MachOp -> [CmmExpr] -> SDoc
379 = ptext (sLit "mulIntMayOflo") <> parens (commafy (map pprExpr args))
380 where isMulMayOfloOp (MO_U_MulMayOflo _) = True
381 isMulMayOfloOp (MO_S_MulMayOflo _) = True
382 isMulMayOfloOp _ = False
384 pprMachOpApp mop args
385 | Just ty <- machOpNeedsCast mop
386 = ty <> parens (pprMachOpApp' mop args)
388 = pprMachOpApp' mop args
390 -- Comparisons in C have type 'int', but we want type W_ (this is what
391 -- resultRepOfMachOp says). The other C operations inherit their type
392 -- from their operands, so no casting is required.
393 machOpNeedsCast :: MachOp -> Maybe SDoc
395 | isComparisonMachOp mop = Just mkW_
396 | otherwise = Nothing
398 pprMachOpApp' mop args
401 [x,y] -> pprArg x <+> pprMachOp_for_C mop <+> pprArg y
404 [x] -> pprMachOp_for_C mop <> parens (pprArg x)
406 _ -> panic "PprC.pprMachOp : machop with wrong number of args"
409 -- Cast needed for signed integer ops
410 pprArg e | signedOp mop = cCast (machRep_S_CType (typeWidth (cmmExprType e))) e
411 | needsFCasts mop = cCast (machRep_F_CType (typeWidth (cmmExprType e))) e
412 | otherwise = pprExpr1 e
413 needsFCasts (MO_F_Eq _) = False
414 needsFCasts (MO_F_Ne _) = False
415 needsFCasts (MO_F_Neg _) = True
416 needsFCasts (MO_F_Quot _) = True
417 needsFCasts mop = floatComparison mop
419 -- --------------------------------------------------------------------------
422 pprLit :: CmmLit -> SDoc
423 pprLit lit = case lit of
424 CmmInt i rep -> pprHexVal i rep
426 CmmFloat f w -> parens (machRep_F_CType w) <> str
427 where d = fromRational f :: Double
428 str | isInfinite d && d < 0 = ptext (sLit "-INFINITY")
429 | isInfinite d = ptext (sLit "INFINITY")
430 | isNaN d = ptext (sLit "NAN")
431 | otherwise = text (show d)
432 -- these constants come from <math.h>
435 CmmLabel clbl -> mkW_ <> pprCLabelAddr clbl
436 CmmLabelOff clbl i -> mkW_ <> pprCLabelAddr clbl <> char '+' <> int i
437 CmmLabelDiffOff clbl1 clbl2 i
439 -- * the lit must occur in the info table clbl2
440 -- * clbl1 must be an SRT, a slow entry point or a large bitmap
441 -- The Mangler is expected to convert any reference to an SRT,
442 -- a slow entry point or a large bitmap
443 -- from an info table to an offset.
444 -> mkW_ <> pprCLabelAddr clbl1 <> char '+' <> int i
446 pprCLabelAddr lbl = char '&' <> pprCLabel lbl
448 pprLit1 :: CmmLit -> SDoc
449 pprLit1 lit@(CmmLabelOff _ _) = parens (pprLit lit)
450 pprLit1 lit@(CmmLabelDiffOff _ _ _) = parens (pprLit lit)
451 pprLit1 lit@(CmmFloat _ _) = parens (pprLit lit)
452 pprLit1 other = pprLit other
454 -- ---------------------------------------------------------------------------
457 pprStatics :: [CmmStatic] -> [SDoc]
459 pprStatics (CmmStaticLit (CmmFloat f W32) : rest)
460 -- floats are padded to a word, see #1852
461 | wORD_SIZE == 8, CmmStaticLit (CmmInt 0 W32) : rest' <- rest
462 = pprLit1 (floatToWord f) : pprStatics rest'
464 = pprLit1 (floatToWord f) : pprStatics rest
466 = pprPanic "pprStatics: float" (vcat (map (\(CmmStaticLit l) -> ppr (cmmLitType l)) rest))
467 pprStatics (CmmStaticLit (CmmFloat f W64) : rest)
468 = map pprLit1 (doubleToWords f) ++ pprStatics rest
469 pprStatics (CmmStaticLit (CmmInt i W64) : rest)
471 #ifdef WORDS_BIGENDIAN
472 = pprStatics (CmmStaticLit (CmmInt q W32) :
473 CmmStaticLit (CmmInt r W32) : rest)
475 = pprStatics (CmmStaticLit (CmmInt r W32) :
476 CmmStaticLit (CmmInt q W32) : rest)
478 where r = i .&. 0xffffffff
480 pprStatics (CmmStaticLit (CmmInt i w) : rest)
482 = panic "pprStatics: cannot emit a non-word-sized static literal"
483 pprStatics (CmmStaticLit lit : rest)
484 = pprLit1 lit : pprStatics rest
485 pprStatics (other : rest)
486 = pprPanic "pprWord" (pprStatic other)
488 pprStatic :: CmmStatic -> SDoc
489 pprStatic s = case s of
491 CmmStaticLit lit -> nest 4 (pprLit lit)
492 CmmAlign i -> nest 4 (ptext (sLit "/* align */") <+> int i)
493 CmmDataLabel clbl -> pprCLabel clbl <> colon
494 CmmUninitialised i -> nest 4 (mkC_ <> brackets (int i))
496 -- these should be inlined, like the old .hc
497 CmmString s' -> nest 4 (mkW_ <> parens(pprStringInCStyle s'))
500 -- ---------------------------------------------------------------------------
503 pprBlockId :: BlockId -> SDoc
504 pprBlockId b = char '_' <> ppr (getUnique b)
506 -- --------------------------------------------------------------------------
507 -- Print a MachOp in a way suitable for emitting via C.
510 pprMachOp_for_C :: MachOp -> SDoc
512 pprMachOp_for_C mop = case mop of
514 -- Integer operations
517 MO_Eq _ -> ptext (sLit "==")
518 MO_Ne _ -> ptext (sLit "!=")
521 MO_S_Quot _ -> char '/'
522 MO_S_Rem _ -> char '%'
523 MO_S_Neg _ -> char '-'
525 MO_U_Quot _ -> char '/'
526 MO_U_Rem _ -> char '%'
528 -- & Floating-point operations
529 MO_F_Add _ -> char '+'
530 MO_F_Sub _ -> char '-'
531 MO_F_Neg _ -> char '-'
532 MO_F_Mul _ -> char '*'
533 MO_F_Quot _ -> char '/'
535 -- Signed comparisons
536 MO_S_Ge _ -> ptext (sLit ">=")
537 MO_S_Le _ -> ptext (sLit "<=")
538 MO_S_Gt _ -> char '>'
539 MO_S_Lt _ -> char '<'
541 -- & Unsigned comparisons
542 MO_U_Ge _ -> ptext (sLit ">=")
543 MO_U_Le _ -> ptext (sLit "<=")
544 MO_U_Gt _ -> char '>'
545 MO_U_Lt _ -> char '<'
547 -- & Floating-point comparisons
548 MO_F_Eq _ -> ptext (sLit "==")
549 MO_F_Ne _ -> ptext (sLit "!=")
550 MO_F_Ge _ -> ptext (sLit ">=")
551 MO_F_Le _ -> ptext (sLit "<=")
552 MO_F_Gt _ -> char '>'
553 MO_F_Lt _ -> char '<'
555 -- Bitwise operations. Not all of these may be supported at all
556 -- sizes, and only integral MachReps are valid.
561 MO_Shl _ -> ptext (sLit "<<")
562 MO_U_Shr _ -> ptext (sLit ">>") -- unsigned shift right
563 MO_S_Shr _ -> ptext (sLit ">>") -- signed shift right
565 -- Conversions. Some of these will be NOPs, but never those that convert
566 -- between ints and floats.
567 -- Floating-point conversions use the signed variant.
568 -- We won't know to generate (void*) casts here, but maybe from
572 MO_UU_Conv from to | from == to -> empty
573 MO_UU_Conv _from to -> parens (machRep_U_CType to)
575 MO_SS_Conv from to | from == to -> empty
576 MO_SS_Conv _from to -> parens (machRep_S_CType to)
578 -- TEMPORARY: the old code didn't check this case, so let's leave it out
579 -- to facilitate comparisons against the old output code.
580 --MO_FF_Conv from to | from == to -> empty
581 MO_FF_Conv _from to -> parens (machRep_F_CType to)
583 MO_SF_Conv _from to -> parens (machRep_F_CType to)
584 MO_FS_Conv _from to -> parens (machRep_S_CType to)
586 _ -> pprTrace "offending mop" (ptext $ sLit $ show mop) $
587 panic "PprC.pprMachOp_for_C: unknown machop"
589 signedOp :: MachOp -> Bool -- Argument type(s) are signed ints
590 signedOp (MO_S_Quot _) = True
591 signedOp (MO_S_Rem _) = True
592 signedOp (MO_S_Neg _) = True
593 signedOp (MO_S_Ge _) = True
594 signedOp (MO_S_Le _) = True
595 signedOp (MO_S_Gt _) = True
596 signedOp (MO_S_Lt _) = True
597 signedOp (MO_S_Shr _) = True
598 signedOp (MO_SS_Conv _ _) = True
599 signedOp (MO_SF_Conv _ _) = True
602 floatComparison :: MachOp -> Bool -- comparison between float args
603 floatComparison (MO_F_Eq _) = True
604 floatComparison (MO_F_Ne _) = True
605 floatComparison (MO_F_Ge _) = True
606 floatComparison (MO_F_Le _) = True
607 floatComparison (MO_F_Gt _) = True
608 floatComparison (MO_F_Lt _) = True
609 floatComparison _ = False
611 -- ---------------------------------------------------------------------
612 -- tend to be implemented by foreign calls
614 pprCallishMachOp_for_C :: CallishMachOp -> SDoc
616 pprCallishMachOp_for_C mop
618 MO_F64_Pwr -> ptext (sLit "pow")
619 MO_F64_Sin -> ptext (sLit "sin")
620 MO_F64_Cos -> ptext (sLit "cos")
621 MO_F64_Tan -> ptext (sLit "tan")
622 MO_F64_Sinh -> ptext (sLit "sinh")
623 MO_F64_Cosh -> ptext (sLit "cosh")
624 MO_F64_Tanh -> ptext (sLit "tanh")
625 MO_F64_Asin -> ptext (sLit "asin")
626 MO_F64_Acos -> ptext (sLit "acos")
627 MO_F64_Atan -> ptext (sLit "atan")
628 MO_F64_Log -> ptext (sLit "log")
629 MO_F64_Exp -> ptext (sLit "exp")
630 MO_F64_Sqrt -> ptext (sLit "sqrt")
631 MO_F32_Pwr -> ptext (sLit "powf")
632 MO_F32_Sin -> ptext (sLit "sinf")
633 MO_F32_Cos -> ptext (sLit "cosf")
634 MO_F32_Tan -> ptext (sLit "tanf")
635 MO_F32_Sinh -> ptext (sLit "sinhf")
636 MO_F32_Cosh -> ptext (sLit "coshf")
637 MO_F32_Tanh -> ptext (sLit "tanhf")
638 MO_F32_Asin -> ptext (sLit "asinf")
639 MO_F32_Acos -> ptext (sLit "acosf")
640 MO_F32_Atan -> ptext (sLit "atanf")
641 MO_F32_Log -> ptext (sLit "logf")
642 MO_F32_Exp -> ptext (sLit "expf")
643 MO_F32_Sqrt -> ptext (sLit "sqrtf")
644 MO_WriteBarrier -> ptext (sLit "write_barrier")
646 -- ---------------------------------------------------------------------
650 mkJMP_, mkFN_, mkIF_ :: SDoc -> SDoc
652 mkJMP_ i = ptext (sLit "JMP_") <> parens i
653 mkFN_ i = ptext (sLit "FN_") <> parens i -- externally visible function
654 mkIF_ i = ptext (sLit "IF_") <> parens i -- locally visible
658 mkFB_ = ptext (sLit "FB_") -- function code begin
659 mkFE_ = ptext (sLit "FE_") -- function code end
661 -- from includes/Stg.h
663 mkC_,mkW_,mkP_,mkPP_,mkI_,mkA_,mkD_,mkF_,mkB_,mkL_,mkLI_,mkLW_ :: SDoc
665 mkC_ = ptext (sLit "(C_)") -- StgChar
666 mkW_ = ptext (sLit "(W_)") -- StgWord
667 mkP_ = ptext (sLit "(P_)") -- StgWord*
668 mkPP_ = ptext (sLit "(PP_)") -- P_*
669 mkI_ = ptext (sLit "(I_)") -- StgInt
670 mkA_ = ptext (sLit "(A_)") -- StgAddr
671 mkD_ = ptext (sLit "(D_)") -- const StgWord*
672 mkF_ = ptext (sLit "(F_)") -- StgFunPtr
673 mkB_ = ptext (sLit "(B_)") -- StgByteArray
674 mkL_ = ptext (sLit "(L_)") -- StgClosurePtr
676 mkLI_ = ptext (sLit "(LI_)") -- StgInt64
677 mkLW_ = ptext (sLit "(LW_)") -- StgWord64
680 -- ---------------------------------------------------------------------
684 -- Generating assignments is what we're all about, here
686 pprAssign :: CmmReg -> CmmExpr -> SDoc
688 -- dest is a reg, rhs is a reg
689 pprAssign r1 (CmmReg r2)
690 | isPtrReg r1 && isPtrReg r2
691 = hcat [ pprAsPtrReg r1, equals, pprAsPtrReg r2, semi ]
693 -- dest is a reg, rhs is a CmmRegOff
694 pprAssign r1 (CmmRegOff r2 off)
695 | isPtrReg r1 && isPtrReg r2 && (off `rem` wORD_SIZE == 0)
696 = hcat [ pprAsPtrReg r1, equals, pprAsPtrReg r2, op, int off', semi ]
698 off1 = off `shiftR` wordShift
700 (op,off') | off >= 0 = (char '+', off1)
701 | otherwise = (char '-', -off1)
703 -- dest is a reg, rhs is anything.
704 -- We can't cast the lvalue, so we have to cast the rhs if necessary. Casting
705 -- the lvalue elicits a warning from new GCC versions (3.4+).
707 | isFixedPtrReg r1 = mkAssign (mkP_ <> pprExpr1 r2)
708 | Just ty <- strangeRegType r1 = mkAssign (parens ty <> pprExpr1 r2)
709 | otherwise = mkAssign (pprExpr r2)
710 where mkAssign x = if r1 == CmmGlobal BaseReg
711 then ptext (sLit "ASSIGN_BaseReg") <> parens x <> semi
712 else pprReg r1 <> ptext (sLit " = ") <> x <> semi
714 -- ---------------------------------------------------------------------
718 | isStrangeTypeReg reg = mkW_ <> pprReg reg
719 | otherwise = pprReg reg
721 -- True if (pprReg reg) will give an expression with type StgPtr. We
722 -- need to take care with pointer arithmetic on registers with type
724 isFixedPtrReg :: CmmReg -> Bool
725 isFixedPtrReg (CmmLocal _) = False
726 isFixedPtrReg (CmmGlobal r) = isFixedPtrGlobalReg r
728 -- True if (pprAsPtrReg reg) will give an expression with type StgPtr
729 -- JD: THIS IS HORRIBLE AND SHOULD BE RENAMED, AT THE VERY LEAST.
730 -- THE GARBAGE WITH THE VNonGcPtr HELPS MATCH THE OLD CODE GENERATOR'S OUTPUT;
731 -- I'M NOT SURE IF IT SHOULD REALLY STAY THAT WAY.
732 isPtrReg :: CmmReg -> Bool
733 isPtrReg (CmmLocal _) = False
734 isPtrReg (CmmGlobal (VanillaReg n VGcPtr)) = True -- if we print via pprAsPtrReg
735 isPtrReg (CmmGlobal (VanillaReg n VNonGcPtr)) = False --if we print via pprAsPtrReg
736 isPtrReg (CmmGlobal reg) = isFixedPtrGlobalReg reg
738 -- True if this global reg has type StgPtr
739 isFixedPtrGlobalReg :: GlobalReg -> Bool
740 isFixedPtrGlobalReg Sp = True
741 isFixedPtrGlobalReg Hp = True
742 isFixedPtrGlobalReg HpLim = True
743 isFixedPtrGlobalReg SpLim = True
744 isFixedPtrGlobalReg _ = False
746 -- True if in C this register doesn't have the type given by
747 -- (machRepCType (cmmRegType reg)), so it has to be cast.
748 isStrangeTypeReg :: CmmReg -> Bool
749 isStrangeTypeReg (CmmLocal _) = False
750 isStrangeTypeReg (CmmGlobal g) = isStrangeTypeGlobal g
752 isStrangeTypeGlobal :: GlobalReg -> Bool
753 isStrangeTypeGlobal CurrentTSO = True
754 isStrangeTypeGlobal CurrentNursery = True
755 isStrangeTypeGlobal BaseReg = True
756 isStrangeTypeGlobal r = isFixedPtrGlobalReg r
758 strangeRegType :: CmmReg -> Maybe SDoc
759 strangeRegType (CmmGlobal CurrentTSO) = Just (ptext (sLit "struct StgTSO_ *"))
760 strangeRegType (CmmGlobal CurrentNursery) = Just (ptext (sLit "struct bdescr_ *"))
761 strangeRegType (CmmGlobal BaseReg) = Just (ptext (sLit "struct StgRegTable_ *"))
762 strangeRegType _ = Nothing
764 -- pprReg just prints the register name.
766 pprReg :: CmmReg -> SDoc
768 CmmLocal local -> pprLocalReg local
769 CmmGlobal global -> pprGlobalReg global
771 pprAsPtrReg :: CmmReg -> SDoc
772 pprAsPtrReg (CmmGlobal (VanillaReg n gcp))
773 = WARN( gcp /= VGcPtr, ppr n ) char 'R' <> int n <> ptext (sLit ".p")
774 pprAsPtrReg other_reg = pprReg other_reg
776 pprGlobalReg :: GlobalReg -> SDoc
777 pprGlobalReg gr = case gr of
778 VanillaReg n _ -> char 'R' <> int n <> ptext (sLit ".w")
779 -- pprGlobalReg prints a VanillaReg as a .w regardless
780 -- Example: R1.w = R1.w & (-0x8UL);
782 FloatReg n -> char 'F' <> int n
783 DoubleReg n -> char 'D' <> int n
784 LongReg n -> char 'L' <> int n
785 Sp -> ptext (sLit "Sp")
786 SpLim -> ptext (sLit "SpLim")
787 Hp -> ptext (sLit "Hp")
788 HpLim -> ptext (sLit "HpLim")
789 CurrentTSO -> ptext (sLit "CurrentTSO")
790 CurrentNursery -> ptext (sLit "CurrentNursery")
791 HpAlloc -> ptext (sLit "HpAlloc")
792 BaseReg -> ptext (sLit "BaseReg")
793 EagerBlackholeInfo -> ptext (sLit "stg_EAGER_BLACKHOLE_info")
794 GCEnter1 -> ptext (sLit "stg_gc_enter_1")
795 GCFun -> ptext (sLit "stg_gc_fun")
797 pprLocalReg :: LocalReg -> SDoc
798 pprLocalReg (LocalReg uniq _) = char '_' <> ppr uniq
800 -- -----------------------------------------------------------------------------
803 pprCall :: SDoc -> CCallConv -> HintedCmmFormals -> HintedCmmActuals -> CmmSafety
806 pprCall ppr_fn cconv results args _
807 | not (is_cish cconv)
808 = panic "pprCall: unknown calling convention"
812 #if x86_64_TARGET_ARCH
813 -- HACK around gcc optimisations.
814 -- x86_64 needs a __DISCARD__() here, to create a barrier between
815 -- putting the arguments into temporaries and passing the arguments
816 -- to the callee, because the argument expressions may refer to
817 -- machine registers that are also used for passing arguments in the
818 -- C calling convention.
819 (if (not opt_Unregisterised)
820 then ptext (sLit "__DISCARD__();")
823 ppr_assign results (ppr_fn <> parens (commafy (map pprArg args))) <> semi
825 ppr_assign [] rhs = rhs
826 ppr_assign [CmmHinted one hint] rhs
827 = pprLocalReg one <> ptext (sLit " = ")
828 <> pprUnHint hint (localRegType one) <> rhs
829 ppr_assign _other _rhs = panic "pprCall: multiple results"
831 pprArg (CmmHinted expr AddrHint)
832 = cCast (ptext (sLit "void *")) expr
833 -- see comment by machRepHintCType below
834 pprArg (CmmHinted expr SignedHint)
835 = cCast (machRep_S_CType $ typeWidth $ cmmExprType expr) expr
836 pprArg (CmmHinted expr _other)
839 pprUnHint AddrHint rep = parens (machRepCType rep)
840 pprUnHint SignedHint rep = parens (machRepCType rep)
841 pprUnHint _ _ = empty
843 pprGlobalRegName :: GlobalReg -> SDoc
844 pprGlobalRegName gr = case gr of
845 VanillaReg n _ -> char 'R' <> int n -- without the .w suffix
848 -- Currently we only have these two calling conventions, but this might
849 -- change in the future...
850 is_cish CCallConv = True
851 is_cish StdCallConv = True
853 -- ---------------------------------------------------------------------
854 -- Find and print local and external declarations for a list of
857 pprTempAndExternDecls :: [CmmBasicBlock] -> (SDoc{-temps-}, SDoc{-externs-})
858 pprTempAndExternDecls stmts
859 = (vcat (map pprTempDecl (uniqSetToList temps)),
860 vcat (map (pprExternDecl False{-ToDo-}) (keysFM lbls)))
861 where (temps, lbls) = runTE (mapM_ te_BB stmts)
863 pprDataExterns :: [CmmStatic] -> SDoc
864 pprDataExterns statics
865 = vcat (map (pprExternDecl False{-ToDo-}) (keysFM lbls))
866 where (_, lbls) = runTE (mapM_ te_Static statics)
868 pprTempDecl :: LocalReg -> SDoc
869 pprTempDecl l@(LocalReg _ rep)
870 = hcat [ machRepCType rep, space, pprLocalReg l, semi ]
872 pprExternDecl :: Bool -> CLabel -> SDoc
873 pprExternDecl in_srt lbl
874 -- do not print anything for "known external" things
875 | not (needsCDecl lbl) = empty
876 | Just sz <- foreignLabelStdcallInfo lbl = stdcall_decl sz
878 hcat [ visibility, label_type lbl,
879 lparen, pprCLabel lbl, text ");" ]
881 label_type lbl | isCFunctionLabel lbl = ptext (sLit "F_")
882 | otherwise = ptext (sLit "I_")
885 | externallyVisibleCLabel lbl = char 'E'
886 | otherwise = char 'I'
888 -- If the label we want to refer to is a stdcall function (on Windows) then
889 -- we must generate an appropriate prototype for it, so that the C compiler will
890 -- add the @n suffix to the label (#2276)
892 ptext (sLit "extern __attribute__((stdcall)) void ") <> pprCLabel lbl
893 <> parens (commafy (replicate (sz `quot` wORD_SIZE) (machRep_U_CType wordWidth)))
896 type TEState = (UniqSet LocalReg, FiniteMap CLabel ())
897 newtype TE a = TE { unTE :: TEState -> (a, TEState) }
899 instance Monad TE where
900 TE m >>= k = TE $ \s -> case m s of (a, s') -> unTE (k a) s'
901 return a = TE $ \s -> (a, s)
903 te_lbl :: CLabel -> TE ()
904 te_lbl lbl = TE $ \(temps,lbls) -> ((), (temps, addToFM lbls lbl ()))
906 te_temp :: LocalReg -> TE ()
907 te_temp r = TE $ \(temps,lbls) -> ((), (addOneToUniqSet temps r, lbls))
909 runTE :: TE () -> TEState
910 runTE (TE m) = snd (m (emptyUniqSet, emptyFM))
912 te_Static :: CmmStatic -> TE ()
913 te_Static (CmmStaticLit lit) = te_Lit lit
914 te_Static _ = return ()
916 te_BB :: CmmBasicBlock -> TE ()
917 te_BB (BasicBlock _ ss) = mapM_ te_Stmt ss
919 te_Lit :: CmmLit -> TE ()
920 te_Lit (CmmLabel l) = te_lbl l
921 te_Lit (CmmLabelOff l _) = te_lbl l
922 te_Lit (CmmLabelDiffOff l1 l2 _) = te_lbl l1
925 te_Stmt :: CmmStmt -> TE ()
926 te_Stmt (CmmAssign r e) = te_Reg r >> te_Expr e
927 te_Stmt (CmmStore l r) = te_Expr l >> te_Expr r
928 te_Stmt (CmmCall _ rs es _ _) = mapM_ (te_temp.hintlessCmm) rs >>
929 mapM_ (te_Expr.hintlessCmm) es
930 te_Stmt (CmmCondBranch e _) = te_Expr e
931 te_Stmt (CmmSwitch e _) = te_Expr e
932 te_Stmt (CmmJump e _) = te_Expr e
933 te_Stmt _ = return ()
935 te_Expr :: CmmExpr -> TE ()
936 te_Expr (CmmLit lit) = te_Lit lit
937 te_Expr (CmmLoad e _) = te_Expr e
938 te_Expr (CmmReg r) = te_Reg r
939 te_Expr (CmmMachOp _ es) = mapM_ te_Expr es
940 te_Expr (CmmRegOff r _) = te_Reg r
942 te_Reg :: CmmReg -> TE ()
943 te_Reg (CmmLocal l) = te_temp l
947 -- ---------------------------------------------------------------------
948 -- C types for MachReps
950 cCast :: SDoc -> CmmExpr -> SDoc
951 cCast ty expr = parens ty <> pprExpr1 expr
953 cLoad :: CmmExpr -> CmmType -> SDoc
954 #ifdef BEWARE_LOAD_STORE_ALIGNMENT
956 let decl = machRepCType rep <+> ptext (sLit "x") <> semi
957 struct = ptext (sLit "struct") <+> braces (decl)
958 packed_attr = ptext (sLit "__attribute__((packed))")
959 cast = parens (struct <+> packed_attr <> char '*')
960 in parens (cast <+> pprExpr1 expr) <> ptext (sLit "->x")
962 cLoad expr rep = char '*' <> parens (cCast (machRepPtrCType rep) expr)
965 isCmmWordType :: CmmType -> Bool
966 -- True of GcPtrReg/NonGcReg of native word size
967 isCmmWordType ty = not (isFloatType ty)
968 && typeWidth ty == wordWidth
970 -- This is for finding the types of foreign call arguments. For a pointer
971 -- argument, we always cast the argument to (void *), to avoid warnings from
973 machRepHintCType :: CmmType -> ForeignHint -> SDoc
974 machRepHintCType rep AddrHint = ptext (sLit "void *")
975 machRepHintCType rep SignedHint = machRep_S_CType (typeWidth rep)
976 machRepHintCType rep _other = machRepCType rep
978 machRepPtrCType :: CmmType -> SDoc
979 machRepPtrCType r | isCmmWordType r = ptext (sLit "P_")
980 | otherwise = machRepCType r <> char '*'
982 machRepCType :: CmmType -> SDoc
983 machRepCType ty | isFloatType ty = machRep_F_CType w
984 | otherwise = machRep_U_CType w
988 machRep_F_CType :: Width -> SDoc
989 machRep_F_CType W32 = ptext (sLit "StgFloat") -- ToDo: correct?
990 machRep_F_CType W64 = ptext (sLit "StgDouble")
991 machRep_F_CType _ = panic "machRep_F_CType"
993 machRep_U_CType :: Width -> SDoc
994 machRep_U_CType w | w == wordWidth = ptext (sLit "W_")
995 machRep_U_CType W8 = ptext (sLit "StgWord8")
996 machRep_U_CType W16 = ptext (sLit "StgWord16")
997 machRep_U_CType W32 = ptext (sLit "StgWord32")
998 machRep_U_CType W64 = ptext (sLit "StgWord64")
999 machRep_U_CType _ = panic "machRep_U_CType"
1001 machRep_S_CType :: Width -> SDoc
1002 machRep_S_CType w | w == wordWidth = ptext (sLit "I_")
1003 machRep_S_CType W8 = ptext (sLit "StgInt8")
1004 machRep_S_CType W16 = ptext (sLit "StgInt16")
1005 machRep_S_CType W32 = ptext (sLit "StgInt32")
1006 machRep_S_CType W64 = ptext (sLit "StgInt64")
1007 machRep_S_CType _ = panic "machRep_S_CType"
1010 -- ---------------------------------------------------------------------
1011 -- print strings as valid C strings
1013 pprStringInCStyle :: [Word8] -> SDoc
1014 pprStringInCStyle s = doubleQuotes (text (concatMap charToC s))
1016 charToC :: Word8 -> String
1018 case chr (fromIntegral w) of
1022 c | c >= ' ' && c <= '~' -> [c]
1023 | otherwise -> ['\\',
1024 chr (ord '0' + ord c `div` 64),
1025 chr (ord '0' + ord c `div` 8 `mod` 8),
1026 chr (ord '0' + ord c `mod` 8)]
1028 -- ---------------------------------------------------------------------------
1029 -- Initialising static objects with floating-point numbers. We can't
1030 -- just emit the floating point number, because C will cast it to an int
1031 -- by rounding it. We want the actual bit-representation of the float.
1033 -- This is a hack to turn the floating point numbers into ints that we
1034 -- can safely initialise to static locations.
1037 | widthInBytes W64 == 2 * wORD_SIZE = True
1038 | widthInBytes W64 == wORD_SIZE = False
1039 | otherwise = panic "big_doubles"
1041 castFloatToIntArray :: STUArray s Int Float -> ST s (STUArray s Int Int)
1042 castFloatToIntArray = castSTUArray
1044 castDoubleToIntArray :: STUArray s Int Double -> ST s (STUArray s Int Int)
1045 castDoubleToIntArray = castSTUArray
1047 -- floats are always 1 word
1048 floatToWord :: Rational -> CmmLit
1051 arr <- newArray_ ((0::Int),0)
1052 writeArray arr 0 (fromRational r)
1053 arr' <- castFloatToIntArray arr
1054 i <- readArray arr' 0
1055 return (CmmInt (toInteger i) wordWidth)
1058 doubleToWords :: Rational -> [CmmLit]
1060 | big_doubles -- doubles are 2 words
1062 arr <- newArray_ ((0::Int),1)
1063 writeArray arr 0 (fromRational r)
1064 arr' <- castDoubleToIntArray arr
1065 i1 <- readArray arr' 0
1066 i2 <- readArray arr' 1
1067 return [ CmmInt (toInteger i1) wordWidth
1068 , CmmInt (toInteger i2) wordWidth
1071 | otherwise -- doubles are 1 word
1073 arr <- newArray_ ((0::Int),0)
1074 writeArray arr 0 (fromRational r)
1075 arr' <- castDoubleToIntArray arr
1076 i <- readArray arr' 0
1077 return [ CmmInt (toInteger i) wordWidth ]
1080 -- ---------------------------------------------------------------------------
1084 wordShift = widthInLog wordWidth
1086 commafy :: [SDoc] -> SDoc
1087 commafy xs = hsep $ punctuate comma xs
1089 -- Print in C hex format: 0x13fa
1090 pprHexVal :: Integer -> Width -> SDoc
1091 pprHexVal 0 _ = ptext (sLit "0x0")
1093 | w < 0 = parens (char '-' <> ptext (sLit "0x") <> go (-w) <> repsuffix rep)
1094 | otherwise = ptext (sLit "0x") <> go w <> repsuffix rep
1096 -- type suffix for literals:
1097 -- Integer literals are unsigned in Cmm/C. We explicitly cast to
1098 -- signed values for doing signed operations, but at all other
1099 -- times values are unsigned. This also helps eliminate occasional
1100 -- warnings about integer overflow from gcc.
1102 -- on 32-bit platforms, add "ULL" to 64-bit literals
1103 repsuffix W64 | wORD_SIZE == 4 = ptext (sLit "ULL")
1104 -- on 64-bit platforms with 32-bit int, add "L" to 64-bit literals
1105 repsuffix W64 | cINT_SIZE == 4 = ptext (sLit "UL")
1106 repsuffix _ = char 'U'
1111 (q,r) = w' `quotRem` 16
1112 dig | r < 10 = char (chr (fromInteger r + ord '0'))
1113 | otherwise = char (chr (fromInteger r - 10 + ord 'a'))