fix types in generated C for comparison MachOps
[ghc-hetmet.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 -- This is simpler than the old PprAbsC, because Cmm is "macro-expanded"
13 -- relative to the old AbstractC, and many oddities/decorations have
14 -- disappeared from the data type.
15 --
16
17 -- ToDo: save/restore volatile registers around calls.
18
19 module PprC (
20         writeCs,
21         pprStringInCStyle 
22   ) where
23
24 #include "HsVersions.h"
25
26 -- Cmm stuff
27 import Cmm
28 import CLabel
29 import MachOp
30 import ForeignCall
31
32 -- Utils
33 import DynFlags
34 import Unique
35 import UniqSet
36 import FiniteMap
37 import UniqFM
38 import FastString
39 import Outputable
40 import Constants
41
42 -- The rest
43 import Data.List
44 import Data.Bits
45 import Data.Char
46 import System.IO
47 import Data.Word
48
49 #ifdef DEBUG
50 import PprCmm           () -- instances only
51 -- import Debug.Trace
52 #endif
53
54 #if __GLASGOW_HASKELL__ >= 504
55 import Data.Array.ST
56 #endif
57 import Control.Monad.ST
58
59 #if x86_64_TARGET_ARCH
60 import StaticFlags      ( opt_Unregisterised )
61 #endif
62
63 -- --------------------------------------------------------------------------
64 -- Top level
65
66 pprCs :: DynFlags -> [Cmm] -> SDoc
67 pprCs dflags cmms
68  = pprCode CStyle (vcat $ map (\c -> split_marker $$ pprC c) cmms)
69  where
70    split_marker
71      | dopt Opt_SplitObjs dflags = ptext SLIT("__STG_SPLIT_MARKER")
72      | otherwise                 = empty
73
74 writeCs :: DynFlags -> Handle -> [Cmm] -> IO ()
75 writeCs dflags handle cmms 
76   = printForC handle (pprCs dflags cmms)
77
78 -- --------------------------------------------------------------------------
79 -- Now do some real work
80 --
81 -- for fun, we could call cmmToCmm over the tops...
82 --
83
84 pprC :: Cmm -> SDoc
85 pprC (Cmm tops) = vcat $ intersperse (text "") $ map pprTop tops
86
87 --
88 -- top level procs
89 -- 
90 pprTop :: CmmTop -> SDoc
91 pprTop (CmmProc info clbl _params blocks) =
92     (if not (null info)
93         then pprDataExterns info $$
94              pprWordArray (entryLblToInfoLbl clbl) info
95         else empty) $$
96     (case blocks of
97         [] -> empty
98          -- the first block doesn't get a label:
99         (BasicBlock _ stmts : rest) -> vcat [
100            text "",
101            extern_decls,
102            (if (externallyVisibleCLabel clbl)
103                     then mkFN_ else mkIF_) (pprCLabel clbl) <+> lbrace,
104            nest 8 temp_decls,
105            nest 8 mkFB_,
106            nest 8 (vcat (map pprStmt stmts)) $$
107               vcat (map pprBBlock rest),
108            nest 8 mkFE_,
109            rbrace ]
110     )
111   where
112         (temp_decls, extern_decls) = pprTempAndExternDecls blocks 
113
114
115 -- Chunks of static data.
116
117 -- We only handle (a) arrays of word-sized things and (b) strings.
118
119 pprTop (CmmData _section _ds@[CmmDataLabel lbl, CmmString str]) = 
120   hcat [
121     pprLocalness lbl, ptext SLIT("char "), pprCLabel lbl,
122     ptext SLIT("[] = "), pprStringInCStyle str, semi
123   ]
124
125 pprTop (CmmData _section _ds@[CmmDataLabel lbl, CmmUninitialised size]) = 
126   hcat [
127     pprLocalness lbl, ptext SLIT("char "), pprCLabel lbl,
128     brackets (int size), semi
129   ]
130
131 pprTop top@(CmmData _section (CmmDataLabel lbl : lits)) = 
132   pprDataExterns lits $$
133   pprWordArray lbl lits  
134
135 -- these shouldn't appear?
136 pprTop (CmmData _ _) = panic "PprC.pprTop: can't handle this data"
137
138
139 -- --------------------------------------------------------------------------
140 -- BasicBlocks are self-contained entities: they always end in a jump.
141 --
142 -- Like nativeGen/AsmCodeGen, we could probably reorder blocks to turn
143 -- as many jumps as possible into fall throughs.
144 --
145
146 pprBBlock :: CmmBasicBlock -> SDoc
147 pprBBlock (BasicBlock lbl stmts) = 
148     if null stmts then
149         pprTrace "pprC.pprBBlock: curious empty code block for" 
150                         (pprBlockId lbl) empty
151     else 
152         nest 4 (pprBlockId lbl <> colon) $$
153         nest 8 (vcat (map pprStmt stmts))
154
155 -- --------------------------------------------------------------------------
156 -- Info tables. Just arrays of words. 
157 -- See codeGen/ClosureInfo, and nativeGen/PprMach
158
159 pprWordArray :: CLabel -> [CmmStatic] -> SDoc
160 pprWordArray lbl ds
161   = hcat [ pprLocalness lbl, ptext SLIT("StgWord")
162          , space, pprCLabel lbl, ptext SLIT("[] = {") ] 
163     $$ nest 8 (commafy (pprStatics ds))
164     $$ ptext SLIT("};")
165
166 --
167 -- has to be static, if it isn't globally visible
168 --
169 pprLocalness :: CLabel -> SDoc
170 pprLocalness lbl | not $ externallyVisibleCLabel lbl = ptext SLIT("static ")
171                  | otherwise = empty
172
173 -- --------------------------------------------------------------------------
174 -- Statements.
175 --
176
177 pprStmt :: CmmStmt -> SDoc
178
179 pprStmt stmt = case stmt of
180     CmmNop       -> empty
181     CmmComment s -> (hang (ptext SLIT("/*")) 3 (ftext s)) $$ ptext SLIT("*/")
182
183     CmmAssign dest src -> pprAssign dest src
184
185     CmmStore  dest src
186         | rep == I64 && wordRep /= I64
187         -> ptext SLIT("ASSIGN_Word64") <> 
188                 parens (mkP_ <> pprExpr1 dest <> comma <> pprExpr src) <> semi
189
190         | rep == F64 && wordRep /= I64
191         -> ptext SLIT("ASSIGN_DBL") <> 
192                 parens (mkP_ <> pprExpr1 dest <> comma <> pprExpr src) <> semi
193
194         | otherwise
195         -> hsep [ pprExpr (CmmLoad dest rep), equals, pprExpr src <> semi ]
196         where
197           rep = cmmExprRep src
198
199     CmmCall (CmmForeignCall fn cconv) results args volatile -> 
200         -- Controversial: leave this out for now.
201         -- pprUndef fn $$
202
203         pprCall ppr_fn cconv results args volatile
204         where
205         ppr_fn = case fn of
206                    CmmLit (CmmLabel lbl) -> pprCLabel lbl
207                    _other -> parens (cCast (pprCFunType cconv results args) fn)
208                         -- for a dynamic call, cast the expression to
209                         -- a function of the right type (we hope).
210
211         -- we #undef a function before calling it: the FFI is supposed to be
212         -- an interface specifically to C, not to C+CPP.  For one thing, this
213         -- makes the via-C route more compatible with the NCG.  If macros
214         -- are being used for optimisation, then inline functions are probably
215         -- better anyway.
216         pprUndef (CmmLit (CmmLabel lbl)) = 
217            ptext SLIT("#undef") <+> pprCLabel lbl
218         pprUndef _ = empty
219
220     CmmCall (CmmPrim op) results args volatile -> 
221         pprCall ppr_fn CCallConv results args volatile
222         where
223         ppr_fn = pprCallishMachOp_for_C op
224
225     CmmBranch ident          -> pprBranch ident
226     CmmCondBranch expr ident -> pprCondBranch expr ident
227     CmmJump lbl _params      -> mkJMP_(pprExpr lbl) <> semi
228     CmmSwitch arg ids        -> pprSwitch arg ids
229
230 pprCFunType :: CCallConv -> [(CmmReg,MachHint)] -> [(CmmExpr,MachHint)] -> SDoc
231 pprCFunType cconv ress args
232   = hcat [
233         res_type ress,
234         parens (text (ccallConvAttribute cconv) <>  char '*'),
235         parens (commafy (map arg_type args))
236    ]
237   where
238         res_type [] = ptext SLIT("void")
239         res_type [(one,hint)] = machRepHintCType (cmmRegRep one) hint
240
241         arg_type (expr,hint) = machRepHintCType (cmmExprRep expr) hint
242
243 -- ---------------------------------------------------------------------
244 -- unconditional branches
245 pprBranch :: BlockId -> SDoc
246 pprBranch ident = ptext SLIT("goto") <+> pprBlockId ident <> semi
247
248
249 -- ---------------------------------------------------------------------
250 -- conditional branches to local labels
251 pprCondBranch :: CmmExpr -> BlockId -> SDoc
252 pprCondBranch expr ident 
253         = hsep [ ptext SLIT("if") , parens(pprExpr expr) ,
254                         ptext SLIT("goto") , (pprBlockId ident) <> semi ]
255
256
257 -- ---------------------------------------------------------------------
258 -- a local table branch
259 --
260 -- we find the fall-through cases
261 --
262 -- N.B. we remove Nothing's from the list of branches, as they are
263 -- 'undefined'. However, they may be defined one day, so we better
264 -- document this behaviour.
265 --
266 pprSwitch :: CmmExpr -> [ Maybe BlockId ] -> SDoc
267 pprSwitch e maybe_ids 
268   = let pairs  = [ (ix, ident) | (ix,Just ident) <- zip [0..] maybe_ids ]
269         pairs2 = [ (map fst as, snd (head as)) | as <- groupBy sndEq pairs ]
270     in 
271         (hang (ptext SLIT("switch") <+> parens ( pprExpr e ) <+> lbrace)
272                 4 (vcat ( map caseify pairs2 )))
273         $$ rbrace
274
275   where
276     sndEq (_,x) (_,y) = x == y
277
278     -- fall through case
279     caseify (ix:ixs, ident) = vcat (map do_fallthrough ixs) $$ final_branch ix
280         where 
281         do_fallthrough ix =
282                  hsep [ ptext SLIT("case") , pprHexVal ix wordRep <> colon ,
283                         ptext SLIT("/* fall through */") ]
284
285         final_branch ix = 
286                 hsep [ ptext SLIT("case") , pprHexVal ix wordRep <> colon ,
287                        ptext SLIT("goto") , (pprBlockId ident) <> semi ]
288
289 -- ---------------------------------------------------------------------
290 -- Expressions.
291 --
292
293 -- C Types: the invariant is that the C expression generated by
294 --
295 --      pprExpr e
296 --
297 -- has a type in C which is also given by
298 --
299 --      machRepCType (cmmExprRep e)
300 --
301 -- (similar invariants apply to the rest of the pretty printer).
302
303 pprExpr :: CmmExpr -> SDoc
304 pprExpr e = case e of
305     CmmLit lit -> pprLit lit
306
307     CmmLoad e I64 | wordRep /= I64
308         -> ptext SLIT("PK_Word64") <> parens (mkP_ <> pprExpr1 e)
309
310     CmmLoad e F64 | wordRep /= I64
311         -> ptext SLIT("PK_DBL") <> parens (mkP_ <> pprExpr1 e)
312
313     CmmLoad (CmmReg r) rep 
314         | isPtrReg r && rep == wordRep
315         -> char '*' <> pprAsPtrReg r
316
317     CmmLoad (CmmRegOff r 0) rep 
318         | isPtrReg r && rep == wordRep
319         -> char '*' <> pprAsPtrReg r
320
321     CmmLoad (CmmRegOff r off) rep
322         | isPtrReg r && rep == wordRep 
323         -- ToDo: check that the offset is a word multiple?
324         -> pprAsPtrReg r <> brackets (ppr (off `shiftR` wordShift))
325
326     CmmLoad expr rep ->
327         -- the general case:
328         char '*' <> parens (cCast (machRepPtrCType rep) expr)
329
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 pprExpr1 :: CmmExpr -> SDoc
342 pprExpr1 (CmmLit lit)     = pprLit1 lit
343 pprExpr1 e@(CmmReg _reg)  = pprExpr e
344 pprExpr1 other            = parens (pprExpr other)
345
346 -- --------------------------------------------------------------------------
347 -- MachOp applications
348
349 pprMachOpApp :: MachOp -> [CmmExpr] -> SDoc
350
351 pprMachOpApp op args
352   | isMulMayOfloOp op
353   = ptext SLIT("mulIntMayOflo") <> parens (commafy (map pprExpr args))
354   where isMulMayOfloOp (MO_U_MulMayOflo _) = True
355         isMulMayOfloOp (MO_S_MulMayOflo _) = True
356         isMulMayOfloOp _ = False
357
358 pprMachOpApp mop args
359   | Just ty <- machOpNeedsCast mop 
360   = ty <> parens (pprMachOpApp' mop args)
361   | otherwise
362   = pprMachOpApp' mop args
363
364 -- Comparisons in C have type 'int', but we want type W_ (this is what
365 -- resultRepOfMachOp says).  The other C operations inherit their type
366 -- from their operands, so no casting is required.
367 machOpNeedsCast :: MachOp -> Maybe SDoc
368 machOpNeedsCast mop
369   | isComparisonMachOp mop = Just mkW_
370   | otherwise              = Nothing
371
372 pprMachOpApp' mop args
373  = case args of
374     -- dyadic
375     [x,y] -> pprArg x <+> pprMachOp_for_C mop <+> pprArg y
376
377     -- unary
378     [x]   -> pprMachOp_for_C mop <> parens (pprArg x)
379
380     _     -> panic "PprC.pprMachOp : machop with wrong number of args"
381
382   where
383     pprArg e | signedOp mop = cCast (machRepSignedCType (cmmExprRep e)) e
384              | otherwise    = pprExpr1 e
385
386 -- --------------------------------------------------------------------------
387 -- Literals
388
389 pprLit :: CmmLit -> SDoc
390 pprLit lit = case lit of
391     CmmInt i rep      -> pprHexVal i rep
392     CmmFloat f rep     -> parens (machRepCType rep) <> (rational f)
393     CmmLabel clbl      -> mkW_ <> pprCLabelAddr clbl
394     CmmLabelOff clbl i -> mkW_ <> pprCLabelAddr clbl <> char '+' <> int i
395     CmmLabelDiffOff clbl1 clbl2 i
396         -- WARNING:
397         --  * the lit must occur in the info table clbl2
398         --  * clbl1 must be an SRT, a slow entry point or a large bitmap
399         -- The Mangler is expected to convert any reference to an SRT,
400         -- a slow entry point or a large bitmap
401         -- from an info table to an offset.
402         -> mkW_ <> pprCLabelAddr clbl1 <> char '+' <> int i
403
404 pprCLabelAddr lbl = char '&' <> pprCLabel lbl
405
406 pprLit1 :: CmmLit -> SDoc
407 pprLit1 lit@(CmmLabelOff _ _) = parens (pprLit lit)
408 pprLit1 lit@(CmmLabelDiffOff _ _ _) = parens (pprLit lit)
409 pprLit1 lit@(CmmFloat _ _)    = parens (pprLit lit)
410 pprLit1 other = pprLit other
411
412 -- ---------------------------------------------------------------------------
413 -- Static data
414
415 pprStatics :: [CmmStatic] -> [SDoc]
416 pprStatics [] = []
417 pprStatics (CmmStaticLit (CmmFloat f F32) : rest) 
418   = pprLit1 (floatToWord f) : pprStatics rest
419 pprStatics (CmmStaticLit (CmmFloat f F64) : rest)
420   = map pprLit1 (doubleToWords f) ++ pprStatics rest
421 pprStatics (CmmStaticLit (CmmInt i I64) : rest)
422   | machRepByteWidth I32 == wORD_SIZE
423 #ifdef WORDS_BIGENDIAN
424   = pprStatics (CmmStaticLit (CmmInt q I32) : 
425                 CmmStaticLit (CmmInt r I32) : rest)
426 #else
427   = pprStatics (CmmStaticLit (CmmInt r I32) : 
428                 CmmStaticLit (CmmInt q I32) : rest)
429 #endif
430   where r = i .&. 0xffffffff
431         q = i `shiftR` 32
432 pprStatics (CmmStaticLit lit : rest)
433   = pprLit1 lit : pprStatics rest
434 pprStatics (other : rest)
435   = pprPanic "pprWord" (pprStatic other)
436
437 pprStatic :: CmmStatic -> SDoc
438 pprStatic s = case s of
439
440     CmmStaticLit lit   -> nest 4 (pprLit lit)
441     CmmAlign i         -> nest 4 (ptext SLIT("/* align */") <+> int i)
442     CmmDataLabel clbl  -> pprCLabel clbl <> colon
443     CmmUninitialised i -> nest 4 (mkC_ <> brackets (int i))
444
445     -- these should be inlined, like the old .hc
446     CmmString s'       -> nest 4 (mkW_ <> parens(pprStringInCStyle s'))
447
448
449 -- ---------------------------------------------------------------------------
450 -- Block Ids
451
452 pprBlockId :: BlockId -> SDoc
453 pprBlockId b = char '_' <> ppr (getUnique b)
454
455 -- --------------------------------------------------------------------------
456 -- Print a MachOp in a way suitable for emitting via C.
457 --
458
459 pprMachOp_for_C :: MachOp -> SDoc
460
461 pprMachOp_for_C mop = case mop of 
462
463         -- Integer operations
464         MO_Add          _ -> char '+'
465         MO_Sub          _ -> char '-'
466         MO_Eq           _ -> ptext SLIT("==")
467         MO_Ne           _ -> ptext SLIT("!=")
468         MO_Mul          _ -> char '*'
469
470         MO_S_Quot       _ -> char '/'
471         MO_S_Rem        _ -> char '%'
472         MO_S_Neg        _ -> char '-'
473
474         MO_U_Quot       _ -> char '/'
475         MO_U_Rem        _ -> char '%'
476
477         -- Signed comparisons (floating-point comparisons also use these)
478         -- & Unsigned comparisons
479         MO_S_Ge         _ -> ptext SLIT(">=")
480         MO_S_Le         _ -> ptext SLIT("<=")
481         MO_S_Gt         _ -> char '>'
482         MO_S_Lt         _ -> char '<'
483
484         MO_U_Ge         _ -> ptext SLIT(">=")
485         MO_U_Le         _ -> ptext SLIT("<=")
486         MO_U_Gt         _ -> char '>'
487         MO_U_Lt         _ -> char '<'
488
489         -- Bitwise operations.  Not all of these may be supported at all
490         -- sizes, and only integral MachReps are valid.
491         MO_And          _ -> char '&'
492         MO_Or           _ -> char '|'
493         MO_Xor          _ -> char '^'
494         MO_Not          _ -> char '~'
495         MO_Shl          _ -> ptext SLIT("<<")
496         MO_U_Shr        _ -> ptext SLIT(">>") -- unsigned shift right
497         MO_S_Shr        _ -> ptext SLIT(">>") -- signed shift right
498
499 -- Conversions.  Some of these will be NOPs.
500 -- Floating-point conversions use the signed variant.
501 -- We won't know to generate (void*) casts here, but maybe from
502 -- context elsewhere
503
504 -- noop casts
505         MO_U_Conv I8 I8     -> empty
506         MO_U_Conv I16 I16   -> empty
507         MO_U_Conv I32 I32   -> empty
508         MO_U_Conv I64 I64   -> empty
509         MO_U_Conv I128 I128 -> empty
510         MO_S_Conv I8 I8     -> empty
511         MO_S_Conv I16 I16   -> empty
512         MO_S_Conv I32 I32   -> empty
513         MO_S_Conv I64 I64   -> empty
514         MO_S_Conv I128 I128 -> empty
515
516         MO_U_Conv _from to  -> parens (machRepCType to)
517         MO_S_Conv _from to  -> parens (machRepSignedCType to)
518
519         _ -> panic "PprC.pprMachOp_for_C: unknown machop"
520
521 signedOp :: MachOp -> Bool
522 signedOp (MO_S_Quot _)   = True
523 signedOp (MO_S_Rem  _)   = True
524 signedOp (MO_S_Neg  _)   = True
525 signedOp (MO_S_Ge   _)   = True
526 signedOp (MO_S_Le   _)   = True
527 signedOp (MO_S_Gt   _)   = True
528 signedOp (MO_S_Lt   _)   = True
529 signedOp (MO_S_Shr  _)   = True
530 signedOp (MO_S_Conv _ _) = True
531 signedOp _ = False
532
533 -- ---------------------------------------------------------------------
534 -- tend to be implemented by foreign calls
535
536 pprCallishMachOp_for_C :: CallishMachOp -> SDoc
537
538 pprCallishMachOp_for_C mop 
539     = case mop of
540         MO_F64_Pwr  -> ptext SLIT("pow")
541         MO_F64_Sin  -> ptext SLIT("sin")
542         MO_F64_Cos  -> ptext SLIT("cos")
543         MO_F64_Tan  -> ptext SLIT("tan")
544         MO_F64_Sinh -> ptext SLIT("sinh")
545         MO_F64_Cosh -> ptext SLIT("cosh")
546         MO_F64_Tanh -> ptext SLIT("tanh")
547         MO_F64_Asin -> ptext SLIT("asin")
548         MO_F64_Acos -> ptext SLIT("acos")
549         MO_F64_Atan -> ptext SLIT("atan")
550         MO_F64_Log  -> ptext SLIT("log")
551         MO_F64_Exp  -> ptext SLIT("exp")
552         MO_F64_Sqrt -> ptext SLIT("sqrt")
553         MO_F32_Pwr  -> ptext SLIT("powf")
554         MO_F32_Sin  -> ptext SLIT("sinf")
555         MO_F32_Cos  -> ptext SLIT("cosf")
556         MO_F32_Tan  -> ptext SLIT("tanf")
557         MO_F32_Sinh -> ptext SLIT("sinhf")
558         MO_F32_Cosh -> ptext SLIT("coshf")
559         MO_F32_Tanh -> ptext SLIT("tanhf")
560         MO_F32_Asin -> ptext SLIT("asinf")
561         MO_F32_Acos -> ptext SLIT("acosf")
562         MO_F32_Atan -> ptext SLIT("atanf")
563         MO_F32_Log  -> ptext SLIT("logf")
564         MO_F32_Exp  -> ptext SLIT("expf")
565         MO_F32_Sqrt -> ptext SLIT("sqrtf")
566         MO_WriteBarrier -> ptext SLIT("write_barrier")
567
568 -- ---------------------------------------------------------------------
569 -- Useful #defines
570 --
571
572 mkJMP_, mkFN_, mkIF_ :: SDoc -> SDoc
573
574 mkJMP_ i = ptext SLIT("JMP_") <> parens i
575 mkFN_  i = ptext SLIT("FN_")  <> parens i -- externally visible function
576 mkIF_  i = ptext SLIT("IF_")  <> parens i -- locally visible
577
578
579 mkFB_, mkFE_ :: SDoc
580 mkFB_ = ptext SLIT("FB_") -- function code begin
581 mkFE_ = ptext SLIT("FE_") -- function code end
582
583 -- from includes/Stg.h
584 --
585 mkC_,mkW_,mkP_,mkPP_,mkI_,mkA_,mkD_,mkF_,mkB_,mkL_,mkLI_,mkLW_ :: SDoc
586
587 mkC_  = ptext SLIT("(C_)")        -- StgChar
588 mkW_  = ptext SLIT("(W_)")        -- StgWord
589 mkP_  = ptext SLIT("(P_)")        -- StgWord*
590 mkPP_ = ptext SLIT("(PP_)")       -- P_*
591 mkI_  = ptext SLIT("(I_)")        -- StgInt
592 mkA_  = ptext SLIT("(A_)")        -- StgAddr
593 mkD_  = ptext SLIT("(D_)")        -- const StgWord*
594 mkF_  = ptext SLIT("(F_)")        -- StgFunPtr
595 mkB_  = ptext SLIT("(B_)")        -- StgByteArray
596 mkL_  = ptext SLIT("(L_)")        -- StgClosurePtr
597
598 mkLI_ = ptext SLIT("(LI_)")       -- StgInt64
599 mkLW_ = ptext SLIT("(LW_)")       -- StgWord64
600
601
602 -- ---------------------------------------------------------------------
603 --
604 -- Assignments
605 --
606 -- Generating assignments is what we're all about, here
607 --
608 pprAssign :: CmmReg -> CmmExpr -> SDoc
609
610 -- dest is a reg, rhs is a reg
611 pprAssign r1 (CmmReg r2)
612    | not (isStrangeTypeReg r1) && not (isStrangeTypeReg r2)
613    || isPtrReg r1 && isPtrReg r2
614    = hcat [ pprAsPtrReg r1, equals, pprAsPtrReg r2, semi ]
615
616 -- dest is a reg, rhs is a CmmRegOff
617 pprAssign r1 (CmmRegOff r2 off)
618    | not (isStrangeTypeReg r1) && not (isStrangeTypeReg r2)
619    || isPtrReg r1 && isPtrReg r2
620    = hcat [ pprAsPtrReg r1, equals, pprAsPtrReg r2, op, int off', semi ]
621   where
622         off1 | isPtrReg r2 = off `shiftR` wordShift
623              | otherwise   = off
624
625         (op,off') | off >= 0  = (char '+', off1)
626                   | otherwise = (char '-', -off1)
627
628 -- dest is a reg, rhs is anything.
629 -- We can't cast the lvalue, so we have to cast the rhs if necessary.  Casting
630 -- the lvalue elicits a warning from new GCC versions (3.4+).
631 pprAssign r1 r2
632   | isPtrReg r1
633   = pprAsPtrReg r1 <> ptext SLIT(" = ") <> mkP_ <> pprExpr1 r2 <> semi
634   | Just ty <- strangeRegType r1
635   = pprReg r1 <> ptext SLIT(" = ") <> parens ty <> pprExpr1 r2 <> semi
636   | otherwise
637   = pprReg r1 <> ptext SLIT(" = ") <> pprExpr r2 <> semi
638
639 -- ---------------------------------------------------------------------
640 -- Registers
641
642 pprCastReg reg
643    | isStrangeTypeReg reg = mkW_ <> pprReg reg
644    | otherwise            = pprReg reg
645
646 -- True if the register has type StgPtr in C, otherwise it has an
647 -- integer type.  We need to take care with pointer arithmetic on registers
648 -- with type StgPtr.
649 isPtrReg :: CmmReg -> Bool
650 isPtrReg (CmmLocal _) = False
651 isPtrReg (CmmGlobal r) = isPtrGlobalReg r
652
653 isPtrGlobalReg :: GlobalReg -> Bool
654 isPtrGlobalReg (VanillaReg n)   = True
655 isPtrGlobalReg Sp               = True
656 isPtrGlobalReg Hp               = True
657 isPtrGlobalReg HpLim            = True
658 isPtrGlobalReg SpLim            = True
659 isPtrGlobalReg _                = False
660
661 -- True if in C this register doesn't have the type given by 
662 -- (machRepCType (cmmRegRep reg)), so it has to be cast.
663 isStrangeTypeReg :: CmmReg -> Bool
664 isStrangeTypeReg (CmmLocal _)   = False
665 isStrangeTypeReg (CmmGlobal g)  = isStrangeTypeGlobal g
666
667 isStrangeTypeGlobal :: GlobalReg -> Bool
668 isStrangeTypeGlobal CurrentTSO          = True
669 isStrangeTypeGlobal CurrentNursery      = True
670 isStrangeTypeGlobal BaseReg             = True
671 isStrangeTypeGlobal r                   = isPtrGlobalReg r
672
673 strangeRegType :: CmmReg -> Maybe SDoc
674 strangeRegType (CmmGlobal CurrentTSO) = Just (ptext SLIT("struct StgTSO_ *"))
675 strangeRegType (CmmGlobal CurrentNursery) = Just (ptext SLIT("struct bdescr_ *"))
676 strangeRegType (CmmGlobal BaseReg) = Just (ptext SLIT("struct StgRegTable_ *"))
677 strangeRegType _ = Nothing
678
679 -- pprReg just prints the register name.
680 --
681 pprReg :: CmmReg -> SDoc
682 pprReg r = case r of
683         CmmLocal  local  -> pprLocalReg local
684         CmmGlobal global -> pprGlobalReg global
685                 
686 pprAsPtrReg :: CmmReg -> SDoc
687 pprAsPtrReg (CmmGlobal (VanillaReg n)) = char 'R' <> int n <> ptext SLIT(".p")
688 pprAsPtrReg other_reg = pprReg other_reg
689
690 pprGlobalReg :: GlobalReg -> SDoc
691 pprGlobalReg gr = case gr of
692     VanillaReg n   -> char 'R' <> int n  <> ptext SLIT(".w")
693     FloatReg   n   -> char 'F' <> int n
694     DoubleReg  n   -> char 'D' <> int n
695     LongReg    n   -> char 'L' <> int n
696     Sp             -> ptext SLIT("Sp")
697     SpLim          -> ptext SLIT("SpLim")
698     Hp             -> ptext SLIT("Hp")
699     HpLim          -> ptext SLIT("HpLim")
700     CurrentTSO     -> ptext SLIT("CurrentTSO")
701     CurrentNursery -> ptext SLIT("CurrentNursery")
702     HpAlloc        -> ptext SLIT("HpAlloc")
703     BaseReg        -> ptext SLIT("BaseReg")
704     GCEnter1       -> ptext SLIT("stg_gc_enter_1")
705     GCFun          -> ptext SLIT("stg_gc_fun")
706
707 pprLocalReg :: LocalReg -> SDoc
708 pprLocalReg (LocalReg uniq _rep) = char '_' <> ppr uniq
709
710 -- -----------------------------------------------------------------------------
711 -- Foreign Calls
712
713 pprCall :: SDoc -> CCallConv -> [(CmmReg,MachHint)] -> [(CmmExpr,MachHint)]
714         -> Maybe [GlobalReg] -> SDoc
715
716 pprCall ppr_fn cconv results args vols
717   | not (is_cish cconv)
718   = panic "pprCall: unknown calling convention"
719
720   | otherwise
721   = save vols $$
722     ptext SLIT("CALLER_SAVE_SYSTEM") $$
723 #if x86_64_TARGET_ARCH
724         -- HACK around gcc optimisations.
725         -- x86_64 needs a __DISCARD__() here, to create a barrier between
726         -- putting the arguments into temporaries and passing the arguments
727         -- to the callee, because the argument expressions may refer to
728         -- machine registers that are also used for passing arguments in the
729         -- C calling convention.
730     (if (not opt_Unregisterised) 
731         then ptext SLIT("__DISCARD__();") 
732         else empty) $$
733 #endif
734     ppr_assign results (ppr_fn <> parens (commafy (map pprArg args))) <> semi $$
735     ptext SLIT("CALLER_RESTORE_SYSTEM") $$
736     restore vols
737   where 
738      ppr_assign []           rhs = rhs
739      ppr_assign [(reg@(CmmGlobal BaseReg), hint)] rhs
740          | Just ty <- strangeRegType reg
741          = ptext SLIT("ASSIGN_BaseReg") <> parens (parens ty <> rhs)
742          -- BaseReg is special, sometimes it isn't an lvalue and we
743          -- can't assign to it.
744      ppr_assign [(one,hint)] rhs
745          | Just ty <- strangeRegType one
746          = pprReg one <> ptext SLIT(" = ") <> parens ty <> rhs
747          | otherwise
748          = pprReg one <> ptext SLIT(" = ")
749                  <> pprUnHint hint (cmmRegRep one) <> rhs
750      ppr_assign _other _rhs = panic "pprCall: multiple results"
751
752      pprArg (expr, PtrHint)
753         = cCast (ptext SLIT("void *")) expr
754         -- see comment by machRepHintCType below
755      pprArg (expr, SignedHint)
756         = cCast (machRepSignedCType (cmmExprRep expr)) expr
757      pprArg (expr, _other)
758         = pprExpr expr
759
760      pprUnHint PtrHint    rep = parens (machRepCType rep)
761      pprUnHint SignedHint rep = parens (machRepCType rep)
762      pprUnHint _          _   = empty
763
764      save    = save_restore SLIT("CALLER_SAVE")
765      restore = save_restore SLIT("CALLER_RESTORE")
766
767         -- Nothing says "I don't know what's live; save everything"
768         -- CALLER_SAVE_USER is defined in ghc/includes/Regs.h
769      save_restore txt Nothing     = ptext txt <> ptext SLIT("_USER")
770      save_restore txt (Just these) = vcat (map saveRestoreGlobal these)
771         where saveRestoreGlobal r = ptext txt <> char '_' <> pprGlobalRegName r
772
773 pprGlobalRegName :: GlobalReg -> SDoc
774 pprGlobalRegName gr = case gr of
775     VanillaReg n   -> char 'R' <> int n  -- without the .w suffix
776     _              -> pprGlobalReg gr
777
778 -- Currently we only have these two calling conventions, but this might
779 -- change in the future...
780 is_cish CCallConv   = True
781 is_cish StdCallConv = True
782
783 -- ---------------------------------------------------------------------
784 -- Find and print local and external declarations for a list of
785 -- Cmm statements.
786 -- 
787 pprTempAndExternDecls :: [CmmBasicBlock] -> (SDoc{-temps-}, SDoc{-externs-})
788 pprTempAndExternDecls stmts 
789   = (vcat (map pprTempDecl (eltsUFM temps)), 
790      vcat (map (pprExternDecl False{-ToDo-}) (keysFM lbls)))
791   where (temps, lbls) = runTE (mapM_ te_BB stmts)
792
793 pprDataExterns :: [CmmStatic] -> SDoc
794 pprDataExterns statics
795   = vcat (map (pprExternDecl False{-ToDo-}) (keysFM lbls))
796   where (_, lbls) = runTE (mapM_ te_Static statics)
797
798 pprTempDecl :: LocalReg -> SDoc
799 pprTempDecl l@(LocalReg _uniq rep)
800   = hcat [ machRepCType rep, space, pprLocalReg l, semi ]
801
802 pprExternDecl :: Bool -> CLabel -> SDoc
803 pprExternDecl in_srt lbl
804   -- do not print anything for "known external" things
805   | not (needsCDecl lbl) = empty
806   | otherwise               = 
807         hcat [ visibility, label_type (labelType lbl), 
808                lparen, dyn_wrapper (pprCLabel lbl), text ");" ]
809  where
810   dyn_wrapper d
811     | in_srt && labelDynamic lbl = text "DLL_IMPORT_DATA_VAR" <> parens d
812     | otherwise                  = d
813
814   label_type CodeLabel = ptext SLIT("F_")
815   label_type DataLabel = ptext SLIT("I_")
816
817   visibility
818      | externallyVisibleCLabel lbl = char 'E'
819      | otherwise                   = char 'I'
820
821
822 type TEState = (UniqSet LocalReg, FiniteMap CLabel ())
823 newtype TE a = TE { unTE :: TEState -> (a, TEState) }
824
825 instance Monad TE where
826    TE m >>= k  = TE $ \s -> case m s of (a, s') -> unTE (k a) s'
827    return a    = TE $ \s -> (a, s)
828
829 te_lbl :: CLabel -> TE ()
830 te_lbl lbl = TE $ \(temps,lbls) -> ((), (temps, addToFM lbls lbl ()))
831
832 te_temp :: LocalReg -> TE ()
833 te_temp r = TE $ \(temps,lbls) -> ((), (addOneToUniqSet temps r, lbls))
834
835 runTE :: TE () -> TEState
836 runTE (TE m) = snd (m (emptyUniqSet, emptyFM))
837
838 te_Static :: CmmStatic -> TE ()
839 te_Static (CmmStaticLit lit) = te_Lit lit
840 te_Static _ = return ()
841
842 te_BB :: CmmBasicBlock -> TE ()
843 te_BB (BasicBlock _ ss)         = mapM_ te_Stmt ss
844
845 te_Lit :: CmmLit -> TE ()
846 te_Lit (CmmLabel l) = te_lbl l
847 te_Lit (CmmLabelOff l _) = te_lbl l
848 te_Lit (CmmLabelDiffOff l1 l2 _) = te_lbl l1
849 te_Lit _ = return ()
850
851 te_Stmt :: CmmStmt -> TE ()
852 te_Stmt (CmmAssign r e)         = te_Reg r >> te_Expr e
853 te_Stmt (CmmStore l r)          = te_Expr l >> te_Expr r
854 te_Stmt (CmmCall _ rs es _)     = mapM_ (te_Reg.fst) rs >>
855                                   mapM_ (te_Expr.fst) es
856 te_Stmt (CmmCondBranch e _)     = te_Expr e
857 te_Stmt (CmmSwitch e _)         = te_Expr e
858 te_Stmt (CmmJump e _)           = te_Expr e
859 te_Stmt _                       = return ()
860
861 te_Expr :: CmmExpr -> TE ()
862 te_Expr (CmmLit lit)            = te_Lit lit
863 te_Expr (CmmLoad e _)           = te_Expr e
864 te_Expr (CmmReg r)              = te_Reg r
865 te_Expr (CmmMachOp _ es)        = mapM_ te_Expr es
866 te_Expr (CmmRegOff r _)         = te_Reg r
867
868 te_Reg :: CmmReg -> TE ()
869 te_Reg (CmmLocal l) = te_temp l
870 te_Reg _            = return ()
871
872
873 -- ---------------------------------------------------------------------
874 -- C types for MachReps
875
876 cCast :: SDoc -> CmmExpr -> SDoc
877 cCast ty expr = parens ty <> pprExpr1 expr
878
879 -- This is for finding the types of foreign call arguments.  For a pointer
880 -- argument, we always cast the argument to (void *), to avoid warnings from
881 -- the C compiler.
882 machRepHintCType :: MachRep -> MachHint -> SDoc
883 machRepHintCType rep PtrHint    = ptext SLIT("void *")
884 machRepHintCType rep SignedHint = machRepSignedCType rep
885 machRepHintCType rep _other     = machRepCType rep
886
887 machRepPtrCType :: MachRep -> SDoc
888 machRepPtrCType r | r == wordRep = ptext SLIT("P_")
889                   | otherwise    = machRepCType r <> char '*'
890
891 machRepCType :: MachRep -> SDoc
892 machRepCType r | r == wordRep = ptext SLIT("W_")
893                | otherwise    = sized_type
894   where sized_type = case r of
895                         I8      -> ptext SLIT("StgWord8")
896                         I16     -> ptext SLIT("StgWord16")
897                         I32     -> ptext SLIT("StgWord32")
898                         I64     -> ptext SLIT("StgWord64")
899                         F32     -> ptext SLIT("StgFloat") -- ToDo: correct?
900                         F64     -> ptext SLIT("StgDouble")
901                         _  -> panic "machRepCType"
902
903 machRepSignedCType :: MachRep -> SDoc
904 machRepSignedCType r | r == wordRep = ptext SLIT("I_")
905                      | otherwise    = sized_type
906   where sized_type = case r of
907                         I8      -> ptext SLIT("StgInt8")
908                         I16     -> ptext SLIT("StgInt16")
909                         I32     -> ptext SLIT("StgInt32")
910                         I64     -> ptext SLIT("StgInt64")
911                         F32     -> ptext SLIT("StgFloat") -- ToDo: correct?
912                         F64     -> ptext SLIT("StgDouble")
913                         _ -> panic "machRepCType"
914
915 -- ---------------------------------------------------------------------
916 -- print strings as valid C strings
917
918 pprStringInCStyle :: [Word8] -> SDoc
919 pprStringInCStyle s = doubleQuotes (text (concatMap charToC s))
920
921 charToC :: Word8 -> String
922 charToC w = 
923   case chr (fromIntegral w) of
924         '\"' -> "\\\""
925         '\'' -> "\\\'"
926         '\\' -> "\\\\"
927         c | c >= ' ' && c <= '~' -> [c]
928           | otherwise -> ['\\',
929                          chr (ord '0' + ord c `div` 64),
930                          chr (ord '0' + ord c `div` 8 `mod` 8),
931                          chr (ord '0' + ord c         `mod` 8)]
932
933 -- ---------------------------------------------------------------------------
934 -- Initialising static objects with floating-point numbers.  We can't
935 -- just emit the floating point number, because C will cast it to an int
936 -- by rounding it.  We want the actual bit-representation of the float.
937
938 -- This is a hack to turn the floating point numbers into ints that we
939 -- can safely initialise to static locations.
940
941 big_doubles 
942   | machRepByteWidth F64 == 2 * wORD_SIZE  = True
943   | machRepByteWidth F64 == wORD_SIZE      = False
944   | otherwise = panic "big_doubles"
945
946 #if __GLASGOW_HASKELL__ >= 504
947 newFloatArray :: (Int,Int) -> ST s (STUArray s Int Float)
948 newFloatArray = newArray_
949
950 newDoubleArray :: (Int,Int) -> ST s (STUArray s Int Double)
951 newDoubleArray = newArray_
952
953 castFloatToIntArray :: STUArray s Int Float -> ST s (STUArray s Int Int)
954 castFloatToIntArray = castSTUArray
955
956 castDoubleToIntArray :: STUArray s Int Double -> ST s (STUArray s Int Int)
957 castDoubleToIntArray = castSTUArray
958
959 writeFloatArray :: STUArray s Int Float -> Int -> Float -> ST s ()
960 writeFloatArray = writeArray
961
962 writeDoubleArray :: STUArray s Int Double -> Int -> Double -> ST s ()
963 writeDoubleArray = writeArray
964
965 readIntArray :: STUArray s Int Int -> Int -> ST s Int
966 readIntArray = readArray
967
968 #else
969
970 castFloatToIntArray :: MutableByteArray s t -> ST s (MutableByteArray s t)
971 castFloatToIntArray = return
972
973 castDoubleToIntArray :: MutableByteArray s t -> ST s (MutableByteArray s t)
974 castDoubleToIntArray = return
975
976 #endif
977
978 -- floats are always 1 word
979 floatToWord :: Rational -> CmmLit
980 floatToWord r
981   = runST (do
982         arr <- newFloatArray ((0::Int),0)
983         writeFloatArray arr 0 (fromRational r)
984         arr' <- castFloatToIntArray arr
985         i <- readIntArray arr' 0
986         return (CmmInt (toInteger i) wordRep)
987     )
988
989 doubleToWords :: Rational -> [CmmLit]
990 doubleToWords r
991   | big_doubles                         -- doubles are 2 words
992   = runST (do
993         arr <- newDoubleArray ((0::Int),1)
994         writeDoubleArray arr 0 (fromRational r)
995         arr' <- castDoubleToIntArray arr
996         i1 <- readIntArray arr' 0
997         i2 <- readIntArray arr' 1
998         return [ CmmInt (toInteger i1) wordRep
999                , CmmInt (toInteger i2) wordRep
1000                ]
1001     )
1002   | otherwise                           -- doubles are 1 word
1003   = runST (do
1004         arr <- newDoubleArray ((0::Int),0)
1005         writeDoubleArray arr 0 (fromRational r)
1006         arr' <- castDoubleToIntArray arr
1007         i <- readIntArray arr' 0
1008         return [ CmmInt (toInteger i) wordRep ]
1009     )
1010
1011 -- ---------------------------------------------------------------------------
1012 -- Utils
1013
1014 wordShift :: Int
1015 wordShift = machRepLogWidth wordRep
1016
1017 commafy :: [SDoc] -> SDoc
1018 commafy xs = hsep $ punctuate comma xs
1019
1020 -- Print in C hex format: 0x13fa
1021 pprHexVal :: Integer -> MachRep -> SDoc
1022 pprHexVal 0 _ = ptext SLIT("0x0")
1023 pprHexVal w rep
1024   | w < 0     = parens (char '-' <> ptext SLIT("0x") <> go (-w) <> repsuffix rep)
1025   | otherwise = ptext SLIT("0x") <> go w <> repsuffix rep
1026   where
1027         -- type suffix for literals:
1028         -- Integer literals are unsigned in Cmm/C.  We explicitly cast to
1029         -- signed values for doing signed operations, but at all other
1030         -- times values are unsigned.  This also helps eliminate occasional
1031         -- warnings about integer overflow from gcc.
1032
1033         -- on 32-bit platforms, add "ULL" to 64-bit literals
1034       repsuffix I64 | wORD_SIZE == 4 = ptext SLIT("ULL")
1035         -- on 64-bit platforms with 32-bit int, add "L" to 64-bit literals
1036       repsuffix I64 | cINT_SIZE == 4 = ptext SLIT("UL")
1037       repsuffix _ = char 'U'
1038       
1039       go 0 = empty
1040       go w' = go q <> dig
1041            where
1042              (q,r) = w' `quotRem` 16
1043              dig | r < 10    = char (chr (fromInteger r + ord '0'))
1044                  | otherwise = char (chr (fromInteger r - 10 + ord 'a'))
1045