Added pointerhood to LocalReg
[ghc-hetmet.git] / compiler / cmm / Cmm.hs
1 -----------------------------------------------------------------------------
2 --
3 -- Cmm data types
4 --
5 -- (c) The University of Glasgow 2004-2006
6 --
7 -----------------------------------------------------------------------------
8
9 module Cmm ( 
10         GenCmm(..), Cmm,
11         GenCmmTop(..), CmmTop,
12         GenBasicBlock(..), CmmBasicBlock, blockId, blockStmts,
13         CmmStmt(..), CmmActuals, CmmFormal, CmmFormals, CmmHintFormals,
14         CmmCallTarget(..),
15         CmmStatic(..), Section(..),
16         CmmExpr(..), cmmExprRep, 
17         CmmReg(..), cmmRegRep,
18         CmmLit(..), cmmLitRep,
19         LocalReg(..), localRegRep, Kind(..),
20         BlockId(..), BlockEnv,
21         GlobalReg(..), globalRegRep,
22
23         node, nodeReg, spReg, hpReg, spLimReg
24   ) where
25
26 #include "HsVersions.h"
27
28 import MachOp
29 import CLabel
30 import ForeignCall
31 import Unique
32 import UniqFM
33 import FastString
34
35 import Data.Word
36
37 -----------------------------------------------------------------------------
38 --              Cmm, CmmTop, CmmBasicBlock
39 -----------------------------------------------------------------------------
40
41 -- A file is a list of top-level chunks.  These may be arbitrarily
42 -- re-orderd during code generation.
43
44 -- GenCmm is abstracted over
45 --   (a) the type of static data elements
46 --   (b) the contents of a basic block.
47 -- We expect there to be two main instances of this type:
48 --   (a) Plain C--, i.e. populated with CmmLit and CmmExpr respectively,
49 --   (b) Native code, populated with instructions
50 --
51 newtype GenCmm d i = Cmm [GenCmmTop d i]
52
53 type Cmm = GenCmm CmmStatic CmmStmt
54
55 -- A top-level chunk, abstracted over the type of the contents of
56 -- the basic blocks (Cmm or instructions are the likely instantiations).
57 data GenCmmTop d i
58   = CmmProc
59      [d]               -- Info table, may be empty
60      CLabel            -- Used to generate both info & entry labels
61      CmmFormals        -- Argument locals live on entry (C-- procedure params)
62      [GenBasicBlock i] -- Code, may be empty.  The first block is
63                        -- the entry point.  The order is otherwise initially 
64                        -- unimportant, but at some point the code gen will
65                        -- fix the order.
66
67                        -- the BlockId of the first block does not give rise
68                        -- to a label.  To jump to the first block in a Proc,
69                        -- use the appropriate CLabel.
70
71   -- some static data.
72   | CmmData Section [d] -- constant values only
73
74 type CmmTop = GenCmmTop CmmStatic CmmStmt
75
76 -- A basic block containing a single label, at the beginning.
77 -- The list of basic blocks in a top-level code block may be re-ordered.
78 -- Fall-through is not allowed: there must be an explicit jump at the
79 -- end of each basic block, but the code generator might rearrange basic
80 -- blocks in order to turn some jumps into fallthroughs.
81
82 data GenBasicBlock i = BasicBlock BlockId [i]
83   -- ToDo: Julian suggests that we might need to annotate this type
84   -- with the out & in edges in the graph, i.e. two * [BlockId].  This
85   -- information can be derived from the contents, but it might be
86   -- helpful to cache it here.
87
88 type CmmBasicBlock = GenBasicBlock CmmStmt
89
90 blockId :: GenBasicBlock i -> BlockId
91 -- The branch block id is that of the first block in 
92 -- the branch, which is that branch's entry point
93 blockId (BasicBlock blk_id _ ) = blk_id
94
95 blockStmts :: GenBasicBlock i -> [i]
96 blockStmts (BasicBlock _ stmts) = stmts
97
98
99 -----------------------------------------------------------------------------
100 --              CmmStmt
101 -- A "statement".  Note that all branches are explicit: there are no
102 -- control transfers to computed addresses, except when transfering
103 -- control to a new function.
104 -----------------------------------------------------------------------------
105
106 data CmmStmt
107   = CmmNop
108   | CmmComment FastString
109
110   | CmmAssign CmmReg CmmExpr     -- Assign to register
111
112   | CmmStore CmmExpr CmmExpr     -- Assign to memory location.  Size is
113                                  -- given by cmmExprRep of the rhs.
114
115   | CmmCall                      -- A foreign call, with 
116      CmmCallTarget
117      CmmHintFormals              -- zero or more results
118      CmmActuals                  -- zero or more arguments
119
120   | CmmBranch BlockId             -- branch to another BB in this fn
121
122   | CmmCondBranch CmmExpr BlockId -- conditional branch
123
124   | CmmSwitch CmmExpr [Maybe BlockId]   -- Table branch
125         -- The scrutinee is zero-based; 
126         --      zero -> first block
127         --      one  -> second block etc
128         -- Undefined outside range, and when there's a Nothing
129
130   | CmmJump CmmExpr               -- Jump to another function,
131       CmmActuals                  -- with these parameters.
132
133   | CmmReturn                     -- Return from a function,
134       CmmActuals                  -- with these return values.
135
136 type CmmActual = CmmExpr
137 type CmmActuals = [(CmmActual,MachHint)]
138 type CmmFormal = LocalReg
139 type CmmHintFormals = [(CmmFormal,MachHint)]
140 type CmmFormals = [CmmFormal]
141
142 {-
143 Discussion
144 ~~~~~~~~~~
145
146 One possible problem with the above type is that the only way to do a
147 non-local conditional jump is to encode it as a branch to a block that
148 contains a single jump.  This leads to inefficient code in the back end.
149
150 One possible way to fix this would be:
151
152 data CmmStat = 
153   ...
154   | CmmJump CmmBranchDest
155   | CmmCondJump CmmExpr CmmBranchDest
156   ...
157
158 data CmmBranchDest
159   = Local BlockId
160   | NonLocal CmmExpr [LocalReg]
161
162 In favour:
163
164 + one fewer constructors in CmmStmt
165 + allows both cond branch and switch to jump to non-local destinations
166
167 Against:
168
169 - not strictly necessary: can already encode as branch+jump
170 - not always possible to implement any better in the back end
171 - could do the optimisation in the back end (but then plat-specific?)
172 - C-- doesn't have it
173 - back-end optimisation might be more general (jump shortcutting)
174
175 So we'll stick with the way it is, and add the optimisation to the NCG.
176 -}
177
178 -----------------------------------------------------------------------------
179 --              CmmCallTarget
180 --
181 -- The target of a CmmCall.
182 -----------------------------------------------------------------------------
183
184 data CmmCallTarget
185   = CmmForeignCall              -- Call to a foreign function
186         CmmExpr                 -- literal label <=> static call
187                                 -- other expression <=> dynamic call
188         CCallConv               -- The calling convention
189
190   | CmmPrim                     -- Call to a "primitive" (eg. sin, cos)
191         CallishMachOp           -- These might be implemented as inline
192                                 -- code by the backend.
193
194 -----------------------------------------------------------------------------
195 --              CmmExpr
196 -- An expression.  Expressions have no side effects.
197 -----------------------------------------------------------------------------
198
199 data CmmExpr
200   = CmmLit CmmLit               -- Literal
201   | CmmLoad CmmExpr MachRep     -- Read memory location
202   | CmmReg CmmReg               -- Contents of register
203   | CmmMachOp MachOp [CmmExpr]  -- Machine operation (+, -, *, etc.)
204   | CmmRegOff CmmReg Int        
205         -- CmmRegOff reg i
206         --        ** is shorthand only, meaning **
207         -- CmmMachOp (MO_S_Add rep (CmmReg reg) (CmmLit (CmmInt i rep)))
208         --      where rep = cmmRegRep reg
209   deriving Eq
210
211 cmmExprRep :: CmmExpr -> MachRep
212 cmmExprRep (CmmLit lit)      = cmmLitRep lit
213 cmmExprRep (CmmLoad _ rep)   = rep
214 cmmExprRep (CmmReg reg)      = cmmRegRep reg
215 cmmExprRep (CmmMachOp op _)  = resultRepOfMachOp op
216 cmmExprRep (CmmRegOff reg _) = cmmRegRep reg
217
218 data CmmReg 
219   = CmmLocal  LocalReg
220   | CmmGlobal GlobalReg
221   deriving( Eq )
222
223 cmmRegRep :: CmmReg -> MachRep
224 cmmRegRep (CmmLocal  reg)       = localRegRep reg
225 cmmRegRep (CmmGlobal reg)       = globalRegRep reg
226
227 -- | Whether a 'LocalReg' is a GC followable pointer
228 data Kind = KindPtr | KindNonPtr deriving (Eq)
229
230 data LocalReg
231   = LocalReg
232       !Unique   -- ^ Identifier
233       MachRep   -- ^ Type
234       Kind      -- ^ Should the GC follow as a pointer
235
236 instance Eq LocalReg where
237   (LocalReg u1 _ _) == (LocalReg u2 _ _) = u1 == u2
238
239 instance Uniquable LocalReg where
240   getUnique (LocalReg uniq _ _) = uniq
241
242 localRegRep :: LocalReg -> MachRep
243 localRegRep (LocalReg _ rep _) = rep
244
245 localRegGCFollow (LocalReg _ _ p) = p
246
247 data CmmLit
248   = CmmInt Integer  MachRep
249         -- Interpretation: the 2's complement representation of the value
250         -- is truncated to the specified size.  This is easier than trying
251         -- to keep the value within range, because we don't know whether
252         -- it will be used as a signed or unsigned value (the MachRep doesn't
253         -- distinguish between signed & unsigned).
254   | CmmFloat  Rational MachRep
255   | CmmLabel    CLabel                  -- Address of label
256   | CmmLabelOff CLabel Int              -- Address of label + byte offset
257   
258         -- Due to limitations in the C backend, the following
259         -- MUST ONLY be used inside the info table indicated by label2
260         -- (label2 must be the info label), and label1 must be an
261         -- SRT, a slow entrypoint or a large bitmap (see the Mangler)
262         -- Don't use it at all unless tablesNextToCode.
263         -- It is also used inside the NCG during when generating
264         -- position-independent code. 
265   | CmmLabelDiffOff CLabel CLabel Int   -- label1 - label2 + offset
266   deriving Eq
267
268 cmmLitRep :: CmmLit -> MachRep
269 cmmLitRep (CmmInt _ rep)    = rep
270 cmmLitRep (CmmFloat _ rep)  = rep
271 cmmLitRep (CmmLabel _)      = wordRep
272 cmmLitRep (CmmLabelOff _ _) = wordRep
273 cmmLitRep (CmmLabelDiffOff _ _ _) = wordRep
274
275 -----------------------------------------------------------------------------
276 -- A local label.
277
278 -- Local labels must be unique within a single compilation unit.
279
280 newtype BlockId = BlockId Unique
281   deriving (Eq,Ord)
282
283 instance Uniquable BlockId where
284   getUnique (BlockId u) = u
285
286 type BlockEnv a = UniqFM {- BlockId -} a
287
288 -----------------------------------------------------------------------------
289 --              Static Data
290 -----------------------------------------------------------------------------
291
292 data Section
293   = Text
294   | Data
295   | ReadOnlyData
296   | RelocatableReadOnlyData
297   | UninitialisedData
298   | ReadOnlyData16      -- .rodata.cst16 on x86_64, 16-byte aligned
299   | OtherSection String
300
301 data CmmStatic
302   = CmmStaticLit CmmLit 
303         -- a literal value, size given by cmmLitRep of the literal.
304   | CmmUninitialised Int
305         -- uninitialised data, N bytes long
306   | CmmAlign Int
307         -- align to next N-byte boundary (N must be a power of 2).
308   | CmmDataLabel CLabel
309         -- label the current position in this section.
310   | CmmString [Word8]
311         -- string of 8-bit values only, not zero terminated.
312
313 -----------------------------------------------------------------------------
314 --              Global STG registers
315 -----------------------------------------------------------------------------
316
317 data GlobalReg
318   -- Argument and return registers
319   = VanillaReg                  -- pointers, unboxed ints and chars
320         {-# UNPACK #-} !Int     -- its number
321
322   | FloatReg            -- single-precision floating-point registers
323         {-# UNPACK #-} !Int     -- its number
324
325   | DoubleReg           -- double-precision floating-point registers
326         {-# UNPACK #-} !Int     -- its number
327
328   | LongReg             -- long int registers (64-bit, really)
329         {-# UNPACK #-} !Int     -- its number
330
331   -- STG registers
332   | Sp                  -- Stack ptr; points to last occupied stack location.
333   | SpLim               -- Stack limit
334   | Hp                  -- Heap ptr; points to last occupied heap location.
335   | HpLim               -- Heap limit register
336   | CurrentTSO          -- pointer to current thread's TSO
337   | CurrentNursery      -- pointer to allocation area
338   | HpAlloc             -- allocation count for heap check failure
339
340                 -- We keep the address of some commonly-called 
341                 -- functions in the register table, to keep code
342                 -- size down:
343   | GCEnter1            -- stg_gc_enter_1
344   | GCFun               -- stg_gc_fun
345
346   -- Base offset for the register table, used for accessing registers
347   -- which do not have real registers assigned to them.  This register
348   -- will only appear after we have expanded GlobalReg into memory accesses
349   -- (where necessary) in the native code generator.
350   | BaseReg
351
352   -- Base Register for PIC (position-independent code) calculations
353   -- Only used inside the native code generator. It's exact meaning differs
354   -- from platform to platform (see module PositionIndependentCode).
355   | PicBaseReg
356
357   deriving( Eq
358 #ifdef DEBUG
359         , Show
360 #endif
361          )
362
363 -- convenient aliases
364 spReg, hpReg, spLimReg, nodeReg :: CmmReg
365 spReg = CmmGlobal Sp
366 hpReg = CmmGlobal Hp
367 spLimReg = CmmGlobal SpLim
368 nodeReg = CmmGlobal node
369
370 node :: GlobalReg
371 node = VanillaReg 1
372
373 globalRegRep :: GlobalReg -> MachRep
374 globalRegRep (VanillaReg _)     = wordRep
375 globalRegRep (FloatReg _)       = F32
376 globalRegRep (DoubleReg _)      = F64
377 globalRegRep (LongReg _)        = I64
378 globalRegRep _                  = wordRep