2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
4 \section[AbstractC]{Abstract C: the last stop before machine code}
6 This ``Abstract C'' data type describes the raw Spineless Tagless
7 machine model at a C-ish level; it is ``abstract'' in that it only
8 includes C-like structures that we happen to need. The conversion of
9 programs from @StgSyntax@ (basically a functional language) to
10 @AbstractC@ (basically imperative C) is the heart of code generation.
11 From @AbstractC@, one may convert to real C (for portability) or to
12 raw assembler/machine code.
22 mkAbstractCs, mkAbsCStmts, mkAlgAltsCSwitch,
31 MagicId(..), node, infoptr,
32 isVolatileReg, noLiveRegsMask, mkLiveRegsMask,
36 #include "HsVersions.h"
38 import {-# SOURCE #-} ClosureInfo ( ClosureInfo )
39 import {-# SOURCE #-} CLabel ( CLabel )
41 #if ! OMIT_NATIVE_CODEGEN
42 import {-# SOURCE #-} MachMisc
45 import Constants ( mAX_Vanilla_REG, mAX_Float_REG,
46 mAX_Double_REG, lIVENESS_R1, lIVENESS_R2,
47 lIVENESS_R3, lIVENESS_R4, lIVENESS_R5,
48 lIVENESS_R6, lIVENESS_R7, lIVENESS_R8
50 import HeapOffs ( VirtualSpAOffset, VirtualSpBOffset,
51 VirtualHeapOffset, HeapOffset
53 import CostCentre ( CostCentre )
54 import Literal ( mkMachInt, Literal )
55 import PrimRep ( isFollowableRep, PrimRep(..) )
56 import PrimOp ( PrimOp )
57 import Unique ( Unique )
61 @AbstractC@ is a list of Abstract~C statements, but the data structure
62 is tree-ish, for easier and more efficient putting-together.
68 | AbsCStmts AbstractC AbstractC
70 -- and the individual stmts...
73 A note on @CAssign@: In general, the type associated with an assignment
74 is the type of the lhs. However, when the lhs is a pointer to mixed
75 types (e.g. SpB relative), the type of the assignment is the type of
76 the rhs for float types, or the generic StgWord for all other types.
77 (In particular, a CharRep on the rhs is promoted to IntRep when
78 stored in a mixed type location.)
86 CAddrMode -- Put this in the program counter
87 -- eg `CJump (CReg (VanillaReg PtrRep 1))' puts Ret1 in PC
88 -- Enter can be done by:
89 -- CJump (CVal NodeRel zeroOff)
92 CAddrMode -- Fall through into this routine
93 -- (for the benefit of the native code generators)
94 -- Equivalent to CJump in C land
96 | CReturn -- This used to be RetVecRegRel
97 CAddrMode -- Any base address mode
98 ReturnInfo -- How to get the return address from the base address
101 [(Literal, AbstractC)] -- alternatives
102 AbstractC -- default; if there is no real Abstract C in here
103 -- (e.g., all comments; see function "nonemptyAbsC"),
104 -- then that means the default _cannot_ occur.
105 -- If there is only one alternative & no default code,
106 -- then there is no need to check the tag.
108 -- CSwitch m [(tag,code)] AbsCNop == code
110 | CCodeBlock CLabel AbstractC
111 -- [amode analog: CLabelledCode]
112 -- A labelled block of code; this "statement" is not
113 -- executed; rather, the labelled code will be hoisted
114 -- out to the top level (out of line) & it can be
117 | CInitHdr -- to initialise the header of a closure (both fixed/var parts)
119 RegRelative -- address of the info ptr
120 CAddrMode -- cost centre to place in closure
121 -- CReg CurCostCentre or CC_HDR(R1.p{-Node-})
122 Bool -- inplace update or allocate
125 [CAddrMode] -- Results
127 [CAddrMode] -- Arguments
128 Int -- Live registers (may be obtainable from volatility? ADR)
129 [MagicId] -- Potentially volatile/live registers
130 -- (to save/restore around the call/op)
132 -- INVARIANT: When a PrimOp which can cause GC is used, the
133 -- only live data is tidily on the STG stacks or in the STG
134 -- registers (the code generator ensures this).
136 -- Why this? Because if the arguments were arbitrary
137 -- addressing modes, they might be things like (Hp+6) which
138 -- will get utterly spongled by GC.
140 | CSimultaneous -- Perform simultaneously all the statements
141 AbstractC -- in the nested AbstractC. They are only
142 -- allowed to be CAssigns, COpStmts and AbsCNops, so the
143 -- "simultaneous" part just concerns making
144 -- sure that permutations work.
145 -- For example { a := b, b := a }
146 -- needs to go via (at least one) temporary
148 -- see the notes about these next few; they follow below...
149 | CMacroStmt CStmtMacro [CAddrMode]
150 | CCallProfCtrMacro FAST_STRING [CAddrMode]
151 | CCallProfCCMacro FAST_STRING [CAddrMode]
153 {- The presence of this constructor is a makeshift solution;
154 it being used to work around a gcc-related problem of
155 handling typedefs within statement blocks (or, rather,
156 the inability to do so.)
158 The AbstractC flattener takes care of lifting out these
159 typedefs if needs be (i.e., when generating .hc code and
160 compiling 'foreign import dynamic's)
162 | CCallTypedef PrimOp{-CCallOp-} [CAddrMode] [CAddrMode]
164 -- *** the next three [or so...] are DATA (those above are CODE) ***
167 CLabel -- The (full, not base) label to use for labelling the closure.
169 CAddrMode -- cost centre identifier to place in closure
170 [CAddrMode] -- free vars; ptrs, then non-ptrs
173 | CClosureInfoAndCode
174 ClosureInfo -- Explains placement and layout of closure
175 AbstractC -- Slow entry point code
177 -- Fast entry point code, if any
178 CAddrMode -- Address of update code; Nothing => should never be used
179 -- (which is the case for all except constructors)
180 String -- Closure description; NB we can't get this from
181 -- ClosureInfo, because the latter refers to the *right* hand
182 -- side of a defn, whereas the "description" refers to *left*
184 Int -- Liveness info; this is here because it is
185 -- easy to produce w/in the CgMonad; hard
186 -- thereafter. (WDP 95/11)
188 | CRetVector -- Return vector with "holes"
189 -- (Nothings) for the default
190 CLabel -- vector-table label
192 AbstractC -- (and what to put in a "hole" [when Nothing])
194 | CRetUnVector -- Direct return
195 CLabel -- unvector-table label
196 CAddrMode -- return code
198 | CFlatRetVector -- A labelled block of static data
199 CLabel -- This is the flattened version of CRetVector
202 | CCostCentreDecl -- A cost centre *declaration*
203 Bool -- True <=> local => full declaration
204 -- False <=> extern; just say so
208 AbstractC -- InRegs Info Table (CClosureInfoTable)
210 -- out of date -- HWL
212 | CSplitMarker -- Split into separate object modules here
215 About @CMacroStmt@, etc.: notionally, they all just call some
216 arbitrary C~macro or routine, passing the @CAddrModes@ as arguments.
217 However, we distinguish between various flavours of these things,
218 mostly just to keep things somewhat less wild and wooly.
222 Some {\em essential} bits of the STG execution model are done with C
223 macros. An example is @STK_CHK@, which checks for stack-space
224 overflow. This enumeration type lists all such macros:
227 = ARGS_CHK_A_LOAD_NODE
229 | ARGS_CHK_B_LOAD_NODE
238 | UPD_BH_SINGLE_ENTRY
242 | GRAN_FETCH -- for GrAnSim only -- HWL
243 | GRAN_RESCHEDULE -- for GrAnSim only -- HWL
244 | GRAN_FETCH_AND_RESCHEDULE -- for GrAnSim only -- HWL
245 | THREAD_CONTEXT_SWITCH -- for GrAnSim only -- HWL
246 | GRAN_YIELD -- for GrAnSim only -- HWL
250 \item[@CCallProfCtrMacro@:]
251 The @String@ names a macro that, if \tr{#define}d, will bump one/some
252 of the STG-event profiling counters.
254 \item[@CCallProfCCMacro@:]
255 The @String@ names a macro that, if \tr{#define}d, will perform some
256 cost-centre-profiling-related action.
259 HERE ARE SOME OLD NOTES ABOUT HEAP-CHK ENTRY POINTS:
262 Some parts of the system, {\em notably the storage manager}, are
263 implemented by C~routines that must know something about the internals
264 of the STG world, e.g., where the heap-pointer is. (The
265 ``C-as-assembler'' documents describes this stuff in detail.)
267 This is quite a tricky business, especially with ``optimised~C,'' so
268 we keep close tabs on these fellows. This enumeration type lists all
269 such ``STG~C'' routines:
271 HERE ARE SOME *OLD* NOTES ABOUT HEAP-CHK ENTRY POINTS:
273 Heap overflow invokes the garbage collector (of your choice :-), and
274 we have different entry points, to tell the GC the exact configuration
277 \item[Branch of a boxed case:]
278 The @Node@ register points off to somewhere legitimate, the @TagReg@
279 holds the tag, and the @RetReg@ points to the code for the
280 alterative which should be resumed. (ToDo: update)
282 \item[Branch of an unboxed case:]
283 The @Node@ register points nowhere of any particular interest, a
284 kind-specific register (@IntReg@, @FloatReg@, etc.) holds the unboxed
285 value, and the @RetReg@ points to the code for the alternative
286 which should be resumed. (ToDo: update)
288 \item[Closure entry:]
289 The @Node@ register points to the closure, and the @RetReg@ points
290 to the code to be resumed. (ToDo: update)
293 %************************************************************************
295 \subsection[CAddrMode]{C addressing modes}
297 %************************************************************************
299 Addressing modes: these have @PrimitiveKinds@ pinned on them.
302 = CVal RegRelative PrimRep
303 -- On RHS of assign: Contents of Magic[n]
304 -- On LHS of assign: location Magic[n]
305 -- (ie at addr Magic+n)
308 -- On RHS of assign: Address of Magic[n]; ie Magic+n
309 -- n=0 gets the Magic location itself
310 -- (NB: n=0 case superceded by CReg)
311 -- On LHS of assign: only sensible if n=0,
312 -- which gives the magic location itself
313 -- (NB: superceded by CReg)
315 | CReg MagicId -- To replace (CAddr MagicId 0)
317 | CTableEntry -- CVal should be generalized to allow this
320 PrimRep -- For casting
322 | CTemp Unique PrimRep -- Temporary locations
323 -- ``Temporaries'' correspond to local variables in C, and registers in
326 | CLbl CLabel -- Labels in the runtime system, etc.
327 -- See comment under CLabelledData about (String,Name)
328 PrimRep -- the kind is so we can generate accurate C decls
330 | CUnVecLbl -- A choice of labels left up to the back end
334 | CCharLike CAddrMode -- The address of a static char-like closure for
335 -- the specified character. It is guaranteed to be in
338 | CIntLike CAddrMode -- The address of a static int-like closure for the
339 -- specified small integer. It is guaranteed to be in the
340 -- range mIN_INTLIKE..mAX_INTLIKE
342 | CString FAST_STRING -- The address of the null-terminated string
344 | CLitLit FAST_STRING -- completely literal literal: just spit this String
348 | COffset HeapOffset -- A literal constant, not an offset *from* anything!
349 -- ToDo: this should really be CLitOffset
351 | CCode AbstractC -- Some code. Used mainly for return addresses.
353 | CLabelledCode CLabel AbstractC -- Almost defunct? (ToDo?) --JSM
354 -- Some code that must have a particular label
355 -- (which is jumpable to)
357 | CJoinPoint -- This is used as the amode of a let-no-escape-bound variable
358 VirtualSpAOffset -- SpA and SpB values after any volatile free vars
359 VirtualSpBOffset -- of the rhs have been saved on stack.
360 -- Just before the code for the thing is jumped to,
361 -- SpA/B will be set to these values,
362 -- and then any stack-passed args pushed,
363 -- then the code for this thing will be entered
366 PrimRep -- the kind of the result
367 CExprMacro -- the macro to generate a value
368 [CAddrMode] -- and its arguments
370 | CCostCentre -- If Bool is True ==> it to be printed as a String,
371 CostCentre -- (*not* as a C identifier or some such).
372 Bool -- (It's not just the double-quotes on either side;
373 -- spaces and other funny characters will have been
374 -- fiddled in the non-String variant.)
377 = --ASSERT(not (currentOrSubsumedCosts cc))
378 --FALSE: We do put subsumedCC in static closures
382 Various C macros for values which are dependent on the back-end layout.
397 mkIntCLit :: Int -> CAddrMode
398 mkIntCLit i = CLit (mkMachInt (toInteger i))
401 %************************************************************************
403 \subsection[RegRelative]{@RegRelatives@: ???}
405 %************************************************************************
409 = HpRel VirtualHeapOffset -- virtual offset of Hp
410 VirtualHeapOffset -- virtual offset of The Thing
411 | SpARel VirtualSpAOffset -- virtual offset of SpA
412 VirtualSpAOffset -- virtual offset of The Thing
413 | SpBRel VirtualSpBOffset -- virtual offset of SpB
414 VirtualSpBOffset -- virtual offset of The Thing
415 | NodeRel VirtualHeapOffset
418 = DirectReturn -- Jump directly, if possible
419 | StaticVectoredReturn Int -- Fixed tag, starting at zero
420 | DynamicVectoredReturn CAddrMode -- Dynamic tag given by amode, starting at zero
423 %************************************************************************
425 \subsection[MagicId]{@MagicIds@: registers and such}
427 %************************************************************************
429 Much of what happens in Abstract-C is in terms of ``magic'' locations,
430 such as the stack pointer, heap pointer, etc. If possible, these will
431 be held in registers.
433 Here are some notes about what's active when:
435 \item[Always active:]
436 Hp, HpLim, SpA, SpB, SuA, SuB
442 Ptr regs: RetPtr1 (= Node), RetPtr2...
443 Int/char regs: RetData1 (= TagReg = IntReg), RetData2...
444 Float regs: RetFloat1, ...
445 Double regs: RetDouble1, ...
450 = BaseReg -- mentioned only in nativeGen
452 | StkOReg -- mentioned only in nativeGen
454 -- Argument and return registers
455 | VanillaReg -- pointers, unboxed ints and chars
456 PrimRep -- PtrRep, IntRep, CharRep, StablePtrRep or ForeignObjRep
457 -- (in case we need to distinguish)
458 FAST_INT -- its number (1 .. mAX_Vanilla_REG)
460 | FloatReg -- single-precision floating-point registers
461 FAST_INT -- its number (1 .. mAX_Float_REG)
463 | DoubleReg -- double-precision floating-point registers
464 FAST_INT -- its number (1 .. mAX_Double_REG)
466 | LongReg -- long int registers (64-bit, really)
467 PrimRep -- Int64Rep or Word64Rep
468 FAST_INT -- its number (1 .. mAX_Long_REG)
470 | TagReg -- to return constructor tags; as almost all returns are vectored,
471 -- this is rarely used.
473 | RetReg -- topmost return address from the B stack
475 | SpA -- Stack ptr; points to last occupied stack location.
476 -- Stack grows downward.
477 | SuA -- mentioned only in nativeGen
479 | SpB -- Basic values, return addresses and update frames.
481 | SuB -- mentioned only in nativeGen
483 | Hp -- Heap ptr; points to last occupied heap location.
484 -- Free space at lower addresses.
486 | HpLim -- Heap limit register: mentioned only in nativeGen
488 | LivenessReg -- (parallel only) used when we need to record explicitly
489 -- what registers are live
491 | StdUpdRetVecReg -- mentioned only in nativeGen
492 | StkStubReg -- register holding STK_STUB_closure (for stubbing dead stack slots)
494 | CurCostCentre -- current cost centre register.
496 | VoidReg -- see "VoidPrim" type; just a placeholder; no actual register
498 node = VanillaReg PtrRep ILIT(1) -- A convenient alias for Node
499 infoptr = VanillaReg DataPtrRep ILIT(2) -- An alias for InfoPtr
502 noLiveRegsMask :: Int -- Mask indicating nothing live
506 :: [MagicId] -- Candidate live regs; depends what they have in them
510 = foldl do_reg noLiveRegsMask regs
512 do_reg acc (VanillaReg kind reg_no)
513 | isFollowableRep kind
514 = acc + (reg_tbl !! IBOX(reg_no _SUB_ ILIT(1)))
516 do_reg acc anything_else = acc
518 reg_tbl -- ToDo: mk Array!
519 = [lIVENESS_R1, lIVENESS_R2, lIVENESS_R3, lIVENESS_R4,
520 lIVENESS_R5, lIVENESS_R6, lIVENESS_R7, lIVENESS_R8]
523 We need magical @Eq@ because @VanillaReg@s come in multiple flavors.
526 instance Eq MagicId where
527 reg1 == reg2 = tag reg1 _EQ_ tag reg2
529 tag BaseReg = (ILIT(0) :: FAST_INT)
530 tag StkOReg = ILIT(1)
539 tag LivenessReg = ILIT(10)
540 tag StdUpdRetVecReg = ILIT(12)
541 tag StkStubReg = ILIT(13)
542 tag CurCostCentre = ILIT(14)
543 tag VoidReg = ILIT(15)
549 FloatReg i -> maxv _ADD_ i
550 DoubleReg i -> maxv _ADD_ maxf _ADD_ i
551 LongReg _ i -> maxv _ADD_ maxf _ADD_ maxd _ADD_ i
554 maxv = case mAX_Vanilla_REG of { IBOX(x) -> x }
555 maxf = case mAX_Float_REG of { IBOX(x) -> x }
556 maxd = case mAX_Double_REG of { IBOX(x) -> x }
559 Returns True for any register that {\em potentially} dies across
560 C calls (or anything near equivalent). We just say @True@ and
561 let the (machine-specific) registering macros sort things out...
563 isVolatileReg :: MagicId -> Bool
565 isVolatileReg any = True
566 --isVolatileReg (FloatReg _) = True
567 --isVolatileReg (DoubleReg _) = True
570 %************************************************************************
572 \subsection[AbsCSyn-printing]{Pretty-printing Abstract~C}
574 %************************************************************************
576 It's in \tr{PprAbsC.lhs}.