2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 % $Id: AbsCSyn.lhs,v 1.36 2001/05/22 13:43:14 simonpj Exp $
6 \section[AbstractC]{Abstract C: the last stop before machine code}
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.
24 mkAbstractCs, mkAbsCStmts, mkAlgAltsCSwitch,
33 MagicId(..), node, infoptr,
38 #include "HsVersions.h"
40 import {-# SOURCE #-} ClosureInfo ( ClosureInfo )
43 import Constants ( mAX_Vanilla_REG, mAX_Float_REG,
44 mAX_Double_REG, spRelToInt )
45 import CostCentre ( CostCentre, CostCentreStack )
46 import Literal ( mkMachInt, Literal(..) )
47 import ForeignCall ( CCallSpec )
48 import PrimRep ( PrimRep(..) )
49 import Unique ( Unique )
50 import StgSyn ( StgOp, SRT(..) )
51 import TyCon ( TyCon )
52 import BitSet -- for liveness masks
57 @AbstractC@ is a list of Abstract~C statements, but the data structure
58 is tree-ish, for easier and more efficient putting-together.
64 | AbsCStmts AbstractC AbstractC
66 -- and the individual stmts...
69 A note on @CAssign@: In general, the type associated with an assignment
70 is the type of the lhs. However, when the lhs is a pointer to mixed
71 types (e.g. SpB relative), the type of the assignment is the type of
72 the rhs for float types, or the generic StgWord for all other types.
73 (In particular, a CharRep on the rhs is promoted to IntRep when
74 stored in a mixed type location.)
82 CAddrMode -- Put this in the program counter
83 -- eg `CJump (CReg (VanillaReg PtrRep 1))' puts Ret1 in PC
84 -- Enter can be done by:
85 -- CJump (CVal NodeRel zeroOff)
88 CAddrMode -- Fall through into this routine
89 -- (for the benefit of the native code generators)
90 -- Equivalent to CJump in C land
92 | CReturn -- Perform a return
93 CAddrMode -- Address of a RET_<blah> info table
94 ReturnInfo -- Whether it's a direct or vectored return
97 [(Literal, AbstractC)] -- alternatives
98 AbstractC -- default; if there is no real Abstract C in here
99 -- (e.g., all comments; see function "nonemptyAbsC"),
100 -- then that means the default _cannot_ occur.
101 -- If there is only one alternative & no default code,
102 -- then there is no need to check the tag.
104 -- CSwitch m [(tag,code)] AbsCNop == code
106 | CCodeBlock CLabel AbstractC
107 -- A labelled block of code; this "statement" is not
108 -- executed; rather, the labelled code will be hoisted
109 -- out to the top level (out of line) & it can be
112 | CInitHdr -- to initialise the header of a closure (both fixed/var parts)
114 CAddrMode -- address of the info ptr
115 CAddrMode -- cost centre to place in closure
116 -- CReg CurCostCentre or CC_HDR(R1.p{-Node-})
119 [CAddrMode] -- Results
121 [CAddrMode] -- Arguments
122 [MagicId] -- Potentially volatile/live registers
123 -- (to save/restore around the call/op)
125 -- INVARIANT: When a PrimOp which can cause GC is used, the
126 -- only live data is tidily on the STG stacks or in the STG
127 -- registers (the code generator ensures this).
129 -- Why this? Because if the arguments were arbitrary
130 -- addressing modes, they might be things like (Hp+6) which
131 -- will get utterly spongled by GC.
133 | CSimultaneous -- Perform simultaneously all the statements
134 AbstractC -- in the nested AbstractC. They are only
135 -- allowed to be CAssigns, COpStmts and AbsCNops, so the
136 -- "simultaneous" part just concerns making
137 -- sure that permutations work.
138 -- For example { a := b, b := a }
139 -- needs to go via (at least one) temporary
141 | CCheck -- heap or stack checks, or both.
142 CCheckMacro -- These might include some code to fill in tags
143 [CAddrMode] -- on the stack, so we can't use CMacroStmt below.
146 | CRetDirect -- Direct return
147 !Unique -- for making labels
148 AbstractC -- return code
149 (CLabel,SRT) -- SRT info
150 Liveness -- stack liveness at the return point
152 -- see the notes about these next few; they follow below...
153 | CMacroStmt CStmtMacro [CAddrMode]
154 | CCallProfCtrMacro FAST_STRING [CAddrMode]
155 | CCallProfCCMacro FAST_STRING [CAddrMode]
157 {- The presence of this constructor is a makeshift solution;
158 it being used to work around a gcc-related problem of
159 handling typedefs within statement blocks (or, rather,
160 the inability to do so.)
162 The AbstractC flattener takes care of lifting out these
163 typedefs if needs be (i.e., when generating .hc code and
164 compiling 'foreign import dynamic's)
166 | CCallTypedef Bool {- True => use "typedef"; False => use "extern"-}
167 CCallSpec Unique [CAddrMode] [CAddrMode]
169 -- *** the next three [or so...] are DATA (those above are CODE) ***
172 CLabel -- The (full, not base) label to use for labelling the closure.
174 CAddrMode -- cost centre identifier to place in closure
175 [CAddrMode] -- free vars; ptrs, then non-ptrs.
177 | CSRT CLabel [CLabel] -- SRT declarations: basically an array of
178 -- pointers to static closures.
180 | CBitmap CLabel LivenessMask -- A larger-than-32-bits bitmap.
182 | CClosureInfoAndCode
183 ClosureInfo -- Explains placement and layout of closure
184 AbstractC -- Slow entry point code
186 -- Fast entry point code, if any
187 String -- Closure description; NB we can't get this
188 -- from ClosureInfo, because the latter refers
189 -- to the *right* hand side of a defn, whereas
190 -- the "description" refers to *left* hand side
192 | CRetVector -- A labelled block of static data
195 (CLabel,SRT) -- SRT info
196 Liveness -- stack liveness at the return point
198 | CClosureTbl -- table of constructors for enumerated types
199 TyCon -- which TyCon this table is for
201 | CModuleInitBlock -- module initialisation block
202 CLabel -- label for init block
203 AbstractC -- initialisation code
205 | CCostCentreDecl -- A cost centre *declaration*
206 Bool -- True <=> local => full declaration
207 -- False <=> extern; just say so
210 | CCostCentreStackDecl -- A cost centre stack *declaration*
211 CostCentreStack -- this is the declaration for a
212 -- pre-defined singleton CCS (see
215 | CSplitMarker -- Split into separate object modules here
218 About @CMacroStmt@, etc.: notionally, they all just call some
219 arbitrary C~macro or routine, passing the @CAddrModes@ as arguments.
220 However, we distinguish between various flavours of these things,
221 mostly just to keep things somewhat less wild and wooly.
225 Some {\em essential} bits of the STG execution model are done with C
226 macros. An example is @STK_CHK@, which checks for stack-space
227 overflow. This enumeration type lists all such macros:
230 = ARGS_CHK -- arg satisfaction check
231 | ARGS_CHK_LOAD_NODE -- arg check for top-level functions
232 | UPD_CAF -- update CAF closure with indirection
233 | UPD_BH_UPDATABLE -- eager backholing
234 | UPD_BH_SINGLE_ENTRY -- more eager blackholing
235 | PUSH_UPD_FRAME -- push update frame
236 | PUSH_SEQ_FRAME -- push seq frame
237 | UPDATE_SU_FROM_UPD_FRAME -- pull Su out of the update frame
238 | SET_TAG -- set TagReg if it exists
240 | REGISTER_FOREIGN_EXPORT -- register a foreign exported fun
241 | REGISTER_IMPORT -- register an imported module
242 | REGISTER_DIMPORT -- register an imported module from
245 | GRAN_FETCH -- for GrAnSim only -- HWL
246 | GRAN_RESCHEDULE -- for GrAnSim only -- HWL
247 | GRAN_FETCH_AND_RESCHEDULE -- for GrAnSim only -- HWL
248 | THREAD_CONTEXT_SWITCH -- for GrAnSim only -- HWL
249 | GRAN_YIELD -- for GrAnSim only -- HWL
252 Heap/Stack checks. There are far too many of these.
257 = HP_CHK_NP -- heap/stack checks when
258 | STK_CHK_NP -- node points to the closure
260 | HP_CHK_SEQ_NP -- for 'seq' style case alternatives
262 | HP_CHK -- heap/stack checks when
263 | STK_CHK -- node doesn't point
265 -- case alternative heap checks:
267 | HP_CHK_NOREGS -- no registers live
268 | HP_CHK_UNPT_R1 -- R1 is boxed/unlifted
269 | HP_CHK_UNBX_R1 -- R1 is unboxed
270 | HP_CHK_F1 -- FloatReg1 (only) is live
271 | HP_CHK_D1 -- DblReg1 (only) is live
272 | HP_CHK_L1 -- LngReg1 (only) is live
273 | HP_CHK_UT_ALT -- unboxed tuple return.
275 | HP_CHK_GEN -- generic heap check
278 \item[@CCallProfCtrMacro@:]
279 The @String@ names a macro that, if \tr{#define}d, will bump one/some
280 of the STG-event profiling counters.
282 \item[@CCallProfCCMacro@:]
283 The @String@ names a macro that, if \tr{#define}d, will perform some
284 cost-centre-profiling-related action.
287 %************************************************************************
289 \subsection[CAddrMode]{C addressing modes}
291 %************************************************************************
295 = CVal RegRelative PrimRep
296 -- On RHS of assign: Contents of Magic[n]
297 -- On LHS of assign: location Magic[n]
298 -- (ie at addr Magic+n)
301 -- On RHS of assign: Address of Magic[n]; ie Magic+n
302 -- n=0 gets the Magic location itself
303 -- (NB: n=0 case superceded by CReg)
304 -- On LHS of assign: only sensible if n=0,
305 -- which gives the magic location itself
306 -- (NB: superceded by CReg)
308 | CReg MagicId -- To replace (CAddr MagicId 0)
310 | CTemp !Unique !PrimRep -- Temporary locations
311 -- ``Temporaries'' correspond to local variables in C, and registers in
314 | CLbl CLabel -- Labels in the runtime system, etc.
315 PrimRep -- the kind is so we can generate accurate C decls
317 | CCharLike CAddrMode -- The address of a static char-like closure for
318 -- the specified character. It is guaranteed to be in
319 -- the range mIN_CHARLIKE..mAX_CHARLIKE
321 | CIntLike CAddrMode -- The address of a static int-like closure for the
322 -- specified small integer. It is guaranteed to be in
323 -- the range mIN_INTLIKE..mAX_INTLIKE
327 | CJoinPoint -- This is used as the amode of a let-no-escape-bound
329 VirtualSpOffset -- Sp value after any volatile free vars
330 -- of the rhs have been saved on stack.
331 -- Just before the code for the thing is jumped to,
332 -- Sp will be set to this value,
333 -- and then any stack-passed args pushed,
334 -- then the code for this thing will be entered
336 !PrimRep -- the kind of the result
337 CExprMacro -- the macro to generate a value
338 [CAddrMode] -- and its arguments
341 Various C macros for values which are dependent on the back-end layout.
347 | ARG_TAG -- stack argument tagging
348 | GET_TAG -- get current constructor tag
354 Convenience functions:
357 mkIntCLit :: Int -> CAddrMode
358 mkIntCLit i = CLit (mkMachInt (toInteger i))
360 mkCString :: FAST_STRING -> CAddrMode
361 mkCString s = CLit (MachStr s)
363 mkCCostCentre :: CostCentre -> CAddrMode
364 mkCCostCentre cc = CLbl (mkCC_Label cc) DataPtrRep
366 mkCCostCentreStack :: CostCentreStack -> CAddrMode
367 mkCCostCentreStack ccs = CLbl (mkCCS_Label ccs) DataPtrRep
370 %************************************************************************
372 \subsection[RegRelative]{@RegRelatives@: ???}
374 %************************************************************************
379 | SpRel FastInt -- }- offsets in StgWords
380 | NodeRel FastInt -- }
381 | CIndex CAddrMode CAddrMode PrimRep -- pointer arithmetic :-)
382 -- CIndex a b k === (k*)a[b]
385 = DirectReturn -- Jump directly, if possible
386 | StaticVectoredReturn Int -- Fixed tag, starting at zero
387 | DynamicVectoredReturn CAddrMode -- Dynamic tag given by amode, starting at zero
389 hpRel :: VirtualHeapOffset -- virtual offset of Hp
390 -> VirtualHeapOffset -- virtual offset of The Thing
391 -> RegRelative -- integer offset
392 hpRel hp off = HpRel (iUnbox (hp - off))
394 spRel :: VirtualSpOffset -- virtual offset of Sp
395 -> VirtualSpOffset -- virtual offset of The Thing
396 -> RegRelative -- integer offset
397 spRel sp off = SpRel (iUnbox (spRelToInt sp off))
399 nodeRel :: VirtualHeapOffset
401 nodeRel off = NodeRel (iUnbox off)
405 %************************************************************************
407 \subsection[Liveness]{Liveness Masks}
409 %************************************************************************
411 We represent liveness bitmaps as a BitSet (whose internal
412 representation really is a bitmap). These are pinned onto case return
413 vectors to indicate the state of the stack for the garbage collector.
416 type LivenessMask = [BitSet]
418 data Liveness = LvSmall BitSet
422 %************************************************************************
424 \subsection[HeapOffset]{@Heap Offsets@}
426 %************************************************************************
428 This used to be a grotesquely complicated datatype in an attempt to
429 hide the details of header sizes from the compiler itself. Now these
430 constants are imported from the RTS, and we deal in real Ints.
433 type HeapOffset = Int -- ToDo: remove
435 type VirtualHeapOffset = HeapOffset
436 type VirtualSpOffset = Int
438 type HpRelOffset = HeapOffset
439 type SpRelOffset = Int
442 %************************************************************************
444 \subsection[MagicId]{@MagicIds@: registers and such}
446 %************************************************************************
450 = BaseReg -- mentioned only in nativeGen
452 -- Argument and return registers
453 | VanillaReg -- pointers, unboxed ints and chars
455 FastInt -- its number (1 .. mAX_Vanilla_REG)
457 | FloatReg -- single-precision floating-point registers
458 FastInt -- its number (1 .. mAX_Float_REG)
460 | DoubleReg -- double-precision floating-point registers
461 FastInt -- its number (1 .. mAX_Double_REG)
464 | Sp -- Stack ptr; points to last occupied stack location.
465 | Su -- Stack update frame pointer
466 | SpLim -- Stack limit
467 | Hp -- Heap ptr; points to last occupied heap location.
468 | HpLim -- Heap limit register
469 | CurCostCentre -- current cost centre register.
470 | VoidReg -- see "VoidPrim" type; just a placeholder;
471 -- no actual register
472 | LongReg -- long int registers (64-bit, really)
473 PrimRep -- Int64Rep or Word64Rep
474 FastInt -- its number (1 .. mAX_Long_REG)
476 | CurrentTSO -- pointer to current thread's TSO
477 | CurrentNursery -- pointer to allocation area
480 node = VanillaReg PtrRep (_ILIT 1) -- A convenient alias for Node
481 tagreg = VanillaReg WordRep (_ILIT 2) -- A convenient alias for TagReg
486 We need magical @Eq@ because @VanillaReg@s come in multiple flavors.
489 instance Eq MagicId where
490 reg1 == reg2 = tag reg1 ==# tag reg2
492 tag BaseReg = (_ILIT(0) :: FastInt)
498 tag CurCostCentre = _ILIT(6)
499 tag VoidReg = _ILIT(7)
501 tag (VanillaReg _ i) = _ILIT(8) +# i
503 tag (FloatReg i) = _ILIT(8) +# maxv +# i
504 tag (DoubleReg i) = _ILIT(8) +# maxv +# maxf +# i
505 tag (LongReg _ i) = _ILIT(8) +# maxv +# maxf +# maxd +# i
507 maxv = iUnbox mAX_Vanilla_REG
508 maxf = iUnbox mAX_Float_REG
509 maxd = iUnbox mAX_Double_REG
512 Returns True for any register that {\em potentially} dies across
513 C calls (or anything near equivalent). We just say @True@ and
514 let the (machine-specific) registering macros sort things out...
517 isVolatileReg :: MagicId -> Bool
518 isVolatileReg any = True