Snapshot of codegen refactoring to share with simonpj
[ghc.git] / compiler / cmm / PprC.hs
1 -----------------------------------------------------------------------------
2 --
3 -- Pretty-printing of Cmm as C, suitable for feeding gcc
4 --
5 -- (c) The University of Glasgow 2004-2006
6 --
7 -----------------------------------------------------------------------------
8
9 --
10 -- Print Cmm as real C, for -fvia-C
11 --
12 -- See wiki:Commentary/Compiler/Backends/PprC
13 --
14 -- This is simpler than the old PprAbsC, because Cmm is "macro-expanded"
15 -- relative to the old AbstractC, and many oddities/decorations have
16 -- disappeared from the data type.
17 --
18
19 module PprC (
20 writeCs,
21 pprStringInCStyle
22 ) where
23
24 #include "HsVersions.h"
25
26 -- Cmm stuff
27 import BlockId
28 import OldCmm
29 import OldPprCmm ()
30 import CLabel
31 import ForeignCall
32
33 -- Utils
34 import DynFlags
35 import Unique
36 import UniqSet
37 import FastString
38 import Outputable
39 import Constants
40 import Util
41
42 -- The rest
43 import Data.List
44 import Data.Bits
45 import Data.Char
46 import System.IO
47 import Data.Map (Map)
48 import qualified Data.Map as Map
49 import Data.Word
50
51 -- castSTUArray has moved to Data.Array.Unsafe
52 #if __GLASGOW_HASKELL__ >= 703
53 import Data.Array.Unsafe( castSTUArray )
54 import Data.Array.ST hiding( castSTUArray )
55 #else
56 import Data.Array.ST
57 #endif
58
59 import Control.Monad.ST
60
61 #if defined(alpha_TARGET_ARCH) || defined(mips_TARGET_ARCH) || defined(mipsel_TARGET_ARCH) || defined(arm_TARGET_ARCH)
62 #define BEWARE_LOAD_STORE_ALIGNMENT
63 #endif
64
65 -- --------------------------------------------------------------------------
66 -- Top level
67
68 pprCs :: DynFlags -> [RawCmmPgm] -> SDoc
69 pprCs dflags cmms
70 = pprCode CStyle (vcat $ map (\c -> split_marker $$ pprC c) cmms)
71 where
72 split_marker
73 | dopt Opt_SplitObjs dflags = ptext (sLit "__STG_SPLIT_MARKER")
74 | otherwise = empty
75
76 writeCs :: DynFlags -> Handle -> [RawCmmPgm] -> IO ()
77 writeCs dflags handle cmms
78 = printForC handle (pprCs dflags cmms)
79
80 -- --------------------------------------------------------------------------
81 -- Now do some real work
82 --
83 -- for fun, we could call cmmToCmm over the tops...
84 --
85
86 pprC :: RawCmmPgm -> SDoc
87 pprC tops = vcat $ intersperse blankLine $ map pprTop tops
88
89 --
90 -- top level procs
91 --
92 pprTop :: RawCmmTop -> SDoc
93 pprTop (CmmProc mb_info clbl (ListGraph blocks)) =
94 (case mb_info of
95 Nothing -> empty
96 Just (Statics info_clbl info_dat) -> pprDataExterns info_dat $$
97 pprWordArray info_clbl info_dat) $$
98 (vcat [
99 blankLine,
100 extern_decls,
101 (if (externallyVisibleCLabel clbl)
102 then mkFN_ else mkIF_) (pprCLabel clbl) <+> lbrace,
103 nest 8 temp_decls,
104 nest 8 mkFB_,
105 case blocks of
106 [] -> empty
107 -- the first block doesn't get a label:
108 (BasicBlock _ stmts : rest) ->
109 nest 8 (vcat (map pprStmt stmts)) $$
110 vcat (map pprBBlock rest),
111 nest 8 mkFE_,
112 rbrace ]
113 )
114 where
115 (temp_decls, extern_decls) = pprTempAndExternDecls blocks
116
117
118 -- Chunks of static data.
119
120 -- We only handle (a) arrays of word-sized things and (b) strings.
121
122 pprTop (CmmData _section (Statics lbl [CmmString str])) =
123 hcat [
124 pprLocalness lbl, ptext (sLit "char "), pprCLabel lbl,
125 ptext (sLit "[] = "), pprStringInCStyle str, semi
126 ]
127
128 pprTop (CmmData _section (Statics lbl [CmmUninitialised size])) =
129 hcat [
130 pprLocalness lbl, ptext (sLit "char "), pprCLabel lbl,
131 brackets (int size), semi
132 ]
133
134 pprTop (CmmData _section (Statics lbl lits)) =
135 pprDataExterns lits $$
136 pprWordArray lbl lits
137
138 -- --------------------------------------------------------------------------
139 -- BasicBlocks are self-contained entities: they always end in a jump.
140 --
141 -- Like nativeGen/AsmCodeGen, we could probably reorder blocks to turn
142 -- as many jumps as possible into fall throughs.
143 --
144
145 pprBBlock :: CmmBasicBlock -> SDoc
146 pprBBlock (BasicBlock lbl stmts) =
147 if null stmts then
148 pprTrace "pprC.pprBBlock: curious empty code block for"
149 (pprBlockId lbl) empty
150 else
151 nest 4 (pprBlockId lbl <> colon) $$
152 nest 8 (vcat (map pprStmt stmts))
153
154 -- --------------------------------------------------------------------------
155 -- Info tables. Just arrays of words.
156 -- See codeGen/ClosureInfo, and nativeGen/PprMach
157
158 pprWordArray :: CLabel -> [CmmStatic] -> SDoc
159 pprWordArray lbl ds
160 = hcat [ pprLocalness lbl, ptext (sLit "StgWord")
161 , space, pprCLabel lbl, ptext (sLit "[] = {") ]
162 $$ nest 8 (commafy (pprStatics ds))
163 $$ ptext (sLit "};")
164
165 --
166 -- has to be static, if it isn't globally visible
167 --
168 pprLocalness :: CLabel -> SDoc
169 pprLocalness lbl | not $ externallyVisibleCLabel lbl = ptext (sLit "static ")
170 | otherwise = empty
171
172 -- --------------------------------------------------------------------------
173 -- Statements.
174 --
175
176 pprStmt :: CmmStmt -> SDoc
177
178 pprStmt stmt = case stmt of
179 CmmReturn _ -> panic "pprStmt: return statement should have been cps'd away"
180 CmmNop -> empty
181 CmmComment _ -> empty -- (hang (ptext (sLit "/*")) 3 (ftext s)) $$ ptext (sLit "*/")
182 -- XXX if the string contains "*/", we need to fix it
183 -- XXX we probably want to emit these comments when
184 -- some debugging option is on. They can get quite
185 -- large.
186
187 CmmAssign dest src -> pprAssign dest src
188
189 CmmStore dest src
190 | typeWidth rep == W64 && wordWidth /= W64
191 -> (if isFloatType rep then ptext (sLit "ASSIGN_DBL")
192 else ptext (sLit ("ASSIGN_Word64"))) <>
193 parens (mkP_ <> pprExpr1 dest <> comma <> pprExpr src) <> semi
194
195 | otherwise
196 -> hsep [ pprExpr (CmmLoad dest rep), equals, pprExpr src <> semi ]
197 where
198 rep = cmmExprType src
199
200 CmmCall (CmmCallee fn cconv) results args safety ret ->
201 maybe_proto $$
202 fnCall
203 where
204 cast_fn = parens (cCast (pprCFunType (char '*') cconv results args) fn)
205
206 real_fun_proto lbl = char ';' <>
207 pprCFunType (pprCLabel lbl) cconv results args <>
208 noreturn_attr <> semi
209
210 fun_proto lbl = ptext (sLit ";EF_(") <>
211 pprCLabel lbl <> char ')' <> semi
212
213 noreturn_attr = case ret of
214 CmmNeverReturns -> text "__attribute__ ((noreturn))"
215 CmmMayReturn -> empty
216
217 -- See wiki:Commentary/Compiler/Backends/PprC#Prototypes
218 (maybe_proto, fnCall) =
219 case fn of
220 CmmLit (CmmLabel lbl)
221 | StdCallConv <- cconv ->
222 let myCall = pprCall (pprCLabel lbl) cconv results args safety
223 in (real_fun_proto lbl, myCall)
224 -- stdcall functions must be declared with
225 -- a function type, otherwise the C compiler
226 -- doesn't add the @n suffix to the label. We
227 -- can't add the @n suffix ourselves, because
228 -- it isn't valid C.
229 | CmmNeverReturns <- ret ->
230 let myCall = pprCall (pprCLabel lbl) cconv results args safety
231 in (real_fun_proto lbl, myCall)
232 | not (isMathFun lbl) ->
233 let myCall = braces (
234 pprCFunType (char '*' <> text "ghcFunPtr") cconv results args <> semi
235 $$ text "ghcFunPtr" <+> equals <+> cast_fn <> semi
236 $$ pprCall (text "ghcFunPtr") cconv results args safety <> semi
237 )
238 in (fun_proto lbl, myCall)
239 _ ->
240 (empty {- no proto -},
241 pprCall cast_fn cconv results args safety <> semi)
242 -- for a dynamic call, no declaration is necessary.
243
244 CmmCall (CmmPrim op) results args safety _ret ->
245 pprCall ppr_fn CCallConv results args' safety
246 where
247 ppr_fn = pprCallishMachOp_for_C op
248 -- The mem primops carry an extra alignment arg, must drop it.
249 -- We could maybe emit an alignment directive using this info.
250 args' | op == MO_Memcpy || op == MO_Memset || op == MO_Memmove = init args
251 | otherwise = args
252
253 CmmBranch ident -> pprBranch ident
254 CmmCondBranch expr ident -> pprCondBranch expr ident
255 CmmJump lbl _params -> mkJMP_(pprExpr lbl) <> semi
256 CmmSwitch arg ids -> pprSwitch arg ids
257
258 pprCFunType :: SDoc -> CCallConv -> [HintedCmmFormal] -> [HintedCmmActual] -> SDoc
259 pprCFunType ppr_fn cconv ress args
260 = res_type ress <+>
261 parens (text (ccallConvAttribute cconv) <> ppr_fn) <>
262 parens (commafy (map arg_type args))
263 where
264 res_type [] = ptext (sLit "void")
265 res_type [CmmHinted one hint] = machRepHintCType (localRegType one) hint
266 res_type _ = panic "pprCFunType: only void or 1 return value supported"
267
268 arg_type (CmmHinted expr hint) = machRepHintCType (cmmExprType expr) hint
269
270 -- ---------------------------------------------------------------------
271 -- unconditional branches
272 pprBranch :: BlockId -> SDoc
273 pprBranch ident = ptext (sLit "goto") <+> pprBlockId ident <> semi
274
275
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 ]
282
283
284 -- ---------------------------------------------------------------------
285 -- a local table branch
286 --
287 -- we find the fall-through cases
288 --
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.
292 --
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 ]
297 in
298 (hang (ptext (sLit "switch") <+> parens ( pprExpr e ) <+> lbrace)
299 4 (vcat ( map caseify pairs2 )))
300 $$ rbrace
301
302 where
303 sndEq (_,x) (_,y) = x == y
304
305 -- fall through case
306 caseify (ix:ixs, ident) = vcat (map do_fallthrough ixs) $$ final_branch ix
307 where
308 do_fallthrough ix =
309 hsep [ ptext (sLit "case") , pprHexVal ix wordWidth <> colon ,
310 ptext (sLit "/* fall through */") ]
311
312 final_branch ix =
313 hsep [ ptext (sLit "case") , pprHexVal ix wordWidth <> colon ,
314 ptext (sLit "goto") , (pprBlockId ident) <> semi ]
315
316 caseify (_ , _ ) = panic "pprSwtich: swtich with no cases!"
317
318 -- ---------------------------------------------------------------------
319 -- Expressions.
320 --
321
322 -- C Types: the invariant is that the C expression generated by
323 --
324 -- pprExpr e
325 --
326 -- has a type in C which is also given by
327 --
328 -- machRepCType (cmmExprType e)
329 --
330 -- (similar invariants apply to the rest of the pretty printer).
331
332 pprExpr :: CmmExpr -> SDoc
333 pprExpr e = case e of
334 CmmLit lit -> pprLit lit
335
336
337 CmmLoad e ty -> pprLoad e ty
338 CmmReg reg -> pprCastReg reg
339 CmmRegOff reg 0 -> pprCastReg reg
340
341 CmmRegOff reg i
342 | i > 0 -> pprRegOff (char '+') i
343 | otherwise -> pprRegOff (char '-') (-i)
344 where
345 pprRegOff op i' = pprCastReg reg <> op <> int i'
346
347 CmmMachOp mop args -> pprMachOpApp mop args
348
349 CmmStackSlot _ _ -> panic "pprExpr: CmmStackSlot not supported!"
350
351
352 pprLoad :: CmmExpr -> CmmType -> SDoc
353 pprLoad e ty
354 | width == W64, wordWidth /= W64
355 = (if isFloatType ty then ptext (sLit "PK_DBL")
356 else ptext (sLit "PK_Word64"))
357 <> parens (mkP_ <> pprExpr1 e)
358
359 | otherwise
360 = case e of
361 CmmReg r | isPtrReg r && width == wordWidth && not (isFloatType ty)
362 -> char '*' <> pprAsPtrReg r
363
364 CmmRegOff r 0 | isPtrReg r && width == wordWidth && not (isFloatType ty)
365 -> char '*' <> pprAsPtrReg r
366
367 CmmRegOff r off | isPtrReg r && width == wordWidth
368 , off `rem` wORD_SIZE == 0 && not (isFloatType ty)
369 -- ToDo: check that the offset is a word multiple?
370 -- (For tagging to work, I had to avoid unaligned loads. --ARY)
371 -> pprAsPtrReg r <> brackets (ppr (off `shiftR` wordShift))
372
373 _other -> cLoad e ty
374 where
375 width = typeWidth ty
376
377 pprExpr1 :: CmmExpr -> SDoc
378 pprExpr1 (CmmLit lit) = pprLit1 lit
379 pprExpr1 e@(CmmReg _reg) = pprExpr e
380 pprExpr1 other = parens (pprExpr other)
381
382 -- --------------------------------------------------------------------------
383 -- MachOp applications
384
385 pprMachOpApp :: MachOp -> [CmmExpr] -> SDoc
386
387 pprMachOpApp op args
388 | isMulMayOfloOp op
389 = ptext (sLit "mulIntMayOflo") <> parens (commafy (map pprExpr args))
390 where isMulMayOfloOp (MO_U_MulMayOflo _) = True
391 isMulMayOfloOp (MO_S_MulMayOflo _) = True
392 isMulMayOfloOp _ = False
393
394 pprMachOpApp mop args
395 | Just ty <- machOpNeedsCast mop
396 = ty <> parens (pprMachOpApp' mop args)
397 | otherwise
398 = pprMachOpApp' mop args
399
400 -- Comparisons in C have type 'int', but we want type W_ (this is what
401 -- resultRepOfMachOp says). The other C operations inherit their type
402 -- from their operands, so no casting is required.
403 machOpNeedsCast :: MachOp -> Maybe SDoc
404 machOpNeedsCast mop
405 | isComparisonMachOp mop = Just mkW_
406 | otherwise = Nothing
407
408 pprMachOpApp' :: MachOp -> [CmmExpr] -> SDoc
409 pprMachOpApp' mop args
410 = case args of
411 -- dyadic
412 [x,y] -> pprArg x <+> pprMachOp_for_C mop <+> pprArg y
413
414 -- unary
415 [x] -> pprMachOp_for_C mop <> parens (pprArg x)
416
417 _ -> panic "PprC.pprMachOp : machop with wrong number of args"
418
419 where
420 -- Cast needed for signed integer ops
421 pprArg e | signedOp mop = cCast (machRep_S_CType (typeWidth (cmmExprType e))) e
422 | needsFCasts mop = cCast (machRep_F_CType (typeWidth (cmmExprType e))) e
423 | otherwise = pprExpr1 e
424 needsFCasts (MO_F_Eq _) = False
425 needsFCasts (MO_F_Ne _) = False
426 needsFCasts (MO_F_Neg _) = True
427 needsFCasts (MO_F_Quot _) = True
428 needsFCasts mop = floatComparison mop
429
430 -- --------------------------------------------------------------------------
431 -- Literals
432
433 pprLit :: CmmLit -> SDoc
434 pprLit lit = case lit of
435 CmmInt i rep -> pprHexVal i rep
436
437 CmmFloat f w -> parens (machRep_F_CType w) <> str
438 where d = fromRational f :: Double
439 str | isInfinite d && d < 0 = ptext (sLit "-INFINITY")
440 | isInfinite d = ptext (sLit "INFINITY")
441 | isNaN d = ptext (sLit "NAN")
442 | otherwise = text (show d)
443 -- these constants come from <math.h>
444 -- see #1861
445
446 CmmBlock bid -> mkW_ <> pprCLabelAddr (infoTblLbl bid)
447 CmmHighStackMark -> panic "PprC printing high stack mark"
448 CmmLabel clbl -> mkW_ <> pprCLabelAddr clbl
449 CmmLabelOff clbl i -> mkW_ <> pprCLabelAddr clbl <> char '+' <> int i
450 CmmLabelDiffOff clbl1 _ i
451 -- WARNING:
452 -- * the lit must occur in the info table clbl2
453 -- * clbl1 must be an SRT, a slow entry point or a large bitmap
454 -- The Mangler is expected to convert any reference to an SRT,
455 -- a slow entry point or a large bitmap
456 -- from an info table to an offset.
457 -> mkW_ <> pprCLabelAddr clbl1 <> char '+' <> int i
458
459 where
460 pprCLabelAddr lbl = char '&' <> pprCLabel lbl
461
462 pprLit1 :: CmmLit -> SDoc
463 pprLit1 lit@(CmmLabelOff _ _) = parens (pprLit lit)
464 pprLit1 lit@(CmmLabelDiffOff _ _ _) = parens (pprLit lit)
465 pprLit1 lit@(CmmFloat _ _) = parens (pprLit lit)
466 pprLit1 other = pprLit other
467
468 -- ---------------------------------------------------------------------------
469 -- Static data
470
471 pprStatics :: [CmmStatic] -> [SDoc]
472 pprStatics [] = []
473 pprStatics (CmmStaticLit (CmmFloat f W32) : rest)
474 -- floats are padded to a word, see #1852
475 | wORD_SIZE == 8, CmmStaticLit (CmmInt 0 W32) : rest' <- rest
476 = pprLit1 (floatToWord f) : pprStatics rest'
477 | wORD_SIZE == 4
478 = pprLit1 (floatToWord f) : pprStatics rest
479 | otherwise
480 = pprPanic "pprStatics: float" (vcat (map ppr' rest))
481 where ppr' (CmmStaticLit l) = ppr (cmmLitType l)
482 ppr' _other = ptext (sLit "bad static!")
483 pprStatics (CmmStaticLit (CmmFloat f W64) : rest)
484 = map pprLit1 (doubleToWords f) ++ pprStatics rest
485 pprStatics (CmmStaticLit (CmmInt i W64) : rest)
486 | wordWidth == W32
487 #ifdef WORDS_BIGENDIAN
488 = pprStatics (CmmStaticLit (CmmInt q W32) :
489 CmmStaticLit (CmmInt r W32) : rest)
490 #else
491 = pprStatics (CmmStaticLit (CmmInt r W32) :
492 CmmStaticLit (CmmInt q W32) : rest)
493 #endif
494 where r = i .&. 0xffffffff
495 q = i `shiftR` 32
496 pprStatics (CmmStaticLit (CmmInt _ w) : _)
497 | w /= wordWidth
498 = panic "pprStatics: cannot emit a non-word-sized static literal"
499 pprStatics (CmmStaticLit lit : rest)
500 = pprLit1 lit : pprStatics rest
501 pprStatics (other : _)
502 = pprPanic "pprWord" (pprStatic other)
503
504 pprStatic :: CmmStatic -> SDoc
505 pprStatic s = case s of
506
507 CmmStaticLit lit -> nest 4 (pprLit lit)
508 CmmUninitialised i -> nest 4 (mkC_ <> brackets (int i))
509
510 -- these should be inlined, like the old .hc
511 CmmString s' -> nest 4 (mkW_ <> parens(pprStringInCStyle s'))
512
513
514 -- ---------------------------------------------------------------------------
515 -- Block Ids
516
517 pprBlockId :: BlockId -> SDoc
518 pprBlockId b = char '_' <> ppr (getUnique b)
519
520 -- --------------------------------------------------------------------------
521 -- Print a MachOp in a way suitable for emitting via C.
522 --
523
524 pprMachOp_for_C :: MachOp -> SDoc
525
526 pprMachOp_for_C mop = case mop of
527
528 -- Integer operations
529 MO_Add _ -> char '+'
530 MO_Sub _ -> char '-'
531 MO_Eq _ -> ptext (sLit "==")
532 MO_Ne _ -> ptext (sLit "!=")
533 MO_Mul _ -> char '*'
534
535 MO_S_Quot _ -> char '/'
536 MO_S_Rem _ -> char '%'
537 MO_S_Neg _ -> char '-'
538
539 MO_U_Quot _ -> char '/'
540 MO_U_Rem _ -> char '%'
541
542 -- & Floating-point operations
543 MO_F_Add _ -> char '+'
544 MO_F_Sub _ -> char '-'
545 MO_F_Neg _ -> char '-'
546 MO_F_Mul _ -> char '*'
547 MO_F_Quot _ -> char '/'
548
549 -- Signed comparisons
550 MO_S_Ge _ -> ptext (sLit ">=")
551 MO_S_Le _ -> ptext (sLit "<=")
552 MO_S_Gt _ -> char '>'
553 MO_S_Lt _ -> char '<'
554
555 -- & Unsigned comparisons
556 MO_U_Ge _ -> ptext (sLit ">=")
557 MO_U_Le _ -> ptext (sLit "<=")
558 MO_U_Gt _ -> char '>'
559 MO_U_Lt _ -> char '<'
560
561 -- & Floating-point comparisons
562 MO_F_Eq _ -> ptext (sLit "==")
563 MO_F_Ne _ -> ptext (sLit "!=")
564 MO_F_Ge _ -> ptext (sLit ">=")
565 MO_F_Le _ -> ptext (sLit "<=")
566 MO_F_Gt _ -> char '>'
567 MO_F_Lt _ -> char '<'
568
569 -- Bitwise operations. Not all of these may be supported at all
570 -- sizes, and only integral MachReps are valid.
571 MO_And _ -> char '&'
572 MO_Or _ -> char '|'
573 MO_Xor _ -> char '^'
574 MO_Not _ -> char '~'
575 MO_Shl _ -> ptext (sLit "<<")
576 MO_U_Shr _ -> ptext (sLit ">>") -- unsigned shift right
577 MO_S_Shr _ -> ptext (sLit ">>") -- signed shift right
578
579 -- Conversions. Some of these will be NOPs, but never those that convert
580 -- between ints and floats.
581 -- Floating-point conversions use the signed variant.
582 -- We won't know to generate (void*) casts here, but maybe from
583 -- context elsewhere
584
585 -- noop casts
586 MO_UU_Conv from to | from == to -> empty
587 MO_UU_Conv _from to -> parens (machRep_U_CType to)
588
589 MO_SS_Conv from to | from == to -> empty
590 MO_SS_Conv _from to -> parens (machRep_S_CType to)
591
592 -- TEMPORARY: the old code didn't check this case, so let's leave it out
593 -- to facilitate comparisons against the old output code.
594 --MO_FF_Conv from to | from == to -> empty
595 MO_FF_Conv _from to -> parens (machRep_F_CType to)
596
597 MO_SF_Conv _from to -> parens (machRep_F_CType to)
598 MO_FS_Conv _from to -> parens (machRep_S_CType to)
599
600 _ -> pprTrace "offending mop" (ptext $ sLit $ show mop) $
601 panic "PprC.pprMachOp_for_C: unknown machop"
602
603 signedOp :: MachOp -> Bool -- Argument type(s) are signed ints
604 signedOp (MO_S_Quot _) = True
605 signedOp (MO_S_Rem _) = True
606 signedOp (MO_S_Neg _) = True
607 signedOp (MO_S_Ge _) = True
608 signedOp (MO_S_Le _) = True
609 signedOp (MO_S_Gt _) = True
610 signedOp (MO_S_Lt _) = True
611 signedOp (MO_S_Shr _) = True
612 signedOp (MO_SS_Conv _ _) = True
613 signedOp (MO_SF_Conv _ _) = True
614 signedOp _ = False
615
616 floatComparison :: MachOp -> Bool -- comparison between float args
617 floatComparison (MO_F_Eq _) = True
618 floatComparison (MO_F_Ne _) = True
619 floatComparison (MO_F_Ge _) = True
620 floatComparison (MO_F_Le _) = True
621 floatComparison (MO_F_Gt _) = True
622 floatComparison (MO_F_Lt _) = True
623 floatComparison _ = False
624
625 -- ---------------------------------------------------------------------
626 -- tend to be implemented by foreign calls
627
628 pprCallishMachOp_for_C :: CallishMachOp -> SDoc
629
630 pprCallishMachOp_for_C mop
631 = case mop of
632 MO_F64_Pwr -> ptext (sLit "pow")
633 MO_F64_Sin -> ptext (sLit "sin")
634 MO_F64_Cos -> ptext (sLit "cos")
635 MO_F64_Tan -> ptext (sLit "tan")
636 MO_F64_Sinh -> ptext (sLit "sinh")
637 MO_F64_Cosh -> ptext (sLit "cosh")
638 MO_F64_Tanh -> ptext (sLit "tanh")
639 MO_F64_Asin -> ptext (sLit "asin")
640 MO_F64_Acos -> ptext (sLit "acos")
641 MO_F64_Atan -> ptext (sLit "atan")
642 MO_F64_Log -> ptext (sLit "log")
643 MO_F64_Exp -> ptext (sLit "exp")
644 MO_F64_Sqrt -> ptext (sLit "sqrt")
645 MO_F32_Pwr -> ptext (sLit "powf")
646 MO_F32_Sin -> ptext (sLit "sinf")
647 MO_F32_Cos -> ptext (sLit "cosf")
648 MO_F32_Tan -> ptext (sLit "tanf")
649 MO_F32_Sinh -> ptext (sLit "sinhf")
650 MO_F32_Cosh -> ptext (sLit "coshf")
651 MO_F32_Tanh -> ptext (sLit "tanhf")
652 MO_F32_Asin -> ptext (sLit "asinf")
653 MO_F32_Acos -> ptext (sLit "acosf")
654 MO_F32_Atan -> ptext (sLit "atanf")
655 MO_F32_Log -> ptext (sLit "logf")
656 MO_F32_Exp -> ptext (sLit "expf")
657 MO_F32_Sqrt -> ptext (sLit "sqrtf")
658 MO_WriteBarrier -> ptext (sLit "write_barrier")
659 MO_Memcpy -> ptext (sLit "memcpy")
660 MO_Memset -> ptext (sLit "memset")
661 MO_Memmove -> ptext (sLit "memmove")
662 a -> panic $ "pprCallishMachOp_for_C: Unknown callish op! ("
663 ++ show a ++ ")"
664
665 -- ---------------------------------------------------------------------
666 -- Useful #defines
667 --
668
669 mkJMP_, mkFN_, mkIF_ :: SDoc -> SDoc
670
671 mkJMP_ i = ptext (sLit "JMP_") <> parens i
672 mkFN_ i = ptext (sLit "FN_") <> parens i -- externally visible function
673 mkIF_ i = ptext (sLit "IF_") <> parens i -- locally visible
674
675
676 mkFB_, mkFE_ :: SDoc
677 mkFB_ = ptext (sLit "FB_") -- function code begin
678 mkFE_ = ptext (sLit "FE_") -- function code end
679
680 -- from includes/Stg.h
681 --
682 mkC_,mkW_,mkP_ :: SDoc
683
684 mkC_ = ptext (sLit "(C_)") -- StgChar
685 mkW_ = ptext (sLit "(W_)") -- StgWord
686 mkP_ = ptext (sLit "(P_)") -- StgWord*
687
688 -- ---------------------------------------------------------------------
689 --
690 -- Assignments
691 --
692 -- Generating assignments is what we're all about, here
693 --
694 pprAssign :: CmmReg -> CmmExpr -> SDoc
695
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 ]
700
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 ]
705 where
706 off1 = off `shiftR` wordShift
707
708 (op,off') | off >= 0 = (char '+', off1)
709 | otherwise = (char '-', -off1)
710
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+).
714 pprAssign r1 r2
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
721
722 -- ---------------------------------------------------------------------
723 -- Registers
724
725 pprCastReg :: CmmReg -> SDoc
726 pprCastReg reg
727 | isStrangeTypeReg reg = mkW_ <> pprReg reg
728 | otherwise = pprReg reg
729
730 -- True if (pprReg reg) will give an expression with type StgPtr. We
731 -- need to take care with pointer arithmetic on registers with type
732 -- StgPtr.
733 isFixedPtrReg :: CmmReg -> Bool
734 isFixedPtrReg (CmmLocal _) = False
735 isFixedPtrReg (CmmGlobal r) = isFixedPtrGlobalReg r
736
737 -- True if (pprAsPtrReg reg) will give an expression with type StgPtr
738 -- JD: THIS IS HORRIBLE AND SHOULD BE RENAMED, AT THE VERY LEAST.
739 -- THE GARBAGE WITH THE VNonGcPtr HELPS MATCH THE OLD CODE GENERATOR'S OUTPUT;
740 -- I'M NOT SURE IF IT SHOULD REALLY STAY THAT WAY.
741 isPtrReg :: CmmReg -> Bool
742 isPtrReg (CmmLocal _) = False
743 isPtrReg (CmmGlobal (VanillaReg _ VGcPtr)) = True -- if we print via pprAsPtrReg
744 isPtrReg (CmmGlobal (VanillaReg _ VNonGcPtr)) = False -- if we print via pprAsPtrReg
745 isPtrReg (CmmGlobal reg) = isFixedPtrGlobalReg reg
746
747 -- True if this global reg has type StgPtr
748 isFixedPtrGlobalReg :: GlobalReg -> Bool
749 isFixedPtrGlobalReg Sp = True
750 isFixedPtrGlobalReg Hp = True
751 isFixedPtrGlobalReg HpLim = True
752 isFixedPtrGlobalReg SpLim = True
753 isFixedPtrGlobalReg _ = False
754
755 -- True if in C this register doesn't have the type given by
756 -- (machRepCType (cmmRegType reg)), so it has to be cast.
757 isStrangeTypeReg :: CmmReg -> Bool
758 isStrangeTypeReg (CmmLocal _) = False
759 isStrangeTypeReg (CmmGlobal g) = isStrangeTypeGlobal g
760
761 isStrangeTypeGlobal :: GlobalReg -> Bool
762 isStrangeTypeGlobal CurrentTSO = True
763 isStrangeTypeGlobal CurrentNursery = True
764 isStrangeTypeGlobal BaseReg = True
765 isStrangeTypeGlobal r = isFixedPtrGlobalReg r
766
767 strangeRegType :: CmmReg -> Maybe SDoc
768 strangeRegType (CmmGlobal CurrentTSO) = Just (ptext (sLit "struct StgTSO_ *"))
769 strangeRegType (CmmGlobal CurrentNursery) = Just (ptext (sLit "struct bdescr_ *"))
770 strangeRegType (CmmGlobal BaseReg) = Just (ptext (sLit "struct StgRegTable_ *"))
771 strangeRegType _ = Nothing
772
773 -- pprReg just prints the register name.
774 --
775 pprReg :: CmmReg -> SDoc
776 pprReg r = case r of
777 CmmLocal local -> pprLocalReg local
778 CmmGlobal global -> pprGlobalReg global
779
780 pprAsPtrReg :: CmmReg -> SDoc
781 pprAsPtrReg (CmmGlobal (VanillaReg n gcp))
782 = WARN( gcp /= VGcPtr, ppr n ) char 'R' <> int n <> ptext (sLit ".p")
783 pprAsPtrReg other_reg = pprReg other_reg
784
785 pprGlobalReg :: GlobalReg -> SDoc
786 pprGlobalReg gr = case gr of
787 VanillaReg n _ -> char 'R' <> int n <> ptext (sLit ".w")
788 -- pprGlobalReg prints a VanillaReg as a .w regardless
789 -- Example: R1.w = R1.w & (-0x8UL);
790 -- JMP_(*R1.p);
791 FloatReg n -> char 'F' <> int n
792 DoubleReg n -> char 'D' <> int n
793 LongReg n -> char 'L' <> int n
794 Sp -> ptext (sLit "Sp")
795 SpLim -> ptext (sLit "SpLim")
796 Hp -> ptext (sLit "Hp")
797 HpLim -> ptext (sLit "HpLim")
798 CurrentTSO -> ptext (sLit "CurrentTSO")
799 CurrentNursery -> ptext (sLit "CurrentNursery")
800 HpAlloc -> ptext (sLit "HpAlloc")
801 BaseReg -> ptext (sLit "BaseReg")
802 EagerBlackholeInfo -> ptext (sLit "stg_EAGER_BLACKHOLE_info")
803 GCEnter1 -> ptext (sLit "stg_gc_enter_1")
804 GCFun -> ptext (sLit "stg_gc_fun")
805 other -> panic $ "pprGlobalReg: Unsupported register: " ++ show other
806
807 pprLocalReg :: LocalReg -> SDoc
808 pprLocalReg (LocalReg uniq _) = char '_' <> ppr uniq
809
810 -- -----------------------------------------------------------------------------
811 -- Foreign Calls
812
813 pprCall :: SDoc -> CCallConv -> [HintedCmmFormal] -> [HintedCmmActual] -> CmmSafety
814 -> SDoc
815
816 pprCall ppr_fn cconv results args _
817 | not (is_cishCC cconv)
818 = panic $ "pprCall: unknown calling convention"
819
820 | otherwise
821 =
822 ppr_assign results (ppr_fn <> parens (commafy (map pprArg args))) <> semi
823 where
824 ppr_assign [] rhs = rhs
825 ppr_assign [CmmHinted one hint] rhs
826 = pprLocalReg one <> ptext (sLit " = ")
827 <> pprUnHint hint (localRegType one) <> rhs
828 ppr_assign _other _rhs = panic "pprCall: multiple results"
829
830 pprArg (CmmHinted expr AddrHint)
831 = cCast (ptext (sLit "void *")) expr
832 -- see comment by machRepHintCType below
833 pprArg (CmmHinted expr SignedHint)
834 = cCast (machRep_S_CType $ typeWidth $ cmmExprType expr) expr
835 pprArg (CmmHinted expr _other)
836 = pprExpr expr
837
838 pprUnHint AddrHint rep = parens (machRepCType rep)
839 pprUnHint SignedHint rep = parens (machRepCType rep)
840 pprUnHint _ _ = empty
841
842 -- Currently we only have these two calling conventions, but this might
843 -- change in the future...
844 is_cishCC :: CCallConv -> Bool
845 is_cishCC CCallConv = True
846 is_cishCC StdCallConv = True
847 is_cishCC CmmCallConv = False
848 is_cishCC PrimCallConv = False
849
850 -- ---------------------------------------------------------------------
851 -- Find and print local and external declarations for a list of
852 -- Cmm statements.
853 --
854 pprTempAndExternDecls :: [CmmBasicBlock] -> (SDoc{-temps-}, SDoc{-externs-})
855 pprTempAndExternDecls stmts
856 = (vcat (map pprTempDecl (uniqSetToList temps)),
857 vcat (map (pprExternDecl False{-ToDo-}) (Map.keys lbls)))
858 where (temps, lbls) = runTE (mapM_ te_BB stmts)
859
860 pprDataExterns :: [CmmStatic] -> SDoc
861 pprDataExterns statics
862 = vcat (map (pprExternDecl False{-ToDo-}) (Map.keys lbls))
863 where (_, lbls) = runTE (mapM_ te_Static statics)
864
865 pprTempDecl :: LocalReg -> SDoc
866 pprTempDecl l@(LocalReg _ rep)
867 = hcat [ machRepCType rep, space, pprLocalReg l, semi ]
868
869 pprExternDecl :: Bool -> CLabel -> SDoc
870 pprExternDecl _in_srt lbl
871 -- do not print anything for "known external" things
872 | not (needsCDecl lbl) = empty
873 | Just sz <- foreignLabelStdcallInfo lbl = stdcall_decl sz
874 | otherwise =
875 hcat [ visibility, label_type lbl,
876 lparen, pprCLabel lbl, text ");" ]
877 where
878 label_type lbl | isCFunctionLabel lbl = ptext (sLit "F_")
879 | otherwise = ptext (sLit "I_")
880
881 visibility
882 | externallyVisibleCLabel lbl = char 'E'
883 | otherwise = char 'I'
884
885 -- If the label we want to refer to is a stdcall function (on Windows) then
886 -- we must generate an appropriate prototype for it, so that the C compiler will
887 -- add the @n suffix to the label (#2276)
888 stdcall_decl sz =
889 ptext (sLit "extern __attribute__((stdcall)) void ") <> pprCLabel lbl
890 <> parens (commafy (replicate (sz `quot` wORD_SIZE) (machRep_U_CType wordWidth)))
891 <> semi
892
893 type TEState = (UniqSet LocalReg, Map CLabel ())
894 newtype TE a = TE { unTE :: TEState -> (a, TEState) }
895
896 instance Monad TE where
897 TE m >>= k = TE $ \s -> case m s of (a, s') -> unTE (k a) s'
898 return a = TE $ \s -> (a, s)
899
900 te_lbl :: CLabel -> TE ()
901 te_lbl lbl = TE $ \(temps,lbls) -> ((), (temps, Map.insert lbl () lbls))
902
903 te_temp :: LocalReg -> TE ()
904 te_temp r = TE $ \(temps,lbls) -> ((), (addOneToUniqSet temps r, lbls))
905
906 runTE :: TE () -> TEState
907 runTE (TE m) = snd (m (emptyUniqSet, Map.empty))
908
909 te_Static :: CmmStatic -> TE ()
910 te_Static (CmmStaticLit lit) = te_Lit lit
911 te_Static _ = return ()
912
913 te_BB :: CmmBasicBlock -> TE ()
914 te_BB (BasicBlock _ ss) = mapM_ te_Stmt ss
915
916 te_Lit :: CmmLit -> TE ()
917 te_Lit (CmmLabel l) = te_lbl l
918 te_Lit (CmmLabelOff l _) = te_lbl l
919 te_Lit (CmmLabelDiffOff l1 _ _) = te_lbl l1
920 te_Lit _ = return ()
921
922 te_Stmt :: CmmStmt -> TE ()
923 te_Stmt (CmmAssign r e) = te_Reg r >> te_Expr e
924 te_Stmt (CmmStore l r) = te_Expr l >> te_Expr r
925 te_Stmt (CmmCall _ rs es _ _) = mapM_ (te_temp.hintlessCmm) rs >>
926 mapM_ (te_Expr.hintlessCmm) es
927 te_Stmt (CmmCondBranch e _) = te_Expr e
928 te_Stmt (CmmSwitch e _) = te_Expr e
929 te_Stmt (CmmJump e _) = te_Expr e
930 te_Stmt _ = return ()
931
932 te_Expr :: CmmExpr -> TE ()
933 te_Expr (CmmLit lit) = te_Lit lit
934 te_Expr (CmmLoad e _) = te_Expr e
935 te_Expr (CmmReg r) = te_Reg r
936 te_Expr (CmmMachOp _ es) = mapM_ te_Expr es
937 te_Expr (CmmRegOff r _) = te_Reg r
938 te_Expr (CmmStackSlot _ _) = panic "te_Expr: CmmStackSlot not supported!"
939
940 te_Reg :: CmmReg -> TE ()
941 te_Reg (CmmLocal l) = te_temp l
942 te_Reg _ = return ()
943
944
945 -- ---------------------------------------------------------------------
946 -- C types for MachReps
947
948 cCast :: SDoc -> CmmExpr -> SDoc
949 cCast ty expr = parens ty <> pprExpr1 expr
950
951 cLoad :: CmmExpr -> CmmType -> SDoc
952 #ifdef BEWARE_LOAD_STORE_ALIGNMENT
953 cLoad expr rep =
954 let decl = machRepCType rep <+> ptext (sLit "x") <> semi
955 struct = ptext (sLit "struct") <+> braces (decl)
956 packed_attr = ptext (sLit "__attribute__((packed))")
957 cast = parens (struct <+> packed_attr <> char '*')
958 in parens (cast <+> pprExpr1 expr) <> ptext (sLit "->x")
959 #else
960 cLoad expr rep = char '*' <> parens (cCast (machRepPtrCType rep) expr)
961 #endif
962
963 isCmmWordType :: CmmType -> Bool
964 -- True of GcPtrReg/NonGcReg of native word size
965 isCmmWordType ty = not (isFloatType ty)
966 && typeWidth ty == wordWidth
967
968 -- This is for finding the types of foreign call arguments. For a pointer
969 -- argument, we always cast the argument to (void *), to avoid warnings from
970 -- the C compiler.
971 machRepHintCType :: CmmType -> ForeignHint -> SDoc
972 machRepHintCType _ AddrHint = ptext (sLit "void *")
973 machRepHintCType rep SignedHint = machRep_S_CType (typeWidth rep)
974 machRepHintCType rep _other = machRepCType rep
975
976 machRepPtrCType :: CmmType -> SDoc
977 machRepPtrCType r | isCmmWordType r = ptext (sLit "P_")
978 | otherwise = machRepCType r <> char '*'
979
980 machRepCType :: CmmType -> SDoc
981 machRepCType ty | isFloatType ty = machRep_F_CType w
982 | otherwise = machRep_U_CType w
983 where
984 w = typeWidth ty
985
986 machRep_F_CType :: Width -> SDoc
987 machRep_F_CType W32 = ptext (sLit "StgFloat") -- ToDo: correct?
988 machRep_F_CType W64 = ptext (sLit "StgDouble")
989 machRep_F_CType _ = panic "machRep_F_CType"
990
991 machRep_U_CType :: Width -> SDoc
992 machRep_U_CType w | w == wordWidth = ptext (sLit "W_")
993 machRep_U_CType W8 = ptext (sLit "StgWord8")
994 machRep_U_CType W16 = ptext (sLit "StgWord16")
995 machRep_U_CType W32 = ptext (sLit "StgWord32")
996 machRep_U_CType W64 = ptext (sLit "StgWord64")
997 machRep_U_CType _ = panic "machRep_U_CType"
998
999 machRep_S_CType :: Width -> SDoc
1000 machRep_S_CType w | w == wordWidth = ptext (sLit "I_")
1001 machRep_S_CType W8 = ptext (sLit "StgInt8")
1002 machRep_S_CType W16 = ptext (sLit "StgInt16")
1003 machRep_S_CType W32 = ptext (sLit "StgInt32")
1004 machRep_S_CType W64 = ptext (sLit "StgInt64")
1005 machRep_S_CType _ = panic "machRep_S_CType"
1006
1007
1008 -- ---------------------------------------------------------------------
1009 -- print strings as valid C strings
1010
1011 pprStringInCStyle :: [Word8] -> SDoc
1012 pprStringInCStyle s = doubleQuotes (text (concatMap charToC s))
1013
1014 -- ---------------------------------------------------------------------------
1015 -- Initialising static objects with floating-point numbers. We can't
1016 -- just emit the floating point number, because C will cast it to an int
1017 -- by rounding it. We want the actual bit-representation of the float.
1018
1019 -- This is a hack to turn the floating point numbers into ints that we
1020 -- can safely initialise to static locations.
1021
1022 big_doubles :: Bool
1023 big_doubles
1024 | widthInBytes W64 == 2 * wORD_SIZE = True
1025 | widthInBytes W64 == wORD_SIZE = False
1026 | otherwise = panic "big_doubles"
1027
1028 castFloatToIntArray :: STUArray s Int Float -> ST s (STUArray s Int Int)
1029 castFloatToIntArray = castSTUArray
1030
1031 castDoubleToIntArray :: STUArray s Int Double -> ST s (STUArray s Int Int)
1032 castDoubleToIntArray = castSTUArray
1033
1034 -- floats are always 1 word
1035 floatToWord :: Rational -> CmmLit
1036 floatToWord r
1037 = runST (do
1038 arr <- newArray_ ((0::Int),0)
1039 writeArray arr 0 (fromRational r)
1040 arr' <- castFloatToIntArray arr
1041 i <- readArray arr' 0
1042 return (CmmInt (toInteger i) wordWidth)
1043 )
1044
1045 doubleToWords :: Rational -> [CmmLit]
1046 doubleToWords r
1047 | big_doubles -- doubles are 2 words
1048 = runST (do
1049 arr <- newArray_ ((0::Int),1)
1050 writeArray arr 0 (fromRational r)
1051 arr' <- castDoubleToIntArray arr
1052 i1 <- readArray arr' 0
1053 i2 <- readArray arr' 1
1054 return [ CmmInt (toInteger i1) wordWidth
1055 , CmmInt (toInteger i2) wordWidth
1056 ]
1057 )
1058 | otherwise -- doubles are 1 word
1059 = runST (do
1060 arr <- newArray_ ((0::Int),0)
1061 writeArray arr 0 (fromRational r)
1062 arr' <- castDoubleToIntArray arr
1063 i <- readArray arr' 0
1064 return [ CmmInt (toInteger i) wordWidth ]
1065 )
1066
1067 -- ---------------------------------------------------------------------------
1068 -- Utils
1069
1070 wordShift :: Int
1071 wordShift = widthInLog wordWidth
1072
1073 commafy :: [SDoc] -> SDoc
1074 commafy xs = hsep $ punctuate comma xs
1075
1076 -- Print in C hex format: 0x13fa
1077 pprHexVal :: Integer -> Width -> SDoc
1078 pprHexVal 0 _ = ptext (sLit "0x0")
1079 pprHexVal w rep
1080 | w < 0 = parens (char '-' <> ptext (sLit "0x") <> go (-w) <> repsuffix rep)
1081 | otherwise = ptext (sLit "0x") <> go w <> repsuffix rep
1082 where
1083 -- type suffix for literals:
1084 -- Integer literals are unsigned in Cmm/C. We explicitly cast to
1085 -- signed values for doing signed operations, but at all other
1086 -- times values are unsigned. This also helps eliminate occasional
1087 -- warnings about integer overflow from gcc.
1088
1089 -- on 32-bit platforms, add "ULL" to 64-bit literals
1090 repsuffix W64 | wORD_SIZE == 4 = ptext (sLit "ULL")
1091 -- on 64-bit platforms with 32-bit int, add "L" to 64-bit literals
1092 repsuffix W64 | cINT_SIZE == 4 = ptext (sLit "UL")
1093 repsuffix _ = char 'U'
1094
1095 go 0 = empty
1096 go w' = go q <> dig
1097 where
1098 (q,r) = w' `quotRem` 16
1099 dig | r < 10 = char (chr (fromInteger r + ord '0'))
1100 | otherwise = char (chr (fromInteger r - 10 + ord 'a'))
1101