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