don't emit CmmComments for now
[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 -- Floating info table for safe a foreign call.
144 pprTop top@(CmmData _section d@(_ : _))
145   | CmmDataLabel lbl : lits <- reverse d = 
146   let lits' = reverse lits
147   in pprDataExterns lits' $$
148      pprWordArray lbl lits'
149
150 -- these shouldn't appear?
151 pprTop (CmmData _ _) = panic "PprC.pprTop: can't handle this data"
152
153 -- --------------------------------------------------------------------------
154 -- BasicBlocks are self-contained entities: they always end in a jump.
155 --
156 -- Like nativeGen/AsmCodeGen, we could probably reorder blocks to turn
157 -- as many jumps as possible into fall throughs.
158 --
159
160 pprBBlock :: CmmBasicBlock -> SDoc
161 pprBBlock (BasicBlock lbl stmts) = 
162     if null stmts then
163         pprTrace "pprC.pprBBlock: curious empty code block for" 
164                         (pprBlockId lbl) empty
165     else 
166         nest 4 (pprBlockId lbl <> colon) $$
167         nest 8 (vcat (map pprStmt stmts))
168
169 -- --------------------------------------------------------------------------
170 -- Info tables. Just arrays of words. 
171 -- See codeGen/ClosureInfo, and nativeGen/PprMach
172
173 pprWordArray :: CLabel -> [CmmStatic] -> SDoc
174 pprWordArray lbl ds
175   = hcat [ pprLocalness lbl, ptext (sLit "StgWord")
176          , space, pprCLabel lbl, ptext (sLit "[] = {") ] 
177     $$ nest 8 (commafy (pprStatics ds))
178     $$ ptext (sLit "};")
179
180 --
181 -- has to be static, if it isn't globally visible
182 --
183 pprLocalness :: CLabel -> SDoc
184 pprLocalness lbl | not $ externallyVisibleCLabel lbl = ptext (sLit "static ")
185                  | otherwise = empty
186
187 -- --------------------------------------------------------------------------
188 -- Statements.
189 --
190
191 pprStmt :: CmmStmt -> SDoc
192
193 pprStmt stmt = case stmt of
194     CmmNop       -> empty
195     CmmComment s -> empty -- (hang (ptext (sLit "/*")) 3 (ftext s)) $$ ptext (sLit "*/")
196                           -- XXX if the string contains "*/", we need to fix it
197                           -- XXX we probably want to emit these comments when
198                           -- some debugging option is on.  They can get quite
199                           -- large.
200
201     CmmAssign dest src -> pprAssign dest src
202
203     CmmStore  dest src
204         | typeWidth rep == W64 && wordWidth /= W64
205         -> (if isFloatType rep then ptext (sLit "ASSIGN_DBL")
206                                else ptext (sLit ("ASSIGN_Word64"))) <> 
207            parens (mkP_ <> pprExpr1 dest <> comma <> pprExpr src) <> semi
208
209         | otherwise
210         -> hsep [ pprExpr (CmmLoad dest rep), equals, pprExpr src <> semi ]
211         where
212           rep = cmmExprType src
213
214     CmmCall (CmmCallee fn cconv) results args safety ret ->
215         maybe_proto $$
216         pprCall ppr_fn cconv results args safety
217         where
218         cast_fn = parens (cCast (pprCFunType (char '*') cconv results args) fn)
219
220         real_fun_proto lbl = char ';' <> 
221                         pprCFunType (pprCLabel lbl) cconv results args <> 
222                         noreturn_attr <> semi
223
224         data_proto lbl = ptext (sLit ";EI_(") <> 
225                          pprCLabel lbl <> char ')' <> semi
226
227         noreturn_attr = case ret of
228                           CmmNeverReturns -> text "__attribute__ ((noreturn))"
229                           CmmMayReturn    -> empty
230
231         -- See wiki:Commentary/Compiler/Backends/PprC#Prototypes
232         (maybe_proto, ppr_fn) = 
233             case fn of
234               CmmLit (CmmLabel lbl) 
235                 | StdCallConv <- cconv -> (real_fun_proto lbl, pprCLabel lbl)
236                         -- stdcall functions must be declared with
237                         -- a function type, otherwise the C compiler
238                         -- doesn't add the @n suffix to the label.  We
239                         -- can't add the @n suffix ourselves, because
240                         -- it isn't valid C.
241                 | CmmNeverReturns <- ret -> (real_fun_proto lbl, pprCLabel lbl)
242                 | not (isMathFun lbl) -> (data_proto lbl, cast_fn)
243                         -- we declare all other called functions as
244                         -- data labels, and then cast them to the
245                         -- right type when calling.  This is because
246                         -- the label might already have a declaration
247                         -- as a data label in the same file,
248                         -- e.g. Foreign.Marshal.Alloc declares 'free'
249                         -- as both a data label and a function label.
250               _ -> 
251                    (empty {- no proto -}, cast_fn)
252                         -- for a dynamic call, no declaration is necessary.
253
254     CmmCall (CmmPrim op) results args safety _ret ->
255         pprCall ppr_fn CCallConv results args safety
256         where
257         ppr_fn = pprCallishMachOp_for_C op
258
259     CmmBranch ident          -> pprBranch ident
260     CmmCondBranch expr ident -> pprCondBranch expr ident
261     CmmJump lbl _params      -> mkJMP_(pprExpr lbl) <> semi
262     CmmSwitch arg ids        -> pprSwitch arg ids
263
264 pprCFunType :: SDoc -> CCallConv -> HintedCmmFormals -> HintedCmmActuals -> SDoc
265 pprCFunType ppr_fn cconv ress args
266   = res_type ress <+>
267     parens (text (ccallConvAttribute cconv) <>  ppr_fn) <>
268     parens (commafy (map arg_type args))
269   where
270         res_type [] = ptext (sLit "void")
271         res_type [CmmHinted one hint] = machRepHintCType (localRegType one) hint
272
273         arg_type (CmmHinted expr hint) = machRepHintCType (cmmExprType expr) hint
274
275 -- ---------------------------------------------------------------------
276 -- unconditional branches
277 pprBranch :: BlockId -> SDoc
278 pprBranch ident = ptext (sLit "goto") <+> pprBlockId ident <> semi
279
280
281 -- ---------------------------------------------------------------------
282 -- conditional branches to local labels
283 pprCondBranch :: CmmExpr -> BlockId -> SDoc
284 pprCondBranch expr ident 
285         = hsep [ ptext (sLit "if") , parens(pprExpr expr) ,
286                         ptext (sLit "goto") , (pprBlockId ident) <> semi ]
287
288
289 -- ---------------------------------------------------------------------
290 -- a local table branch
291 --
292 -- we find the fall-through cases
293 --
294 -- N.B. we remove Nothing's from the list of branches, as they are
295 -- 'undefined'. However, they may be defined one day, so we better
296 -- document this behaviour.
297 --
298 pprSwitch :: CmmExpr -> [ Maybe BlockId ] -> SDoc
299 pprSwitch e maybe_ids 
300   = let pairs  = [ (ix, ident) | (ix,Just ident) <- zip [0..] maybe_ids ]
301         pairs2 = [ (map fst as, snd (head as)) | as <- groupBy sndEq pairs ]
302     in 
303         (hang (ptext (sLit "switch") <+> parens ( pprExpr e ) <+> lbrace)
304                 4 (vcat ( map caseify pairs2 )))
305         $$ rbrace
306
307   where
308     sndEq (_,x) (_,y) = x == y
309
310     -- fall through case
311     caseify (ix:ixs, ident) = vcat (map do_fallthrough ixs) $$ final_branch ix
312         where 
313         do_fallthrough ix =
314                  hsep [ ptext (sLit "case") , pprHexVal ix wordWidth <> colon ,
315                         ptext (sLit "/* fall through */") ]
316
317         final_branch ix = 
318                 hsep [ ptext (sLit "case") , pprHexVal ix wordWidth <> colon ,
319                        ptext (sLit "goto") , (pprBlockId ident) <> semi ]
320
321 -- ---------------------------------------------------------------------
322 -- Expressions.
323 --
324
325 -- C Types: the invariant is that the C expression generated by
326 --
327 --      pprExpr e
328 --
329 -- has a type in C which is also given by
330 --
331 --      machRepCType (cmmExprType e)
332 --
333 -- (similar invariants apply to the rest of the pretty printer).
334
335 pprExpr :: CmmExpr -> SDoc
336 pprExpr e = case e of
337     CmmLit lit -> pprLit lit
338
339
340     CmmLoad e ty -> pprLoad e ty
341     CmmReg reg      -> pprCastReg reg
342     CmmRegOff reg 0 -> pprCastReg reg
343
344     CmmRegOff reg i
345         | i >  0    -> pprRegOff (char '+') i
346         | otherwise -> pprRegOff (char '-') (-i)
347       where
348         pprRegOff op i' = pprCastReg reg <> op <> int i'
349
350     CmmMachOp mop args -> pprMachOpApp mop args
351
352
353 pprLoad :: CmmExpr -> CmmType -> SDoc
354 pprLoad e ty
355   | width == W64, wordWidth /= W64
356   = (if isFloatType ty then ptext (sLit "PK_DBL")
357                        else ptext (sLit "PK_Word64"))
358     <> parens (mkP_ <> pprExpr1 e)
359
360   | otherwise 
361   = case e of
362         CmmReg r | isPtrReg r && width == wordWidth && not (isFloatType ty)
363                  -> char '*' <> pprAsPtrReg r
364
365         CmmRegOff r 0 | isPtrReg r && width == wordWidth && not (isFloatType ty)
366                       -> char '*' <> pprAsPtrReg r
367
368         CmmRegOff r off | isPtrReg r && width == wordWidth
369                         , off `rem` wORD_SIZE == 0 && not (isFloatType ty)
370         -- ToDo: check that the offset is a word multiple?
371         --       (For tagging to work, I had to avoid unaligned loads. --ARY)
372                         -> pprAsPtrReg r <> brackets (ppr (off `shiftR` wordShift))
373
374         _other -> cLoad e ty
375   where
376     width = typeWidth ty
377
378 pprExpr1 :: CmmExpr -> SDoc
379 pprExpr1 (CmmLit lit)     = pprLit1 lit
380 pprExpr1 e@(CmmReg _reg)  = pprExpr e
381 pprExpr1 other            = parens (pprExpr other)
382
383 -- --------------------------------------------------------------------------
384 -- MachOp applications
385
386 pprMachOpApp :: MachOp -> [CmmExpr] -> SDoc
387
388 pprMachOpApp op args
389   | isMulMayOfloOp op
390   = ptext (sLit "mulIntMayOflo") <> parens (commafy (map pprExpr args))
391   where isMulMayOfloOp (MO_U_MulMayOflo _) = True
392         isMulMayOfloOp (MO_S_MulMayOflo _) = True
393         isMulMayOfloOp _ = False
394
395 pprMachOpApp mop args
396   | Just ty <- machOpNeedsCast mop 
397   = ty <> parens (pprMachOpApp' mop args)
398   | otherwise
399   = pprMachOpApp' mop args
400
401 -- Comparisons in C have type 'int', but we want type W_ (this is what
402 -- resultRepOfMachOp says).  The other C operations inherit their type
403 -- from their operands, so no casting is required.
404 machOpNeedsCast :: MachOp -> Maybe SDoc
405 machOpNeedsCast mop
406   | isComparisonMachOp mop = Just mkW_
407   | otherwise              = Nothing
408
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 clbl2 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 pprCLabelAddr lbl = char '&' <> pprCLabel lbl
460
461 pprLit1 :: CmmLit -> SDoc
462 pprLit1 lit@(CmmLabelOff _ _) = parens (pprLit lit)
463 pprLit1 lit@(CmmLabelDiffOff _ _ _) = parens (pprLit lit)
464 pprLit1 lit@(CmmFloat _ _)    = parens (pprLit lit)
465 pprLit1 other = pprLit other
466
467 -- ---------------------------------------------------------------------------
468 -- Static data
469
470 pprStatics :: [CmmStatic] -> [SDoc]
471 pprStatics [] = []
472 pprStatics (CmmStaticLit (CmmFloat f W32) : rest) 
473   -- floats are padded to a word, see #1852
474   | wORD_SIZE == 8, CmmStaticLit (CmmInt 0 W32) : rest' <- rest
475   = pprLit1 (floatToWord f) : pprStatics rest'
476   | wORD_SIZE == 4
477   = pprLit1 (floatToWord f) : pprStatics rest
478   | otherwise
479   = pprPanic "pprStatics: float" (vcat (map (\(CmmStaticLit l) -> ppr (cmmLitType l)) rest))
480 pprStatics (CmmStaticLit (CmmFloat f W64) : rest)
481   = map pprLit1 (doubleToWords f) ++ pprStatics rest
482 pprStatics (CmmStaticLit (CmmInt i W64) : rest)
483   | wordWidth == W32
484 #ifdef WORDS_BIGENDIAN
485   = pprStatics (CmmStaticLit (CmmInt q W32) : 
486                 CmmStaticLit (CmmInt r W32) : rest)
487 #else
488   = pprStatics (CmmStaticLit (CmmInt r W32) : 
489                 CmmStaticLit (CmmInt q W32) : rest)
490 #endif
491   where r = i .&. 0xffffffff
492         q = i `shiftR` 32
493 pprStatics (CmmStaticLit (CmmInt i w) : rest)
494   | w /= wordWidth
495   = panic "pprStatics: cannot emit a non-word-sized static literal"
496 pprStatics (CmmStaticLit lit : rest)
497   = pprLit1 lit : pprStatics rest
498 pprStatics (other : rest)
499   = pprPanic "pprWord" (pprStatic other)
500
501 pprStatic :: CmmStatic -> SDoc
502 pprStatic s = case s of
503
504     CmmStaticLit lit   -> nest 4 (pprLit lit)
505     CmmAlign i         -> nest 4 (ptext (sLit "/* align */") <+> int i)
506     CmmDataLabel clbl  -> pprCLabel clbl <> colon
507     CmmUninitialised i -> nest 4 (mkC_ <> brackets (int i))
508
509     -- these should be inlined, like the old .hc
510     CmmString s'       -> nest 4 (mkW_ <> parens(pprStringInCStyle s'))
511
512
513 -- ---------------------------------------------------------------------------
514 -- Block Ids
515
516 pprBlockId :: BlockId -> SDoc
517 pprBlockId b = char '_' <> ppr (getUnique b)
518
519 -- --------------------------------------------------------------------------
520 -- Print a MachOp in a way suitable for emitting via C.
521 --
522
523 pprMachOp_for_C :: MachOp -> SDoc
524
525 pprMachOp_for_C mop = case mop of 
526
527         -- Integer operations
528         MO_Add          _ -> char '+'
529         MO_Sub          _ -> char '-'
530         MO_Eq           _ -> ptext (sLit "==")
531         MO_Ne           _ -> ptext (sLit "!=")
532         MO_Mul          _ -> char '*'
533
534         MO_S_Quot       _ -> char '/'
535         MO_S_Rem        _ -> char '%'
536         MO_S_Neg        _ -> char '-'
537
538         MO_U_Quot       _ -> char '/'
539         MO_U_Rem        _ -> char '%'
540
541         -- & Floating-point operations
542         MO_F_Add        _ -> char '+'
543         MO_F_Sub        _ -> char '-'
544         MO_F_Neg        _ -> char '-'
545         MO_F_Mul        _ -> char '*'
546         MO_F_Quot       _ -> char '/'
547
548         -- Signed comparisons
549         MO_S_Ge         _ -> ptext (sLit ">=")
550         MO_S_Le         _ -> ptext (sLit "<=")
551         MO_S_Gt         _ -> char '>'
552         MO_S_Lt         _ -> char '<'
553
554         -- & Unsigned comparisons
555         MO_U_Ge         _ -> ptext (sLit ">=")
556         MO_U_Le         _ -> ptext (sLit "<=")
557         MO_U_Gt         _ -> char '>'
558         MO_U_Lt         _ -> char '<'
559
560         -- & Floating-point comparisons
561         MO_F_Eq         _ -> ptext (sLit "==")
562         MO_F_Ne         _ -> ptext (sLit "!=")
563         MO_F_Ge         _ -> ptext (sLit ">=")
564         MO_F_Le         _ -> ptext (sLit "<=")
565         MO_F_Gt         _ -> char '>'
566         MO_F_Lt         _ -> char '<'
567
568         -- Bitwise operations.  Not all of these may be supported at all
569         -- sizes, and only integral MachReps are valid.
570         MO_And          _ -> char '&'
571         MO_Or           _ -> char '|'
572         MO_Xor          _ -> char '^'
573         MO_Not          _ -> char '~'
574         MO_Shl          _ -> ptext (sLit "<<")
575         MO_U_Shr        _ -> ptext (sLit ">>") -- unsigned shift right
576         MO_S_Shr        _ -> ptext (sLit ">>") -- signed shift right
577
578 -- Conversions.  Some of these will be NOPs, but never those that convert
579 -- between ints and floats.
580 -- Floating-point conversions use the signed variant.
581 -- We won't know to generate (void*) casts here, but maybe from
582 -- context elsewhere
583
584 -- noop casts
585         MO_UU_Conv from to | from == to -> empty
586         MO_UU_Conv _from to  -> parens (machRep_U_CType to)
587
588         MO_SS_Conv from to | from == to -> empty
589         MO_SS_Conv _from to  -> parens (machRep_S_CType to)
590
591         -- TEMPORARY: the old code didn't check this case, so let's leave it out
592         -- to facilitate comparisons against the old output code.
593         --MO_FF_Conv from to | from == to -> empty
594         MO_FF_Conv _from to  -> parens (machRep_F_CType to)
595
596         MO_SF_Conv _from to  -> parens (machRep_F_CType to)
597         MO_FS_Conv _from to  -> parens (machRep_S_CType to)
598
599         _ -> pprTrace "offending mop" (ptext $ sLit $ show mop) $
600              panic "PprC.pprMachOp_for_C: unknown machop"
601
602 signedOp :: MachOp -> Bool      -- Argument type(s) are signed ints
603 signedOp (MO_S_Quot _)   = True
604 signedOp (MO_S_Rem  _)   = True
605 signedOp (MO_S_Neg  _)   = True
606 signedOp (MO_S_Ge   _)   = True
607 signedOp (MO_S_Le   _)   = True
608 signedOp (MO_S_Gt   _)   = True
609 signedOp (MO_S_Lt   _)   = True
610 signedOp (MO_S_Shr  _)   = True
611 signedOp (MO_SS_Conv _ _) = True
612 signedOp (MO_SF_Conv _ _) = True
613 signedOp _ = False
614
615 floatComparison :: MachOp -> Bool  -- comparison between float args
616 floatComparison (MO_F_Eq   _)    = True
617 floatComparison (MO_F_Ne   _)    = True
618 floatComparison (MO_F_Ge   _)    = True
619 floatComparison (MO_F_Le   _)    = True
620 floatComparison (MO_F_Gt   _)    = True
621 floatComparison (MO_F_Lt   _)    = True
622 floatComparison _ = False
623
624 -- ---------------------------------------------------------------------
625 -- tend to be implemented by foreign calls
626
627 pprCallishMachOp_for_C :: CallishMachOp -> SDoc
628
629 pprCallishMachOp_for_C mop 
630     = case mop of
631         MO_F64_Pwr  -> ptext (sLit "pow")
632         MO_F64_Sin  -> ptext (sLit "sin")
633         MO_F64_Cos  -> ptext (sLit "cos")
634         MO_F64_Tan  -> ptext (sLit "tan")
635         MO_F64_Sinh -> ptext (sLit "sinh")
636         MO_F64_Cosh -> ptext (sLit "cosh")
637         MO_F64_Tanh -> ptext (sLit "tanh")
638         MO_F64_Asin -> ptext (sLit "asin")
639         MO_F64_Acos -> ptext (sLit "acos")
640         MO_F64_Atan -> ptext (sLit "atan")
641         MO_F64_Log  -> ptext (sLit "log")
642         MO_F64_Exp  -> ptext (sLit "exp")
643         MO_F64_Sqrt -> ptext (sLit "sqrt")
644         MO_F32_Pwr  -> ptext (sLit "powf")
645         MO_F32_Sin  -> ptext (sLit "sinf")
646         MO_F32_Cos  -> ptext (sLit "cosf")
647         MO_F32_Tan  -> ptext (sLit "tanf")
648         MO_F32_Sinh -> ptext (sLit "sinhf")
649         MO_F32_Cosh -> ptext (sLit "coshf")
650         MO_F32_Tanh -> ptext (sLit "tanhf")
651         MO_F32_Asin -> ptext (sLit "asinf")
652         MO_F32_Acos -> ptext (sLit "acosf")
653         MO_F32_Atan -> ptext (sLit "atanf")
654         MO_F32_Log  -> ptext (sLit "logf")
655         MO_F32_Exp  -> ptext (sLit "expf")
656         MO_F32_Sqrt -> ptext (sLit "sqrtf")
657         MO_WriteBarrier -> ptext (sLit "write_barrier")
658
659 -- ---------------------------------------------------------------------
660 -- Useful #defines
661 --
662
663 mkJMP_, mkFN_, mkIF_ :: SDoc -> SDoc
664
665 mkJMP_ i = ptext (sLit "JMP_") <> parens i
666 mkFN_  i = ptext (sLit "FN_")  <> parens i -- externally visible function
667 mkIF_  i = ptext (sLit "IF_")  <> parens i -- locally visible
668
669
670 mkFB_, mkFE_ :: SDoc
671 mkFB_ = ptext (sLit "FB_") -- function code begin
672 mkFE_ = ptext (sLit "FE_") -- function code end
673
674 -- from includes/Stg.h
675 --
676 mkC_,mkW_,mkP_,mkPP_,mkI_,mkA_,mkD_,mkF_,mkB_,mkL_,mkLI_,mkLW_ :: SDoc
677
678 mkC_  = ptext (sLit "(C_)")        -- StgChar
679 mkW_  = ptext (sLit "(W_)")        -- StgWord
680 mkP_  = ptext (sLit "(P_)")        -- StgWord*
681 mkPP_ = ptext (sLit "(PP_)")       -- P_*
682 mkI_  = ptext (sLit "(I_)")        -- StgInt
683 mkA_  = ptext (sLit "(A_)")        -- StgAddr
684 mkD_  = ptext (sLit "(D_)")        -- const StgWord*
685 mkF_  = ptext (sLit "(F_)")        -- StgFunPtr
686 mkB_  = ptext (sLit "(B_)")        -- StgByteArray
687 mkL_  = ptext (sLit "(L_)")        -- StgClosurePtr
688
689 mkLI_ = ptext (sLit "(LI_)")       -- StgInt64
690 mkLW_ = ptext (sLit "(LW_)")       -- StgWord64
691
692
693 -- ---------------------------------------------------------------------
694 --
695 -- Assignments
696 --
697 -- Generating assignments is what we're all about, here
698 --
699 pprAssign :: CmmReg -> CmmExpr -> SDoc
700
701 -- dest is a reg, rhs is a reg
702 pprAssign r1 (CmmReg r2)
703    | isPtrReg r1 && isPtrReg r2
704    = hcat [ pprAsPtrReg r1, equals, pprAsPtrReg r2, semi ]
705
706 -- dest is a reg, rhs is a CmmRegOff
707 pprAssign r1 (CmmRegOff r2 off)
708    | isPtrReg r1 && isPtrReg r2 && (off `rem` wORD_SIZE == 0)
709    = hcat [ pprAsPtrReg r1, equals, pprAsPtrReg r2, op, int off', semi ]
710   where
711         off1 = off `shiftR` wordShift
712
713         (op,off') | off >= 0  = (char '+', off1)
714                   | otherwise = (char '-', -off1)
715
716 -- dest is a reg, rhs is anything.
717 -- We can't cast the lvalue, so we have to cast the rhs if necessary.  Casting
718 -- the lvalue elicits a warning from new GCC versions (3.4+).
719 pprAssign r1 r2
720   | isFixedPtrReg r1             = mkAssign (mkP_ <> pprExpr1 r2)
721   | Just ty <- strangeRegType r1 = mkAssign (parens ty <> pprExpr1 r2)
722   | otherwise                    = mkAssign (pprExpr r2)
723     where mkAssign x = if r1 == CmmGlobal BaseReg
724                        then ptext (sLit "ASSIGN_BaseReg") <> parens x <> semi
725                        else pprReg r1 <> ptext (sLit " = ") <> x <> semi
726
727 -- ---------------------------------------------------------------------
728 -- Registers
729
730 pprCastReg reg
731    | isStrangeTypeReg reg = mkW_ <> pprReg reg
732    | otherwise            = pprReg reg
733
734 -- True if (pprReg reg) will give an expression with type StgPtr.  We
735 -- need to take care with pointer arithmetic on registers with type
736 -- StgPtr.
737 isFixedPtrReg :: CmmReg -> Bool
738 isFixedPtrReg (CmmLocal _) = False
739 isFixedPtrReg (CmmGlobal r) = isFixedPtrGlobalReg r
740
741 -- True if (pprAsPtrReg reg) will give an expression with type StgPtr
742 -- JD: THIS IS HORRIBLE AND SHOULD BE RENAMED, AT THE VERY LEAST.
743 -- THE GARBAGE WITH THE VNonGcPtr HELPS MATCH THE OLD CODE GENERATOR'S OUTPUT;
744 -- I'M NOT SURE IF IT SHOULD REALLY STAY THAT WAY.
745 isPtrReg :: CmmReg -> Bool
746 isPtrReg (CmmLocal _)               = False
747 isPtrReg (CmmGlobal (VanillaReg n VGcPtr)) = True -- if we print via pprAsPtrReg
748 isPtrReg (CmmGlobal (VanillaReg n VNonGcPtr)) = False --if we print via pprAsPtrReg
749 isPtrReg (CmmGlobal reg)            = isFixedPtrGlobalReg reg
750
751 -- True if this global reg has type StgPtr
752 isFixedPtrGlobalReg :: GlobalReg -> Bool
753 isFixedPtrGlobalReg Sp          = True
754 isFixedPtrGlobalReg Hp          = True
755 isFixedPtrGlobalReg HpLim       = True
756 isFixedPtrGlobalReg SpLim       = True
757 isFixedPtrGlobalReg _           = False
758
759 -- True if in C this register doesn't have the type given by 
760 -- (machRepCType (cmmRegType reg)), so it has to be cast.
761 isStrangeTypeReg :: CmmReg -> Bool
762 isStrangeTypeReg (CmmLocal _)   = False
763 isStrangeTypeReg (CmmGlobal g)  = isStrangeTypeGlobal g
764
765 isStrangeTypeGlobal :: GlobalReg -> Bool
766 isStrangeTypeGlobal CurrentTSO          = True
767 isStrangeTypeGlobal CurrentNursery      = True
768 isStrangeTypeGlobal BaseReg             = True
769 isStrangeTypeGlobal r                   = isFixedPtrGlobalReg r
770
771 strangeRegType :: CmmReg -> Maybe SDoc
772 strangeRegType (CmmGlobal CurrentTSO) = Just (ptext (sLit "struct StgTSO_ *"))
773 strangeRegType (CmmGlobal CurrentNursery) = Just (ptext (sLit "struct bdescr_ *"))
774 strangeRegType (CmmGlobal BaseReg) = Just (ptext (sLit "struct StgRegTable_ *"))
775 strangeRegType _ = Nothing
776
777 -- pprReg just prints the register name.
778 --
779 pprReg :: CmmReg -> SDoc
780 pprReg r = case r of
781         CmmLocal  local  -> pprLocalReg local
782         CmmGlobal global -> pprGlobalReg global
783                 
784 pprAsPtrReg :: CmmReg -> SDoc
785 pprAsPtrReg (CmmGlobal (VanillaReg n gcp)) 
786   = WARN( gcp /= VGcPtr, ppr n ) char 'R' <> int n <> ptext (sLit ".p")
787 pprAsPtrReg other_reg = pprReg other_reg
788
789 pprGlobalReg :: GlobalReg -> SDoc
790 pprGlobalReg gr = case gr of
791     VanillaReg n _ -> char 'R' <> int n  <> ptext (sLit ".w")
792         -- pprGlobalReg prints a VanillaReg as a .w regardless
793         -- Example:     R1.w = R1.w & (-0x8UL);
794         --              JMP_(*R1.p);
795     FloatReg   n   -> char 'F' <> int n
796     DoubleReg  n   -> char 'D' <> int n
797     LongReg    n   -> char 'L' <> int n
798     Sp             -> ptext (sLit "Sp")
799     SpLim          -> ptext (sLit "SpLim")
800     Hp             -> ptext (sLit "Hp")
801     HpLim          -> ptext (sLit "HpLim")
802     CurrentTSO     -> ptext (sLit "CurrentTSO")
803     CurrentNursery -> ptext (sLit "CurrentNursery")
804     HpAlloc        -> ptext (sLit "HpAlloc")
805     BaseReg        -> ptext (sLit "BaseReg")
806     EagerBlackholeInfo -> ptext (sLit "stg_EAGER_BLACKHOLE_info")
807     GCEnter1       -> ptext (sLit "stg_gc_enter_1")
808     GCFun          -> ptext (sLit "stg_gc_fun")
809
810 pprLocalReg :: LocalReg -> SDoc
811 pprLocalReg (LocalReg uniq _) = char '_' <> ppr uniq
812
813 -- -----------------------------------------------------------------------------
814 -- Foreign Calls
815
816 pprCall :: SDoc -> CCallConv -> HintedCmmFormals -> HintedCmmActuals -> CmmSafety
817         -> SDoc
818
819 pprCall ppr_fn cconv results args _
820   | not (is_cish cconv)
821   = panic "pprCall: unknown calling convention"
822
823   | otherwise
824   =
825 #if x86_64_TARGET_ARCH
826         -- HACK around gcc optimisations.
827         -- x86_64 needs a __DISCARD__() here, to create a barrier between
828         -- putting the arguments into temporaries and passing the arguments
829         -- to the callee, because the argument expressions may refer to
830         -- machine registers that are also used for passing arguments in the
831         -- C calling convention.
832     (if (not opt_Unregisterised) 
833         then ptext (sLit "__DISCARD__();") 
834         else empty) $$
835 #endif
836     ppr_assign results (ppr_fn <> parens (commafy (map pprArg args))) <> semi
837   where 
838      ppr_assign []           rhs = rhs
839      ppr_assign [CmmHinted one hint] rhs
840          = pprLocalReg one <> ptext (sLit " = ")
841                  <> pprUnHint hint (localRegType one) <> rhs
842      ppr_assign _other _rhs = panic "pprCall: multiple results"
843
844      pprArg (CmmHinted expr AddrHint)
845         = cCast (ptext (sLit "void *")) expr
846         -- see comment by machRepHintCType below
847      pprArg (CmmHinted expr SignedHint)
848         = cCast (machRep_S_CType $ typeWidth $ cmmExprType expr) expr
849      pprArg (CmmHinted expr _other)
850         = pprExpr expr
851
852      pprUnHint AddrHint   rep = parens (machRepCType rep)
853      pprUnHint SignedHint rep = parens (machRepCType rep)
854      pprUnHint _          _   = empty
855
856 pprGlobalRegName :: GlobalReg -> SDoc
857 pprGlobalRegName gr = case gr of
858     VanillaReg n _  -> char 'R' <> int n  -- without the .w suffix
859     _               -> pprGlobalReg gr
860
861 -- Currently we only have these two calling conventions, but this might
862 -- change in the future...
863 is_cish CCallConv   = True
864 is_cish StdCallConv = True
865
866 -- ---------------------------------------------------------------------
867 -- Find and print local and external declarations for a list of
868 -- Cmm statements.
869 -- 
870 pprTempAndExternDecls :: [CmmBasicBlock] -> (SDoc{-temps-}, SDoc{-externs-})
871 pprTempAndExternDecls stmts 
872   = (vcat (map pprTempDecl (uniqSetToList temps)), 
873      vcat (map (pprExternDecl False{-ToDo-}) (keysFM lbls)))
874   where (temps, lbls) = runTE (mapM_ te_BB stmts)
875
876 pprDataExterns :: [CmmStatic] -> SDoc
877 pprDataExterns statics
878   = vcat (map (pprExternDecl False{-ToDo-}) (keysFM lbls))
879   where (_, lbls) = runTE (mapM_ te_Static statics)
880
881 pprTempDecl :: LocalReg -> SDoc
882 pprTempDecl l@(LocalReg _ rep)
883   = hcat [ machRepCType rep, space, pprLocalReg l, semi ]
884
885 pprExternDecl :: Bool -> CLabel -> SDoc
886 pprExternDecl in_srt lbl
887   -- do not print anything for "known external" things
888   | not (needsCDecl lbl) = empty
889   | Just sz <- foreignLabelStdcallInfo lbl = stdcall_decl sz
890   | otherwise =
891         hcat [ visibility, label_type lbl,
892                lparen, pprCLabel lbl, text ");" ]
893  where
894   label_type lbl | isCFunctionLabel lbl = ptext (sLit "F_")
895                  | otherwise            = ptext (sLit "I_")
896
897   visibility
898      | externallyVisibleCLabel lbl = char 'E'
899      | otherwise                   = char 'I'
900
901   -- If the label we want to refer to is a stdcall function (on Windows) then
902   -- we must generate an appropriate prototype for it, so that the C compiler will
903   -- add the @n suffix to the label (#2276)
904   stdcall_decl sz =
905         ptext (sLit "extern __attribute__((stdcall)) void ") <> pprCLabel lbl
906         <> parens (commafy (replicate (sz `quot` wORD_SIZE) (machRep_U_CType wordWidth)))
907         <> semi
908
909 type TEState = (UniqSet LocalReg, FiniteMap CLabel ())
910 newtype TE a = TE { unTE :: TEState -> (a, TEState) }
911
912 instance Monad TE where
913    TE m >>= k  = TE $ \s -> case m s of (a, s') -> unTE (k a) s'
914    return a    = TE $ \s -> (a, s)
915
916 te_lbl :: CLabel -> TE ()
917 te_lbl lbl = TE $ \(temps,lbls) -> ((), (temps, addToFM lbls lbl ()))
918
919 te_temp :: LocalReg -> TE ()
920 te_temp r = TE $ \(temps,lbls) -> ((), (addOneToUniqSet temps r, lbls))
921
922 runTE :: TE () -> TEState
923 runTE (TE m) = snd (m (emptyUniqSet, emptyFM))
924
925 te_Static :: CmmStatic -> TE ()
926 te_Static (CmmStaticLit lit) = te_Lit lit
927 te_Static _ = return ()
928
929 te_BB :: CmmBasicBlock -> TE ()
930 te_BB (BasicBlock _ ss)         = mapM_ te_Stmt ss
931
932 te_Lit :: CmmLit -> TE ()
933 te_Lit (CmmLabel l) = te_lbl l
934 te_Lit (CmmLabelOff l _) = te_lbl l
935 te_Lit (CmmLabelDiffOff l1 l2 _) = te_lbl l1
936 te_Lit _ = return ()
937
938 te_Stmt :: CmmStmt -> TE ()
939 te_Stmt (CmmAssign r e)         = te_Reg r >> te_Expr e
940 te_Stmt (CmmStore l r)          = te_Expr l >> te_Expr r
941 te_Stmt (CmmCall _ rs es _ _)   = mapM_ (te_temp.hintlessCmm) rs >>
942                                   mapM_ (te_Expr.hintlessCmm) es
943 te_Stmt (CmmCondBranch e _)     = te_Expr e
944 te_Stmt (CmmSwitch e _)         = te_Expr e
945 te_Stmt (CmmJump e _)           = te_Expr e
946 te_Stmt _                       = return ()
947
948 te_Expr :: CmmExpr -> TE ()
949 te_Expr (CmmLit lit)            = te_Lit lit
950 te_Expr (CmmLoad e _)           = te_Expr e
951 te_Expr (CmmReg r)              = te_Reg r
952 te_Expr (CmmMachOp _ es)        = mapM_ te_Expr es
953 te_Expr (CmmRegOff r _)         = te_Reg r
954
955 te_Reg :: CmmReg -> TE ()
956 te_Reg (CmmLocal l) = te_temp l
957 te_Reg _            = return ()
958
959
960 -- ---------------------------------------------------------------------
961 -- C types for MachReps
962
963 cCast :: SDoc -> CmmExpr -> SDoc
964 cCast ty expr = parens ty <> pprExpr1 expr
965
966 cLoad :: CmmExpr -> CmmType -> SDoc
967 #ifdef BEWARE_LOAD_STORE_ALIGNMENT
968 cLoad expr rep =
969     let decl = machRepCType rep <+> ptext (sLit "x") <> semi
970         struct = ptext (sLit "struct") <+> braces (decl)
971         packed_attr = ptext (sLit "__attribute__((packed))")
972         cast = parens (struct <+> packed_attr <> char '*')
973     in parens (cast <+> pprExpr1 expr) <> ptext (sLit "->x")
974 #else
975 cLoad expr rep = char '*' <> parens (cCast (machRepPtrCType rep) expr)
976 #endif
977
978 isCmmWordType :: CmmType -> Bool
979 -- True of GcPtrReg/NonGcReg of native word size
980 isCmmWordType ty = not (isFloatType ty) 
981                    && typeWidth ty == wordWidth
982
983 -- This is for finding the types of foreign call arguments.  For a pointer
984 -- argument, we always cast the argument to (void *), to avoid warnings from
985 -- the C compiler.
986 machRepHintCType :: CmmType -> ForeignHint -> SDoc
987 machRepHintCType rep AddrHint    = ptext (sLit "void *")
988 machRepHintCType rep SignedHint = machRep_S_CType (typeWidth rep)
989 machRepHintCType rep _other     = machRepCType rep
990
991 machRepPtrCType :: CmmType -> SDoc
992 machRepPtrCType r | isCmmWordType r = ptext (sLit "P_")
993                   | otherwise       = machRepCType r <> char '*'
994
995 machRepCType :: CmmType -> SDoc
996 machRepCType ty | isFloatType ty = machRep_F_CType w
997                 | otherwise      = machRep_U_CType w
998                 where
999                   w = typeWidth ty
1000
1001 machRep_F_CType :: Width -> SDoc
1002 machRep_F_CType W32 = ptext (sLit "StgFloat") -- ToDo: correct?
1003 machRep_F_CType W64 = ptext (sLit "StgDouble")
1004 machRep_F_CType _   = panic "machRep_F_CType"
1005
1006 machRep_U_CType :: Width -> SDoc
1007 machRep_U_CType w | w == wordWidth = ptext (sLit "W_")
1008 machRep_U_CType W8  = ptext (sLit "StgWord8")
1009 machRep_U_CType W16 = ptext (sLit "StgWord16")
1010 machRep_U_CType W32 = ptext (sLit "StgWord32")
1011 machRep_U_CType W64 = ptext (sLit "StgWord64")
1012 machRep_U_CType _   = panic "machRep_U_CType"
1013
1014 machRep_S_CType :: Width -> SDoc
1015 machRep_S_CType w | w == wordWidth = ptext (sLit "I_")
1016 machRep_S_CType W8  = ptext (sLit "StgInt8")
1017 machRep_S_CType W16 = ptext (sLit "StgInt16")
1018 machRep_S_CType W32 = ptext (sLit "StgInt32")
1019 machRep_S_CType W64 = ptext (sLit "StgInt64")
1020 machRep_S_CType _   = panic "machRep_S_CType"
1021   
1022
1023 -- ---------------------------------------------------------------------
1024 -- print strings as valid C strings
1025
1026 pprStringInCStyle :: [Word8] -> SDoc
1027 pprStringInCStyle s = doubleQuotes (text (concatMap charToC s))
1028
1029 charToC :: Word8 -> String
1030 charToC w = 
1031   case chr (fromIntegral w) of
1032         '\"' -> "\\\""
1033         '\'' -> "\\\'"
1034         '\\' -> "\\\\"
1035         c | c >= ' ' && c <= '~' -> [c]
1036           | otherwise -> ['\\',
1037                          chr (ord '0' + ord c `div` 64),
1038                          chr (ord '0' + ord c `div` 8 `mod` 8),
1039                          chr (ord '0' + ord c         `mod` 8)]
1040
1041 -- ---------------------------------------------------------------------------
1042 -- Initialising static objects with floating-point numbers.  We can't
1043 -- just emit the floating point number, because C will cast it to an int
1044 -- by rounding it.  We want the actual bit-representation of the float.
1045
1046 -- This is a hack to turn the floating point numbers into ints that we
1047 -- can safely initialise to static locations.
1048
1049 big_doubles 
1050   | widthInBytes W64 == 2 * wORD_SIZE  = True
1051   | widthInBytes W64 == wORD_SIZE      = False
1052   | otherwise = panic "big_doubles"
1053
1054 castFloatToIntArray :: STUArray s Int Float -> ST s (STUArray s Int Int)
1055 castFloatToIntArray = castSTUArray
1056
1057 castDoubleToIntArray :: STUArray s Int Double -> ST s (STUArray s Int Int)
1058 castDoubleToIntArray = castSTUArray
1059
1060 -- floats are always 1 word
1061 floatToWord :: Rational -> CmmLit
1062 floatToWord r
1063   = runST (do
1064         arr <- newArray_ ((0::Int),0)
1065         writeArray arr 0 (fromRational r)
1066         arr' <- castFloatToIntArray arr
1067         i <- readArray arr' 0
1068         return (CmmInt (toInteger i) wordWidth)
1069     )
1070
1071 doubleToWords :: Rational -> [CmmLit]
1072 doubleToWords r
1073   | big_doubles                         -- doubles are 2 words
1074   = runST (do
1075         arr <- newArray_ ((0::Int),1)
1076         writeArray arr 0 (fromRational r)
1077         arr' <- castDoubleToIntArray arr
1078         i1 <- readArray arr' 0
1079         i2 <- readArray arr' 1
1080         return [ CmmInt (toInteger i1) wordWidth
1081                , CmmInt (toInteger i2) wordWidth
1082                ]
1083     )
1084   | otherwise                           -- doubles are 1 word
1085   = runST (do
1086         arr <- newArray_ ((0::Int),0)
1087         writeArray arr 0 (fromRational r)
1088         arr' <- castDoubleToIntArray arr
1089         i <- readArray arr' 0
1090         return [ CmmInt (toInteger i) wordWidth ]
1091     )
1092
1093 -- ---------------------------------------------------------------------------
1094 -- Utils
1095
1096 wordShift :: Int
1097 wordShift = widthInLog wordWidth
1098
1099 commafy :: [SDoc] -> SDoc
1100 commafy xs = hsep $ punctuate comma xs
1101
1102 -- Print in C hex format: 0x13fa
1103 pprHexVal :: Integer -> Width -> SDoc
1104 pprHexVal 0 _ = ptext (sLit "0x0")
1105 pprHexVal w rep
1106   | w < 0     = parens (char '-' <> ptext (sLit "0x") <> go (-w) <> repsuffix rep)
1107   | otherwise = ptext (sLit "0x") <> go w <> repsuffix rep
1108   where
1109         -- type suffix for literals:
1110         -- Integer literals are unsigned in Cmm/C.  We explicitly cast to
1111         -- signed values for doing signed operations, but at all other
1112         -- times values are unsigned.  This also helps eliminate occasional
1113         -- warnings about integer overflow from gcc.
1114
1115         -- on 32-bit platforms, add "ULL" to 64-bit literals
1116       repsuffix W64 | wORD_SIZE == 4 = ptext (sLit "ULL")
1117         -- on 64-bit platforms with 32-bit int, add "L" to 64-bit literals
1118       repsuffix W64 | cINT_SIZE == 4 = ptext (sLit "UL")
1119       repsuffix _ = char 'U'
1120       
1121       go 0 = empty
1122       go w' = go q <> dig
1123            where
1124              (q,r) = w' `quotRem` 16
1125              dig | r < 10    = char (chr (fromInteger r + ord '0'))
1126                  | otherwise = char (chr (fromInteger r - 10 + ord 'a'))
1127