Haddockify and clean up commenting
[ghc-hetmet.git] / compiler / cmm / CLabel.hs
1 {-# OPTIONS -w #-}
2 -- The above warning supression flag is a temporary kludge.
3 -- While working on this module you are encouraged to remove it and fix
4 -- any warnings in the module. See
5 --     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
6 -- for details
7
8 -----------------------------------------------------------------------------
9 --
10 -- Object-file symbols (called CLabel for histerical raisins).
11 --
12 -- (c) The University of Glasgow 2004-2006
13 --
14 -----------------------------------------------------------------------------
15
16 module CLabel (
17         CLabel, -- abstract type
18
19         mkClosureLabel,
20         mkSRTLabel,
21         mkInfoTableLabel,
22         mkEntryLabel,
23         mkSlowEntryLabel,
24         mkConEntryLabel,
25         mkStaticConEntryLabel,
26         mkRednCountsLabel,
27         mkConInfoTableLabel,
28         mkStaticInfoTableLabel,
29         mkLargeSRTLabel,
30         mkApEntryLabel,
31         mkApInfoTableLabel,
32         mkClosureTableLabel,
33
34         mkLocalClosureLabel,
35         mkLocalInfoTableLabel,
36         mkLocalEntryLabel,
37         mkLocalConEntryLabel,
38         mkLocalStaticConEntryLabel,
39         mkLocalConInfoTableLabel,
40         mkLocalStaticInfoTableLabel,
41         mkLocalClosureTableLabel,
42
43         mkReturnPtLabel,
44         mkReturnInfoLabel,
45         mkAltLabel,
46         mkDefaultLabel,
47         mkBitmapLabel,
48         mkStringLitLabel,
49
50         mkAsmTempLabel,
51
52         mkModuleInitLabel,
53         mkPlainModuleInitLabel,
54         mkModuleInitTableLabel,
55
56         mkSplitMarkerLabel,
57         mkDirty_MUT_VAR_Label,
58         mkUpdInfoLabel,
59         mkIndStaticInfoLabel,
60         mkMainCapabilityLabel,
61         mkMAP_FROZEN_infoLabel,
62         mkMAP_DIRTY_infoLabel,
63         mkEMPTY_MVAR_infoLabel,
64
65         mkTopTickyCtrLabel,
66         mkCAFBlackHoleInfoTableLabel,
67         mkRtsPrimOpLabel,
68         mkRtsSlowTickyCtrLabel,
69
70         moduleRegdLabel,
71         moduleRegTableLabel,
72
73         mkSelectorInfoLabel,
74         mkSelectorEntryLabel,
75
76         mkRtsInfoLabel,
77         mkRtsEntryLabel,
78         mkRtsRetInfoLabel,
79         mkRtsRetLabel,
80         mkRtsCodeLabel,
81         mkRtsDataLabel,
82         mkRtsGcPtrLabel,
83
84         mkRtsApFastLabel,
85
86         mkPrimCallLabel,
87
88         mkForeignLabel,
89         addLabelSize,
90         foreignLabelStdcallInfo,
91
92         mkCCLabel, mkCCSLabel,
93
94         DynamicLinkerLabelInfo(..),
95         mkDynamicLinkerLabel,
96         dynamicLinkerLabelInfo,
97         
98         mkPicBaseLabel,
99         mkDeadStripPreventer,
100
101         mkHpcTicksLabel,
102         mkHpcModuleNameLabel,
103
104         hasCAF,
105         infoLblToEntryLbl, entryLblToInfoLbl, cvtToClosureLbl, cvtToSRTLbl,
106         needsCDecl, isAsmTemp, maybeAsmTemp, externallyVisibleCLabel,
107         isMathFun,
108         isCFunctionLabel, isGcPtrLabel, labelDynamic,
109
110         pprCLabel
111     ) where
112
113 #include "HsVersions.h"
114
115 import IdInfo
116 import StaticFlags
117 import BasicTypes
118 import Literal
119 import Packages
120 import DataCon
121 import PackageConfig
122 import Module
123 import Name
124 import Unique
125 import PrimOp
126 import Config
127 import CostCentre
128 import Outputable
129 import FastString
130 import DynFlags
131 import UniqSet
132
133 -- -----------------------------------------------------------------------------
134 -- The CLabel type
135
136 {-
137   | CLabel is an abstract type that supports the following operations:
138
139   - Pretty printing
140
141   - In a C file, does it need to be declared before use?  (i.e. is it
142     guaranteed to be already in scope in the places we need to refer to it?)
143
144   - If it needs to be declared, what type (code or data) should it be
145     declared to have?
146
147   - Is it visible outside this object file or not?
148
149   - Is it "dynamic" (see details below)
150
151   - Eq and Ord, so that we can make sets of CLabels (currently only
152     used in outputting C as far as I can tell, to avoid generating
153     more than one declaration for any given label).
154
155   - Converting an info table label into an entry label.
156 -}
157
158 data CLabel
159   = -- | A label related to the definition of a particular Id or Con in a .hs file.
160     IdLabel                     
161         Name                    
162         CafInfo
163         IdLabelInfo
164
165   -- | A label with a baked-in name that definitely comes from the RTS.
166   --    The code for it must compile into libHSrts.a \/ libHSrts.so \/ libHSrts.dll
167   | RtsLabel                    
168         RtsLabelInfo
169
170   -- | A 'C' (or otherwise foreign) label
171   | ForeignLabel FastString     
172         (Maybe Int)             -- possible '@n' suffix for stdcall functions
173                                 -- When generating C, the '@n' suffix is omitted, but when
174                                 -- generating assembler we must add it to the label.
175         Bool                    -- True <=> is dynamic
176         FunctionOrData
177
178   -- | A family of labels related to a particular case expression.
179   | CaseLabel                   
180         {-# UNPACK #-} !Unique  -- Unique says which case expression
181         CaseLabelInfo
182
183   | AsmTempLabel 
184         {-# UNPACK #-} !Unique
185
186   | StringLitLabel
187         {-# UNPACK #-} !Unique
188
189   | ModuleInitLabel 
190         Module                  -- the module name
191         String                  -- its "way"
192         -- at some point we might want some kind of version number in
193         -- the module init label, to guard against compiling modules in
194         -- the wrong order.  We can't use the interface file version however,
195         -- because we don't always recompile modules which depend on a module
196         -- whose version has changed.
197
198   | PlainModuleInitLabel        -- without the version & way info
199         Module
200
201   | ModuleInitTableLabel        -- table of imported modules to init
202         Module
203
204   | ModuleRegdLabel
205
206   | CC_Label  CostCentre
207   | CCS_Label CostCentreStack
208
209     
210   -- | These labels are generated and used inside the NCG only. 
211   --    They are special variants of a label used for dynamic linking
212   --    see module PositionIndependentCode for details.
213   | DynamicLinkerLabel DynamicLinkerLabelInfo CLabel
214  
215   -- | This label is generated and used inside the NCG only. 
216   --    It is used as a base for PIC calculations on some platforms.
217   --    It takes the form of a local numeric assembler label '1'; and 
218   --    is pretty-printed as 1b, referring to the previous definition
219   --    of 1: in the assembler source file.
220   | PicBaseLabel                
221  
222   -- | A label before an info table to prevent excessive dead-stripping on darwin
223   | DeadStripPreventer CLabel
224
225
226   -- | Per-module table of tick locations
227   | HpcTicksLabel Module
228
229   -- | Per-module name of the module for Hpc
230   | HpcModuleNameLabel
231
232   -- | Label of an StgLargeSRT
233   | LargeSRTLabel
234         {-# UNPACK #-} !Unique
235
236   -- | A bitmap (function or case return)
237   | LargeBitmapLabel
238         {-# UNPACK #-} !Unique
239
240   deriving (Eq, Ord)
241
242 data IdLabelInfo
243   = Closure             -- ^ Label for closure
244   | SRT                 -- ^ Static reference table
245   | InfoTable           -- ^ Info tables for closures; always read-only
246   | Entry               -- ^ Entry point
247   | Slow                -- ^ Slow entry point
248
249   | RednCounts          -- ^ Label of place to keep Ticky-ticky  info for this Id
250
251   | ConEntry            -- ^ Constructor entry point
252   | ConInfoTable        -- ^ Corresponding info table
253   | StaticConEntry      -- ^ Static constructor entry point
254   | StaticInfoTable     -- ^ Corresponding info table
255
256   | ClosureTable        -- ^ Table of closures for Enum tycons
257
258   deriving (Eq, Ord)
259
260
261 data CaseLabelInfo
262   = CaseReturnPt
263   | CaseReturnInfo
264   | CaseAlt ConTag
265   | CaseDefault
266   deriving (Eq, Ord)
267
268
269 data RtsLabelInfo
270   = RtsSelectorInfoTable Bool{-updatable-} Int{-offset-}  -- ^ Selector thunks
271   | RtsSelectorEntry     Bool{-updatable-} Int{-offset-}
272
273   | RtsApInfoTable       Bool{-updatable-} Int{-arity-}    -- ^ AP thunks
274   | RtsApEntry           Bool{-updatable-} Int{-arity-}
275
276   | RtsPrimOp PrimOp
277
278   | RtsInfo       FastString    -- ^ misc rts info tables
279   | RtsEntry      FastString    -- ^ misc rts entry points
280   | RtsRetInfo    FastString    -- ^ misc rts ret info tables
281   | RtsRet        FastString    -- ^ misc rts return points
282   | RtsData       FastString    -- ^ misc rts data bits, eg CHARLIKE_closure
283   | RtsCode       FastString    -- ^ misc rts code
284   | RtsGcPtr      FastString    -- ^ GcPtrs eg CHARLIKE_closure  
285
286   | RtsApFast     FastString    -- ^ _fast versions of generic apply
287
288   | RtsSlowTickyCtr String
289
290   deriving (Eq, Ord)
291   -- NOTE: Eq on LitString compares the pointer only, so this isn't
292   -- a real equality.
293
294 data DynamicLinkerLabelInfo
295   = CodeStub                    -- MachO: Lfoo$stub, ELF: foo@plt
296   | SymbolPtr                   -- MachO: Lfoo$non_lazy_ptr, Windows: __imp_foo
297   | GotSymbolPtr                -- ELF: foo@got
298   | GotSymbolOffset             -- ELF: foo@gotoff
299   
300   deriving (Eq, Ord)
301   
302 -- -----------------------------------------------------------------------------
303 -- Constructing CLabels
304
305 -- These are always local:
306 mkSRTLabel              name c  = IdLabel name  c SRT
307 mkSlowEntryLabel        name c  = IdLabel name  c Slow
308 mkRednCountsLabel       name c  = IdLabel name  c RednCounts
309
310 -- These have local & (possibly) external variants:
311 mkLocalClosureLabel     name c  = IdLabel name  c Closure
312 mkLocalInfoTableLabel   name c  = IdLabel name  c InfoTable
313 mkLocalEntryLabel       name c  = IdLabel name  c Entry
314 mkLocalClosureTableLabel name c = IdLabel name  c ClosureTable
315
316 mkClosureLabel name         c     = IdLabel name c Closure
317 mkInfoTableLabel name       c     = IdLabel name c InfoTable
318 mkEntryLabel name           c     = IdLabel name c Entry
319 mkClosureTableLabel name    c     = IdLabel name c ClosureTable
320 mkLocalConInfoTableLabel    c con = IdLabel con c ConInfoTable
321 mkLocalConEntryLabel        c con = IdLabel con c ConEntry
322 mkLocalStaticInfoTableLabel c con = IdLabel con c StaticInfoTable
323 mkLocalStaticConEntryLabel  c con = IdLabel con c StaticConEntry
324 mkConInfoTableLabel name    c     = IdLabel    name c ConInfoTable
325 mkStaticInfoTableLabel name c     = IdLabel    name c StaticInfoTable
326
327 mkConEntryLabel name        c     = IdLabel name c ConEntry
328 mkStaticConEntryLabel name  c     = IdLabel name c StaticConEntry
329
330 mkLargeSRTLabel uniq    = LargeSRTLabel uniq
331 mkBitmapLabel   uniq    = LargeBitmapLabel uniq
332
333 mkReturnPtLabel uniq            = CaseLabel uniq CaseReturnPt
334 mkReturnInfoLabel uniq          = CaseLabel uniq CaseReturnInfo
335 mkAltLabel      uniq tag        = CaseLabel uniq (CaseAlt tag)
336 mkDefaultLabel  uniq            = CaseLabel uniq CaseDefault
337
338 mkStringLitLabel                = StringLitLabel
339 mkAsmTempLabel :: Uniquable a => a -> CLabel
340 mkAsmTempLabel a                = AsmTempLabel (getUnique a)
341
342 mkModuleInitLabel :: Module -> String -> CLabel
343 mkModuleInitLabel mod way        = ModuleInitLabel mod way
344
345 mkPlainModuleInitLabel :: Module -> CLabel
346 mkPlainModuleInitLabel mod       = PlainModuleInitLabel mod
347
348 mkModuleInitTableLabel :: Module -> CLabel
349 mkModuleInitTableLabel mod       = ModuleInitTableLabel mod
350
351         -- Some fixed runtime system labels
352
353 mkSplitMarkerLabel              = RtsLabel (RtsCode (fsLit "__stg_split_marker"))
354 mkDirty_MUT_VAR_Label           = RtsLabel (RtsCode (fsLit "dirty_MUT_VAR"))
355 mkUpdInfoLabel                  = RtsLabel (RtsInfo (fsLit "stg_upd_frame"))
356 mkIndStaticInfoLabel            = RtsLabel (RtsInfo (fsLit "stg_IND_STATIC"))
357 mkMainCapabilityLabel           = RtsLabel (RtsData (fsLit "MainCapability"))
358 mkMAP_FROZEN_infoLabel          = RtsLabel (RtsInfo (fsLit "stg_MUT_ARR_PTRS_FROZEN0"))
359 mkMAP_DIRTY_infoLabel           = RtsLabel (RtsInfo (fsLit "stg_MUT_ARR_PTRS_DIRTY"))
360 mkEMPTY_MVAR_infoLabel          = RtsLabel (RtsInfo (fsLit "stg_EMPTY_MVAR"))
361
362 mkTopTickyCtrLabel              = RtsLabel (RtsData (fsLit "top_ct"))
363 mkCAFBlackHoleInfoTableLabel    = RtsLabel (RtsInfo (fsLit "stg_CAF_BLACKHOLE"))
364 mkRtsPrimOpLabel primop         = RtsLabel (RtsPrimOp primop)
365
366 moduleRegdLabel                 = ModuleRegdLabel
367 moduleRegTableLabel             = ModuleInitTableLabel  
368
369 mkSelectorInfoLabel  upd off    = RtsLabel (RtsSelectorInfoTable upd off)
370 mkSelectorEntryLabel upd off    = RtsLabel (RtsSelectorEntry   upd off)
371
372 mkApInfoTableLabel  upd off     = RtsLabel (RtsApInfoTable upd off)
373 mkApEntryLabel upd off          = RtsLabel (RtsApEntry   upd off)
374
375         -- Primitive / cmm call labels
376
377 mkPrimCallLabel :: PrimCall -> CLabel
378 mkPrimCallLabel (PrimCall str)  = ForeignLabel str Nothing False IsFunction
379
380         -- Foreign labels
381
382 mkForeignLabel :: FastString -> Maybe Int -> Bool -> FunctionOrData -> CLabel
383 mkForeignLabel str mb_sz is_dynamic fod
384     = ForeignLabel str mb_sz is_dynamic fod
385
386 addLabelSize :: CLabel -> Int -> CLabel
387 addLabelSize (ForeignLabel str _ is_dynamic fod) sz
388   = ForeignLabel str (Just sz) is_dynamic fod
389 addLabelSize label _
390   = label
391
392 foreignLabelStdcallInfo :: CLabel -> Maybe Int
393 foreignLabelStdcallInfo (ForeignLabel _ info _ _) = info
394 foreignLabelStdcallInfo _lbl = Nothing
395
396         -- Cost centres etc.
397
398 mkCCLabel       cc              = CC_Label cc
399 mkCCSLabel      ccs             = CCS_Label ccs
400
401 mkRtsInfoLabel      str = RtsLabel (RtsInfo      str)
402 mkRtsEntryLabel     str = RtsLabel (RtsEntry     str)
403 mkRtsRetInfoLabel   str = RtsLabel (RtsRetInfo   str)
404 mkRtsRetLabel       str = RtsLabel (RtsRet       str)
405 mkRtsCodeLabel      str = RtsLabel (RtsCode      str)
406 mkRtsDataLabel      str = RtsLabel (RtsData      str)
407 mkRtsGcPtrLabel     str = RtsLabel (RtsGcPtr     str)
408
409 mkRtsApFastLabel str = RtsLabel (RtsApFast str)
410
411 mkRtsSlowTickyCtrLabel :: String -> CLabel
412 mkRtsSlowTickyCtrLabel pat = RtsLabel (RtsSlowTickyCtr pat)
413
414         -- Coverage
415
416 mkHpcTicksLabel                = HpcTicksLabel
417 mkHpcModuleNameLabel           = HpcModuleNameLabel
418
419         -- Dynamic linking
420         
421 mkDynamicLinkerLabel :: DynamicLinkerLabelInfo -> CLabel -> CLabel
422 mkDynamicLinkerLabel = DynamicLinkerLabel
423
424 dynamicLinkerLabelInfo :: CLabel -> Maybe (DynamicLinkerLabelInfo, CLabel)
425 dynamicLinkerLabelInfo (DynamicLinkerLabel info lbl) = Just (info, lbl)
426 dynamicLinkerLabelInfo _ = Nothing
427
428         -- Position independent code
429         
430 mkPicBaseLabel :: CLabel
431 mkPicBaseLabel = PicBaseLabel
432
433 mkDeadStripPreventer :: CLabel -> CLabel
434 mkDeadStripPreventer lbl = DeadStripPreventer lbl
435
436 -- -----------------------------------------------------------------------------
437 -- Converting between info labels and entry/ret labels.
438
439 infoLblToEntryLbl :: CLabel -> CLabel 
440 infoLblToEntryLbl (IdLabel n c InfoTable)       = IdLabel n c Entry
441 infoLblToEntryLbl (IdLabel n c ConInfoTable)    = IdLabel n c ConEntry
442 infoLblToEntryLbl (IdLabel n c StaticInfoTable) = IdLabel n c StaticConEntry
443 infoLblToEntryLbl (CaseLabel n CaseReturnInfo)  = CaseLabel n CaseReturnPt
444 infoLblToEntryLbl (RtsLabel (RtsInfo s))      = RtsLabel (RtsEntry s)
445 infoLblToEntryLbl (RtsLabel (RtsRetInfo s))   = RtsLabel (RtsRet s)
446 infoLblToEntryLbl _ = panic "CLabel.infoLblToEntryLbl"
447
448 entryLblToInfoLbl :: CLabel -> CLabel 
449 entryLblToInfoLbl (IdLabel n c Entry)           = IdLabel n c InfoTable
450 entryLblToInfoLbl (IdLabel n c ConEntry)        = IdLabel n c ConInfoTable
451 entryLblToInfoLbl (IdLabel n c StaticConEntry)  = IdLabel n c StaticInfoTable
452 entryLblToInfoLbl (CaseLabel n CaseReturnPt)    = CaseLabel n CaseReturnInfo
453 entryLblToInfoLbl (RtsLabel (RtsEntry s))     = RtsLabel (RtsInfo s)
454 entryLblToInfoLbl (RtsLabel (RtsRet s))       = RtsLabel (RtsRetInfo s)
455 entryLblToInfoLbl l = pprPanic "CLabel.entryLblToInfoLbl" (pprCLabel l)
456
457 cvtToClosureLbl   (IdLabel n c InfoTable) = IdLabel n c Closure
458 cvtToClosureLbl   (IdLabel n c Entry)     = IdLabel n c Closure
459 cvtToClosureLbl   (IdLabel n c ConEntry)  = IdLabel n c Closure
460 cvtToClosureLbl l@(IdLabel n c Closure)   = l
461 cvtToClosureLbl l = pprPanic "cvtToClosureLbl" (pprCLabel l)
462
463 cvtToSRTLbl   (IdLabel n c InfoTable) = mkSRTLabel n c
464 cvtToSRTLbl   (IdLabel n c Entry)     = mkSRTLabel n c
465 cvtToSRTLbl   (IdLabel n c ConEntry)  = mkSRTLabel n c
466 cvtToSRTLbl l@(IdLabel n c Closure)   = mkSRTLabel n c
467 cvtToSRTLbl l = pprPanic "cvtToSRTLbl" (pprCLabel l)
468
469 -- -----------------------------------------------------------------------------
470 -- Does a CLabel refer to a CAF?
471 hasCAF :: CLabel -> Bool
472 hasCAF (IdLabel _ MayHaveCafRefs _) = True
473 hasCAF _                            = False
474
475 -- -----------------------------------------------------------------------------
476 -- Does a CLabel need declaring before use or not?
477 --
478 -- See wiki:Commentary/Compiler/Backends/PprC#Prototypes
479
480 needsCDecl :: CLabel -> Bool
481   -- False <=> it's pre-declared; don't bother
482   -- don't bother declaring SRT & Bitmap labels, we always make sure
483   -- they are defined before use.
484 needsCDecl (IdLabel _ _ SRT)            = False
485 needsCDecl (LargeSRTLabel _)            = False
486 needsCDecl (LargeBitmapLabel _)         = False
487 needsCDecl (IdLabel _ _ _)              = True
488 needsCDecl (CaseLabel _ _)              = True
489 needsCDecl (ModuleInitLabel _ _)        = True
490 needsCDecl (PlainModuleInitLabel _)     = True
491 needsCDecl (ModuleInitTableLabel _)     = True
492 needsCDecl ModuleRegdLabel              = False
493
494 needsCDecl (StringLitLabel _)           = False
495 needsCDecl (AsmTempLabel _)             = False
496 needsCDecl (RtsLabel _)                 = False
497 needsCDecl l@(ForeignLabel _ _ _ _)     = not (isMathFun l)
498 needsCDecl (CC_Label _)                 = True
499 needsCDecl (CCS_Label _)                = True
500 needsCDecl (HpcTicksLabel _)            = True
501 needsCDecl HpcModuleNameLabel           = False
502
503 -- Whether the label is an assembler temporary:
504
505 isAsmTemp  :: CLabel -> Bool    -- is a local temporary for native code generation
506 isAsmTemp (AsmTempLabel _) = True
507 isAsmTemp _                = False
508
509 maybeAsmTemp :: CLabel -> Maybe Unique
510 maybeAsmTemp (AsmTempLabel uq) = Just uq
511 maybeAsmTemp _                 = Nothing
512
513 -- some labels have C prototypes in scope when compiling via C, because
514 -- they are builtin to the C compiler.  For these labels we avoid
515 -- generating our own C prototypes.
516 isMathFun :: CLabel -> Bool
517 isMathFun (ForeignLabel fs _ _ _) = fs `elementOfUniqSet` math_funs
518 isMathFun _ = False
519
520 math_funs = mkUniqSet [
521         -- _ISOC99_SOURCE
522         (fsLit "acos"),         (fsLit "acosf"),        (fsLit "acosh"),
523         (fsLit "acoshf"),       (fsLit "acoshl"),       (fsLit "acosl"),
524         (fsLit "asin"),         (fsLit "asinf"),        (fsLit "asinl"),
525         (fsLit "asinh"),        (fsLit "asinhf"),       (fsLit "asinhl"),
526         (fsLit "atan"),         (fsLit "atanf"),        (fsLit "atanl"),
527         (fsLit "atan2"),        (fsLit "atan2f"),       (fsLit "atan2l"),
528         (fsLit "atanh"),        (fsLit "atanhf"),       (fsLit "atanhl"),
529         (fsLit "cbrt"),         (fsLit "cbrtf"),        (fsLit "cbrtl"),
530         (fsLit "ceil"),         (fsLit "ceilf"),        (fsLit "ceill"),
531         (fsLit "copysign"),     (fsLit "copysignf"),    (fsLit "copysignl"),
532         (fsLit "cos"),          (fsLit "cosf"),         (fsLit "cosl"),
533         (fsLit "cosh"),         (fsLit "coshf"),        (fsLit "coshl"),
534         (fsLit "erf"),          (fsLit "erff"),         (fsLit "erfl"),
535         (fsLit "erfc"),         (fsLit "erfcf"),        (fsLit "erfcl"),
536         (fsLit "exp"),          (fsLit "expf"),         (fsLit "expl"),
537         (fsLit "exp2"),         (fsLit "exp2f"),        (fsLit "exp2l"),
538         (fsLit "expm1"),        (fsLit "expm1f"),       (fsLit "expm1l"),
539         (fsLit "fabs"),         (fsLit "fabsf"),        (fsLit "fabsl"),
540         (fsLit "fdim"),         (fsLit "fdimf"),        (fsLit "fdiml"),
541         (fsLit "floor"),        (fsLit "floorf"),       (fsLit "floorl"),
542         (fsLit "fma"),          (fsLit "fmaf"),         (fsLit "fmal"),
543         (fsLit "fmax"),         (fsLit "fmaxf"),        (fsLit "fmaxl"),
544         (fsLit "fmin"),         (fsLit "fminf"),        (fsLit "fminl"),
545         (fsLit "fmod"),         (fsLit "fmodf"),        (fsLit "fmodl"),
546         (fsLit "frexp"),        (fsLit "frexpf"),       (fsLit "frexpl"),
547         (fsLit "hypot"),        (fsLit "hypotf"),       (fsLit "hypotl"),
548         (fsLit "ilogb"),        (fsLit "ilogbf"),       (fsLit "ilogbl"),
549         (fsLit "ldexp"),        (fsLit "ldexpf"),       (fsLit "ldexpl"),
550         (fsLit "lgamma"),       (fsLit "lgammaf"),      (fsLit "lgammal"),
551         (fsLit "llrint"),       (fsLit "llrintf"),      (fsLit "llrintl"),
552         (fsLit "llround"),      (fsLit "llroundf"),     (fsLit "llroundl"),
553         (fsLit "log"),          (fsLit "logf"),         (fsLit "logl"),
554         (fsLit "log10l"),       (fsLit "log10"),        (fsLit "log10f"),
555         (fsLit "log1pl"),       (fsLit "log1p"),        (fsLit "log1pf"),
556         (fsLit "log2"),         (fsLit "log2f"),        (fsLit "log2l"),
557         (fsLit "logb"),         (fsLit "logbf"),        (fsLit "logbl"),
558         (fsLit "lrint"),        (fsLit "lrintf"),       (fsLit "lrintl"),
559         (fsLit "lround"),       (fsLit "lroundf"),      (fsLit "lroundl"),
560         (fsLit "modf"),         (fsLit "modff"),        (fsLit "modfl"),
561         (fsLit "nan"),          (fsLit "nanf"),         (fsLit "nanl"),
562         (fsLit "nearbyint"),    (fsLit "nearbyintf"),   (fsLit "nearbyintl"),
563         (fsLit "nextafter"),    (fsLit "nextafterf"),   (fsLit "nextafterl"),
564         (fsLit "nexttoward"),   (fsLit "nexttowardf"),  (fsLit "nexttowardl"),
565         (fsLit "pow"),          (fsLit "powf"),         (fsLit "powl"),
566         (fsLit "remainder"),    (fsLit "remainderf"),   (fsLit "remainderl"),
567         (fsLit "remquo"),       (fsLit "remquof"),      (fsLit "remquol"),
568         (fsLit "rint"),         (fsLit "rintf"),        (fsLit "rintl"),
569         (fsLit "round"),        (fsLit "roundf"),       (fsLit "roundl"),
570         (fsLit "scalbln"),      (fsLit "scalblnf"),     (fsLit "scalblnl"),
571         (fsLit "scalbn"),       (fsLit "scalbnf"),      (fsLit "scalbnl"),
572         (fsLit "sin"),          (fsLit "sinf"),         (fsLit "sinl"),
573         (fsLit "sinh"),         (fsLit "sinhf"),        (fsLit "sinhl"),
574         (fsLit "sqrt"),         (fsLit "sqrtf"),        (fsLit "sqrtl"),
575         (fsLit "tan"),          (fsLit "tanf"),         (fsLit "tanl"),
576         (fsLit "tanh"),         (fsLit "tanhf"),        (fsLit "tanhl"),
577         (fsLit "tgamma"),       (fsLit "tgammaf"),      (fsLit "tgammal"),
578         (fsLit "trunc"),        (fsLit "truncf"),       (fsLit "truncl"),
579         -- ISO C 99 also defines these function-like macros in math.h:
580         -- fpclassify, isfinite, isinf, isnormal, signbit, isgreater,
581         -- isgreaterequal, isless, islessequal, islessgreater, isunordered
582
583         -- additional symbols from _BSD_SOURCE
584         (fsLit "drem"),         (fsLit "dremf"),        (fsLit "dreml"),
585         (fsLit "finite"),       (fsLit "finitef"),      (fsLit "finitel"),
586         (fsLit "gamma"),        (fsLit "gammaf"),       (fsLit "gammal"),
587         (fsLit "isinf"),        (fsLit "isinff"),       (fsLit "isinfl"),
588         (fsLit "isnan"),        (fsLit "isnanf"),       (fsLit "isnanl"),
589         (fsLit "j0"),           (fsLit "j0f"),          (fsLit "j0l"),
590         (fsLit "j1"),           (fsLit "j1f"),          (fsLit "j1l"),
591         (fsLit "jn"),           (fsLit "jnf"),          (fsLit "jnl"),
592         (fsLit "lgamma_r"),     (fsLit "lgammaf_r"),    (fsLit "lgammal_r"),
593         (fsLit "scalb"),        (fsLit "scalbf"),       (fsLit "scalbl"),
594         (fsLit "significand"),  (fsLit "significandf"), (fsLit "significandl"),
595         (fsLit "y0"),           (fsLit "y0f"),          (fsLit "y0l"),
596         (fsLit "y1"),           (fsLit "y1f"),          (fsLit "y1l"),
597         (fsLit "yn"),           (fsLit "ynf"),          (fsLit "ynl")
598     ]
599
600 -- -----------------------------------------------------------------------------
601 -- Is a CLabel visible outside this object file or not?
602
603 -- From the point of view of the code generator, a name is
604 -- externally visible if it has to be declared as exported
605 -- in the .o file's symbol table; that is, made non-static.
606
607 externallyVisibleCLabel :: CLabel -> Bool -- not C "static"
608 externallyVisibleCLabel (CaseLabel _ _)    = False
609 externallyVisibleCLabel (StringLitLabel _) = False
610 externallyVisibleCLabel (AsmTempLabel _)   = False
611 externallyVisibleCLabel (ModuleInitLabel _ _) = True
612 externallyVisibleCLabel (PlainModuleInitLabel _)= True
613 externallyVisibleCLabel (ModuleInitTableLabel _)= False
614 externallyVisibleCLabel ModuleRegdLabel    = False
615 externallyVisibleCLabel (RtsLabel _)       = True
616 externallyVisibleCLabel (ForeignLabel _ _ _ _) = True
617 externallyVisibleCLabel (IdLabel name _ _)     = isExternalName name
618 externallyVisibleCLabel (CC_Label _)       = True
619 externallyVisibleCLabel (CCS_Label _)      = True
620 externallyVisibleCLabel (DynamicLinkerLabel _ _)  = False
621 externallyVisibleCLabel (HpcTicksLabel _)   = True
622 externallyVisibleCLabel HpcModuleNameLabel      = False
623 externallyVisibleCLabel (LargeBitmapLabel _) = False
624 externallyVisibleCLabel (LargeSRTLabel _) = False
625
626 -- -----------------------------------------------------------------------------
627 -- Finding the "type" of a CLabel 
628
629 -- For generating correct types in label declarations:
630
631 data CLabelType
632   = CodeLabel   -- Address of some executable instructions
633   | DataLabel   -- Address of data, not a GC ptr
634   | GcPtrLabel  -- Address of a (presumably static) GC object
635
636 isCFunctionLabel :: CLabel -> Bool
637 isCFunctionLabel lbl = case labelType lbl of
638                         CodeLabel -> True
639                         _other    -> False
640
641 isGcPtrLabel :: CLabel -> Bool
642 isGcPtrLabel lbl = case labelType lbl of
643                         GcPtrLabel -> True
644                         _other     -> False
645
646 labelType :: CLabel -> CLabelType
647 labelType (RtsLabel (RtsSelectorInfoTable _ _)) = DataLabel
648 labelType (RtsLabel (RtsApInfoTable _ _))       = DataLabel
649 labelType (RtsLabel (RtsData _))              = DataLabel
650 labelType (RtsLabel (RtsGcPtr _))             = GcPtrLabel
651 labelType (RtsLabel (RtsCode _))              = CodeLabel
652 labelType (RtsLabel (RtsInfo _))              = DataLabel
653 labelType (RtsLabel (RtsEntry _))             = CodeLabel
654 labelType (RtsLabel (RtsRetInfo _))           = DataLabel
655 labelType (RtsLabel (RtsRet _))               = CodeLabel
656 labelType (RtsLabel (RtsApFast _))              = CodeLabel
657 labelType (CaseLabel _ CaseReturnInfo)          = DataLabel
658 labelType (CaseLabel _ _)                       = CodeLabel
659 labelType (ModuleInitLabel _ _)                 = CodeLabel
660 labelType (PlainModuleInitLabel _)              = CodeLabel
661 labelType (ModuleInitTableLabel _)              = DataLabel
662 labelType (LargeSRTLabel _)                     = DataLabel
663 labelType (LargeBitmapLabel _)                  = DataLabel
664 labelType (ForeignLabel _ _ _ IsFunction)       = CodeLabel
665 labelType (IdLabel _ _ info)                    = idInfoLabelType info
666 labelType _                                     = DataLabel
667
668 idInfoLabelType info =
669   case info of
670     InfoTable     -> DataLabel
671     Closure       -> GcPtrLabel
672     ConInfoTable  -> DataLabel
673     StaticInfoTable -> DataLabel
674     ClosureTable  -> DataLabel
675     RednCounts    -> DataLabel
676     _             -> CodeLabel
677
678
679 -- -----------------------------------------------------------------------------
680 -- Does a CLabel need dynamic linkage?
681
682 -- When referring to data in code, we need to know whether
683 -- that data resides in a DLL or not. [Win32 only.]
684 -- @labelDynamic@ returns @True@ if the label is located
685 -- in a DLL, be it a data reference or not.
686
687 labelDynamic :: PackageId -> CLabel -> Bool
688 labelDynamic this_pkg lbl =
689   case lbl of
690    RtsLabel _        -> not opt_Static && (this_pkg /= rtsPackageId) -- i.e., is the RTS in a DLL or not?
691    IdLabel n _ k       -> isDllName this_pkg n
692 #if mingw32_TARGET_OS
693    ForeignLabel _ _ d _ -> d
694 #else
695    -- On Mac OS X and on ELF platforms, false positives are OK,
696    -- so we claim that all foreign imports come from dynamic libraries
697    ForeignLabel _ _ _ _ -> True
698 #endif
699    ModuleInitLabel m _    -> not opt_Static && this_pkg /= (modulePackageId m)
700    PlainModuleInitLabel m -> not opt_Static && this_pkg /= (modulePackageId m)
701    ModuleInitTableLabel m -> not opt_Static && this_pkg /= (modulePackageId m)
702    
703    -- Note that DynamicLinkerLabels do NOT require dynamic linking themselves.
704    _                 -> False
705
706 {-
707 OLD?: These GRAN functions are needed for spitting out GRAN_FETCH() at the
708 right places. It is used to detect when the abstractC statement of an
709 CCodeBlock actually contains the code for a slow entry point.  -- HWL
710
711 We need at least @Eq@ for @CLabels@, because we want to avoid
712 duplicate declarations in generating C (see @labelSeenTE@ in
713 @PprAbsC@).
714 -}
715
716 -----------------------------------------------------------------------------
717 -- Printing out CLabels.
718
719 {-
720 Convention:
721
722       <name>_<type>
723
724 where <name> is <Module>_<name> for external names and <unique> for
725 internal names. <type> is one of the following:
726
727          info                   Info table
728          srt                    Static reference table
729          srtd                   Static reference table descriptor
730          entry                  Entry code (function, closure)
731          slow                   Slow entry code (if any)
732          ret                    Direct return address    
733          vtbl                   Vector table
734          <n>_alt                Case alternative (tag n)
735          dflt                   Default case alternative
736          btm                    Large bitmap vector
737          closure                Static closure
738          con_entry              Dynamic Constructor entry code
739          con_info               Dynamic Constructor info table
740          static_entry           Static Constructor entry code
741          static_info            Static Constructor info table
742          sel_info               Selector info table
743          sel_entry              Selector entry code
744          cc                     Cost centre
745          ccs                    Cost centre stack
746
747 Many of these distinctions are only for documentation reasons.  For
748 example, _ret is only distinguished from _entry to make it easy to
749 tell whether a code fragment is a return point or a closure/function
750 entry.
751 -}
752
753 instance Outputable CLabel where
754   ppr = pprCLabel
755
756 pprCLabel :: CLabel -> SDoc
757
758 #if ! OMIT_NATIVE_CODEGEN
759 pprCLabel (AsmTempLabel u)
760   =  getPprStyle $ \ sty ->
761      if asmStyle sty then 
762         ptext asmTempLabelPrefix <> pprUnique u
763      else
764         char '_' <> pprUnique u
765
766 pprCLabel (DynamicLinkerLabel info lbl)
767    = pprDynamicLinkerAsmLabel info lbl
768    
769 pprCLabel PicBaseLabel
770    = ptext (sLit "1b")
771    
772 pprCLabel (DeadStripPreventer lbl)
773    = pprCLabel lbl <> ptext (sLit "_dsp")
774 #endif
775
776 pprCLabel lbl = 
777 #if ! OMIT_NATIVE_CODEGEN
778     getPprStyle $ \ sty ->
779     if asmStyle sty then 
780         maybe_underscore (pprAsmCLbl lbl)
781     else
782 #endif
783        pprCLbl lbl
784
785 maybe_underscore doc
786   | underscorePrefix = pp_cSEP <> doc
787   | otherwise        = doc
788
789 #ifdef mingw32_TARGET_OS
790 -- In asm mode, we need to put the suffix on a stdcall ForeignLabel.
791 -- (The C compiler does this itself).
792 pprAsmCLbl (ForeignLabel fs (Just sz) _ _)
793    = ftext fs <> char '@' <> int sz
794 #endif
795 pprAsmCLbl lbl
796    = pprCLbl lbl
797
798 pprCLbl (StringLitLabel u)
799   = pprUnique u <> ptext (sLit "_str")
800
801 pprCLbl (CaseLabel u CaseReturnPt)
802   = hcat [pprUnique u, ptext (sLit "_ret")]
803 pprCLbl (CaseLabel u CaseReturnInfo)
804   = hcat [pprUnique u, ptext (sLit "_info")]
805 pprCLbl (CaseLabel u (CaseAlt tag))
806   = hcat [pprUnique u, pp_cSEP, int tag, ptext (sLit "_alt")]
807 pprCLbl (CaseLabel u CaseDefault)
808   = hcat [pprUnique u, ptext (sLit "_dflt")]
809
810 pprCLbl (LargeSRTLabel u)  = pprUnique u <> pp_cSEP <> ptext (sLit "srtd")
811 pprCLbl (LargeBitmapLabel u)  = text "b" <> pprUnique u <> pp_cSEP <> ptext (sLit "btm")
812 -- Some bitsmaps for tuple constructors have a numeric tag (e.g. '7')
813 -- until that gets resolved we'll just force them to start
814 -- with a letter so the label will be legal assmbly code.
815         
816
817 pprCLbl (RtsLabel (RtsCode str))   = ftext str
818 pprCLbl (RtsLabel (RtsData str))   = ftext str
819 pprCLbl (RtsLabel (RtsGcPtr str))  = ftext str
820
821 pprCLbl (RtsLabel (RtsApFast str))   = ftext str <> ptext (sLit "_fast")
822
823 pprCLbl (RtsLabel (RtsSelectorInfoTable upd_reqd offset))
824   = hcat [ptext (sLit "stg_sel_"), text (show offset),
825                 ptext (if upd_reqd 
826                         then (sLit "_upd_info") 
827                         else (sLit "_noupd_info"))
828         ]
829
830 pprCLbl (RtsLabel (RtsSelectorEntry upd_reqd offset))
831   = hcat [ptext (sLit "stg_sel_"), text (show offset),
832                 ptext (if upd_reqd 
833                         then (sLit "_upd_entry") 
834                         else (sLit "_noupd_entry"))
835         ]
836
837 pprCLbl (RtsLabel (RtsApInfoTable upd_reqd arity))
838   = hcat [ptext (sLit "stg_ap_"), text (show arity),
839                 ptext (if upd_reqd 
840                         then (sLit "_upd_info") 
841                         else (sLit "_noupd_info"))
842         ]
843
844 pprCLbl (RtsLabel (RtsApEntry upd_reqd arity))
845   = hcat [ptext (sLit "stg_ap_"), text (show arity),
846                 ptext (if upd_reqd 
847                         then (sLit "_upd_entry") 
848                         else (sLit "_noupd_entry"))
849         ]
850
851 pprCLbl (RtsLabel (RtsInfo fs))
852   = ftext fs <> ptext (sLit "_info")
853
854 pprCLbl (RtsLabel (RtsEntry fs))
855   = ftext fs <> ptext (sLit "_entry")
856
857 pprCLbl (RtsLabel (RtsRetInfo fs))
858   = ftext fs <> ptext (sLit "_info")
859
860 pprCLbl (RtsLabel (RtsRet fs))
861   = ftext fs <> ptext (sLit "_ret")
862
863 pprCLbl (RtsLabel (RtsPrimOp primop)) 
864   = ptext (sLit "stg_") <> ppr primop
865
866 pprCLbl (RtsLabel (RtsSlowTickyCtr pat)) 
867   = ptext (sLit "SLOW_CALL_") <> text pat <> ptext (sLit "_ctr")
868
869 pprCLbl ModuleRegdLabel
870   = ptext (sLit "_module_registered")
871
872 pprCLbl (ForeignLabel str _ _ _)
873   = ftext str
874
875 pprCLbl (IdLabel name cafs flavor) = ppr name <> ppIdFlavor flavor
876
877 pprCLbl (CC_Label cc)           = ppr cc
878 pprCLbl (CCS_Label ccs)         = ppr ccs
879
880 pprCLbl (ModuleInitLabel mod way)
881    = ptext (sLit "__stginit_") <> ppr mod
882         <> char '_' <> text way
883 pprCLbl (PlainModuleInitLabel mod)
884    = ptext (sLit "__stginit_") <> ppr mod
885 pprCLbl (ModuleInitTableLabel mod)
886    = ptext (sLit "__stginittable_") <> ppr mod
887
888 pprCLbl (HpcTicksLabel mod)
889   = ptext (sLit "_hpc_tickboxes_")  <> ppr mod <> ptext (sLit "_hpc")
890
891 pprCLbl HpcModuleNameLabel
892   = ptext (sLit "_hpc_module_name_str")
893
894 ppIdFlavor :: IdLabelInfo -> SDoc
895 ppIdFlavor x = pp_cSEP <>
896                (case x of
897                        Closure          -> ptext (sLit "closure")
898                        SRT              -> ptext (sLit "srt")
899                        InfoTable        -> ptext (sLit "info")
900                        Entry            -> ptext (sLit "entry")
901                        Slow             -> ptext (sLit "slow")
902                        RednCounts       -> ptext (sLit "ct")
903                        ConEntry         -> ptext (sLit "con_entry")
904                        ConInfoTable     -> ptext (sLit "con_info")
905                        StaticConEntry   -> ptext (sLit "static_entry")
906                        StaticInfoTable  -> ptext (sLit "static_info")
907                        ClosureTable     -> ptext (sLit "closure_tbl")
908                       )
909
910
911 pp_cSEP = char '_'
912
913 -- -----------------------------------------------------------------------------
914 -- Machine-dependent knowledge about labels.
915
916 underscorePrefix :: Bool   -- leading underscore on assembler labels?
917 underscorePrefix = (cLeadingUnderscore == "YES")
918
919 asmTempLabelPrefix :: LitString  -- for formatting labels
920 asmTempLabelPrefix =
921 #if alpha_TARGET_OS
922      {- The alpha assembler likes temporary labels to look like $L123
923         instead of L123.  (Don't toss the L, because then Lf28
924         turns into $f28.)
925      -}
926      (sLit "$")
927 #elif darwin_TARGET_OS
928      (sLit "L")
929 #else
930      (sLit ".L")
931 #endif
932
933 pprDynamicLinkerAsmLabel :: DynamicLinkerLabelInfo -> CLabel -> SDoc
934
935 #if x86_64_TARGET_ARCH && darwin_TARGET_OS
936 pprDynamicLinkerAsmLabel CodeStub lbl
937   = char 'L' <> pprCLabel lbl <> text "$stub"
938 pprDynamicLinkerAsmLabel SymbolPtr lbl
939   = char 'L' <> pprCLabel lbl <> text "$non_lazy_ptr"
940 pprDynamicLinkerAsmLabel GotSymbolPtr lbl
941   = pprCLabel lbl <> text "@GOTPCREL"
942 pprDynamicLinkerAsmLabel GotSymbolOffset lbl
943   = pprCLabel lbl
944 pprDynamicLinkerAsmLabel _ _
945   = panic "pprDynamicLinkerAsmLabel"
946 #elif darwin_TARGET_OS
947 pprDynamicLinkerAsmLabel CodeStub lbl
948   = char 'L' <> pprCLabel lbl <> text "$stub"
949 pprDynamicLinkerAsmLabel SymbolPtr lbl
950   = char 'L' <> pprCLabel lbl <> text "$non_lazy_ptr"
951 pprDynamicLinkerAsmLabel _ _
952   = panic "pprDynamicLinkerAsmLabel"
953 #elif powerpc_TARGET_ARCH && linux_TARGET_OS
954 pprDynamicLinkerAsmLabel CodeStub lbl
955   = pprCLabel lbl <> text "@plt"
956 pprDynamicLinkerAsmLabel SymbolPtr lbl
957   = text ".LC_" <> pprCLabel lbl
958 pprDynamicLinkerAsmLabel _ _
959   = panic "pprDynamicLinkerAsmLabel"
960 #elif x86_64_TARGET_ARCH && linux_TARGET_OS
961 pprDynamicLinkerAsmLabel CodeStub lbl
962   = pprCLabel lbl <> text "@plt"
963 pprDynamicLinkerAsmLabel GotSymbolPtr lbl
964   = pprCLabel lbl <> text "@gotpcrel"
965 pprDynamicLinkerAsmLabel GotSymbolOffset lbl
966   = pprCLabel lbl
967 pprDynamicLinkerAsmLabel SymbolPtr lbl
968   = text ".LC_" <> pprCLabel lbl
969 #elif linux_TARGET_OS
970 pprDynamicLinkerAsmLabel CodeStub lbl
971   = pprCLabel lbl <> text "@plt"
972 pprDynamicLinkerAsmLabel SymbolPtr lbl
973   = text ".LC_" <> pprCLabel lbl
974 pprDynamicLinkerAsmLabel GotSymbolPtr lbl
975   = pprCLabel lbl <> text "@got"
976 pprDynamicLinkerAsmLabel GotSymbolOffset lbl
977   = pprCLabel lbl <> text "@gotoff"
978 #elif mingw32_TARGET_OS
979 pprDynamicLinkerAsmLabel SymbolPtr lbl
980   = text "__imp_" <> pprCLabel lbl
981 pprDynamicLinkerAsmLabel _ _
982   = panic "pprDynamicLinkerAsmLabel"
983 #else
984 pprDynamicLinkerAsmLabel _ _
985   = panic "pprDynamicLinkerAsmLabel"
986 #endif