Merging in the new codegen branch
[ghc-hetmet.git] / compiler / cmm / PprC.hs
1 {-# OPTIONS -w #-}
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
6 -- for details
7
8 -----------------------------------------------------------------------------
9 --
10 -- Pretty-printing of Cmm as C, suitable for feeding gcc
11 --
12 -- (c) The University of Glasgow 2004-2006
13 --
14 -----------------------------------------------------------------------------
15
16 --
17 -- Print Cmm as real C, for -fvia-C
18 --
19 -- See wiki:Commentary/Compiler/Backends/PprC
20 --
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.
24 --
25
26 -- ToDo: save/restore volatile registers around calls.
27
28 module PprC (
29         writeCs,
30         pprStringInCStyle 
31   ) where
32
33 #include "HsVersions.h"
34
35 -- Cmm stuff
36 import BlockId
37 import Cmm
38 import PprCmm   ()      -- Instances only
39 import CLabel
40 import ForeignCall
41 import ClosureInfo
42
43 -- Utils
44 import DynFlags
45 import Unique
46 import UniqSet
47 import FiniteMap
48 import UniqFM
49 import FastString
50 import Outputable
51 import Constants
52
53 -- The rest
54 import Data.List
55 import Data.Bits
56 import Data.Char
57 import System.IO
58 import Data.Word
59
60 import Data.Array.ST
61 import Control.Monad.ST
62
63 #if x86_64_TARGET_ARCH
64 import StaticFlags      ( opt_Unregisterised )
65 #endif
66
67 #if defined(alpha_TARGET_ARCH) || defined(mips_TARGET_ARCH) || defined(mipsel_TARGET_ARCH) || defined(arm_TARGET_ARCH)
68 #define BEWARE_LOAD_STORE_ALIGNMENT
69 #endif
70
71 -- --------------------------------------------------------------------------
72 -- Top level
73
74 pprCs :: DynFlags -> [RawCmm] -> SDoc
75 pprCs dflags cmms
76  = pprCode CStyle (vcat $ map (\c -> split_marker $$ pprC c) cmms)
77  where
78    split_marker
79      | dopt Opt_SplitObjs dflags = ptext (sLit "__STG_SPLIT_MARKER")
80      | otherwise                 = empty
81
82 writeCs :: DynFlags -> Handle -> [RawCmm] -> IO ()
83 writeCs dflags handle cmms 
84   = printForC handle (pprCs dflags cmms)
85
86 -- --------------------------------------------------------------------------
87 -- Now do some real work
88 --
89 -- for fun, we could call cmmToCmm over the tops...
90 --
91
92 pprC :: RawCmm -> SDoc
93 pprC (Cmm tops) = vcat $ intersperse (text "") $ map pprTop tops
94
95 --
96 -- top level procs
97 -- 
98 pprTop :: RawCmmTop -> SDoc
99 pprTop (CmmProc info clbl _params (ListGraph blocks)) =
100     (if not (null info)
101         then pprDataExterns info $$
102              pprWordArray (entryLblToInfoLbl clbl) info
103         else empty) $$
104     (case blocks of
105         [] -> empty
106          -- the first block doesn't get a label:
107         (BasicBlock _ stmts : rest) -> vcat [
108            text "",
109            extern_decls,
110            (if (externallyVisibleCLabel clbl)
111                     then mkFN_ else mkIF_) (pprCLabel clbl) <+> lbrace,
112            nest 8 temp_decls,
113            nest 8 mkFB_,
114            nest 8 (vcat (map pprStmt stmts)) $$
115               vcat (map pprBBlock rest),
116            nest 8 mkFE_,
117            rbrace ]
118     )
119   where
120         (temp_decls, extern_decls) = pprTempAndExternDecls blocks 
121
122
123 -- Chunks of static data.
124
125 -- We only handle (a) arrays of word-sized things and (b) strings.
126
127 pprTop (CmmData _section _ds@[CmmDataLabel lbl, CmmString str]) = 
128   hcat [
129     pprLocalness lbl, ptext (sLit "char "), pprCLabel lbl,
130     ptext (sLit "[] = "), pprStringInCStyle str, semi
131   ]
132
133 pprTop (CmmData _section _ds@[CmmDataLabel lbl, CmmUninitialised size]) = 
134   hcat [
135     pprLocalness lbl, ptext (sLit "char "), pprCLabel lbl,
136     brackets (int size), semi
137   ]
138
139 pprTop top@(CmmData _section (CmmDataLabel lbl : lits)) = 
140   pprDataExterns lits $$
141   pprWordArray lbl lits  
142
143 -- these shouldn't appear?
144 pprTop (CmmData _ _) = panic "PprC.pprTop: can't handle this data"
145
146 -- --------------------------------------------------------------------------
147 -- BasicBlocks are self-contained entities: they always end in a jump.
148 --
149 -- Like nativeGen/AsmCodeGen, we could probably reorder blocks to turn
150 -- as many jumps as possible into fall throughs.
151 --
152
153 pprBBlock :: CmmBasicBlock -> SDoc
154 pprBBlock (BasicBlock lbl stmts) = 
155     if null stmts then
156         pprTrace "pprC.pprBBlock: curious empty code block for" 
157                         (pprBlockId lbl) empty
158     else 
159         nest 4 (pprBlockId lbl <> colon) $$
160         nest 8 (vcat (map pprStmt stmts))
161
162 -- --------------------------------------------------------------------------
163 -- Info tables. Just arrays of words. 
164 -- See codeGen/ClosureInfo, and nativeGen/PprMach
165
166 pprWordArray :: CLabel -> [CmmStatic] -> SDoc
167 pprWordArray lbl ds
168   = hcat [ pprLocalness lbl, ptext (sLit "StgWord")
169          , space, pprCLabel lbl, ptext (sLit "[] = {") ] 
170     $$ nest 8 (commafy (pprStatics ds))
171     $$ ptext (sLit "};")
172
173 --
174 -- has to be static, if it isn't globally visible
175 --
176 pprLocalness :: CLabel -> SDoc
177 pprLocalness lbl | not $ externallyVisibleCLabel lbl = ptext (sLit "static ")
178                  | otherwise = empty
179
180 -- --------------------------------------------------------------------------
181 -- Statements.
182 --
183
184 pprStmt :: CmmStmt -> SDoc
185
186 pprStmt stmt = case stmt of
187     CmmNop       -> empty
188     CmmComment s -> (hang (ptext (sLit "/*")) 3 (ftext s)) $$ ptext (sLit "*/")
189
190     CmmAssign dest src -> pprAssign dest src
191
192     CmmStore  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
197
198         | otherwise
199         -> hsep [ pprExpr (CmmLoad dest rep), equals, pprExpr src <> semi ]
200         where
201           rep = cmmExprType src
202
203     CmmCall (CmmCallee fn cconv) results args safety ret ->
204         maybe_proto $$
205         pprCall ppr_fn cconv results args safety
206         where
207         cast_fn = parens (cCast (pprCFunType (char '*') cconv results args) fn)
208
209         real_fun_proto lbl = char ';' <> 
210                         pprCFunType (pprCLabel lbl) cconv results args <> 
211                         noreturn_attr <> semi
212
213         data_proto lbl = ptext (sLit ";EI_(") <> 
214                          pprCLabel lbl <> char ')' <> semi
215
216         noreturn_attr = case ret of
217                           CmmNeverReturns -> text "__attribute__ ((noreturn))"
218                           CmmMayReturn    -> empty
219
220         -- See wiki:Commentary/Compiler/Backends/PprC#Prototypes
221         (maybe_proto, ppr_fn) = 
222             case fn of
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
229                         -- it isn't valid C.
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.
239               _ -> 
240                    (empty {- no proto -}, cast_fn)
241                         -- for a dynamic call, no declaration is necessary.
242
243     CmmCall (CmmPrim op) results args safety _ret ->
244         pprCall ppr_fn CCallConv results args safety
245         where
246         ppr_fn = pprCallishMachOp_for_C op
247
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
252
253 pprCFunType :: SDoc -> CCallConv -> HintedCmmFormals -> HintedCmmActuals -> SDoc
254 pprCFunType ppr_fn cconv ress args
255   = res_type ress <+>
256     parens (text (ccallConvAttribute cconv) <>  ppr_fn) <>
257     parens (commafy (map arg_type args))
258   where
259         res_type [] = ptext (sLit "void")
260         res_type [CmmHinted one hint] = machRepHintCType (localRegType one) hint
261
262         arg_type (CmmHinted expr hint) = machRepHintCType (cmmExprType expr) hint
263
264 -- ---------------------------------------------------------------------
265 -- unconditional branches
266 pprBranch :: BlockId -> SDoc
267 pprBranch ident = ptext (sLit "goto") <+> pprBlockId ident <> semi
268
269
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 ]
276
277
278 -- ---------------------------------------------------------------------
279 -- a local table branch
280 --
281 -- we find the fall-through cases
282 --
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.
286 --
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 ]
291     in 
292         (hang (ptext (sLit "switch") <+> parens ( pprExpr e ) <+> lbrace)
293                 4 (vcat ( map caseify pairs2 )))
294         $$ rbrace
295
296   where
297     sndEq (_,x) (_,y) = x == y
298
299     -- fall through case
300     caseify (ix:ixs, ident) = vcat (map do_fallthrough ixs) $$ final_branch ix
301         where 
302         do_fallthrough ix =
303                  hsep [ ptext (sLit "case") , pprHexVal ix wordWidth <> colon ,
304                         ptext (sLit "/* fall through */") ]
305
306         final_branch ix = 
307                 hsep [ ptext (sLit "case") , pprHexVal ix wordWidth <> colon ,
308                        ptext (sLit "goto") , (pprBlockId ident) <> semi ]
309
310 -- ---------------------------------------------------------------------
311 -- Expressions.
312 --
313
314 -- C Types: the invariant is that the C expression generated by
315 --
316 --      pprExpr e
317 --
318 -- has a type in C which is also given by
319 --
320 --      machRepCType (cmmExprType e)
321 --
322 -- (similar invariants apply to the rest of the pretty printer).
323
324 pprExpr :: CmmExpr -> SDoc
325 pprExpr e = case e of
326     CmmLit lit -> pprLit lit
327
328
329     CmmLoad e ty -> pprLoad e ty
330     CmmReg reg      -> pprCastReg reg
331     CmmRegOff reg 0 -> pprCastReg reg
332
333     CmmRegOff reg i
334         | i >  0    -> pprRegOff (char '+') i
335         | otherwise -> pprRegOff (char '-') (-i)
336       where
337         pprRegOff op i' = pprCastReg reg <> op <> int i'
338
339     CmmMachOp mop args -> pprMachOpApp mop args
340
341
342 pprLoad :: CmmExpr -> CmmType -> SDoc
343 pprLoad e ty
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)
348
349   | otherwise 
350   = case e of
351         CmmReg r | isPtrReg r && width == wordWidth && not (isFloatType ty)
352                  -> char '*' <> pprAsPtrReg r
353
354         CmmRegOff r 0 | isPtrReg r && width == wordWidth && not (isFloatType ty)
355                       -> char '*' <> pprAsPtrReg r
356
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))
362
363         _other -> cLoad e ty
364   where
365     width = typeWidth ty
366
367 pprExpr1 :: CmmExpr -> SDoc
368 pprExpr1 (CmmLit lit)     = pprLit1 lit
369 pprExpr1 e@(CmmReg _reg)  = pprExpr e
370 pprExpr1 other            = parens (pprExpr other)
371
372 -- --------------------------------------------------------------------------
373 -- MachOp applications
374
375 pprMachOpApp :: MachOp -> [CmmExpr] -> SDoc
376
377 pprMachOpApp op args
378   | isMulMayOfloOp op
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
383
384 pprMachOpApp mop args
385   | Just ty <- machOpNeedsCast mop 
386   = ty <> parens (pprMachOpApp' mop args)
387   | otherwise
388   = pprMachOpApp' mop args
389
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
394 machOpNeedsCast mop
395   | isComparisonMachOp mop = Just mkW_
396   | otherwise              = Nothing
397
398 pprMachOpApp' mop args
399  = case args of
400     -- dyadic
401     [x,y] -> pprArg x <+> pprMachOp_for_C mop <+> pprArg y
402
403     -- unary
404     [x]   -> pprMachOp_for_C mop <> parens (pprArg x)
405
406     _     -> panic "PprC.pprMachOp : machop with wrong number of args"
407
408   where
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
418
419 -- --------------------------------------------------------------------------
420 -- Literals
421
422 pprLit :: CmmLit -> SDoc
423 pprLit lit = case lit of
424     CmmInt i rep      -> pprHexVal i rep
425
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>
433                 -- see #1861
434
435     CmmLabel clbl      -> mkW_ <> pprCLabelAddr clbl
436     CmmLabelOff clbl i -> mkW_ <> pprCLabelAddr clbl <> char '+' <> int i
437     CmmLabelDiffOff clbl1 clbl2 i
438         -- WARNING:
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
445
446 pprCLabelAddr lbl = char '&' <> pprCLabel lbl
447
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
453
454 -- ---------------------------------------------------------------------------
455 -- Static data
456
457 pprStatics :: [CmmStatic] -> [SDoc]
458 pprStatics [] = []
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'
463   | wORD_SIZE == 4
464   = pprLit1 (floatToWord f) : pprStatics rest
465   | otherwise
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)
470   | wordWidth == W32
471 #ifdef WORDS_BIGENDIAN
472   = pprStatics (CmmStaticLit (CmmInt q W32) : 
473                 CmmStaticLit (CmmInt r W32) : rest)
474 #else
475   = pprStatics (CmmStaticLit (CmmInt r W32) : 
476                 CmmStaticLit (CmmInt q W32) : rest)
477 #endif
478   where r = i .&. 0xffffffff
479         q = i `shiftR` 32
480 pprStatics (CmmStaticLit (CmmInt i w) : rest)
481   | w /= wordWidth
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)
487
488 pprStatic :: CmmStatic -> SDoc
489 pprStatic s = case s of
490
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))
495
496     -- these should be inlined, like the old .hc
497     CmmString s'       -> nest 4 (mkW_ <> parens(pprStringInCStyle s'))
498
499
500 -- ---------------------------------------------------------------------------
501 -- Block Ids
502
503 pprBlockId :: BlockId -> SDoc
504 pprBlockId b = char '_' <> ppr (getUnique b)
505
506 -- --------------------------------------------------------------------------
507 -- Print a MachOp in a way suitable for emitting via C.
508 --
509
510 pprMachOp_for_C :: MachOp -> SDoc
511
512 pprMachOp_for_C mop = case mop of 
513
514         -- Integer operations
515         MO_Add          _ -> char '+'
516         MO_Sub          _ -> char '-'
517         MO_Eq           _ -> ptext (sLit "==")
518         MO_Ne           _ -> ptext (sLit "!=")
519         MO_Mul          _ -> char '*'
520
521         MO_S_Quot       _ -> char '/'
522         MO_S_Rem        _ -> char '%'
523         MO_S_Neg        _ -> char '-'
524
525         MO_U_Quot       _ -> char '/'
526         MO_U_Rem        _ -> char '%'
527
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 '/'
534
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 '<'
540
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 '<'
546
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 '<'
554
555         -- Bitwise operations.  Not all of these may be supported at all
556         -- sizes, and only integral MachReps are valid.
557         MO_And          _ -> char '&'
558         MO_Or           _ -> char '|'
559         MO_Xor          _ -> char '^'
560         MO_Not          _ -> char '~'
561         MO_Shl          _ -> ptext (sLit "<<")
562         MO_U_Shr        _ -> ptext (sLit ">>") -- unsigned shift right
563         MO_S_Shr        _ -> ptext (sLit ">>") -- signed shift right
564
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
569 -- context elsewhere
570
571 -- noop casts
572         MO_UU_Conv from to | from == to -> empty
573         MO_UU_Conv _from to  -> parens (machRep_U_CType to)
574
575         MO_SS_Conv from to | from == to -> empty
576         MO_SS_Conv _from to  -> parens (machRep_S_CType to)
577
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)
582
583         MO_SF_Conv _from to  -> parens (machRep_F_CType to)
584         MO_FS_Conv _from to  -> parens (machRep_S_CType to)
585
586         _ -> pprTrace "offending mop" (ptext $ sLit $ show mop) $
587              panic "PprC.pprMachOp_for_C: unknown machop"
588
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
600 signedOp _ = False
601
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
610
611 -- ---------------------------------------------------------------------
612 -- tend to be implemented by foreign calls
613
614 pprCallishMachOp_for_C :: CallishMachOp -> SDoc
615
616 pprCallishMachOp_for_C mop 
617     = case mop of
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")
645
646 -- ---------------------------------------------------------------------
647 -- Useful #defines
648 --
649
650 mkJMP_, mkFN_, mkIF_ :: SDoc -> SDoc
651
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
655
656
657 mkFB_, mkFE_ :: SDoc
658 mkFB_ = ptext (sLit "FB_") -- function code begin
659 mkFE_ = ptext (sLit "FE_") -- function code end
660
661 -- from includes/Stg.h
662 --
663 mkC_,mkW_,mkP_,mkPP_,mkI_,mkA_,mkD_,mkF_,mkB_,mkL_,mkLI_,mkLW_ :: SDoc
664
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
675
676 mkLI_ = ptext (sLit "(LI_)")       -- StgInt64
677 mkLW_ = ptext (sLit "(LW_)")       -- StgWord64
678
679
680 -- ---------------------------------------------------------------------
681 --
682 -- Assignments
683 --
684 -- Generating assignments is what we're all about, here
685 --
686 pprAssign :: CmmReg -> CmmExpr -> SDoc
687
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 ]
692
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 ]
697   where
698         off1 = off `shiftR` wordShift
699
700         (op,off') | off >= 0  = (char '+', off1)
701                   | otherwise = (char '-', -off1)
702
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+).
706 pprAssign r1 r2
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
713
714 -- ---------------------------------------------------------------------
715 -- Registers
716
717 pprCastReg reg
718    | isStrangeTypeReg reg = mkW_ <> pprReg reg
719    | otherwise            = pprReg reg
720
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
723 -- StgPtr.
724 isFixedPtrReg :: CmmReg -> Bool
725 isFixedPtrReg (CmmLocal _) = False
726 isFixedPtrReg (CmmGlobal r) = isFixedPtrGlobalReg r
727
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
737
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
745
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
751
752 isStrangeTypeGlobal :: GlobalReg -> Bool
753 isStrangeTypeGlobal CurrentTSO          = True
754 isStrangeTypeGlobal CurrentNursery      = True
755 isStrangeTypeGlobal BaseReg             = True
756 isStrangeTypeGlobal r                   = isFixedPtrGlobalReg r
757
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
763
764 -- pprReg just prints the register name.
765 --
766 pprReg :: CmmReg -> SDoc
767 pprReg r = case r of
768         CmmLocal  local  -> pprLocalReg local
769         CmmGlobal global -> pprGlobalReg global
770                 
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
775
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);
781         --              JMP_(*R1.p);
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")
796
797 pprLocalReg :: LocalReg -> SDoc
798 pprLocalReg (LocalReg uniq _) = char '_' <> ppr uniq
799
800 -- -----------------------------------------------------------------------------
801 -- Foreign Calls
802
803 pprCall :: SDoc -> CCallConv -> HintedCmmFormals -> HintedCmmActuals -> CmmSafety
804         -> SDoc
805
806 pprCall ppr_fn cconv results args _
807   | not (is_cish cconv)
808   = panic "pprCall: unknown calling convention"
809
810   | otherwise
811   =
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__();") 
821         else empty) $$
822 #endif
823     ppr_assign results (ppr_fn <> parens (commafy (map pprArg args))) <> semi
824   where 
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"
830
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)
837         = pprExpr expr
838
839      pprUnHint AddrHint   rep = parens (machRepCType rep)
840      pprUnHint SignedHint rep = parens (machRepCType rep)
841      pprUnHint _          _   = empty
842
843 pprGlobalRegName :: GlobalReg -> SDoc
844 pprGlobalRegName gr = case gr of
845     VanillaReg n _  -> char 'R' <> int n  -- without the .w suffix
846     _               -> pprGlobalReg gr
847
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
852
853 -- ---------------------------------------------------------------------
854 -- Find and print local and external declarations for a list of
855 -- Cmm statements.
856 -- 
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)
862
863 pprDataExterns :: [CmmStatic] -> SDoc
864 pprDataExterns statics
865   = vcat (map (pprExternDecl False{-ToDo-}) (keysFM lbls))
866   where (_, lbls) = runTE (mapM_ te_Static statics)
867
868 pprTempDecl :: LocalReg -> SDoc
869 pprTempDecl l@(LocalReg _ rep)
870   = hcat [ machRepCType rep, space, pprLocalReg l, semi ]
871
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
877   | otherwise =
878         hcat [ visibility, label_type lbl,
879                lparen, pprCLabel lbl, text ");" ]
880  where
881   label_type lbl | isCFunctionLabel lbl = ptext (sLit "F_")
882                  | otherwise            = ptext (sLit "I_")
883
884   visibility
885      | externallyVisibleCLabel lbl = char 'E'
886      | otherwise                   = char 'I'
887
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)
891   stdcall_decl sz =
892         ptext (sLit "extern __attribute__((stdcall)) void ") <> pprCLabel lbl
893         <> parens (commafy (replicate (sz `quot` wORD_SIZE) (machRep_U_CType wordWidth)))
894         <> semi
895
896 type TEState = (UniqSet LocalReg, FiniteMap CLabel ())
897 newtype TE a = TE { unTE :: TEState -> (a, TEState) }
898
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)
902
903 te_lbl :: CLabel -> TE ()
904 te_lbl lbl = TE $ \(temps,lbls) -> ((), (temps, addToFM lbls lbl ()))
905
906 te_temp :: LocalReg -> TE ()
907 te_temp r = TE $ \(temps,lbls) -> ((), (addOneToUniqSet temps r, lbls))
908
909 runTE :: TE () -> TEState
910 runTE (TE m) = snd (m (emptyUniqSet, emptyFM))
911
912 te_Static :: CmmStatic -> TE ()
913 te_Static (CmmStaticLit lit) = te_Lit lit
914 te_Static _ = return ()
915
916 te_BB :: CmmBasicBlock -> TE ()
917 te_BB (BasicBlock _ ss)         = mapM_ te_Stmt ss
918
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
923 te_Lit _ = return ()
924
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 ()
934
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
941
942 te_Reg :: CmmReg -> TE ()
943 te_Reg (CmmLocal l) = te_temp l
944 te_Reg _            = return ()
945
946
947 -- ---------------------------------------------------------------------
948 -- C types for MachReps
949
950 cCast :: SDoc -> CmmExpr -> SDoc
951 cCast ty expr = parens ty <> pprExpr1 expr
952
953 cLoad :: CmmExpr -> CmmType -> SDoc
954 #ifdef BEWARE_LOAD_STORE_ALIGNMENT
955 cLoad expr rep =
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")
961 #else
962 cLoad expr rep = char '*' <> parens (cCast (machRepPtrCType rep) expr)
963 #endif
964
965 isCmmWordType :: CmmType -> Bool
966 -- True of GcPtrReg/NonGcReg of native word size
967 isCmmWordType ty = not (isFloatType ty) 
968                    && typeWidth ty == wordWidth
969
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
972 -- the C compiler.
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
977
978 machRepPtrCType :: CmmType -> SDoc
979 machRepPtrCType r | isCmmWordType r = ptext (sLit "P_")
980                   | otherwise       = machRepCType r <> char '*'
981
982 machRepCType :: CmmType -> SDoc
983 machRepCType ty | isFloatType ty = machRep_F_CType w
984                 | otherwise      = machRep_U_CType w
985                 where
986                   w = typeWidth ty
987
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"
992
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"
1000
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"
1008   
1009
1010 -- ---------------------------------------------------------------------
1011 -- print strings as valid C strings
1012
1013 pprStringInCStyle :: [Word8] -> SDoc
1014 pprStringInCStyle s = doubleQuotes (text (concatMap charToC s))
1015
1016 charToC :: Word8 -> String
1017 charToC w = 
1018   case chr (fromIntegral w) of
1019         '\"' -> "\\\""
1020         '\'' -> "\\\'"
1021         '\\' -> "\\\\"
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)]
1027
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.
1032
1033 -- This is a hack to turn the floating point numbers into ints that we
1034 -- can safely initialise to static locations.
1035
1036 big_doubles 
1037   | widthInBytes W64 == 2 * wORD_SIZE  = True
1038   | widthInBytes W64 == wORD_SIZE      = False
1039   | otherwise = panic "big_doubles"
1040
1041 castFloatToIntArray :: STUArray s Int Float -> ST s (STUArray s Int Int)
1042 castFloatToIntArray = castSTUArray
1043
1044 castDoubleToIntArray :: STUArray s Int Double -> ST s (STUArray s Int Int)
1045 castDoubleToIntArray = castSTUArray
1046
1047 -- floats are always 1 word
1048 floatToWord :: Rational -> CmmLit
1049 floatToWord r
1050   = runST (do
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)
1056     )
1057
1058 doubleToWords :: Rational -> [CmmLit]
1059 doubleToWords r
1060   | big_doubles                         -- doubles are 2 words
1061   = runST (do
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
1069                ]
1070     )
1071   | otherwise                           -- doubles are 1 word
1072   = runST (do
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 ]
1078     )
1079
1080 -- ---------------------------------------------------------------------------
1081 -- Utils
1082
1083 wordShift :: Int
1084 wordShift = widthInLog wordWidth
1085
1086 commafy :: [SDoc] -> SDoc
1087 commafy xs = hsep $ punctuate comma xs
1088
1089 -- Print in C hex format: 0x13fa
1090 pprHexVal :: Integer -> Width -> SDoc
1091 pprHexVal 0 _ = ptext (sLit "0x0")
1092 pprHexVal w rep
1093   | w < 0     = parens (char '-' <> ptext (sLit "0x") <> go (-w) <> repsuffix rep)
1094   | otherwise = ptext (sLit "0x") <> go w <> repsuffix rep
1095   where
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.
1101
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'
1107       
1108       go 0 = empty
1109       go w' = go q <> dig
1110            where
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'))
1114