[project @ 2004-10-08 03:09:19 by dons]
[ghc-hetmet.git] / ghc / compiler / nativeGen / PositionIndependentCode.hs
1 #include "../includes/ghcconfig.h"
2
3 module PositionIndependentCode (
4         cmmMakeDynamicReference,
5         needImportedSymbols,
6         pprImportedSymbol,
7         pprGotDeclaration,
8         initializePicBase
9      ) where
10
11 {-
12   This module handles generation of position independent code and
13   dynamic-linking related issues for the native code generator.
14   
15   Things outside this module which are related to this:
16   
17   + module CLabel
18     - PIC base label (pretty printed as local label 1)
19     - DynamicLinkerLabels - several kinds:
20         CodeStub, SymbolPtr, GotSymbolPtr, GotSymbolOffset
21     - labelDynamic predicate
22   + module Cmm
23     - The CmmExpr datatype has a CmmPicBaseReg constructor
24     - The CmmLit datatype has a CmmLabelDiffOff constructor
25   + codeGen & RTS
26     - When tablesNextToCode, no absolute addresses are stored in info tables
27       any more. Instead, offsets from the info label are used.
28     - For Win32 only, SRTs might contain addresses of __imp_ symbol pointers
29       because Win32 doesn't support external references in data sections.
30       TODO: make sure this still works, it might be bitrotted
31   + NCG
32     - The cmmToCmm pass in AsmCodeGen calls cmmMakeDynamicReference for all
33       labels.
34     - nativeCodeGen calls pprImportedSymbol and pprGotDeclaration to output
35       all the necessary stuff for imported symbols.
36     - The NCG monad keeps track of a list of imported symbols.
37     - MachCodeGen invokes initializePicBase to generate code to initialize
38       the PIC base register when needed.
39     - MachCodeGen calls cmmMakeDynamicReference whenever it uses a CLabel
40       that wasn't in the original Cmm code (e.g. floating point literals).
41   + The Mangler
42     - The mangler converts absolure refs to relative refs in info tables
43     - Symbol pointers, stub code and PIC calculations that are generated
44       by GCC are left intact by the mangler (so far only on ppc-darwin
45       and ppc-linux).
46 -}
47      
48 #include "HsVersions.h"
49 #include "nativeGen/NCG.h"
50
51 import Cmm
52 import MachOp           ( MachOp(MO_Add), wordRep )
53 import CLabel           ( CLabel, pprCLabel,
54                           mkDynamicLinkerLabel, DynamicLinkerLabelInfo(..),
55                           dynamicLinkerLabelInfo, mkPicBaseLabel,
56                           labelDynamic, externallyVisibleCLabel )
57
58 import MachRegs
59 import MachInstrs
60 import NCGMonad         ( NatM, getNewRegNat, getNewLabelNat )
61
62 import CmdLineOpts      ( opt_PIC )
63
64 import Pretty
65 import qualified Outputable
66
67 import Panic            ( panic )
68
69
70 -- The most important function here is cmmMakeDynamicReference.
71
72 -- It gets called by the cmmToCmm pass for every CmmLabel in the Cmm
73 -- code. It does The Right Thing(tm) to convert the CmmLabel into a
74 -- position-independent, dynamic-linking-aware reference to the thing
75 -- in question.
76 -- Note that this also has to be called from MachCodeGen in order to
77 -- access static data like floating point literals (labels that were
78 -- created after the cmmToCmm pass).
79 -- The function must run in a monad that can keep track of imported symbols
80 -- A function for recording an imported symbol must be passed in:
81 -- - addImportCmmOpt for the CmmOptM monad
82 -- - addImportNat for the NatM monad.
83
84 cmmMakeDynamicReference
85   :: Monad m => (CLabel -> m ())  -- a monad & a function
86                                   -- used for recording imported symbols
87              -> Bool              -- whether this is the target of a jump
88              -> CLabel            -- the label
89              -> m CmmExpr
90   
91 cmmMakeDynamicReference addImport isJumpTarget lbl
92   | Just _ <- dynamicLinkerLabelInfo lbl
93   = return $ CmmLit $ CmmLabel lbl   -- already processed it, pass through
94   | otherwise = case howToAccessLabel isJumpTarget lbl of
95         AccessViaStub -> do
96               let stub = mkDynamicLinkerLabel CodeStub lbl
97               addImport stub
98               return $ CmmLit $ CmmLabel stub
99         AccessViaSymbolPtr -> do
100               let symbolPtr = mkDynamicLinkerLabel SymbolPtr lbl
101               addImport symbolPtr
102               return $ CmmLoad (cmmMakePicReference symbolPtr) wordRep
103         AccessDirectly
104                 -- all currently supported processors support
105                 -- a PC-relative branch instruction, so just jump there
106           | isJumpTarget -> return $ CmmLit $ CmmLabel lbl
107                 -- for data, we might have to make some calculations:
108           | otherwise    -> return $ cmmMakePicReference lbl  
109   
110 -- -------------------------------------------------------------------
111   
112 -- Create a position independent reference to a label.
113 -- (but do not bother with dynamic linking).
114 -- We calculate the label's address by adding some (platform-dependent)
115 -- offset to our base register; this offset is calculated by
116 -- the function picRelative in the platform-dependent part below.
117
118 cmmMakePicReference :: CLabel -> CmmExpr
119   
120 #if !mingw32_TARGET_OS
121         -- Windows doesn't need PIC,
122         -- everything gets relocated at runtime
123
124 cmmMakePicReference lbl
125     | opt_PIC && absoluteLabel lbl = CmmMachOp (MO_Add wordRep) [
126             CmmPicBaseReg,
127             CmmLit $ picRelative lbl
128         ]
129     where
130         absoluteLabel lbl = case dynamicLinkerLabelInfo lbl of
131                                 Just (GotSymbolPtr, _) -> False
132                                 Just (GotSymbolOffset, _) -> False
133                                 _ -> True
134
135 #endif
136 cmmMakePicReference lbl = CmmLit $ CmmLabel lbl
137
138 -- ===================================================================
139 -- Platform dependent stuff
140 -- ===================================================================
141
142 -- Knowledge about how special dynamic linker labels like symbol
143 -- pointers, code stubs and GOT offsets look like is located in the
144 -- module CLabel.
145
146 -- -------------------------------------------------------------------
147
148 -- We have to decide which labels need to be accessed
149 -- indirectly or via a piece of stub code.
150
151 data LabelAccessStyle = AccessViaStub
152                       | AccessViaSymbolPtr
153                       | AccessDirectly
154
155 howToAccessLabel :: Bool -> CLabel -> LabelAccessStyle
156
157 #if mingw32_TARGET_OS
158 -- Windows
159 -- 
160 -- We need to use access *exactly* those things that
161 -- are imported from a DLL via an __imp_* label.
162 -- There are no stubs for imported code.
163
164 howToAccessLabel _ lbl | labelDynamic lbl = AccessViaSymbolPtr
165                        | otherwise        = AccessDirectly
166
167 #elif darwin_TARGET_OS
168 -- Mach-O (Darwin, Mac OS X)
169 --
170 -- Indirect access is required in the following cases:
171 -- * things imported from a dynamic library
172 -- * things from a different module, if we're generating PIC code
173 -- It is always possible to access something indirectly,
174 -- even when it's not necessary.
175
176 howToAccessLabel True lbl
177       -- jumps to a dynamic library go via a symbol stub
178     | labelDynamic lbl = AccessViaStub
179       -- when generating PIC code, all cross-module references must
180       -- must go via a symbol pointer, too.
181       -- Unfortunately, we don't know whether it's cross-module,
182       -- so we do it for all externally visible labels.
183       -- This is a slight waste of time and space, but otherwise
184       -- we'd need to pass the current Module all the way in to
185       -- this function.
186     | opt_PIC && externallyVisibleCLabel lbl = AccessViaStub
187 howToAccessLabel False lbl
188       -- data access to a dynamic library goes via a symbol pointer
189     | labelDynamic lbl = AccessViaSymbolPtr
190       -- cross-module PIC references: same as above
191     | opt_PIC && externallyVisibleCLabel lbl = AccessViaSymbolPtr
192 howToAccessLabel _ _ = AccessDirectly
193
194 #elif linux_TARGET_OS && powerpc_TARGET_ARCH
195 -- PowerPC Linux
196 --
197 -- PowerPC Linux is just plain broken.
198 -- While it's theoretically possible to use GOT offsets larger
199 -- than 16 bit, the standard crt*.o files don't, which leads to
200 -- linker errors as soon as the GOT size exceeds 16 bit.
201 -- Also, the assembler doesn't support @gotoff labels.
202 -- In order to be able to use a larger GOT, we circumvent the
203 -- entire GOT mechanism and do it ourselves (this is what GCC does).
204
205 -- In this scheme, we need to do _all data references_ (even refs
206 -- to static data) via a SymbolPtr when we are generating PIC.
207 -- Luckily, the PLT works as expected, so we can simply access
208 -- dynamically linked code via the PLT.
209
210 howToAccessLabel _ _ | not opt_PIC = AccessDirectly
211 howToAccessLabel True lbl
212     = if labelDynamic lbl then AccessViaStub
213                           else AccessDirectly
214 howToAccessLabel False lbl
215     = AccessViaSymbolPtr
216
217 #elif linux_TARGET_OS
218 -- ELF (Linux)
219 --
220 -- Indirect access is required for references to imported symbols
221 -- from position independent code.
222 -- It is always possible to access something indirectly,
223 -- even when it's not necessary.
224
225 -- For code, we can use a relative jump to a piece of
226 -- stub code instead (this allows lazy binding of imported symbols).
227
228 howToAccessLabel isJump lbl
229         -- no PIC -> the dynamic linker does everything for us
230    | not opt_PIC = AccessDirectly
231         -- if it's not imported, we need no indirection
232         -- ("foo" will end up being accessed as "foo@GOTOFF")
233    | not (labelDynamic lbl) = AccessDirectly
234 #if !i386_TARGET_ARCH
235 -- for Intel, we temporarily disable the use of the
236 -- Procedure Linkage Table, because PLTs on intel require the
237 -- address of the GOT to be loaded into register %ebx before
238 -- a jump through the PLT is made.
239 -- TODO: make the i386 NCG ensure this before jumping to a
240 --       CodeStub label, so we can remove this special case.
241    | isJump = AccessViaStub
242 #endif
243    | otherwise = AccessViaSymbolPtr
244
245 #else
246 howToAccessLabel = panic "PositionIndependentCode.howToAccessLabel"
247 #endif
248
249 -- -------------------------------------------------------------------
250
251 -- What do we have to add to our 'PIC base register' in order to
252 -- get the address of a label?
253
254 picRelative :: CLabel -> CmmLit
255 #if darwin_TARGET_OS
256 -- Darwin:
257 -- The PIC base register points to the PIC base label at the beginning
258 -- of the current CmmTop. We just have to use a label difference to
259 -- get the offset.
260 -- We have already made sure that all labels that are not from the current
261 -- module are accessed indirectly ('as' can't calculate differences between
262 -- undefined labels).
263
264 picRelative lbl
265   = CmmLabelDiffOff lbl mkPicBaseLabel 0
266
267 #elif powerpc_TARGET_ARCH && linux_TARGET_OS
268 -- PowerPC Linux:
269 -- The PIC base register points to our fake GOT. Use a label difference
270 -- to get the offset.
271 -- We have made sure that *everything* is accessed indirectly, so this
272 -- is only used for offsets from the GOT to symbol pointers inside the
273 -- GOT.
274 picRelative lbl
275   = CmmLabelDiffOff lbl gotLabel 0
276
277 #elif linux_TARGET_OS
278 -- Other Linux versions:
279 -- The PIC base register points to the GOT. Use foo@got for symbol
280 -- pointers, and foo@gotoff for everything else.
281
282 picRelative lbl
283   | Just (SymbolPtr, lbl') <- dynamicLinkerLabelInfo lbl
284   = CmmLabel $ mkDynamicLinkerLabel GotSymbolPtr lbl'
285   | otherwise
286   = CmmLabel $ mkDynamicLinkerLabel GotSymbolOffset lbl
287
288 #else
289 picRelative lbl = panic "PositionIndependentCode.picRelative"
290 #endif
291
292 -- -------------------------------------------------------------------
293
294 -- What do we have to add to every assembly file we generate?
295
296 -- utility function for pretty-printing asm-labels,
297 -- copied from PprMach
298 asmSDoc d = Outputable.withPprStyleDoc (
299               Outputable.mkCodeStyle Outputable.AsmStyle) d
300 pprCLabel_asm l = asmSDoc (pprCLabel l)
301
302
303 #if darwin_TARGET_OS
304
305 needImportedSymbols = True
306
307 -- We don't need to declare any offset tables
308 pprGotDeclaration = Pretty.empty
309
310 -- On Darwin, we have to generate our own stub code for lazy binding..
311 -- There are two versions, one for PIC and one for non-PIC.
312 pprImportedSymbol importedLbl
313     | Just (CodeStub, lbl) <- dynamicLinkerLabelInfo importedLbl
314     = case opt_PIC of
315         False ->
316             vcat [
317                 ptext SLIT(".symbol_stub"),
318                 ptext SLIT("L") <> pprCLabel_asm lbl <> ptext SLIT("$stub:"),
319                     ptext SLIT("\t.indirect_symbol") <+> pprCLabel_asm lbl,
320                     ptext SLIT("\tlis r11,ha16(L") <> pprCLabel_asm lbl
321                         <> ptext SLIT("$lazy_ptr)"),
322                     ptext SLIT("\tlwz r12,lo16(L") <> pprCLabel_asm lbl
323                         <> ptext SLIT("$lazy_ptr)(r11)"),
324                     ptext SLIT("\tmtctr r12"),
325                     ptext SLIT("\taddi r11,r11,lo16(L") <> pprCLabel_asm lbl
326                         <> ptext SLIT("$lazy_ptr)"),
327                     ptext SLIT("\tbctr")
328             ]
329         True ->
330             vcat [
331                 ptext SLIT(".section __TEXT,__picsymbolstub1,")
332                   <> ptext SLIT("symbol_stubs,pure_instructions,32"),
333                 ptext SLIT("L") <> pprCLabel_asm lbl <> ptext SLIT("$stub:"),
334                     ptext SLIT("\t.indirect_symbol") <+> pprCLabel_asm lbl,
335                     ptext SLIT("\tmflr r0"),
336                     ptext SLIT("\tbcl 20,31,L0$") <> pprCLabel_asm lbl,
337                 ptext SLIT("L0$") <> pprCLabel_asm lbl <> char ':',
338                     ptext SLIT("\tmflr r11"),
339                     ptext SLIT("\taddis r11,r11,ha16(L") <> pprCLabel_asm lbl
340                         <> ptext SLIT("$lazy_ptr-L0$") <> pprCLabel_asm lbl <> char ')',
341                     ptext SLIT("\tmtlr r0"),
342                     ptext SLIT("\tlwzu r12,lo16(L") <> pprCLabel_asm lbl
343                         <> ptext SLIT("$lazy_ptr-L0$") <> pprCLabel_asm lbl
344                         <> ptext SLIT(")(r11)"),
345                     ptext SLIT("\tmtctr r12"),
346                     ptext SLIT("\tbctr")
347             ]
348     $+$ vcat [
349         ptext SLIT(".lazy_symbol_pointer"),
350         ptext SLIT("L") <> pprCLabel_asm lbl <> ptext SLIT("$lazy_ptr:"),
351             ptext SLIT("\t.indirect_symbol") <+> pprCLabel_asm lbl,
352             ptext SLIT("\t.long dyld_stub_binding_helper")
353     ]
354
355 -- We also have to declare our symbol pointers ourselves:
356     | Just (SymbolPtr, lbl) <- dynamicLinkerLabelInfo importedLbl
357     = vcat [
358         ptext SLIT(".non_lazy_symbol_pointer"),
359         char 'L' <> pprCLabel_asm lbl <> ptext SLIT("$non_lazy_ptr:"),
360             ptext SLIT("\t.indirect_symbol") <+> pprCLabel_asm lbl,
361             ptext SLIT("\t.long\t0")
362     ]
363
364     | otherwise = empty
365
366 #elif powerpc_TARGET_ARCH && linux_TARGET_OS
367
368 -- For PowerPC linux, we don't do anything unless we're generating PIC.
369 needImportedSymbols = opt_PIC
370
371 -- If we're generating PIC, we need to create our own "fake GOT".
372
373 gotLabel = mkForeignLabel -- HACK: it's not really foreign
374                            FSLIT(".LCTOC1") Nothing False
375
376 -- The .LCTOC1 label is defined to point 32768 bytes into the table,
377 -- to make the most of the PPC's 16-bit displacements.
378
379 pprGotDeclaration = vcat [
380         ptext SLIT(".section \".got2\",\"aw\""),
381         ptext SLIT(".LCTOC1 = .+32768")
382     ]
383
384 -- We generate one .long literal for every symbol we import;
385 -- the dynamic linker will relocate those addresses.
386     
387 pprImportedSymbol importedLbl
388     | Just (SymbolPtr, lbl) <- dynamicLinkerLabelInfo importedLbl
389     vcat [
390         ptext SLIT(".section \".got2\", \"aw\""),
391         ptext SLIT(".LC_") <> pprCLabel_asm lbl <> char ':',
392         ptext SLIT("\t.long") <+> pprCLabel_asm lbl
393     ]
394
395 -- PLT code stubs are generated automatically be the dynamic linker.
396     | otherwise = empty
397
398 #else
399
400 -- For all other currently supported platforms, we don't need to do
401 -- anything at all.
402
403 needImportedSymbols = False
404 pprGotDeclaration = Pretty.empty
405 pprImportedSymbol _ = empty
406 #endif
407
408 -- -------------------------------------------------------------------
409
410 -- Generate code to calculate the address that should be put in the
411 -- PIC base register.
412 -- This is called by MachCodeGen for every CmmProc that accessed the
413 -- PIC base register. It adds the appropriate instructions to the
414 -- top of the CmmProc.
415
416 -- It is assumed that the first NatCmmTop in the input list is a Proc
417 -- and the rest are CmmDatas.
418
419 initializePicBase :: Reg -> [NatCmmTop] -> NatM [NatCmmTop]
420
421 #if powerpc_TARGET_ARCH && darwin_TARGET_OS
422
423 -- Darwin is simple: just fetch the address of a local label.
424 initializePicBase picReg (CmmProc info lab params blocks : statics)
425     = return (CmmProc info lab params (b':tail blocks) : statics)
426     where BasicBlock bID insns = head blocks
427           b' = BasicBlock bID (FETCHPC picReg : insns)
428
429 #elif powerpc_TARGET_ARCH && linux_TARGET_OS
430
431 -- Get a pointer to our own fake GOT, which is defined on a per-module basis.
432 -- This is exactly how GCC does it, and it's quite horrible:
433 -- We first fetch the address of a local label (mkPicBaseLabel).
434 -- Then we add a 16-bit offset to that to get the address of a .long that we
435 -- define in .text space right next to the proc. This .long literal contains
436 -- the (32-bit) offset from our local label to our global offset table
437 -- (.LCTOC1 aka gotOffLabel).
438 initializePicBase picReg
439     (CmmProc info lab params blocks : statics)
440     = do
441         gotOffLabel <- getNewLabelNat
442         tmp <- getNewRegNat wordRep
443         let 
444             gotOffset = CmmData Text [
445                             CmmDataLabel gotOffLabel,
446                             CmmStaticLit (CmmLabelDiffOff gotLabel
447                                                           mkPicBaseLabel
448                                                           0)
449                         ]
450             offsetToOffset = ImmConstantDiff (ImmCLbl gotOffLabel)
451                                              (ImmCLbl mkPicBaseLabel)
452             BasicBlock bID insns = head blocks
453             b' = BasicBlock bID (FETCHPC picReg
454                                : LD wordRep tmp
455                                     (AddrRegImm picReg offsetToOffset)
456                                : ADD picReg picReg (RIReg tmp)
457                                : insns)
458         return (CmmProc info lab params (b' : tail blocks) : gotOffset : statics)
459 #else
460 initializePicBase picReg proc = panic "initializePicBase"
461
462 -- TODO:
463 -- i386_TARGET_ARCH && linux_TARGET_OS:
464 -- generate something like:
465 --              call 1f
466 -- 1:           popl %picReg
467 --              addl __GLOBAL_OFFSET_TABLE__+.-1b, %picReg
468 -- It might be a good idea to use a FETCHPC pseudo-instruction (like for PowerPC)
469 -- in order to avoid having to create a new basic block.
470 -- ((FETCHPC reg) should pretty-print as call 1f; 1: popl reg)
471
472 -- mingw32_TARGET_OS: not needed, won't be called
473
474 -- i386_TARGET_ARCH && darwin_TARGET_OS:
475 -- (just for completeness ;-)
476 --              call 1f
477 -- 1:           popl %picReg
478 #endif