0e627c451e4976adee73b02b12f6fa9fc7f05b24
[ghc-hetmet.git] / ghc / compiler / basicTypes / Const.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1998
3 %
4 \section[Literal]{@Literal@: Machine literals (unboxed, of course)}
5
6 \begin{code}
7 module Const (
8         Con(..),
9         conType, conPrimRep,
10         conOkForApp, conOkForAlt, isWHNFCon, isDataCon, isBoxedDataCon,
11         conIsTrivial, conIsCheap, conIsDupable, conStrictness, 
12         conOkForSpeculation, hashCon,
13
14         DataCon, PrimOp,        -- For completeness
15
16         -- Defined here
17         Literal(..),            -- Exported to ParseIface
18         mkMachInt, mkMachWord,
19         mkMachInt_safe, mkMachInt64, mkMachWord64,
20         mkStrLit,                       -- ToDo: rm (not used anywhere)
21         isNoRepLit, isLitLitLit,
22         literalType, literalPrimRep
23     ) where
24
25 #include "HsVersions.h"
26
27 import TysPrim          ( charPrimTy, addrPrimTy, floatPrimTy, doublePrimTy,
28                           intPrimTy, wordPrimTy, int64PrimTy, word64PrimTy
29                         )
30 import Name             ( hashName )
31 import PrimOp           ( PrimOp, primOpType, primOpIsDupable, primOpTag,
32                           primOpIsCheap, primOpStrictness, primOpOkForSpeculation )
33 import PrimRep          ( PrimRep(..) )
34 import DataCon          ( DataCon, dataConName, dataConType, dataConTyCon, 
35                           isNullaryDataCon, dataConRepStrictness, isUnboxedTupleCon
36                         )
37 import TyCon            ( isNewTyCon )
38 import Type             ( Type, typePrimRep )
39 import PprType          ( pprParendType )
40 import Demand           ( Demand )
41 import CStrings         ( stringToC, charToC, charToEasyHaskell )
42
43 import Outputable
44 import Util             ( thenCmp )
45
46 import Ratio            ( numerator, denominator )
47 import FastString       ( uniqueOfFS )
48 import Char             ( ord )
49
50 #if __GLASGOW_HASKELL__ >= 404
51 import GlaExts          ( fromInt )
52 #endif
53 \end{code}
54
55
56 %************************************************************************
57 %*                                                                      *
58 \subsection{The main data type}
59 %*                                                                      *
60 %************************************************************************
61
62 \begin{code}
63 data Con
64   = DataCon  DataCon
65   | Literal  Literal
66   | PrimOp   PrimOp
67   | DEFAULT                     -- Used in case clauses
68   deriving (Eq, Ord)
69
70 -- The Ord is needed for the FiniteMap used in the lookForConstructor
71 -- in SimplEnv.  If you declared that lookForConstructor *ignores*
72 -- constructor-applications with LitArg args, then you could get
73 -- rid of this Ord.
74
75 instance Outputable Con where
76   ppr (DataCon dc)  = ppr dc
77   ppr (Literal lit) = ppr lit
78   ppr (PrimOp op)   = ppr op
79   ppr DEFAULT       = ptext SLIT("__DEFAULT")
80
81 instance Show Con where
82   showsPrec p con = showsPrecSDoc p (ppr con)
83
84 conType :: Con -> Type
85 conType (DataCon dc)  = dataConType dc
86 conType (Literal lit) = literalType lit
87 conType (PrimOp op)   = primOpType op
88
89 conStrictness :: Con -> ([Demand], Bool)
90 conStrictness (DataCon dc)  = (dataConRepStrictness dc, False)
91 conStrictness (PrimOp op)   = primOpStrictness op
92 conStrictness (Literal lit) = ([], False)
93
94 conPrimRep :: Con -> PrimRep    -- Only data valued constants
95 conPrimRep (DataCon dc)  = ASSERT( isNullaryDataCon dc) PtrRep
96 conPrimRep (Literal lit) = literalPrimRep lit
97
98 conOkForApp, conOkForAlt :: Con -> Bool
99
100 -- OK for appliation site
101 conOkForApp (DataCon dc) = not (isNewTyCon (dataConTyCon dc))
102 conOkForApp (Literal _)  = True
103 conOkForApp (PrimOp op)  = True
104 conOkForApp DEFAULT      = False
105
106 -- OK for case alternative pattern
107 conOkForAlt (DataCon dc)  = not (isNewTyCon (dataConTyCon dc))
108 conOkForAlt (Literal lit) = not (isNoRepLit lit)
109 conOkForAlt (PrimOp _)    = False
110 conOkForAlt DEFAULT       = True
111
112         -- isWHNFCon is false for PrimOps, which contain work
113         -- Ditto for newtype constructors, which can occur in the output
114         -- of the desugarer, but which will be inlined right away thereafter
115 isWHNFCon (DataCon dc) = not (isNewTyCon (dataConTyCon dc))
116 isWHNFCon (Literal _)  = True
117 isWHNFCon (PrimOp _)   = False
118
119 isDataCon (DataCon dc) = True
120 isDataCon other        = False
121
122 isBoxedDataCon (DataCon dc) = not (isUnboxedTupleCon dc)
123 isBoxedDataCon other        = False
124
125 -- conIsTrivial is true for constants we are unconditionally happy to duplicate
126 -- cf CoreUtils.exprIsTrivial
127 conIsTrivial (Literal lit) = not (isNoRepLit lit)
128 conIsTrivial (PrimOp _)    = False
129 conIsTrivial con           = True
130
131 -- conIsCheap is true for constants whose applications we are willing
132 -- to duplicate in exchange for some modest gain.  cf CoreUtils.exprIsCheap
133 conIsCheap (Literal lit) = not (isNoRepLit lit)
134 conIsCheap (DataCon con) = True
135 conIsCheap (PrimOp op)   = primOpIsCheap op
136
137 -- conIsDupable is true for constants whose applications we are willing
138 -- to duplicate in different case branches; i.e no issue about loss of
139 -- work, just space
140 conIsDupable (Literal lit) = not (isNoRepLit lit)
141 conIsDupable (DataCon con) = True
142 conIsDupable (PrimOp op)   = primOpIsDupable op
143
144 -- Similarly conOkForSpeculation
145 conOkForSpeculation (Literal lit) = True
146 conOkForSpeculation (DataCon con) = True
147 conOkForSpeculation (PrimOp op)   = primOpOkForSpeculation op
148 \end{code}
149
150
151 %************************************************************************
152 %*                                                                      *
153 \subsection{Literals}
154 %*                                                                      *
155 %************************************************************************
156
157 So-called @Literals@ are {\em either}:
158 \begin{itemize}
159 \item
160 An unboxed (``machine'') literal (type: @IntPrim@, @FloatPrim@, etc.),
161 which is presumed to be surrounded by appropriate constructors
162 (@mKINT@, etc.), so that the overall thing makes sense.
163 \item
164 An Integer, Rational, or String literal whose representation we are
165 {\em uncommitted} about; i.e., the surrounding with constructors,
166 function applications, etc., etc., has not yet been done.
167 \end{itemize}
168
169 \begin{code}
170 data Literal
171   =     ------------------
172         -- First the primitive guys
173     MachChar    Char
174   | MachStr     FAST_STRING
175
176   | MachAddr    Integer -- Whatever this machine thinks is a "pointer"
177
178   | MachInt     Integer -- For the numeric types, these are
179                 Bool    -- True <=> signed (Int#); False <=> unsigned (Word#)
180
181   | MachInt64   Integer -- guaranteed 64-bit versions of the above.
182                 Bool    -- True <=> signed (Int#); False <=> unsigned (Word#)
183
184
185   | MachFloat   Rational
186   | MachDouble  Rational
187
188   | MachLitLit  FAST_STRING Type        -- Type might be Add# or Int# etc
189
190         ------------------
191         -- The no-rep guys
192   | NoRepStr        FAST_STRING Type    -- This Type is always String
193   | NoRepInteger    Integer     Type    -- This Type is always Integer
194   | NoRepRational   Rational    Type    -- This Type is always Rational
195                         -- We keep these Types in the literal because Rational isn't
196                         -- (currently) wired in, so we can't conjure up its type out of
197                         -- thin air.    Integer is, so the type here is really redundant.
198 \end{code}
199
200 \begin{code}
201 instance Outputable Literal where
202     ppr lit = pprLit lit
203
204 instance Show Literal where
205     showsPrec p lit = showsPrecSDoc p (ppr lit)
206
207 instance Eq Literal where
208     a == b = case (a `compare` b) of { EQ -> True;   _ -> False }
209     a /= b = case (a `compare` b) of { EQ -> False;  _ -> True  }
210
211 instance Ord Literal where
212     a <= b = case (a `compare` b) of { LT -> True;  EQ -> True;  GT -> False }
213     a <  b = case (a `compare` b) of { LT -> True;  EQ -> False; GT -> False }
214     a >= b = case (a `compare` b) of { LT -> False; EQ -> True;  GT -> True  }
215     a >  b = case (a `compare` b) of { LT -> False; EQ -> False; GT -> True  }
216     compare a b = cmpLit a b
217 \end{code}
218
219
220         Construction
221         ~~~~~~~~~~~~
222 \begin{code}
223 mkMachInt, mkMachWord :: Integer -> Literal
224
225 mkMachInt  x = MachInt x True{-signed-}
226 mkMachWord x = MachInt x False{-unsigned-}
227
228 -- check if the int is within range
229 mkMachInt_safe :: Integer -> Literal
230 mkMachInt_safe i
231  | out_of_range = 
232    pprPanic "mkMachInt_safe" 
233             (hsep [text "ERROR: Int ", text (show i), text "out of range",
234                    brackets (int minInt <+> text ".." <+> int maxInt)])
235  | otherwise = MachInt i True{-signed-}
236  where
237   out_of_range =
238 --    i < fromInt minBound ||
239     i > fromInt maxInt
240
241 mkMachInt64  x = MachInt64 x True{-signed-}
242 mkMachWord64 x = MachInt64 x False{-unsigned-}
243
244 mkStrLit :: String -> Type -> Literal
245 mkStrLit s ty = NoRepStr (_PK_ s) ty
246 \end{code}
247
248
249         Predicates
250         ~~~~~~~~~~
251 \begin{code}
252 isNoRepLit (NoRepStr _ _)       = True -- these are not primitive typed!
253 isNoRepLit (NoRepInteger  _ _)  = True
254 isNoRepLit (NoRepRational _ _)  = True
255 isNoRepLit _                    = False
256
257 isLitLitLit (MachLitLit _ _) = True
258 isLitLitLit _                = False
259 \end{code}
260
261         Types
262         ~~~~~
263 \begin{code}
264 literalType :: Literal -> Type
265 literalType (MachChar _)          = charPrimTy
266 literalType (MachStr  _)          = addrPrimTy
267 literalType (MachAddr _)          = addrPrimTy
268 literalType (MachInt  _ signed)   = if signed then intPrimTy else wordPrimTy
269 literalType (MachInt64  _ signed) = if signed then int64PrimTy else word64PrimTy
270 literalType (MachFloat _)         = floatPrimTy
271 literalType (MachDouble _)        = doublePrimTy
272 literalType (MachLitLit _ ty)     = ty
273 literalType (NoRepInteger  _ ty)  = ty
274 literalType (NoRepRational _ ty)  = ty
275 literalType (NoRepStr _ ty)       = ty
276 \end{code}
277
278 \begin{code}
279 literalPrimRep :: Literal -> PrimRep
280
281 literalPrimRep (MachChar _)       = CharRep
282 literalPrimRep (MachStr _)        = AddrRep  -- specifically: "char *"
283 literalPrimRep (MachAddr  _)      = AddrRep
284 literalPrimRep (MachInt _ signed) = if signed then IntRep else WordRep
285 literalPrimRep (MachInt64 _ signed) = if signed then Int64Rep else Word64Rep
286 literalPrimRep (MachFloat _)      = FloatRep
287 literalPrimRep (MachDouble _)     = DoubleRep
288 literalPrimRep (MachLitLit _ ty)  = typePrimRep ty
289 #ifdef DEBUG
290 literalPrimRep (NoRepInteger  _ _) = panic "literalPrimRep:NoRepInteger"
291 literalPrimRep (NoRepRational _ _) = panic "literalPrimRep:NoRepRational"
292 literalPrimRep (NoRepStr _ _)      = panic "literalPrimRep:NoRepString"
293 #endif
294 \end{code}
295
296
297         Comparison
298         ~~~~~~~~~~
299 \begin{code}
300 cmpLit (MachChar      a)   (MachChar       b)   = a `compare` b
301 cmpLit (MachStr       a)   (MachStr        b)   = a `compare` b
302 cmpLit (MachAddr      a)   (MachAddr       b)   = a `compare` b
303 cmpLit (MachInt       a b) (MachInt        c d) = (a `compare` c) `thenCmp` (b `compare` d)
304 cmpLit (MachFloat     a)   (MachFloat      b)   = a `compare` b
305 cmpLit (MachDouble    a)   (MachDouble     b)   = a `compare` b
306 cmpLit (MachLitLit    a b) (MachLitLit    c d)  = (a `compare` c) `thenCmp` (b `compare` d)
307 cmpLit (NoRepStr      a _) (NoRepStr      b _)  = a `compare` b
308 cmpLit (NoRepInteger  a _) (NoRepInteger  b _)  = a `compare` b
309 cmpLit (NoRepRational a _) (NoRepRational b _)  = a `compare` b
310 cmpLit lit1                lit2                 | litTag lit1 _LT_ litTag lit2 = LT
311                                                 | otherwise                    = GT
312
313 litTag (MachChar      _)   = ILIT(1)
314 litTag (MachStr       _)   = ILIT(2)
315 litTag (MachAddr      _)   = ILIT(3)
316 litTag (MachInt       _ _) = ILIT(4)
317 litTag (MachFloat     _)   = ILIT(5)
318 litTag (MachDouble    _)   = ILIT(6)
319 litTag (MachLitLit    _ _) = ILIT(7)
320 litTag (NoRepStr      _ _) = ILIT(8)
321 litTag (NoRepInteger  _ _) = ILIT(9)
322 litTag (NoRepRational _ _) = ILIT(10)
323 \end{code}
324
325         Printing
326         ~~~~~~~~
327 * MachX (i.e. unboxed) things are printed unadornded (e.g. 3, 'a', "foo")
328   exceptions: MachFloat and MachAddr get an initial keyword prefix
329
330 * NoRep things get an initial keyword prefix (e.g. _integer_ 3)
331
332 \begin{code}
333 pprLit lit
334   = getPprStyle $ \ sty ->
335     let
336       code_style = codeStyle sty
337     in
338     case lit of
339       MachChar ch | code_style     -> hcat [ptext SLIT("(C_)"), char '\'', 
340                                             text (charToC ch), char '\'']
341                   | ifaceStyle sty -> char '\'' <> text (charToEasyHaskell ch) <> char '\''
342                   | otherwise      -> text ['\'', ch, '\'']
343
344       MachStr s | code_style -> doubleQuotes (text (stringToC (_UNPK_ s)))
345                 | otherwise  -> pprFSAsString s
346
347
348       NoRepStr s ty | code_style -> pprPanic "NoRep in code style" (ppr lit)
349                     | otherwise  -> ptext SLIT("__string") <+> pprFSAsString s
350
351       MachInt i signed | code_style && out_of_range 
352                        -> pprPanic "" (hsep [text "ERROR: Int ", text (show i), 
353                                              text "out of range",
354                                              brackets (ppr range_min <+> text ".." 
355                                                         <+> ppr range_max)])
356                         -- in interface files, parenthesize raw negative ints.
357                         -- this avoids problems like {-1} being interpreted
358                         -- as a comment starter. -}
359                        | ifaceStyle sty && i < 0 -> parens (integer i)
360                         -- avoid a problem whereby gcc interprets the constant
361                         -- minInt as unsigned.
362                        | code_style && i == (toInteger (minBound :: Int))
363                                 -> parens (hcat [integer (i+1), text "-1"])
364                        | otherwise -> integer i
365
366                        where
367                         range_min = if signed then minInt else 0
368                         range_max = maxInt
369                         out_of_range = not (i >= toInteger range_min && i <= toInteger range_max)
370
371       MachFloat f | code_style -> ptext SLIT("(StgFloat)") <> rational f
372                   | otherwise  -> ptext SLIT("__float") <+> rational f
373
374       MachDouble d | ifaceStyle sty && d < 0 -> parens (rational d)
375                    | otherwise -> rational d
376
377       MachAddr p | code_style -> ptext SLIT("(void*)") <> integer p
378                  | otherwise  -> ptext SLIT("__addr") <+> integer p
379
380       NoRepInteger i _ | code_style -> pprPanic "NoRep in code style" (ppr lit)
381                        | otherwise  -> ptext SLIT("__integer") <+> integer i
382
383       NoRepRational r _ | code_style -> pprPanic "NoRep in code style" (ppr lit)
384                         | otherwise  -> hsep [ptext SLIT("__rational"), integer (numerator r), 
385                                                                         integer (denominator r)]
386
387       MachLitLit s ty | code_style -> ptext s
388                       | otherwise  -> parens (hsep [ptext SLIT("__litlit"), 
389                                                     pprFSAsString s,
390                                                     pprParendType ty])
391 \end{code}
392
393
394 %************************************************************************
395 %*                                                                      *
396 \subsection{Hashing
397 %*                                                                      *
398 %************************************************************************
399
400 Hash values should be zero or a positive integer.  No negatives please.
401 (They mess up the UniqFM for some reason.)
402
403 \begin{code}
404 hashCon :: Con -> Int
405 hashCon (DataCon dc)  = hashName (dataConName dc)
406 hashCon (PrimOp op)   = primOpTag op + 500      -- Keep it out of range of common ints
407 hashCon (Literal lit) = hashLiteral lit
408 hashCon other         = pprTrace "hashCon" (ppr other) 0
409
410 hashLiteral :: Literal -> Int
411 hashLiteral (MachChar c)        = ord c + 1000  -- Keep it out of range of common ints
412 hashLiteral (MachStr s)         = hashFS s
413 hashLiteral (MachAddr i)        = hashInteger i
414 hashLiteral (MachInt i _)       = hashInteger i
415 hashLiteral (MachInt64 i _)     = hashInteger i
416 hashLiteral (MachFloat r)       = hashRational r
417 hashLiteral (MachDouble r)      = hashRational r
418 hashLiteral (MachLitLit s _)    = hashFS s
419 hashLiteral (NoRepStr s _)      = hashFS s
420 hashLiteral (NoRepInteger i _)  = hashInteger i
421 hashLiteral (NoRepRational r _) = hashRational r
422
423 hashRational :: Rational -> Int
424 hashRational r = hashInteger (numerator r)
425
426 hashInteger :: Integer -> Int
427 hashInteger i = abs (fromInteger (i `rem` 10000))
428
429 hashFS :: FAST_STRING -> Int
430 hashFS s = IBOX( uniqueOfFS s )
431 \end{code}
432