3c8a470aae2f4eb2233f979ba0ff9370fe7daf2f
[ghc-hetmet.git] / ghc / compiler / absCSyn / AbsCSyn.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 % $Id: AbsCSyn.lhs,v 1.56 2003/11/17 14:47:53 simonmar Exp $
5 %
6 \section[AbstractC]{Abstract C: the last stop before machine code}
7
8 This ``Abstract C'' data type describes the raw Spineless Tagless
9 machine model at a C-ish level; it is ``abstract'' in that it only
10 includes C-like structures that we happen to need.  The conversion of
11 programs from @StgSyntax@ (basically a functional language) to
12 @AbstractC@ (basically imperative C) is the heart of code generation.
13 From @AbstractC@, one may convert to real C (for portability) or to
14 raw assembler/machine code.
15
16 \begin{code}
17 module AbsCSyn where    -- export everything
18
19 #include "HsVersions.h"
20
21 import {-# SOURCE #-} ClosureInfo ( ClosureInfo )
22
23 import CLabel
24 import Constants        ( mAX_Vanilla_REG, mAX_Float_REG,
25                           mAX_Double_REG, spRelToInt )
26 import CostCentre       ( CostCentre, CostCentreStack )
27 import Literal          ( mkMachInt, Literal(..) )
28 import ForeignCall      ( CCallSpec )
29 import PrimRep          ( PrimRep(..) )
30 import MachOp           ( MachOp(..) )
31 import Unique           ( Unique )
32 import StgSyn           ( StgOp )
33 import TyCon            ( TyCon )
34 import Bitmap           ( Bitmap, mAX_SMALL_BITMAP_SIZE )
35 import SMRep            ( StgWord, StgHalfWord )
36 import FastTypes
37 import FastString
38 \end{code}
39
40 @AbstractC@ is a list of Abstract~C statements, but the data structure
41 is tree-ish, for easier and more efficient putting-together.
42 \begin{code}
43 data AbstractC
44   = AbsCNop
45   | AbsCStmts           AbstractC AbstractC
46
47   -- and the individual stmts...
48 \end{code}
49
50 A note on @CAssign@: In general, the type associated with an assignment
51 is the type of the lhs.  However, when the lhs is a pointer to mixed
52 types (e.g. SpB relative), the type of the assignment is the type of
53 the rhs for float types, or the generic StgWord for all other types.
54 (In particular, a CharRep on the rhs is promoted to IntRep when
55 stored in a mixed type location.)
56
57 \begin{code}
58   | CAssign
59         !CAddrMode      -- target
60         !CAddrMode      -- source
61
62   | CJump
63         CAddrMode       -- Put this in the program counter
64                         -- eg `CJump (CReg (VanillaReg PtrRep 1))' puts Ret1 in PC
65                         -- Enter can be done by:
66                         --        CJump (CVal NodeRel zeroOff)
67
68   | CFallThrough
69         CAddrMode       -- Fall through into this routine
70                         -- (for the benefit of the native code generators)
71                         -- Equivalent to CJump in C land
72
73   | CReturn             -- Perform a return
74         CAddrMode       -- Address of a RET_<blah> info table
75         ReturnInfo      -- Whether it's a direct or vectored return
76
77   | CSwitch !CAddrMode
78         [(Literal, AbstractC)]  -- alternatives
79         AbstractC               -- default; if there is no real Abstract C in here
80                                 -- (e.g., all comments; see function "nonemptyAbsC"),
81                                 -- then that means the default _cannot_ occur.
82                                 -- If there is only one alternative & no default code,
83                                 -- then there is no need to check the tag.
84                                 -- Therefore, e.g.:
85                                 --  CSwitch m [(tag,code)] AbsCNop == code
86
87   | CCodeBlock CLabel AbstractC
88                         -- A labelled block of code; this "statement" is not
89                         -- executed; rather, the labelled code will be hoisted
90                         -- out to the top level (out of line) & it can be
91                         -- jumped to.
92
93   | CInitHdr            -- to initialise the header of a closure (both fixed/var parts)
94         ClosureInfo
95         CAddrMode       -- address of the info ptr
96         !CAddrMode      -- cost centre to place in closure
97                         --   CReg CurCostCentre or CC_HDR(R1.p{-Node-})
98         Int             -- size of closure, for profiling
99
100   -- NEW CASES FOR EXPANDED PRIMOPS
101
102   | CMachOpStmt                 -- Machine-level operation
103         CAddrMode               -- result
104         MachOp
105         [CAddrMode]             -- Arguments
106         (Maybe [MagicId])       -- list of regs which need to be preserved
107         -- across the primop.  This is allowed to be Nothing only if
108         -- machOpIsDefinitelyInline returns True.  And that in turn may
109         -- only return True if we are absolutely sure that the mach op
110         -- can be done inline on all platforms.  
111
112   | CSequential         -- Do the nested AbstractCs sequentially.
113         [AbstractC]     -- In particular, as far as the AbsCUtils.doSimultaneously
114                         -- is concerned, these stmts are to be treated as atomic
115                         -- and are not to be reordered.
116
117   -- end of NEW CASES FOR EXPANDED PRIMOPS
118
119   | COpStmt
120         [CAddrMode]     -- Results
121         StgOp
122         [CAddrMode]     -- Arguments
123         [MagicId]       -- Potentially volatile/live registers
124                         -- (to save/restore around the call/op)
125
126         -- INVARIANT: When a PrimOp which can cause GC is used, the
127         -- only live data is tidily on the STG stacks or in the STG
128         -- registers (the code generator ensures this).
129         --
130         -- Why this?  Because if the arguments were arbitrary
131         -- addressing modes, they might be things like (Hp+6) which
132         -- will get utterly spongled by GC.
133
134   | CSimultaneous       -- Perform simultaneously all the statements
135         AbstractC       -- in the nested AbstractC.  They are only
136                         -- allowed to be CAssigns, COpStmts and AbsCNops, so the
137                         -- "simultaneous" part just concerns making
138                         -- sure that permutations work.
139                         -- For example { a := b, b := a }
140                         --      needs to go via (at least one) temporary
141
142   | CCheck              -- heap or stack checks, or both.  
143         CCheckMacro     -- These might include some code to fill in tags 
144         [CAddrMode]     -- on the stack, so we can't use CMacroStmt below.
145         AbstractC
146
147   | CRetDirect                  -- Direct return
148         !Unique                 -- for making labels
149         AbstractC               -- return code
150         C_SRT                   -- SRT info
151         Liveness                -- stack liveness at the return point
152
153   -- see the notes about these next few; they follow below...
154   | CMacroStmt          CStmtMacro      [CAddrMode]
155   | CCallProfCtrMacro   FastString      [CAddrMode]
156   | CCallProfCCMacro    FastString      [CAddrMode]
157
158     {- The presence of this constructor is a makeshift solution;
159        it being used to work around a gcc-related problem of
160        handling typedefs within statement blocks (or, rather,
161        the inability to do so.)
162        
163        The AbstractC flattener takes care of lifting out these
164        typedefs if needs be (i.e., when generating .hc code and
165        compiling 'foreign import dynamic's)
166     -}
167   | CCallTypedef Bool {- True => use "typedef"; False => use "extern"-}
168                  CCallSpec Unique [CAddrMode] [CAddrMode]
169
170   -- *** the next three [or so...] are DATA (those above are CODE) ***
171
172   | CStaticClosure
173         CLabel                  -- The closure's label
174         ClosureInfo             -- Todo: maybe info_lbl & closure_lbl instead?
175         CAddrMode               -- cost centre identifier to place in closure
176         [CAddrMode]             -- free vars; ptrs, then non-ptrs.
177
178   | CSRT CLabel [CLabel]        -- SRT declarations: basically an array of 
179                                 -- pointers to static closures.
180   
181   | CBitmap Liveness            -- A "large" bitmap to be emitted
182
183   | CSRTDesc                    -- A "large" SRT descriptor (one that doesn't
184                                 -- fit into the half-word bitmap in the itbl).
185         !CLabel                 -- Label for this SRT descriptor
186         !CLabel                 -- Pointer to the SRT
187         !Int                    -- Offset within the SRT
188         !Int                    -- Length
189         !Bitmap                 -- Bitmap
190
191   | CClosureInfoAndCode
192         ClosureInfo             -- Explains placement and layout of closure
193         AbstractC               -- Entry point code
194
195   | CRetVector                  -- A labelled block of static data
196         CLabel
197         [CAddrMode]
198         C_SRT                   -- SRT info
199         Liveness                -- stack liveness at the return point
200
201   | CClosureTbl                 -- table of constructors for enumerated types
202         TyCon                   -- which TyCon this table is for
203
204   | CModuleInitBlock            -- module initialisation block
205         CLabel                  -- "plain" label for init block
206         CLabel                  -- label for init block (with ver + way info)
207         AbstractC               -- initialisation code
208
209   | CCostCentreDecl             -- A cost centre *declaration*
210         Bool                    -- True  <=> local => full declaration
211                                 -- False <=> extern; just say so
212         CostCentre
213
214   | CCostCentreStackDecl        -- A cost centre stack *declaration*
215         CostCentreStack         -- this is the declaration for a
216                                 -- pre-defined singleton CCS (see 
217                                 -- CostCentre.lhs)
218
219   | CSplitMarker                -- Split into separate object modules here
220
221 -- C_SRT is what StgSyn.SRT gets translated to... 
222 -- we add a label for the table, and expect only the 'offset/length' form
223
224 data C_SRT = NoC_SRT
225            | C_SRT !CLabel !Int{-offset-} !StgHalfWord{-bitmap or escape-}
226
227 needsSRT :: C_SRT -> Bool
228 needsSRT NoC_SRT       = False
229 needsSRT (C_SRT _ _ _) = True
230 \end{code}
231
232 About @CMacroStmt@, etc.: notionally, they all just call some
233 arbitrary C~macro or routine, passing the @CAddrModes@ as arguments.
234 However, we distinguish between various flavours of these things,
235 mostly just to keep things somewhat less wild and wooly.
236
237 \begin{description}
238 \item[@CMacroStmt@:]
239 Some {\em essential} bits of the STG execution model are done with C
240 macros.  An example is @STK_CHK@, which checks for stack-space
241 overflow.  This enumeration type lists all such macros:
242 \begin{code}
243 data CStmtMacro
244   = UPD_CAF                             -- update CAF closure with indirection
245   | UPD_BH_UPDATABLE                    -- eager backholing
246   | UPD_BH_SINGLE_ENTRY                 -- more eager blackholing
247   | PUSH_UPD_FRAME                      -- push update frame
248   | SET_TAG                             -- set TagReg if it exists
249       -- dataToTag# primop -- *only* used in unregisterised builds.
250       -- (see AbsCUtils.dsCOpStmt)
251   | DATA_TO_TAGZH
252
253   | REGISTER_FOREIGN_EXPORT             -- register a foreign exported fun
254   | REGISTER_IMPORT                     -- register an imported module
255   | REGISTER_DIMPORT                    -- register an imported module from
256                                         -- another DLL
257
258   | GRAN_FETCH                  -- for GrAnSim only  -- HWL
259   | GRAN_RESCHEDULE             -- for GrAnSim only  -- HWL
260   | GRAN_FETCH_AND_RESCHEDULE   -- for GrAnSim only  -- HWL
261   | THREAD_CONTEXT_SWITCH       -- for GrAnSim only  -- HWL
262   | GRAN_YIELD                  -- for GrAnSim only  -- HWL 
263 \end{code}
264
265 Heap/Stack checks.  There are far too many of these.
266
267 \begin{code}
268 data CCheckMacro
269
270   = HP_CHK_NP                           -- heap/stack checks when
271   | STK_CHK_NP                          -- node points to the closure
272   | HP_STK_CHK_NP
273
274   | HP_CHK_FUN                          -- heap/stack checks when
275   | STK_CHK_FUN                         -- node doesn't point
276   | HP_STK_CHK_FUN
277                                         -- case alternative heap checks:
278
279   | HP_CHK_NOREGS                       --   no registers live
280   | HP_CHK_UNPT_R1                      --   R1 is boxed/unlifted
281   | HP_CHK_UNBX_R1                      --   R1 is unboxed
282   | HP_CHK_F1                           --   FloatReg1 (only) is live 
283   | HP_CHK_D1                           --   DblReg1   (only) is live
284   | HP_CHK_L1                           --   LngReg1   (only) is live
285
286   | HP_CHK_UNBX_TUPLE                   -- unboxed tuple heap check
287 \end{code}
288
289 \item[@CCallProfCtrMacro@:]
290 The @String@ names a macro that, if \tr{#define}d, will bump one/some
291 of the STG-event profiling counters.
292
293 \item[@CCallProfCCMacro@:]
294 The @String@ names a macro that, if \tr{#define}d, will perform some
295 cost-centre-profiling-related action.
296 \end{description}
297
298 %************************************************************************
299 %*                                                                      *
300 \subsection[CAddrMode]{C addressing modes}
301 %*                                                                      *
302 %************************************************************************
303
304 \begin{code}
305 data CAddrMode
306   = CVal  RegRelative PrimRep
307                         -- On RHS of assign: Contents of Magic[n]
308                         -- On LHS of assign: location Magic[n]
309                         -- (ie at addr Magic+n)
310
311   | CAddr RegRelative
312                         -- On RHS of assign: Address of Magic[n]; ie Magic+n
313                         --      n=0 gets the Magic location itself
314                         --      (NB: n=0 case superceded by CReg)
315                         -- On LHS of assign: only sensible if n=0,
316                         --      which gives the magic location itself
317                         --      (NB: superceded by CReg)
318
319              -- JRS 2002-02-05: CAddr is really scummy and should be fixed.
320              -- The effect is that the semantics of CAddr depend on what the
321              -- contained RegRelative is; it is decidely non-orthogonal.
322
323   | CReg MagicId        -- To replace (CAddr MagicId 0)
324
325   | CTemp !Unique !PrimRep      -- Temporary locations
326         -- ``Temporaries'' correspond to local variables in C, and registers in
327         -- native code.
328
329   | CLbl    CLabel      -- Labels in the runtime system, etc.
330             PrimRep     -- the kind is so we can generate accurate C decls
331
332   | CCharLike CAddrMode -- The address of a static char-like closure for
333                         -- the specified character.  It is guaranteed to be in
334                         -- the range mIN_CHARLIKE..mAX_CHARLIKE
335
336   | CIntLike CAddrMode  -- The address of a static int-like closure for the
337                         -- specified small integer.  It is guaranteed to be in
338                         -- the range mIN_INTLIKE..mAX_INTLIKE
339
340   | CLit    Literal
341
342   | CJoinPoint          -- This is used as the amode of a let-no-escape-bound
343                         -- variable.
344         VirtualSpOffset   -- Sp value after any volatile free vars
345                           -- of the rhs have been saved on stack.
346                           -- Just before the code for the thing is jumped to,
347                           -- Sp will be set to this value,
348                           -- and then any stack-passed args pushed,
349                           -- then the code for this thing will be entered
350   | CMacroExpr
351         !PrimRep        -- the kind of the result
352         CExprMacro      -- the macro to generate a value
353         [CAddrMode]     -- and its arguments
354 \end{code}
355
356 Various C macros for values which are dependent on the back-end layout.
357
358 \begin{code}
359
360 data CExprMacro
361   = ENTRY_CODE
362   | ARG_TAG                             -- stack argument tagging
363   | GET_TAG                             -- get current constructor tag
364   | CCS_HDR
365   | BYTE_ARR_CTS                -- used when passing a ByteArray# to a ccall
366   | PTRS_ARR_CTS                -- similarly for an Array#
367   | ForeignObj_CLOSURE_DATA     -- and again for a ForeignObj#
368 \end{code}
369
370 Convenience functions:
371
372 \begin{code}
373 mkIntCLit :: Int -> CAddrMode
374 mkIntCLit i = CLit (mkMachInt (toInteger i))
375
376 mkWordCLit :: StgWord -> CAddrMode
377 mkWordCLit wd = CLit (MachWord (fromIntegral wd))
378
379 mkCString :: FastString -> CAddrMode
380 mkCString s = CLit (MachStr s)
381
382 mkCCostCentre :: CostCentre -> CAddrMode
383 mkCCostCentre cc = CLbl (mkCC_Label cc) DataPtrRep
384
385 mkCCostCentreStack :: CostCentreStack -> CAddrMode
386 mkCCostCentreStack ccs = CLbl (mkCCS_Label ccs) DataPtrRep
387 \end{code}
388
389 %************************************************************************
390 %*                                                                      *
391 \subsection[RegRelative]{@RegRelatives@: ???}
392 %*                                                                      *
393 %************************************************************************
394
395 \begin{code}
396 data RegRelative
397   = HpRel       FastInt -- }
398   | SpRel       FastInt -- }- offsets in StgWords
399   | NodeRel     FastInt -- }
400   | CIndex      CAddrMode CAddrMode PrimRep     -- pointer arithmetic :-)
401                                                 -- CIndex a b k === (k*)a[b]
402
403 data ReturnInfo
404   = DirectReturn                        -- Jump directly, if possible
405   | StaticVectoredReturn Int            -- Fixed tag, starting at zero
406   | DynamicVectoredReturn CAddrMode     -- Dynamic tag given by amode, starting at zero
407
408 hpRel :: VirtualHeapOffset      -- virtual offset of Hp
409       -> VirtualHeapOffset      -- virtual offset of The Thing
410       -> RegRelative            -- integer offset
411 hpRel hp off = HpRel (iUnbox (hp - off))
412
413 spRel :: VirtualSpOffset        -- virtual offset of Sp
414       -> VirtualSpOffset        -- virtual offset of The Thing
415       -> RegRelative            -- integer offset
416 spRel sp off = SpRel (iUnbox (spRelToInt sp off))
417
418 nodeRel :: VirtualHeapOffset
419         -> RegRelative
420 nodeRel off = NodeRel (iUnbox off)
421
422 \end{code}
423
424 %************************************************************************
425 %*                                                                      *
426 \subsection[Liveness]{Liveness Masks}
427 %*                                                                      *
428 %************************************************************************
429
430 We represent liveness bitmaps as a BitSet (whose internal
431 representation really is a bitmap).  These are pinned onto case return
432 vectors to indicate the state of the stack for the garbage collector.
433
434 In the compiled program, liveness bitmaps that fit inside a single
435 word (StgWord) are stored as a single word, while larger bitmaps are
436 stored as a pointer to an array of words. 
437
438 \begin{code}
439 data Liveness = Liveness CLabel !Int Bitmap
440
441 maybeLargeBitmap :: Liveness -> AbstractC
442 maybeLargeBitmap liveness@(Liveness _ size _)
443   | size <= mAX_SMALL_BITMAP_SIZE = AbsCNop
444   | otherwise                     = CBitmap liveness
445 \end{code}
446
447 %************************************************************************
448 %*                                                                      *
449 \subsection[HeapOffset]{@Heap Offsets@}
450 %*                                                                      *
451 %************************************************************************
452
453 This used to be a grotesquely complicated datatype in an attempt to
454 hide the details of header sizes from the compiler itself.  Now these
455 constants are imported from the RTS, and we deal in real Ints.
456
457 \begin{code}
458 type HeapOffset = Int                   -- ToDo: remove
459
460 type VirtualHeapOffset  = HeapOffset
461 type VirtualSpOffset    = Int
462 \end{code}
463
464 %************************************************************************
465 %*                                                                      *
466 \subsection[MagicId]{@MagicIds@: registers and such}
467 %*                                                                      *
468 %************************************************************************
469
470 \begin{code}
471 data MagicId
472   = BaseReg     -- mentioned only in nativeGen
473
474   -- Argument and return registers
475   | VanillaReg          -- pointers, unboxed ints and chars
476         PrimRep
477         FastInt -- its number (1 .. mAX_Vanilla_REG)
478
479   | FloatReg            -- single-precision floating-point registers
480         FastInt -- its number (1 .. mAX_Float_REG)
481
482   | DoubleReg           -- double-precision floating-point registers
483         FastInt -- its number (1 .. mAX_Double_REG)
484
485   -- STG registers
486   | Sp                  -- Stack ptr; points to last occupied stack location.
487   | SpLim               -- Stack limit
488   | Hp                  -- Heap ptr; points to last occupied heap location.
489   | HpLim               -- Heap limit register
490   | CurCostCentre       -- current cost centre register.
491   | VoidReg             -- see "VoidPrim" type; just a placeholder; 
492                         --   no actual register
493   | LongReg             -- long int registers (64-bit, really)
494         PrimRep         -- Int64Rep or Word64Rep
495         FastInt -- its number (1 .. mAX_Long_REG)
496
497   | CurrentTSO          -- pointer to current thread's TSO
498   | CurrentNursery      -- pointer to allocation area
499   | HpAlloc             -- allocation count for heap check failure
500
501
502 node    = VanillaReg PtrRep     (_ILIT 1) -- A convenient alias for Node
503 tagreg  = VanillaReg WordRep    (_ILIT 2) -- A convenient alias for TagReg
504
505 nodeReg = CReg node
506 \end{code}
507
508 We need magical @Eq@ because @VanillaReg@s come in multiple flavors.
509
510 \begin{code}
511 instance Eq MagicId where
512     reg1 == reg2 = tag reg1 ==# tag reg2
513      where
514         tag BaseReg          = (_ILIT(0) :: FastInt)
515         tag Sp               = _ILIT(1)
516         tag SpLim            = _ILIT(3)
517         tag Hp               = _ILIT(4)
518         tag HpLim            = _ILIT(5)
519         tag CurCostCentre    = _ILIT(6)
520         tag VoidReg          = _ILIT(7)
521
522         tag (VanillaReg _ i) = _ILIT(8) +# i
523
524         tag (FloatReg i)  = _ILIT(8) +# maxv +# i
525         tag (DoubleReg i) = _ILIT(8) +# maxv +# maxf +# i
526         tag (LongReg _ i) = _ILIT(8) +# maxv +# maxf +# maxd +# i
527
528         maxv = iUnbox mAX_Vanilla_REG
529         maxf = iUnbox mAX_Float_REG
530         maxd = iUnbox mAX_Double_REG
531 \end{code}
532
533 Returns True for any register that {\em potentially} dies across
534 C calls (or anything near equivalent).  We just say @True@ and
535 let the (machine-specific) registering macros sort things out...
536
537 \begin{code}
538 isVolatileReg :: MagicId -> Bool
539 isVolatileReg any = True
540 \end{code}