Add new LLVM code generator to GHC. (Version 2)
[ghc-hetmet.git] / driver / mangler / ghc-asm.lprl
1 %************************************************************************
2 %*                                                                      *
3 \section[Driver-asm-fiddling]{Fiddling with assembler files}
4 %*                                                                      *
5 %************************************************************************
6
7 Tasks:
8 \begin{itemize}
9 \item
10 Utterly stomp out C functions' prologues and epilogues; i.e., the
11 stuff to do with the C stack.
12 \item
13 Any other required tidying up.
14 \end{itemize}
15
16 General note [chak]: Many regexps are very fragile because they rely on white
17 space being in the right place.  This caused trouble with gcc 2.95 (at least
18 on Linux), where the use of white space in .s files generated by gcc suddenly 
19 changed.  To guarantee compatibility across different versions of gcc, make
20 sure (at least on i386-.*-linux) that regexps tolerate varying amounts of white
21 space between an assembler statement and its arguments as well as after a the
22 comma separating multiple arguments.  
23
24 \emph{For the time being, I have corrected the regexps for i386-.*-linux.  I
25 didn't touch all the regexps for other i386 platforms, as I don't have
26 a box to test these changes.}
27
28 HPPA specific notes:
29 \begin{itemize}
30 \item
31 The HP linker is very picky about symbols being in the appropriate
32 space (code vs. data).  When we mangle the threaded code to put the
33 info tables just prior to the code, they wind up in code space
34 rather than data space.  This means that references to *_info from
35 un-mangled parts of the RTS (e.g. unthreaded GC code) get
36 unresolved symbols.  Solution:  mini-mangler for .c files on HP.  I
37 think this should really be triggered in the driver by a new -rts
38 option, so that user code doesn't get mangled inappropriately.
39 \item
40 With reversed tables, jumps are to the _info label rather than to
41 the _entry label.  The _info label is just an address in code
42 space, rather than an entry point with the descriptive blob we
43 talked about yesterday.  As a result, you can't use the call-style
44 JMP_ macro.  However, some JMP_ macros take _info labels as targets
45 and some take code entry points within the RTS.  The latter won't
46 work with the goto-style JMP_ macro.  Sigh.  Solution: Use the goto
47 style JMP_ macro, and mangle some more assembly, changing all
48 "RP'literal" and "LP'literal" references to "R'literal" and
49 "L'literal," so that you get the real address of the code, rather
50 than the descriptive blob.  Also change all ".word P%literal"
51 entries in info tables and vector tables to just ".word literal,"
52 for the same reason.  Advantage: No more ridiculous call sequences.
53 \end{itemize}
54
55 %************************************************************************
56 %*                                                                      *
57 \subsection{Top-level code}
58 %*                                                                      *
59 %************************************************************************
60
61 \begin{code}
62 $TargetPlatform = $TARGETPLATFORM;
63
64 ($Pgm = $0) =~ s|.*/||m;
65 $ifile = $ARGV[0];
66 $ofile = $ARGV[1];
67
68 if ( $TargetPlatform =~ /^i386-/m ) {
69     if ($ARGV[2] eq '') {
70         $StolenX86Regs = 4;
71     } else {
72         $StolenX86Regs = $ARGV[2];
73     }
74 }
75
76 &mangle_asm($ifile,$ofile);
77
78 exit(0);
79 \end{code}
80
81 %************************************************************************
82 %*                                                                      *
83 \subsection{Constants for various architectures}
84 %*                                                                      *
85 %************************************************************************
86
87 \begin{code}
88 sub init_TARGET_STUFF {
89
90     #--------------------------------------------------------#
91     if ( $TargetPlatform =~ /^alpha-.*-.*/m ) {
92
93     $T_STABBY       = 0; # 1 iff .stab things (usually if a.out format)
94     $T_US           = ''; # _ if symbols have an underscore on the front
95     $T_PRE_APP      = 'DONT THINK THIS APPLIES'; # regexp that says what comes before APP/NO_APP
96     $T_CONST_LBL    = '^\$L?C(\d+):$'; # regexp for what such a lbl looks like
97     $T_POST_LBL     = ':';
98
99     $T_MOVE_DIRVS   = '^(\s*(\$.*\.\.ng:|\.align\s+\d+|\.(globl|ent)\s+\S+|\#.*|\.(file|loc)\s+\S+\s+\S+|\.text|\.r?data)\n)';
100     $T_COPY_DIRVS   = '^\s*(\$.*\.\.ng:|\#|\.(file|globl|ent|loc))';
101
102     $T_DOT_WORD     = '\.(long|quad|byte|word)';
103     $T_DOT_GLOBAL   = '^\t\.globl';
104     $T_HDR_literal  = "\.rdata\n\t\.align 3\n";
105     $T_HDR_misc     = "\.text\n\t\.align 3\n";
106     $T_HDR_data     = "\.data\n\t\.align 3\n";
107     $T_HDR_rodata   = "\.rdata\n\t\.align 3\n";
108     $T_HDR_closure  = "\.data\n\t\.align 3\n";
109     $T_HDR_info     = "\.text\n\t\.align 3\n";
110     $T_HDR_entry    = "\.text\n\t\.align 3\n";
111     $T_HDR_vector   = "\.text\n\t\.align 3\n";
112
113     #--------------------------------------------------------#
114     } elsif ( $TargetPlatform =~ /^hppa/m ) {
115
116     $T_STABBY       = 0; # 1 iff .stab things (usually if a.out format)
117     $T_US           = ''; # _ if symbols have an underscore on the front
118     $T_PRE_APP      = 'DONT THINK THIS APPLIES'; # regexp that says what comes before APP/NO_APP
119     $T_CONST_LBL    = '^L\$C(\d+)$'; # regexp for what such a lbl looks like
120     $T_POST_LBL     = '';
121
122     $T_MOVE_DIRVS   = '^((\s+\.(IMPORT|EXPORT|PARAM).*|\s+\.align\s+\d+|\s+\.(SPACE|SUBSPA)\s+\S+|\s*)\n)';
123     $T_COPY_DIRVS   = '^\s+\.(IMPORT|EXPORT)';
124
125     $T_DOT_WORD     = '\.(blockz|word|half|byte)';
126     $T_DOT_GLOBAL   = '^\s+\.EXPORT';
127     $T_HDR_literal  = "\t.SPACE \$TEXT\$\n\t.SUBSPA \$LIT\$\n";
128     $T_HDR_misc     = "\t.SPACE \$TEXT\$\n\t.SUBSPA \$CODE\$\n\t\.align 4\n";
129     $T_HDR_data     = "\t.SPACE \$PRIVATE\$\n\t.SUBSPA \$DATA\$\n\t\.align 4\n";
130     $T_HDR_rodata   = "\t.SPACE \$PRIVATE\$\n\t.SUBSPA \$DATA\$\n\t\.align 4\n";
131     $T_HDR_closure  = "\t.SPACE \$PRIVATE\$\n\t.SUBSPA \$DATA\$\n\t\.align 4\n";
132     $T_HDR_info     = "\t.SPACE \$TEXT\$\n\t.SUBSPA \$CODE\$\n\t\.align 4\n";
133     $T_HDR_entry    = "\t.SPACE \$TEXT\$\n\t.SUBSPA \$CODE\$\n\t\.align 4\n";
134     $T_HDR_vector   = "\t.SPACE \$TEXT\$\n\t.SUBSPA \$CODE\$\n\t\.align 4\n";
135
136     #--------------------------------------------------------#
137     } elsif ( $TargetPlatform =~ /^i386-.*-(linuxaout|freebsd2|nextstep3|cygwin32|mingw32)$/m ) {
138                                 # NeXT added but not tested. CaS
139
140     $T_STABBY       = 1; # 1 iff .stab things (usually if a.out format)
141     $T_US           = '_'; # _ if symbols have an underscore on the front
142     $T_PRE_APP      = '^#'; # regexp that says what comes before APP/NO_APP
143     $T_CONST_LBL    = '^LC(\d+):$';
144     $T_POST_LBL     = ':';
145     $T_X86_PRE_LLBL_PAT = 'L';
146     $T_X86_PRE_LLBL         = 'L';
147     $T_X86_BADJMP   = '^\tjmp [^L\*]';
148
149     $T_MOVE_DIRVS   = '^(\s*(\.(p2)?align\s.*|\.globl\s+\S+|\.text|\.data|\.stab[^n].*|\.type\s+.*|\.size\s+.*|\.lcomm.*)\n)';
150     $T_COPY_DIRVS   = '\.(globl|stab|lcomm)';
151     $T_DOT_WORD     = '\.(long|word|value|byte|space)';
152     $T_DOT_GLOBAL   = '\.globl';
153     $T_HDR_literal  = "\.text\n\t\.align 4\n";
154     $T_HDR_misc     = "\.text\n\t\.align 4,0x90\n";
155     $T_HDR_data     = "\.data\n\t\.align 4\n";
156     $T_HDR_rodata   = "\.text\n\t\.align 4\n";
157     $T_HDR_closure  = "\.data\n\t\.align 4\n";
158     $T_HDR_info     = "\.text\n\t\.align 4\n"; # NB: requires padding
159     $T_HDR_entry    = "\.text\n"; # no .align so we're right next to _info (arguably wrong...?)
160     $T_HDR_vector   = "\.text\n\t\.align 4\n"; # NB: requires padding
161
162     #--------------------------------------------------------#
163     } elsif ( $TargetPlatform =~ /^i386-.*-(solaris2|linux|gnu|freebsd|dragonfly|netbsd|openbsd|kfreebsdgnu)$/m ) {
164
165     $T_STABBY       = 0; # 1 iff .stab things (usually if a.out format)
166     $T_US           = ''; # _ if symbols have an underscore on the front
167     $T_PRE_APP      = # regexp that says what comes before APP/NO_APP
168                       ($TargetPlatform =~ /-(linux|gnu|freebsd|dragonfly|netbsd|openbsd)$/m) ? '#' : '/' ;
169     $T_CONST_LBL    = '^\.LC(\d+):$'; # regexp for what such a lbl looks like
170     $T_POST_LBL     = ':';
171     $T_X86_PRE_LLBL_PAT = '\.L';
172     $T_X86_PRE_LLBL         = '.L';
173     $T_X86_BADJMP   = '^\tjmp\s+[^\.\*]';
174
175     $T_MOVE_DIRVS   = '^(\s*(\.(p2)?align\s.*|\.globl\s+\S+|\.text|\.data|\.section\s+.*|\.type\s+.*|\.size\s+\S+\s*,\s*\d+|\.ident.*|\.local.*)\n)';
176     if ( $TargetPlatform =~ /solaris2/m ) {
177             # newer Solaris linkers are picky about .size information, so
178             # omit it (see #1421)
179             $T_COPY_DIRVS   = '^\s*\.(globl|local)';
180     } else {
181             $T_COPY_DIRVS   = '^\s*\.(globl|type|size|local)';
182     }
183
184     $T_DOT_WORD     = '\.(long|value|word|byte|zero)';
185     $T_DOT_GLOBAL   = '\.globl';
186     $T_HDR_literal  = "\.section\t\.rodata\n"; # or just use .text??? (WDP 95/11)
187     $T_HDR_misc     = "\.text\n\t\.align 4\n";
188     $T_HDR_data     = "\.data\n\t\.align 4\n";
189     $T_HDR_rodata   = "\.section\t\.rodata\n\t\.align 4\n";
190     $T_HDR_closure  = "\.data\n\t\.align 4\n";
191     $T_HDR_info     = "\.text\n\t\.align 4\n";
192     $T_HDR_entry    = "\.text\n"; # no .align so we're right next to _info (arguably wrong...?)
193     $T_HDR_vector   = "\.text\n\t\.align 4\n"; # NB: requires padding
194
195     #--------------------------------------------------------#
196     } elsif ( $TargetPlatform =~ /^ia64-.*-linux$/m ) {
197
198     $T_STABBY       = 0; # 1 iff .stab things (usually if a.out format)
199     $T_US           = ''; # _ if symbols have an underscore on the front
200     $T_PRE_APP      = '#';
201     $T_CONST_LBL    = '^\.LC(\d+):$'; # regexp for what such a lbl looks like
202     $T_POST_LBL     = ':';
203
204     $T_MOVE_DIRVS   = '^(\s*\.(global|proc|pred\.safe_across_calls|text|data|section|subsection|align|size|type|ident)\s+.*\n)';
205     $T_COPY_DIRVS   = '\.(global|proc)';
206
207     $T_DOT_WORD     = '\.(long|value|byte|zero)';
208     $T_DOT_GLOBAL   = '\.global';
209     $T_HDR_literal  = "\.section\t\.rodata\n";
210     $T_HDR_misc     = "\.text\n\t\.align 16\n"; # May contain code; align like 'entry'
211     $T_HDR_data     = "\.data\n\t\.align 8\n";
212     $T_HDR_rodata   = "\.section\t\.rodata\n\t\.align 8\n";
213     $T_HDR_closure  = "\.data\n\t\.align 8\n";
214     $T_HDR_info     = "\.text\n\t\.align 8\n";
215     $T_HDR_entry    = "\.text\n\t\.align 16\n";
216     $T_HDR_vector   = "\.text\n\t\.align 8\n";
217
218     #--------------------------------------------------------#
219     } elsif ( $TargetPlatform =~ /^x86_64-.*-(linux|openbsd|freebsd|dragonfly|netbsd)$/m ) {
220
221     $T_STABBY       = 0; # 1 iff .stab things (usually if a.out format)
222     $T_US           = ''; # _ if symbols have an underscore on the front
223     $T_PRE_APP      = '#';
224     $T_CONST_LBL    = '^\.LC(\d+):$'; # regexp for what such a lbl looks like
225     $T_POST_LBL     = ':';
226
227     $T_MOVE_DIRVS   = '^(\s*\.(globl|text|data|section|align|size|type|ident|local)([ \t].*)?\n)';
228     $T_COPY_DIRVS   = '\.(globl|type|size|local)';
229
230     $T_DOT_WORD     = '\.(quad|long|value|byte|zero)';
231     $T_DOT_GLOBAL   = '\.global';
232
233     $T_HDR_literal16 = "\.section\t\.rodata.cst16\n\t.align 16\n";
234     $T_HDR_literal  = "\.section\t\.rodata\n";
235
236     $T_HDR_misc     = "\.text\n\t\.align 8\n";
237     $T_HDR_data     = "\.data\n\t\.align 8\n";
238     $T_HDR_rodata   = "\.section\t\.rodata\n\t\.align 8\n";
239
240         # the assembler on x86_64/Linux refuses to generate code for
241         #   .quad  x - y
242         # where x is in the text section and y in the rodata section.
243         # It works if y is in the text section, though.  This is probably
244         # going to cause difficulties for PIC, I imagine.
245         #       
246         # See Note [x86-64-relative] in includes/InfoTables.h
247     $T_HDR_relrodata= "\.text\n\t\.align 8\n";
248
249     $T_HDR_closure  = "\.data\n\t\.align 8\n";
250     $T_HDR_info     = "\.text\n\t\.align 8\n";
251     $T_HDR_entry    = "\.text\n\t\.align 8\n";
252     $T_HDR_vector   = "\.text\n\t\.align 8\n";
253
254     #--------------------------------------------------------#
255     } elsif ( $TargetPlatform =~ /^m68k-.*-sunos4/m ) {
256
257     $T_STABBY       = 1; # 1 iff .stab things (usually if a.out format)
258     $T_US           = '_'; # _ if symbols have an underscore on the front
259     $T_PRE_APP      = '^# MAY NOT APPLY'; # regexp that says what comes before APP/NO_APP
260     $T_CONST_LBL    = '^LC(\d+):$';
261     $T_POST_LBL     = ':';
262
263     $T_MOVE_DIRVS   = '^(\s*(\.align\s+\d+|\.proc\s+\d+|\.const|\.cstring|\.globl\s+\S+|\.text|\.data|\.even|\.stab[^n].*)\n)';
264     $T_COPY_DIRVS   = '\.(globl|proc|stab)';
265
266     $T_DOT_WORD     = '\.long';
267     $T_DOT_GLOBAL   = '\.globl';
268     $T_HDR_literal  = "\.text\n\t\.even\n";
269     $T_HDR_misc     = "\.text\n\t\.even\n";
270     $T_HDR_data     = "\.data\n\t\.even\n";
271     $T_HDR_rodata   = "\.text\n\t\.even\n";
272     $T_HDR_closure  = "\.data\n\t\.even\n";
273     $T_HDR_info     = "\.text\n\t\.even\n";
274     $T_HDR_entry    = "\.text\n\t\.even\n";
275     $T_HDR_vector   = "\.text\n\t\.even\n";
276
277     #--------------------------------------------------------#
278     } elsif ( $TargetPlatform =~ /^mips-.*/m ) {
279
280     $T_STABBY       = 0; # 1 iff .stab things (usually if a.out format)
281     $T_US           = ''; # _ if symbols have an underscore on the front
282     $T_PRE_APP      = '^\s*#'; # regexp that says what comes before APP/NO_APP
283     $T_CONST_LBL    = '^\$LC(\d+):$'; # regexp for what such a lbl looks like
284     $T_POST_LBL     = ':';
285
286     $T_MOVE_DIRVS   = '^(\s*(\.align\s+\d+|\.(globl|ent)\s+\S+|\.text|\.r?data)\n)';
287     $T_COPY_DIRVS   = '\.(globl|ent)';
288
289     $T_DOT_WORD     = '\.word';
290     $T_DOT_GLOBAL   = '^\t\.globl';
291     $T_HDR_literal  = "\t\.rdata\n\t\.align 2\n";
292     $T_HDR_misc     = "\t\.text\n\t\.align 2\n";
293     $T_HDR_data     = "\t\.data\n\t\.align 2\n";
294     $T_HDR_rodata   = "\t\.rdata\n\t\.align 2\n";
295     $T_HDR_closure  = "\t\.data\n\t\.align 2\n";
296     $T_HDR_info     = "\t\.text\n\t\.align 2\n";
297     $T_HDR_entry    = "\t\.text\n\t\.align 2\n";
298     $T_HDR_vector   = "\t\.text\n\t\.align 2\n";
299
300     #--------------------------------------------------------#
301     } elsif ( $TargetPlatform =~ /^powerpc-apple-darwin.*/m ) {
302                                 # Apple PowerPC Darwin/MacOS X.
303     $T_STABBY       = 0; # 1 iff .stab things (usually if a.out format)
304     $T_US           = '_'; # _ if symbols have an underscore on the front
305     $T_PRE_APP      = 'DOESNT APPLY'; # regexp that says what comes before APP/NO_APP
306     $T_CONST_LBL    = '^\LC\d+:'; # regexp for what such a lbl looks like
307     $T_POST_LBL     = ':';
308
309     $T_MOVE_DIRVS   = '^(\s*(\.(p2)?align\s.*|\.text|\.data|\.const_data|\.cstring|\.non_lazy_symbol_pointer|\.const|\.static_const|\.literal4|\.literal8|\.static_data|\.globl \S+|\.section .*|\.lcomm.*)\n)';
310     $T_COPY_DIRVS   = '\.(globl|lcomm)';
311
312     $T_DOT_WORD     = '\.(long|short|byte|fill|space)';
313     $T_DOT_GLOBAL   = '\.globl';
314     $T_HDR_toc      = "\.toc\n";
315     $T_HDR_literal  = "\t\.const\n\t\.align 2\n";
316     $T_HDR_misc     = "\t\.text\n\t\.align 2\n";
317     $T_HDR_data     = "\t\.data\n\t\.align 2\n";
318     $T_HDR_rodata   = "\t\.const\n\t\.align 2\n";
319     $T_HDR_relrodata= "\t\.const_data\n\t\.align 2\n";
320     $T_HDR_closure  = "\t\.data\n\t\.align 2\n";
321     $T_HDR_info     = "\t\.text\n\t\.align 2\n";
322     $T_HDR_entry    = "\t\.text\n\t\.align 2\n";
323     $T_HDR_vector   = "\t\.text\n\t\.align 2\n";
324
325     #--------------------------------------------------------#
326     } elsif ( $TargetPlatform =~ /^i386-apple-darwin.*/m ) {
327                                 # Apple i386 Darwin/MacOS X.
328     $T_STABBY       = 0; # 1 iff .stab things (usually if a.out format)
329     $T_US           = '_'; # _ if symbols have an underscore on the front
330     $T_PRE_APP      = 'DOESNT APPLY'; # regexp that says what comes before APP/NO_APP
331     $T_CONST_LBL    = '^\LC\d+:'; # regexp for what such a lbl looks like
332     $T_POST_LBL     = ':';
333     $T_X86_PRE_LLBL_PAT = 'L';
334     $T_X86_PRE_LLBL         = 'L';
335     $T_X86_BADJMP   = '^\tjmp [^L\*]';
336
337     $T_MOVE_DIRVS   = '^(\s*(\.(p2)?align\s.*|\.text|\.data|\.const_data|\.cstring|\.non_lazy_symbol_pointer|\.const|\.static_const|\.literal4|\.literal8|\.static_data|\.globl \S+|\.section .*|\.lcomm.*)\n)';
338     $T_COPY_DIRVS   = '\.(globl|lcomm)';
339
340     $T_DOT_WORD     = '\.(long|short|byte|fill|space)';
341     $T_DOT_GLOBAL   = '\.globl';
342     $T_HDR_toc      = "\.toc\n";
343     $T_HDR_literal16= "\t\.literal8\n\t\.align 4\n";
344     $T_HDR_literal  = "\t\.const\n\t\.align 4\n";
345     $T_HDR_misc     = "\t\.text\n\t\.align 2\n";
346     $T_HDR_data     = "\t\.data\n\t\.align 2\n";
347     $T_HDR_rodata   = "\t\.const\n\t\.align 2\n";
348     $T_HDR_relrodata= "\t\.const_data\n\t\.align 2\n";
349     $T_HDR_closure  = "\t\.data\n\t\.align 2\n";
350     $T_HDR_info     = "\t\.text\n\t\.align 2\n";
351     $T_HDR_entry    = "\t\.text\n\t\.align 2\n";
352     $T_HDR_vector   = "\t\.text\n\t\.align 2\n";
353
354     #--------------------------------------------------------#
355     } elsif ( $TargetPlatform =~ /^x86_64-apple-darwin.*/m ) {
356                                 # Apple amd64 Darwin/MacOS X.
357     $T_STABBY       = 0; # 1 iff .stab things (usually if a.out format)
358     $T_US           = '_'; # _ if symbols have an underscore on the front
359     $T_PRE_APP      = 'DOESNT APPLY'; # regexp that says what comes before APP/NO_APP
360     $T_CONST_LBL    = '^\LC\d+:'; # regexp for what such a lbl looks like
361     $T_POST_LBL     = ':';
362
363     $T_MOVE_DIRVS   = '^(\s*(\.align \d+|\.text|\.data|\.const_data|\.cstring|\.non_lazy_symbol_pointer|\.const|\.static_const|\.literal4|\.literal8|\.static_data|\.globl \S+|\.section .*|\.lcomm.*)\n)';
364     $T_COPY_DIRVS   = '\.(globl|lcomm)';
365
366     $T_DOT_WORD     = '\.(quad|long|short|byte|fill|space)';
367     $T_DOT_GLOBAL   = '\.globl';
368     $T_HDR_toc      = "\.toc\n";
369     $T_HDR_literal16= "\t\.literal8\n\t\.align 4\n";
370     $T_HDR_literal  = "\t\.const\n\t\.align 4\n";
371     $T_HDR_misc     = "\t\.text\n\t\.align 2\n";
372     $T_HDR_data     = "\t\.data\n\t\.align 2\n";
373     $T_HDR_rodata   = "\t\.const\n\t\.align 2\n";
374     $T_HDR_relrodata= "\t\.const_data\n\t\.align 2\n";
375     $T_HDR_closure  = "\t\.data\n\t\.align 2\n";
376     $T_HDR_info     = "\t\.text\n\t\.align 2\n";
377     $T_HDR_entry    = "\t\.text\n\t\.align 2\n";
378     $T_HDR_vector   = "\t\.text\n\t\.align 2\n";
379
380     #--------------------------------------------------------#
381     } elsif ( $TargetPlatform =~ /^powerpc-.*-linux/m ) {
382                                 # PowerPC Linux
383     $T_STABBY       = 0; # 1 iff .stab things (usually if a.out format)
384     $T_US           = ''; # _ if symbols have an underscore on the front
385     $T_PRE_APP      = '^#'; # regexp that says what comes before APP/NO_APP
386     $T_CONST_LBL    = '^\.LC\d+:'; # regexp for what such a lbl looks like
387     $T_POST_LBL     = ':';
388
389     $T_MOVE_DIRVS   = '^(\s*(\.(p2)?align\s+\d+(,\s*0x90)?|\.globl\s+\S+|\.text|\.data|\.section\s+.*|\.type\s+.*|\.size\s+\S+\s*,\s*\d+|\.ident.*|\.local.*)\n)';
390     $T_COPY_DIRVS   = '^\s*\.(globl|type|size|local)';
391
392     $T_DOT_WORD     = '\.(long|short|byte|fill|space)';
393     $T_DOT_GLOBAL   = '\.globl';
394     $T_HDR_toc      = "\.toc\n";
395     $T_HDR_literal  = "\t\.section\t.rodata\n\t\.align 2\n";
396     $T_HDR_misc     = "\t\.text\n\t\.align 2\n";
397     $T_HDR_data     = "\t\.data\n\t\.align 2\n";
398     $T_HDR_rodata   = "\t\.section\t.rodata\n\t\.align 2\n";
399     $T_HDR_closure  = "\t\.data\n\t\.align 2\n";
400     $T_HDR_info     = "\t\.text\n\t\.align 2\n";
401     $T_HDR_entry    = "\t\.text\n\t\.align 2\n";
402     $T_HDR_vector   = "\t\.text\n\t\.align 2\n";
403
404     #--------------------------------------------------------#
405     } elsif ( $TargetPlatform =~ /^powerpc64-.*-linux/m ) {
406                                 # PowerPC 64 Linux
407     $T_STABBY       = 0; # 1 iff .stab things (usually if a.out format)
408     $T_US           = '\.'; # _ if symbols have an underscore on the front
409     $T_PRE_APP      = '^#'; # regexp that says what comes before APP/NO_APP
410     $T_CONST_LBL    = '^\.LC\d+:'; # regexp for what such a lbl looks like
411     $T_POST_LBL     = ':';
412
413     $T_MOVE_DIRVS   = '^(\s*(\.(p2)?align\s+\d+(,\s*0x90)?|\.globl\s+\S+|\.text|\.data|\.section\s+.*|\.type\s+.*|\.size\s+\S+\s*,\s*\d+|\.ident.*|\.local.*)\n)';
414     $T_COPY_DIRVS   = '^\s*\.(globl|type|size|local)';
415
416     $T_DOT_WORD     = '\.(long|short|byte|fill|space)';
417     $T_DOT_GLOBAL   = '\.globl';
418     $T_HDR_toc      = "\.toc\n";
419     $T_HDR_literal  = "\t\.section\t\".toc\",\"aw\"\n";
420     $T_HDR_misc     = "\t\.text\n\t\.align 2\n";
421     $T_HDR_data     = "\t\.data\n\t\.align 2\n";
422     $T_HDR_rodata   = "\t\.section\t.rodata\n\t\.align 2\n";
423     $T_HDR_closure  = "\t\.data\n\t\.align 2\n";
424     $T_HDR_info     = "\t\.text\n\t\.align 2\n";
425     $T_HDR_entry    = "\t\.text\n\t\.align 2\n";
426     $T_HDR_vector   = "\t\.text\n\t\.align 2\n";
427
428     #--------------------------------------------------------#
429     } elsif ( $TargetPlatform =~ /^sparc-.*-(solaris2|openbsd)/m ) {
430
431     $T_STABBY       = 0; # 1 iff .stab things (usually if a.out format)
432     $T_US           = ''; # _ if symbols have an underscore on the front
433     $T_PRE_APP      = 'DOES NOT SEEM TO APPLY'; # regexp that says what comes before APP/NO_APP
434     $T_CONST_LBL    = '^\.LLC(\d+):$'; # regexp for what such a lbl looks like
435     $T_POST_LBL     = ':';
436
437     $T_MOVE_DIRVS   =  '^((\s+\.align\s+\d+|\s+\.proc\s+\d+|\s+\.global\s+\S+|\s+\.local\s+\S+|\.text|\.data|\.stab.*|\s*\.section.*|\s+\.type.*|\s+\.size.*)\n)';
438     $T_COPY_DIRVS   = '\.(global|local|proc|stab)';
439
440     $T_DOT_WORD     = '\.(long|word|byte|half|skip|uahalf|uaword)';
441     $T_DOT_GLOBAL   = '^\t\.global';
442     $T_HDR_literal  = "\.text\n\t\.align 8\n";
443     $T_HDR_misc     = "\.text\n\t\.align 4\n";
444     $T_HDR_data     = "\.data\n\t\.align 8\n";
445     $T_HDR_rodata   = "\.text\n\t\.align 4\n";
446     $T_HDR_closure  = "\.data\n\t\.align 4\n";
447     $T_HDR_info     = "\.text\n\t\.align 4\n";
448     $T_HDR_entry    = "\.text\n\t\.align 4\n";
449     $T_HDR_vector   = "\.text\n\t\.align 4\n";
450
451     #--------------------------------------------------------#
452     } elsif ( $TargetPlatform =~ /^sparc-.*-sunos4/m ) {
453
454     $T_STABBY       = 1; # 1 iff .stab things (usually if a.out format)
455     $T_US           = '_'; # _ if symbols have an underscore on the front
456     $T_PRE_APP      = '^# DOES NOT SEEM TO APPLY'; # regexp that says what comes before APP/NO_APP
457     $T_CONST_LBL    = '^LC(\d+):$';
458     $T_POST_LBL     = ':';
459
460     $T_MOVE_DIRVS   = '^((\s+\.align\s+\d+|\s+\.proc\s+\d+|\s+\.global\s+\S+|\.text|\.data|\.stab.*)\n)';
461     $T_COPY_DIRVS   = '\.(global|proc|stab)';
462
463     $T_DOT_WORD     = '\.word';
464     $T_DOT_GLOBAL   = '^\t\.global';
465     $T_HDR_literal  = "\.text\n\t\.align 8\n";
466     $T_HDR_misc     = "\.text\n\t\.align 4\n";
467     $T_HDR_data     = "\.data\n\t\.align 8\n";
468     $T_HDR_rodata   = "\.text\n\t\.align 4\n";
469     $T_HDR_closure  = "\.data\n\t\.align 4\n";
470     $T_HDR_info     = "\.text\n\t\.align 4\n";
471     $T_HDR_entry    = "\.text\n\t\.align 4\n";
472     $T_HDR_vector   = "\.text\n\t\.align 4\n";
473
474     #--------------------------------------------------------#
475     } elsif ( $TargetPlatform =~ /^sparc-.*-linux/m ) {
476     $T_STABBY       = 0; # 1 iff .stab things (usually if a.out format)
477     $T_US           = ''; # _ if symbols have an underscore on the front
478     $T_PRE_APP      = '#'; # regexp that says what comes before APP/NO_APP
479                            # Probably doesn't apply anyway
480     $T_CONST_LBL    = '^\.LLC(\d+):$'; # regexp for what such a lbl looks like
481     $T_POST_LBL     = ':';
482
483     $T_MOVE_DIRVS   = '^((\s+\.align\s+\d+|\s+\.proc\s+\d+|\s+\.global\s+\S+|\s+\.local\s+\S+|\.text|\.data|\.seg|\.stab.*|\s+?\.section.*|\s+\.type.*|\s+\.size.*)\n)';
484     $T_COPY_DIRVS   = '\.(global|local|globl|proc|stab)';
485
486     $T_DOT_WORD     = '\.(long|word|nword|xword|byte|half|short|skip|uahalf|uaword)';
487     $T_DOT_GLOBAL   = '^\t\.global';
488     $T_HDR_literal  = "\.text\n\t\.align 8\n";
489     $T_HDR_misc     = "\.text\n\t\.align 4\n";
490     $T_HDR_data     = "\.data\n\t\.align 8\n";
491     $T_HDR_rodata   = "\.text\n\t\.align 4\n";
492     $T_HDR_closure  = "\.data\n\t\.align 4\n";
493     $T_HDR_info     = "\.text\n\t\.align 4\n";
494     $T_HDR_entry    = "\.text\n\t\.align 4\n";
495     $T_HDR_vector   = "\.text\n\t\.align 4\n";
496
497     #--------------------------------------------------------#
498     } else {
499         print STDERR "$Pgm: don't know how to mangle assembly language for: $TargetPlatform\n";
500         exit 1;
501     }
502
503     if($T_HDR_relrodata eq "") {
504             # default values:
505             # relrodata defaults to rodata.
506         $T_HDR_relrodata = $T_HDR_rodata;
507     }
508
509 if ( 0 ) {
510 print STDERR "T_STABBY: $T_STABBY\n";
511 print STDERR "T_US: $T_US\n";
512 print STDERR "T_PRE_APP: $T_PRE_APP\n";
513 print STDERR "T_CONST_LBL: $T_CONST_LBL\n";
514 print STDERR "T_POST_LBL: $T_POST_LBL\n";
515 if ( $TargetPlatform =~ /^i386-/m ) {
516     print STDERR "T_X86_PRE_LLBL_PAT: $T_X86_PRE_LLBL_PAT\n";
517     print STDERR "T_X86_PRE_LLBL: $T_X86_PRE_LLBL\n";
518     print STDERR "T_X86_BADJMP: $T_X86_BADJMP\n";
519 }
520 print STDERR "T_MOVE_DIRVS: $T_MOVE_DIRVS\n";
521 print STDERR "T_COPY_DIRVS: $T_COPY_DIRVS\n";
522 print STDERR "T_DOT_WORD: $T_DOT_WORD\n";
523 print STDERR "T_HDR_literal: $T_HDR_literal\n";
524 print STDERR "T_HDR_misc: $T_HDR_misc\n";
525 print STDERR "T_HDR_data: $T_HDR_data\n";
526 print STDERR "T_HDR_rodata: $T_HDR_rodata\n";
527 print STDERR "T_HDR_closure: $T_HDR_closure\n";
528 print STDERR "T_HDR_info: $T_HDR_info\n";
529 print STDERR "T_HDR_entry: $T_HDR_entry\n";
530 print STDERR "T_HDR_vector: $T_HDR_vector\n";
531 }
532
533 }
534 \end{code}
535
536 %************************************************************************
537 %*                                                                      *
538 \subsection{Mangle away}
539 %*                                                                      *
540 %************************************************************************
541
542 \begin{code}
543 sub mangle_asm {
544     local($in_asmf, $out_asmf) = @_;
545     local($i, $c);
546
547     # ia64-specific information for code chunks
548     my $ia64_locnum;
549     my $ia64_outnum;
550
551     &init_TARGET_STUFF();
552     &init_FUNNY_THINGS();
553
554     open(INASM, "< $in_asmf")
555         || &tidy_up_and_die(1,"$Pgm: failed to open `$in_asmf' (to read)\n");
556     open(OUTASM,"> $out_asmf")
557         || &tidy_up_and_die(1,"$Pgm: failed to open `$out_asmf' (to write)\n");
558
559     # read whole file, divide into "chunks":
560     #   record some info about what we've found...
561
562     @chk = ();          # contents of the chunk
563     $numchks = 0;       # number of them
564     @chkcat = ();       # what category of thing in each chunk
565     @chksymb = ();      # what symbol(base) is defined in this chunk
566     %entrychk = ();     # ditto, its entry code
567     %closurechk = ();   # ditto, the (static) closure
568     %srtchk = ();       # ditto, its SRT (for top-level things)
569     %infochk = ();      # given a symbol base, say what chunk its info tbl is in
570     %vectorchk = ();    # ditto, return vector table
571     $EXTERN_DECLS = ''; # .globl <foo> .text (MIPS only)
572
573     $i = 0; $chkcat[0] = 'misc'; $chk[0] = '';
574
575     while (<INASM>) {
576         tr/\r//d if $TargetPlatform =~ /-mingw32$/m; # In case Perl doesn't convert line endings
577         next if $T_STABBY && /^\.stab.*${T_US}__stg_split_marker/om;
578         next if $T_STABBY && /^\.stab.*ghc.*c_ID/m;
579         next if /^\t\.def.*endef$/m;
580         next if /${T_PRE_APP}(NO_)?APP/om; 
581         next if /^;/m && $TargetPlatform =~ /^hppa/m;
582
583         next if /(^$|^\t\.file\t|^ # )/m && $TargetPlatform =~ /(^mips-|^ia64-|-mingw32$)/m;
584
585         if ( $TargetPlatform =~ /^mips-/m 
586           && /^\t\.(globl\S+\.text|comm\t)/m ) {
587             $EXTERN_DECLS .= $_ unless /(__DISCARD__|\b(PK_|ASSIGN_)(FLT|DBL)\b)/m;
588         # Treat .comm variables as data.  These show up in two (known) places:
589         #
590         #    - the module_registered variable used in the __stginit fragment.
591         #      even though these are declared static and initialised, gcc 3.3
592         #      likes to make them .comm, presumably to save space in the
593         #      object file.
594         #
595         #    - global variables used to pass arguments from C to STG in
596         #      a foreign export.  (is this still true? --SDM)
597         # 
598         } elsif ( /^\t\.comm.*$/m ) {
599             $chk[++$i]   = $_;
600             $chkcat[$i]  = 'data';
601             $chksymb[$i] = '';
602
603         # Labels ending "_str": these are literal strings.
604         } elsif ( /^${T_US}([A-Za-z0-9_]+)_str${T_POST_LBL}$/m ) {
605             $chk[++$i]   = $_;
606             $chkcat[$i]  = 'relrodata';
607             $chksymb[$i] = '';
608         } elsif ( $TargetPlatform =~ /-darwin/m
609                 && (/^\s*\.subsections_via_symbols/m
610                   ||/^\s*\.no_dead_strip.*/m)) {
611             # Don't allow Apple's linker to do any dead-stripping of symbols
612             # in this file, because it will mess up info-tables in mangled
613             # code.
614             # The .no_dead_strip directives are actually put there by
615             # the gcc3 "used" attribute on entry points.
616         
617         } elsif ( $TargetPlatform =~ /^.*-apple-darwin.*/m && ( 
618                    /^\s*\.picsymbol_stub/m
619                 || /^\s*\.section __TEXT,__picsymbol_stub\d,.*/m
620                 || /^\s*\.section __TEXT,__picsymbolstub\d,.*/m
621                 || /^\s*\.symbol_stub/m
622                 || /^\s*\.section __TEXT,__symbol_stub\d,.*/m
623                 || /^\s*\.section __TEXT,__symbolstub\d,.*/m
624                 || /^\s*\.lazy_symbol_pointer/m
625                 || /^\s*\.non_lazy_symbol_pointer/m
626                 || /^\s*\.section __IMPORT.*/m))
627         {
628             $chk[++$i]   = $_;
629             $chkcat[$i]  = 'dyld';
630             $chksymb[$i] = '';
631             $dyld_section = $_;
632
633         } elsif ( $TargetPlatform =~ /^.*-apple-darwin.*/m && $chkcat[$i] eq 'dyld' && /^\s*\.data/m)
634         {       # non_lazy_symbol_ptrs that point to local symbols
635             $chk[++$i]   = $_;
636             $chkcat[$i]  = 'dyld';
637             $chksymb[$i] = '';
638             $dyld_section = $_;
639         } elsif ( $TargetPlatform =~ /^.*-apple-darwin.*/m && $chkcat[$i] eq 'dyld' && /^\s*\.align/m)
640         {       # non_lazy_symbol_ptrs that point to local symbols
641             $dyld_section .= $_;
642         } elsif ( $TargetPlatform =~ /^.*-apple-darwin.*/m && $chkcat[$i] eq 'dyld' && /^L_.*:$/m)
643         {       # non_lazy_symbol_ptrs that point to local symbols
644             $chk[++$i]   = $dyld_section . $_;
645             $chkcat[$i]  = 'dyld';
646             $chksymb[$i] = '';
647
648         } elsif ( /^\s+/m ) { # most common case first -- a simple line!
649             # duplicated from the bottom
650
651             $chk[$i] .= $_;
652
653         } elsif ( /\.\.ng:$/m && $TargetPlatform =~ /^alpha-/m ) {
654             # Alphas: Local labels not to be confused with new chunks
655             $chk[$i] .= $_;
656         # NB: all the rest start with a non-space
657
658         } elsif ( $TargetPlatform =~ /^mips-/m
659                && /^\d+:/m ) { # a funny-looking very-local label
660             $chk[$i] .= $_;
661
662         } elsif ( /$T_CONST_LBL/om ) {
663             $chk[++$i]   = $_;
664             $chkcat[$i]  = 'literal';
665             $chksymb[$i] = $1;
666
667         } elsif ( /^${T_US}__stg_split_marker(\d*)${T_POST_LBL}$/om ) {
668             $chk[++$i]   = $_;
669             $chkcat[$i]  = 'splitmarker';
670             $chksymb[$i] = $1;
671
672         } elsif ( /^${T_US}([A-Za-z0-9_]+)_info${T_POST_LBL}$/om ) {
673             $symb = $1;
674             $chk[++$i]   = $_;
675             $chkcat[$i]  = 'infotbl';
676             $chksymb[$i] = $symb;
677
678             die "Info table already? $symb; $i\n" if defined($infochk{$symb});
679
680             $infochk{$symb} = $i;
681
682         } elsif ( /^${T_US}([A-Za-z0-9_]+)_(entry|ret)${T_POST_LBL}$/om ) {
683             $chk[++$i]   = $_;
684             $chkcat[$i]  = 'entry';
685             $chksymb[$i] = $1;
686
687             $entrychk{$1} = $i;
688
689         } elsif ( /^${T_US}([A-Za-z0-9_]+)_closure${T_POST_LBL}$/om ) {
690             $chk[++$i]   = $_;
691             $chkcat[$i]  = 'closure';
692             $chksymb[$i] = $1;
693
694             $closurechk{$1} = $i;
695
696         } elsif ( /^${T_US}([A-Za-z0-9_]+)_srt${T_POST_LBL}$/om ) {
697             $chk[++$i]   = $_;
698             $chkcat[$i]  = 'srt';
699             $chksymb[$i] = $1;
700
701             $srtchk{$1} = $i;
702
703         } elsif ( /^${T_US}([A-Za-z0-9_]+)_ct${T_POST_LBL}$/om ) {
704             $chk[++$i]   = $_;
705             $chkcat[$i]  = 'data';
706             $chksymb[$i] = '';
707
708         } elsif ( /^${T_US}(stg_ap_stack_entries|stg_stack_save_entries|stg_arg_bitmaps)${T_POST_LBL}$/om ) {
709             $chk[++$i]   = $_;
710             $chkcat[$i]  = 'data';
711             $chksymb[$i] = '';
712
713         } elsif ( /^(${T_US}__gnu_compiled_c|gcc2_compiled\.)${T_POST_LBL}/om ) {
714             ; # toss it
715
716         } elsif ( /^${T_US}[A-Za-z0-9_]+\.\d+${T_POST_LBL}$/om
717                || /^${T_US}.*_CAT${T_POST_LBL}$/om              # PROF: _entryname_CAT
718                || /^${T_US}.*_done${T_POST_LBL}$/om             # PROF: _module_done
719                || /^${T_US}_module_registered${T_POST_LBL}$/om  # PROF: _module_registered
720                ) {
721             $chk[++$i]   = $_;
722             $chkcat[$i]  = 'data';
723             $chksymb[$i] = '';
724
725         } elsif ( /^([A-Za-z0-9_]+)\s+\.comm/m && $TargetPlatform =~ /^hppa/m ) {
726             $chk[++$i]   = $_;
727             $chkcat[$i]  = 'bss';
728             $chksymb[$i] = '';
729
730         } elsif ( /^${T_US}([A-Za-z0-9_]+)_cc(s)?${T_POST_LBL}$/om ) {
731             # all CC_ symbols go in the data section...
732             $chk[++$i]   = $_;
733             $chkcat[$i]  = 'data';
734             $chksymb[$i] = '';
735
736         } elsif ( /^${T_US}([A-Za-z0-9_]+)_hpc${T_POST_LBL}$/om ) {
737            # hpc shares tick boxes across modules
738            $chk[++$i]   = $_;
739            $chkcat[$i]  = 'data';
740            $chksymb[$i] = '';
741
742         } elsif ( /^${T_US}([A-Za-z0-9_]+)_(alt|dflt)${T_POST_LBL}$/om ) {
743             $chk[++$i]   = $_;
744             $chkcat[$i]  = 'misc';
745             $chksymb[$i] = '';
746         } elsif ( /^${T_US}([A-Za-z0-9_]+)_vtbl${T_POST_LBL}$/om ) {
747             $chk[++$i]   = $_;
748             $chkcat[$i]  = 'vector';
749             $chksymb[$i] = $1;
750
751             $vectorchk{$1} = $i;
752
753         } elsif ( $TargetPlatform =~ /^i386-.*-solaris2/m
754              &&   /^[A-Za-z0-9][A-Za-z0-9_]*:/m ) {
755             # Some Solaris system headers contain function definitions (as
756             # opposed to mere prototypes), which end up in the .hc file when
757             # a Haskell module foreign imports the corresponding system 
758             # functions (most notably stat()).  We put them into the text 
759             # segment.  Note that this currently does not extend to function
760             # names starting with an underscore. 
761             # - chak 7/2001
762             $chk[++$i]   = $_;
763             $chkcat[$i]  = 'misc';
764             $chksymb[$i] = $1;
765
766         } elsif ( $TargetPlatform =~ /^i386-apple-darwin/m && /^(___i686\.get_pc_thunk\.[abcd]x):/om) {
767                 # To handle PIC on Darwin/x86, we need to appropriately pass through
768                 # the get_pc_thunk functions. The need to be put into a special section
769                 # marked as coalesced (otherwise the .weak_definition doesn't work
770                 # on Darwin).
771             $chk[++$i]   = $_;
772             $chkcat[$i]  = 'get_pc_thunk';
773             $chksymb[$i] = $1;
774
775         } elsif ( /^${T_US}[A-Za-z0-9_]/om
776                 && ( $TargetPlatform !~ /^hppa/m # need to avoid local labels in this case
777                    || ! /^L\$\d+$/m ) 
778                 && ( $TargetPlatform !~ /^powerpc64/m # we need to avoid local labels in this case
779                    || ! /^\.L\d+:$/m ) ) {
780             local($thing);
781             chop($thing = $_);
782             $thing =~ s/:$//m;
783             $chk[++$i]   = $_;
784             $chksymb[$i] = '';
785             if (
786                        /^${T_US}stg_.*${T_POST_LBL}$/om          # RTS internals
787                     || /^${T_US}__stg_.*${T_POST_LBL}$/om        # more RTS internals
788                     || /^${T_US}__fexp_.*${T_POST_LBL}$/om       # foreign export
789                     || /^${T_US}.*_slow${T_POST_LBL}$/om         # slow entry
790                     || /^${T_US}__stginit.*${T_POST_LBL}$/om     # __stginit<module>
791                     || /^${T_US}.*_btm${T_POST_LBL}$/om          # large bitmaps
792                     || /^${T_US}.*_fast${T_POST_LBL}$/om         # primops
793                     || /^_uname:/om                             # x86/Solaris2
794                 )
795             {
796                 $chkcat[$i]  = 'misc';
797             } elsif (
798                        /^${T_US}.*_srtd${T_POST_LBL}$/om          # large bitmaps
799                     || /^${T_US}.*_closure_tbl${T_POST_LBL}$/om  # closure tables
800                 )
801             {
802                 $chkcat[$i] = 'relrodata';
803             } else
804             {
805                 print STDERR "Warning: retaining unknown function \`$thing' in output from C compiler\n";
806                 $chkcat[$i]  = 'unknown';
807             }
808
809         } elsif ( $TargetPlatform =~ /^powerpc-.*-linux/m && /^\.LCTOC1 = /om ) {
810                 # PowerPC Linux's large-model PIC (-fPIC) generates a gobal offset
811                 # table "by hand". Be sure to copy it over.
812                 # Note that this label and all entries in the table should actually
813                 # go into the .got2 section, but it isn't easy to distinguish them
814                 # from other constant literals (.LC\d+), so we just put everything
815                 # in .rodata.
816             $chk[++$i]   = $_;
817             $chkcat[$i]  = 'literal';
818             $chksymb[$i] = 'LCTOC1';
819         } else { # simple line (duplicated at the top)
820
821             $chk[$i] .= $_;
822         }
823     }
824     $numchks = $#chk + 1;
825     $chk[$numchks] = ''; # We might push .note.GNU-stack into this
826     $chkcat[$numchks] = 'verbatim'; # If we do, write it straight back out
827
828     # open CHUNKS, ">/tmp/chunks1" or die "Cannot open /tmp/chunks1: $!\n";
829     # for (my $i = 0; $i < @chk; ++$i) { print CHUNKS "======= $i =======\n", $chk[$i] }
830     # close CHUNKS;
831
832     # the division into chunks is imperfect;
833     # we throw some things over the fence into the next
834     # chunk.
835     #
836     # also, there are things we would like to know
837     # about the whole module before we start spitting
838     # output.
839
840     local($FIRST_MANGLABLE) = ($TargetPlatform =~ /^(alpha-|hppa|mips-)/m) ? 1 : 0;
841     local($FIRST_TOSSABLE ) = ($TargetPlatform =~ /^(hppa|mips-)/m) ? 1 : 0;
842
843 #   print STDERR "first chunk to mangle: $FIRST_MANGLABLE\n";
844
845     # Alphas: NB: we start meddling at chunk 1, not chunk 0
846     # The first ".rdata" is quite magical; as of GCC 2.7.x, it
847     # spits a ".quad 0" in after the very first ".rdata"; we
848     # detect this special case (tossing the ".quad 0")!
849     local($magic_rdata_seen) = 0;
850   
851     # HPPAs, MIPSen: also start medding at chunk 1
852
853     for ($i = $FIRST_TOSSABLE; $i < $numchks; $i++) {
854         $c = $chk[$i]; # convenience copy
855
856 #       print STDERR "\nCHK $i (BEFORE) (",$chkcat[$i],"):\n", $c;
857
858         # toss all prologue stuff; HPPA is pretty weird
859         # (see elsewhere)
860         $c = &hppa_mash_prologue($c) if $TargetPlatform =~ /^hppa-/m;
861
862         undef $ia64_locnum;
863         undef $ia64_outnum;
864
865         # be slightly paranoid to make sure there's
866         # nothing surprising in there
867         if ( $c =~ /--- BEGIN ---/m ) {
868             if (($p, $r) = split(/--- BEGIN ---/m, $c)) {
869
870                 # remove junk whitespace around the split point
871                 $p =~ s/\t+$//m;
872                 $r =~ s/^\s*\n//m;
873
874                 if ($TargetPlatform =~ /^i386-/m) {
875                     if ($p =~ /^\tsubl\s+\$(\d+),\s*\%esp\n/m) {
876                         if ($1 >= 8192) {
877                             die "Error: reserved stack space exceeded!\n  Possible workarounds: compile with -fasm, or try another version of gcc.\n"
878                         }
879                     }
880
881                 # gcc 3.4.3 puts this kind of stuff in the prologue, eg.
882                 # when compiling PrimOps.cmm with -optc-O2:
883                 #        xorl    %ecx, %ecx
884                 #        xorl    %edx, %edx
885                 #        movl    %ecx, 16(%esp)
886                 #        movl    %edx, 20(%esp)
887                 # but then the code of the function doesn't assume
888                 # anything about the contnets of these stack locations.
889                 # I think it's to do with the use of inline functions for
890                 # PK_Word64() and friends, where gcc is initialising the
891                 # contents of the struct to zero, and failing to optimise
892                 # away the initialisation.  Let's live dangerously and
893                 # discard these initalisations.
894
895                     $p =~ s/^\tpushl\s+\%e(di|si|bx)\n//gm;
896                     $p =~ s/^\txorl\s+\%e(ax|cx|dx),\s*\%e(ax|cx|dx)\n//gm;
897                     $p =~ s/^\tmovl\s+\%e(ax|cx|dx|si|di),\s*\d*\(\%esp\)\n//gm;
898                     $p =~ s/^\tmovl\s+\$\d+,\s*\d*\(\%esp\)\n//gm;
899                     $p =~ s/^\tsubl\s+\$\d+,\s*\%esp\n//m;
900                     $p =~ s/^\tmovl\s+\$\d+,\s*\%eax\n\tcall\s+__alloca\n//m if ($TargetPlatform =~ /^.*-(cygwin32|mingw32)/m);
901
902                     if ($TargetPlatform =~ /^i386-apple-darwin/m) {
903                         $pcrel_label = $p;
904                         $pcrel_label =~ s/(.|\n)*^(\"?L\d+\$pb\"?):\n(.|\n)*/$2/m or $pcrel_label = "";
905                         $pcrel_reg = $p;
906                         $pcrel_reg =~ s/(.|\n)*.*___i686\.get_pc_thunk\.([abcd]x)\n(.|\n)*/$2/m or $pcrel_reg = "";
907                         $p =~ s/^\s+call\s+___i686\.get_pc_thunk\..x//m;
908                         $p =~ s/^\"?L\d+\$pb\"?:\n//m;
909
910                         if ($pcrel_reg eq "bx") {
911                             # Bad gcc. Goes and uses %ebx, our BaseReg, for PIC. Bad gcc.
912                             die "Darwin/x86: -fPIC -via-C doesn't work yet, use -fasm. Aborting."
913                         }
914                     }
915
916                 } elsif ($TargetPlatform =~ /^x86_64-/m) {
917                     $p =~ s/^\tpushq\s+\%r(bx|bp|12|13|14)\n//gm;
918                     $p =~ s/^\tmovq\s+\%r(bx|bp|12|13|14),\s*\d*\(\%rsp\)\n//gm;
919                     $p =~ s/^\tsubq\s+\$\d+,\s*\%rsp\n//m;
920
921                 } elsif ($TargetPlatform =~ /^ia64-/m) {
922                     $p =~ s/^\t\.prologue .*\n//m;
923
924                     # Record the number of local and out registers for register relocation later
925                     $p =~ s/^\t\.save ar\.pfs, r\d+\n\talloc r\d+ = ar\.pfs, 0, (\d+), (\d+), 0\n//m;
926                     $ia64_locnum = $1;
927                     $ia64_outnum = $2;
928
929                     $p =~ s/^\t\.fframe \d+\n\tadds r12 = -\d+, r12\n//m;
930                     $p =~ s/^\t\.save rp, r\d+\n\tmov r\d+ = b0\n//m;
931
932                     # Ignore save/restore of these registers; they're taken
933                     # care of in StgRun()
934                     $p =~ s/^\t\.save ar\.lc, r\d+\n//m;
935                     $p =~ s/^\t\.save pr, r\d+\n//m;
936                     $p =~ s/^\tmov r\d+ = ar\.lc\n//m;
937                     $p =~ s/^\tmov r\d+ = pr\n//m;
938
939                     # Remove .proc and .body directives
940                     $p =~ s/^\t\.proc [a-zA-Z0-9_.]+#\n//m;
941                     $p =~ s/^\t\.body\n//m;
942
943                     # If there's a label, move it to the body
944                     if ($p =~ /^[a-zA-Z0-9.]+:\n/m) {
945                         $p = $` . $';
946                         $r = $& . $r;
947                       }
948
949                     # Remove floating-point spill instructions.
950                     # Only fp registers 2-5 and 16-23 are saved by the runtime.
951                     if ($p =~ s/^\tstf\.spill \[r1[4-9]\] = f([2-5]|1[6-9]|2[0-3])(, [0-9]+)?\n//gm) {
952                         # Being paranoid, only try to remove these if we saw a
953                         # spill operation.
954                         $p =~ s/^\tmov r1[4-9] = r12\n//m;
955                         $p =~ s/^\tadds r1[4-9] = -[0-9]+, r12\n//gm;
956                         $p =~ s/^\t\.save\.f 0x[0-9a-fA-F]\n//gm;
957                         $p =~ s/^\t\.save\.gf 0x0, 0x[0-9a-fA-F]+\n//gm;
958                     }
959
960                     $p =~ s/^\tnop(?:\.[mifb])?\s+\d+\n//gm; # remove nop instructions
961                     $p =~ s/^\t\.(mii|mmi|mfi)\n//gm;    # bundling is no longer sensible
962                     $p =~ s/^\t;;\n//gm;                # discard stops
963                     $p =~ s/^\t\/\/.*\n//gm;    # gcc inserts timings in // comments
964
965                     # GCC 3.3 saves r1 in the prologue, move this to the body
966                     # (Does this register get restored anywhere?)
967                     if ($p =~ /^\tmov r\d+ = r1\n/m) {
968                       $p = $` . $';
969                       $r = $& . $r;
970                     }
971                 } elsif ($TargetPlatform =~ /^m68k-/m) {
972                     $p =~ s/^\tlink a6,#-?\d.*\n//m;
973                     $p =~ s/^\tpea a6@\n\tmovel sp,a6\n//m;    
974                                 # The above showed up in the asm code,
975                                 # so I added it here.
976                                 # I hope it's correct.
977                                 # CaS
978                     $p =~ s/^\tmovel d2,sp\@-\n//m;
979                     $p =~ s/^\tmovel d5,sp\@-\n//m; # SMmark.* only?
980                     $p =~ s/^\tmoveml \#0x[0-9a-f]+,sp\@-\n//m; # SMmark.* only?
981                 } elsif ($TargetPlatform =~ /^mips-/m) {
982                     # the .frame/.mask/.fmask that we use is the same
983                     # as that produced by GCC for miniInterpret; this
984                     # gives GDB some chance of figuring out what happened
985                     $FRAME = "\t.frame\t\$sp,2168,\$31\n\t.mask\t0x90000000,-4\n\t.fmask\t0x00000000,0\n";
986                     $p =~ s/^\t\.(frame).*\n/__FRAME__/gm;
987                     $p =~ s/^\t\.(mask|fmask).*\n//gm;
988                     $p =~ s/^\t\.cprestore.*\n/\t\.cprestore 416\n/m; # 16 + 100 4-byte args
989                     $p =~ s/^\tsubu\t\$sp,\$sp,\d+\n//m;
990                     $p =~ s/^\tsw\t\$31,\d+\(\$sp\)\n//m;
991                     $p =~ s/^\tsw\t\$fp,\d+\(\$sp\)\n//m;
992                     $p =~ s/^\tsw\t\$28,\d+\(\$sp\)\n//m;
993                     $p =~ s/__FRAME__/$FRAME/m;
994                 } elsif ($TargetPlatform =~ /^powerpc-apple-darwin.*/m) {
995                     $pcrel_label = $p;
996                     $pcrel_label =~ s/(.|\n)*^(\"?L\d+\$pb\"?):\n(.|\n)*/$2/m or $pcrel_label = "";
997
998                     $p =~ s/^\tmflr r0\n//m;
999                     $p =~ s/^\tbl saveFP # f\d+\n//m;
1000                     $p =~ s/^\tbl saveFP ; save f\d+-f\d+\n//m;
1001                     $p =~ s/^\"?L\d+\$pb\"?:\n//m;
1002                     $p =~ s/^\tstmw r\d+,-\d+\(r1\)\n//m;
1003                     $p =~ s/^\tstfd f\d+,-\d+\(r1\)\n//gm;
1004                     $p =~ s/^\tstw r0,\d+\(r1\)\n//gm;
1005                     $p =~ s/^\tstwu r1,-\d+\(r1\)\n//m; 
1006                     $p =~ s/^\tstw r\d+,-\d+\(r1\)\n//gm; 
1007                     $p =~ s/^\tbcl 20,31,\"?L\d+\$pb\"?\n//m;
1008                     $p =~ s/^\"?L\d+\$pb\"?:\n//m;
1009                     $p =~ s/^\tmflr r31\n//m;
1010
1011                     # This is bad: GCC 3 seems to zero-fill some local variables in the prologue
1012                     # under some circumstances, only when generating position dependent code.
1013                     # I have no idea why, and I don't think it is necessary, so let's toss it.
1014                     $p =~ s/^\tli r\d+,0\n//gm;
1015                     $p =~ s/^\tstw r\d+,\d+\(r1\)\n//gm;
1016                 } elsif ($TargetPlatform =~ /^powerpc-.*-linux/m) {
1017                     $p =~ s/^\tmflr 0\n//m;
1018                     $p =~ s/^\tstmw \d+,\d+\(1\)\n//m;
1019                     $p =~ s/^\tstfd \d+,\d+\(1\)\n//gm;
1020                     $p =~ s/^\tstw r0,8\(1\)\n//m;
1021                     $p =~ s/^\tstwu 1,-\d+\(1\)\n//m; 
1022                     $p =~ s/^\tstw \d+,\d+\(1\)\n//gm; 
1023                     
1024                         # GCC's "large-model" PIC (-fPIC)
1025                     $pcrel_label = $p;
1026                     $pcrel_label =~ s/(.|\n)*^.LCF(\d+):\n(.|\n)*/$2/m or $pcrel_label = "";
1027
1028                     $p =~ s/^\tbcl 20,31,.LCF\d+\n//m;
1029                     $p =~ s/^.LCF\d+:\n//m;
1030                     $p =~ s/^\tmflr 30\n//m;
1031                     $p =~ s/^\tlwz 0,\.LCL\d+-\.LCF\d+\(30\)\n//m;
1032                     $p =~ s/^\tadd 30,0,30\n//m;
1033
1034                     # This is bad: GCC 3 seems to zero-fill some local variables in the prologue
1035                     # under some circumstances, only when generating position dependent code.
1036                     # I have no idea why, and I don't think it is necessary, so let's toss it.
1037                     $p =~ s/^\tli \d+,0\n//gm;
1038                     $p =~ s/^\tstw \d+,\d+\(1\)\n//gm;
1039                 } elsif ($TargetPlatform =~ /^powerpc64-.*-linux/m) {
1040                     $p =~ s/^\tmr 31,1\n//m;
1041                     $p =~ s/^\tmflr 0\n//m;
1042                     $p =~ s/^\tstmw \d+,\d+\(1\)\n//m;
1043                     $p =~ s/^\tstfd \d+,-?\d+\(1\)\n//gm;
1044                     $p =~ s/^\tstd r0,8\(1\)\n//m;
1045                     $p =~ s/^\tstdu 1,-\d+\(1\)\n//m; 
1046                     $p =~ s/^\tstd \d+,-?\d+\(1\)\n//gm; 
1047                     
1048                     # This is bad: GCC 3 seems to zero-fill some local variables in the prologue
1049                     # under some circumstances, only when generating position dependent code.
1050                     # I have no idea why, and I don't think it is necessary, so let's toss it.
1051                     $p =~ s/^\tli \d+,0\n//gm;
1052                     $p =~ s/^\tstd \d+,\d+\(1\)\n//gm;
1053                 } else {
1054                     print STDERR "$Pgm: unknown prologue mangling? $TargetPlatform\n";
1055                 }
1056                 
1057                 # HWL HACK: dont die, just print a warning
1058                 #print stderr  "HWL: this should die! Prologue junk?: $p\n" if $p =~ /^\t[^\.]/;
1059                 die "Prologue junk?: $p\n" if $p =~ /^\s+[^\s\.]/m;
1060                 
1061                 # For PIC, we want to keep part of the prologue
1062                 if ($TargetPlatform =~ /^powerpc-apple-darwin.*/m && $pcrel_label ne "") {
1063                     # Darwin: load the current instruction pointer into register r31
1064                     $p .= "bcl 20,31,$pcrel_label\n";
1065                     $p .= "$pcrel_label:\n";
1066                     $p .= "\tmflr r31\n";
1067                 } elsif ($TargetPlatform =~ /^powerpc-.*-linux/m && $pcrel_label ne "") {
1068                     # Linux: load the GOT pointer into register 30
1069                     $p .= "\tbcl 20,31,.LCF$pcrel_label\n";
1070                     $p .= ".LCF$pcrel_label:\n";
1071                     $p .= "\tmflr 30\n";
1072                     $p .= "\tlwz 0,.LCL$pcrel_label-.LCF$pcrel_label(30)\n";
1073                     $p .= "\tadd 30,0,30\n";
1074                 } elsif ($TargetPlatform =~ /^i386-apple-darwin.*/m && $pcrel_label ne "") {
1075                     $p .= "\tcall ___i686.get_pc_thunk.$pcrel_reg\n";
1076                     $p .= "$pcrel_label:\n";
1077                 }
1078                 
1079                 # glue together what's left
1080                 $c = $p . $r;
1081             }
1082         }
1083
1084         if ( $TargetPlatform =~ /^mips-/m ) {
1085             # MIPS: first, this basic sequence may occur "--- END ---" or not
1086             $c =~ s/^\tlw\t\$31,\d+\(\$sp\)\n\taddu\t\$sp,\$sp,\d+\n\tj\t\$31\n\t\.end/\t\.end/m;
1087         }
1088
1089         # toss all epilogue stuff; again, paranoidly
1090         if ( $c =~ /--- END ---/m ) {
1091             # Gcc may decide to replicate the function epilogue.  We want
1092             # to process all epilogues, so we split the function and then
1093             # loop here.
1094             @fragments = split(/--- END ---/m, $c);
1095             $r = shift(@fragments);
1096
1097             # Rebuild `c'; processed fragments will be appended to `c'
1098             $c = $r;
1099
1100             foreach $e (@fragments) {
1101                 # etail holds code that is after the epilogue in the assembly-code
1102                 # layout and should not be filtered as part of the epilogue.
1103                 $etail = "";
1104                 if ($TargetPlatform =~ /^i386-/m) {
1105                     $e =~ s/^\tret\n//m;
1106                     $e =~ s/^\tpopl\s+\%edi\n//m;
1107                     $e =~ s/^\tpopl\s+\%esi\n//m;
1108                     $e =~ s/^\tpopl\s+\%edx\n//m;
1109                     $e =~ s/^\tpopl\s+\%ecx\n//m;
1110                     $e =~ s/^\taddl\s+\$\d+,\s*\%esp\n//m;
1111                     $e =~ s/^\tsubl\s+\$-\d+,\s*\%esp\n//m;
1112                 } elsif ($TargetPlatform =~ /^ia64-/m) {
1113                     # The epilogue is first split into:
1114                     #     $e,    the epilogue code (up to the return instruction)
1115                     #     $etail, non-epilogue code (after the return instruction)
1116                     # The return instruction is stripped in the process.
1117                     if (!(($e, $etail) = split(/^\tbr\.ret\.sptk\.many b0\n/m, $e))) {
1118                         die "Epilogue doesn't seem to have one return instruction: $e\n";
1119                     }
1120                     # Remove 'endp' directive from the tail
1121                     $etail =~ s/^\t\.endp [a-zA-Z0-9_.]+#\n//m;
1122
1123                     # If a return value is saved here, discard it
1124                     $e =~ s/^\tmov r8 = r14\n//m;
1125
1126                     # Remove floating-point fill instructions.
1127                     # Only fp registers 2-5 and 16-23 are saved by the runtime.
1128                     if ($e =~ s/^\tldf\.fill f([2-5]|1[6-9]|2[0-3]) = \[r1[4-9]\](, [0-9]+)?\n//gm) {
1129                         # Being paranoid, only try to remove this if we saw a fill
1130                         # operation.
1131                         $e =~ s/^\tadds r1[4-9] = [0-9]+, r12//gm;
1132                     }
1133
1134                     $e =~ s/^\tnop(?:\.[mifb])?\s+\d+\n//gm; # remove nop instructions
1135                     $e =~ s/^\tmov ar\.pfs = r\d+\n//m;
1136                     $e =~ s/^\tmov ar\.lc = r\d+\n//m;
1137                     $e =~ s/^\tmov pr = r\d+, -1\n//m;
1138                     $e =~ s/^\tmov b0 = r\d+\n//m;
1139                     $e =~ s/^\t\.restore sp\n\tadds r12 = \d+, r12\n//m;
1140                     #$e =~ s/^\tbr\.ret\.sptk\.many b0\n//; # already removed
1141                     $e =~ s/^\t\.(mii|mmi|mfi|mib)\n//gm; # bundling is no longer sensible
1142                     $e =~ s/^\t;;\n//gm; # discard stops - stop at end of body is sufficient
1143                     $e =~ s/^\t\/\/.*\n//gm; # gcc inserts timings in // comments
1144                 } elsif ($TargetPlatform =~ /^m68k-/m) {
1145                     $e =~ s/^\tunlk a6\n//m;
1146                     $e =~ s/^\trts\n//m;
1147                 } elsif ($TargetPlatform =~ /^mips-/m) {
1148                     $e =~ s/^\tlw\t\$31,\d+\(\$sp\)\n//m;
1149                     $e =~ s/^\tlw\t\$fp,\d+\(\$sp\)\n//m;
1150                     $e =~ s/^\taddu\t\$sp,\$sp,\d+\n//m;
1151                     $e =~ s/^\tj\t\$31\n//m;
1152                 } elsif ($TargetPlatform =~ /^powerpc-apple-darwin.*/m) {
1153                     $e =~ s/^\taddi r1,r1,\d+\n//m;
1154                     $e =~ s/^\tlwz r\d+,\d+\(r1\)\n//m; 
1155                     $e =~ s/^\tlmw r\d+,-\d+\(r1\)\n//m;
1156                     $e =~ s/^\tmtlr r0\n//m;
1157                     $e =~ s/^\tblr\n//m;
1158                     $e =~ s/^\tb restFP ;.*\n//m;
1159                 } elsif ($TargetPlatform =~ /^powerpc64-.*-linux/m) {
1160                     $e =~ s/^\tmr 3,0\n//m;
1161                     $e =~ s/^\taddi 1,1,\d+\n//m;
1162                     $e =~ s/^\tld 0,16\(1\)\n//m;
1163                     $e =~ s/^\tmtlr 0\n//m;
1164
1165                     # callee-save registers
1166                     $e =~ s/^\tld \d+,-?\d+\(1\)\n//gm;
1167                     $e =~ s/^\tlfd \d+,-?\d+\(1\)\n//gm;
1168
1169                     # get rid of the debug junk along with the blr
1170                     $e =~ s/^\tblr\n\t.long .*\n\t.byte .*\n//m;
1171
1172                     # incase we missed it with the last one get the blr alone
1173                     $e =~ s/^\tblr\n//m;
1174                 } else {
1175                     print STDERR "$Pgm: unknown epilogue mangling? $TargetPlatform\n";
1176                 }
1177
1178                 print STDERR "WARNING: Epilogue junk?: $e\n" if $e =~ /^\t\s*[^\.\s\n]/m;
1179
1180                 # glue together what's left
1181                 $c .= $e . $etail;
1182             }
1183             $c =~ s/\n\t\n/\n/m; # junk blank line
1184         }
1185         else {
1186             if ($TargetPlatform =~ /^ia64-/m) {
1187                 # On IA64, remove an .endp directive even if no epilogue was found.
1188                 # Code optimizations may have removed the "--- END ---" token.
1189                 $c =~ s/^\t\.endp [a-zA-Z0-9_.]+#\n//m;
1190             }
1191         }
1192
1193         # On SPARCs, we don't do --- BEGIN/END ---, we just
1194         # toss the register-windowing save/restore/ret* instructions
1195         # directly unless they've been generated by function definitions in header
1196         # files on Solaris:
1197         if ( $TargetPlatform =~ /^sparc-/m ) {
1198             if ( ! ( $TargetPlatform =~ /solaris2$/m && $chkcat[$i] eq 'unknown' )) {
1199                 $c =~ s/^\t(save.*|restore.*|ret|retl)\n//gm;
1200             }
1201             # throw away PROLOGUE comments
1202             $c =~ s/^\t!#PROLOGUE# 0\n\t!#PROLOGUE# 1\n//m;
1203         }
1204
1205         # On Alphas, the prologue mangling is done a little later (below)
1206
1207         # toss all calls to __DISCARD__
1208         $c =~ s/^\t(call|jbsr|jal)\s+${T_US}__DISCARD__\n//gom;
1209         $c =~ s/^\tjsr\s+\$26\s*,\s*${T_US}__DISCARD__\n//gom if $TargetPlatform =~ /^alpha-/m;
1210         $c =~ s/^\tbl\s+L___DISCARD__\$stub\n//gom if $TargetPlatform =~ /^powerpc-apple-darwin.*/m;
1211         $c =~ s/^\tbl\s+__DISCARD__(\@plt)?\n//gom if $TargetPlatform =~ /^powerpc-.*-linux/m;
1212         $c =~ s/^\tbl\s+\.__DISCARD__\n\s+nop\n//gom if $TargetPlatform =~ /^powerpc64-.*-linux/m;
1213         $c =~ s/^\tcall\s+L___DISCARD__\$stub\n//gom if $TargetPlatform =~ /i386-apple-darwin.*/m;
1214
1215         # IA64: fix register allocation; mangle tailcalls into jumps
1216         if ($TargetPlatform =~ /^ia64-/m) {
1217             ia64_rename_registers($ia64_locnum, $ia64_outnum) if (defined($ia64_locnum));
1218             ia64_mangle_tailcalls();
1219         }
1220
1221         # MIPS: that may leave some gratuitous asm macros around
1222         # (no harm done; but we get rid of them to be tidier)
1223         $c =~ s/^\t\.set\tnoreorder\n\t\.set\tnomacro\n\taddu\t(\S+)\n\t\.set\tmacro\n\t\.set\treorder\n/\taddu\t$1\n/m
1224             if $TargetPlatform =~ /^mips-/m;
1225
1226         # toss stack adjustment after DoSparks
1227         $c =~ s/^(\tjbsr _DoSparks\n)\taddqw #8,sp/$1/gm
1228                 if $TargetPlatform =~ /^m68k-/m; # this looks old...
1229
1230         if ( $TargetPlatform =~ /^alpha-/m &&
1231            ! $magic_rdata_seen &&
1232            $c =~ /^\s*\.rdata\n\t\.quad 0\n\t\.align \d\n/m ) {
1233             $c =~ s/^\s*\.rdata\n\t\.quad 0\n\t\.align (\d)\n/\.rdata\n\t\.align $1\n/m;
1234             $magic_rdata_seen = 1;
1235         }
1236
1237         # pick some end-things and move them to the next chunk
1238
1239         # pin a funny end-thing on (for easier matching):
1240         $c .= 'FUNNY#END#THING';
1241
1242         while ( $c =~ /${T_MOVE_DIRVS}FUNNY#END#THING/om ) {
1243
1244             $to_move = $1;
1245
1246             # on x86 we try not to copy any directives into a literal
1247             # chunk, rather we keep looking for the next real chunk.  This
1248             # is because we get things like
1249             #
1250             #    .globl blah_closure
1251             #    .LC32
1252             #           .string "..."
1253             #    blah_closure:
1254             #           ...
1255             #
1256             if ( $TargetPlatform =~ /^(i386|sparc|powerpc)/m && $to_move =~ /${T_COPY_DIRVS}/m ) {
1257                 $j = $i + 1;
1258                 while ( $j < $numchks  && $chk[$j] =~ /$T_CONST_LBL/m) {
1259                         $j++;
1260                 }
1261                 if ( $j < $numchks ) {
1262                         $chk[$j] = $to_move . $chk[$j];
1263                 }
1264             }
1265
1266             elsif (   (    $i < ($numchks - 1)
1267                        && ( $to_move =~ /${T_COPY_DIRVS}/m
1268                            || (   $TargetPlatform =~ /^hppa/m
1269                                && $to_move =~ /align/m
1270                                && $chkcat[$i+1] eq 'literal')
1271                           )
1272                       )
1273                    || ($to_move =~ /^[ \t]*\.section[ \t]+\.note\.GNU-stack,/m)
1274                   ) {
1275                 $chk[$i + 1] = $to_move . $chk[$i + 1];
1276                 # otherwise they're tossed
1277             }
1278
1279             $c =~ s/${T_MOVE_DIRVS}FUNNY#END#THING/FUNNY#END#THING/om;
1280         }
1281
1282         if ( $TargetPlatform =~ /^alpha-/m && $c =~ /^\t\.ent\s+(\S+)/m ) {
1283             $ent = $1;
1284             # toss all prologue stuff, except for loading gp, and the ..ng address
1285             unless ($c =~ /\.ent.*\n\$.*\.\.ng:/m) {
1286                 if (($p, $r) = split(/^\t\.prologue/m, $c)) {
1287                     # use vars '$junk'; # Unused?
1288                     if (($keep, $junk) = split(/\.\.ng:/m, $p)) {
1289                         $keep =~ s/^\t\.frame.*\n/\t.frame \$30,0,\$26,0\n/m;
1290                         $keep =~ s/^\t\.(mask|fmask).*\n//gm;
1291                         $c = $keep . "..ng:\n";
1292                     } else {
1293                         print STDERR "malformed code block ($ent)?\n"
1294                     }
1295                 }
1296                 $c .= "\t.prologue" . $r;
1297             }
1298         }
1299   
1300         $c =~ s/FUNNY#END#THING//m;
1301
1302 #       print STDERR "\nCHK $i (AFTER) (",$chkcat[$i],"):\n", $c;
1303
1304         $chk[$i] = $c; # update w/ convenience copy
1305     }
1306
1307     # open CHUNKS, ">/tmp/chunks2" or die "Cannot open /tmp/chunks2: $!\n";
1308     # for (my $i = 0; $i < @chk; ++$i) { print CHUNKS "======= $i =======\n", $chk[$i] }
1309     # close CHUNKS;
1310
1311     if ( $TargetPlatform =~ /^alpha-/m ) {
1312         # print out the header stuff first
1313         $chk[0] =~ s/^(\t\.file.*)"(ghc\d+\.c)"/$1"$ifile_root.hc"/m;
1314         print OUTASM $chk[0];
1315
1316     } elsif ( $TargetPlatform =~ /^hppa/m ) {
1317         print OUTASM $chk[0];
1318
1319     } elsif ( $TargetPlatform =~ /^mips-/m ) {
1320         $chk[0] = "\t\.file\t1 \"$ifile_root.hc\"\n" . $chk[0];
1321
1322         # get rid of horrible "<dollar>Revision: .*$" strings
1323         local(@lines0) = split(/\n/m, $chk[0]);
1324         local($z) = 0;
1325         while ( $z <= $#lines0 ) {
1326             if ( $lines0[$z] =~ /^\t\.byte\t0x24,0x52,0x65,0x76,0x69,0x73,0x69,0x6f$/m ) {
1327                 undef($lines0[$z]);
1328                 $z++;
1329                 while ( $z <= $#lines0 ) {
1330                     undef($lines0[$z]);
1331                     last if $lines0[$z] =~ /[,\t]0x0$/m;
1332                     $z++;
1333                 }
1334             }
1335             $z++;
1336         }
1337         $chk[0] = join("\n", @lines0);
1338         $chk[0] =~ s/\n\n+/\n/m;
1339         print OUTASM $chk[0];
1340     }
1341
1342     # print out all the literal strings next
1343     for ($i = 0; $i < $numchks; $i++) {
1344         if ( $chkcat[$i] eq 'literal' ) {
1345
1346             # HACK: try to detect 16-byte constants and align them
1347             # on a 16-byte boundary.  x86_64 sometimes needs 128-bit
1348             # aligned constants, and so does Darwin/x86.
1349             if ( $TargetPlatform =~ /^x86_64/m
1350                 || $TargetPlatform =~ /^i386-apple-darwin/m ) { 
1351                 $z = $chk[$i];
1352                 if ($z =~ /(\.long.*\n.*\.long.*\n.*\.long.*\n.*\.long|\.quad.*\n.*\.quad)/m) {
1353                     print OUTASM $T_HDR_literal16;
1354                 } else {
1355                     print OUTASM $T_HDR_literal;
1356                 }
1357             } else {
1358                 print OUTASM $T_HDR_literal;
1359             }
1360
1361             print OUTASM $chk[$i];
1362             print OUTASM "; end literal\n" if $TargetPlatform =~ /^hppa/m; # for the splitter
1363
1364             $chkcat[$i] = 'DONE ALREADY';
1365         }
1366     }
1367
1368     # on the HPPA, print out all the bss next
1369     if ( $TargetPlatform =~ /^hppa/m ) {
1370         for ($i = 1; $i < $numchks; $i++) {
1371             if ( $chkcat[$i] eq 'bss' ) {
1372                 print OUTASM "\t.SPACE \$PRIVATE\$\n\t.SUBSPA \$BSS\$\n\t.align 4\n";
1373                 print OUTASM $chk[$i];
1374
1375                 $chkcat[$i] = 'DONE ALREADY';
1376             }
1377         }
1378     }
1379
1380     # $numchks + 1 as we have the extra one for .note.GNU-stack
1381     for ($i = $FIRST_MANGLABLE; $i < $numchks + 1; $i++) {
1382 #       print STDERR "$i: cat $chkcat[$i], symb $chksymb[$i]\n";
1383
1384         next if $chkcat[$i] eq 'DONE ALREADY';
1385
1386         if ( $chkcat[$i] eq 'misc' || $chkcat[$i] eq 'unknown' ) {
1387             if ($chk[$i] ne '') {
1388                 print OUTASM $T_HDR_misc;
1389                 &print_doctored($chk[$i], 0);
1390             }
1391
1392         } elsif ( $chkcat[$i] eq 'verbatim' ) {
1393             print OUTASM $chk[$i];
1394
1395         } elsif ( $chkcat[$i] eq 'toss' ) {
1396             print STDERR "*** NB: TOSSING code for $chksymb[$i] !!! ***\n";
1397
1398         } elsif ( $chkcat[$i] eq 'data' ) {
1399             if ($chk[$i] ne '') {
1400                 print OUTASM $T_HDR_data;
1401                 print OUTASM $chk[$i];
1402             }
1403
1404         } elsif ( $chkcat[$i] eq 'splitmarker' ) {
1405             # we can just re-constitute this one...
1406             # NB: we emit _three_ underscores no matter what,
1407             # so ghc-split doesn't have to care.
1408             print OUTASM "___stg_split_marker",$chksymb[$i],"${T_POST_LBL}\n";
1409
1410         } elsif ( $chkcat[$i] eq 'closure'
1411                || $chkcat[$i] eq 'srt'
1412                || $chkcat[$i] eq 'infotbl'
1413                || $chkcat[$i] eq 'entry') { # do them in that order
1414             $symb = $chksymb[$i];
1415
1416             # CLOSURE
1417             if ( defined($closurechk{$symb}) ) {
1418                 print OUTASM $T_HDR_closure;
1419                 print OUTASM $chk[$closurechk{$symb}];
1420                 $chkcat[$closurechk{$symb}] = 'DONE ALREADY';
1421             }
1422
1423             # SRT
1424             if ( defined($srtchk{$symb}) ) {
1425                 print OUTASM $T_HDR_relrodata;
1426                 print OUTASM $chk[$srtchk{$symb}];
1427                 $chkcat[$srtchk{$symb}] = 'DONE ALREADY';
1428             }
1429
1430             # INFO TABLE
1431             if ( defined($infochk{$symb}) ) {
1432
1433                 print OUTASM $T_HDR_info;
1434                 print OUTASM &rev_tbl($symb, $chk[$infochk{$symb}], 1);
1435                 
1436                 # entry code will be put here!
1437
1438                 $chkcat[$infochk{$symb}] = 'DONE ALREADY';
1439             }
1440
1441             # ENTRY POINT
1442             if ( defined($entrychk{$symb}) ) {
1443
1444                 $c = $chk[$entrychk{$symb}];
1445
1446                 # If this is an entry point with an info table,
1447                 # eliminate the entry symbol and all directives involving it.
1448                 if (defined($infochk{$symb}) && $TargetPlatform !~ /^ia64-/m
1449                                 && $TABLES_NEXT_TO_CODE ~~ "YES") {
1450                         @o = ();
1451                         foreach $l (split(/\n/m,$c)) {
1452                             next if $l =~ /^.*$symb_(entry|ret)${T_POST_LBL}/m;
1453
1454                             # If we have .type/.size direrctives involving foo_entry,
1455                             # then make them refer to foo_info instead.  The information
1456                             # in these directives is used by the cachegrind annotator,
1457                             # so it is worthwhile keeping.
1458                             if ($l =~ /^\s*\.(type|size).*$symb_(entry|ret)/m) {
1459                                 $l =~ s/$symb(_entry|_ret)/${symb}_info/gm;
1460                                 push(@o,$l);
1461                                 next;
1462                             }
1463                             next if $l =~ /^\s*\..*$symb.*\n?/m;
1464                             push(@o,$l);
1465                         }
1466                         $c = join("\n",@o) . "\n";
1467                 }
1468
1469                 print OUTASM $T_HDR_entry;
1470
1471                 &print_doctored($c, 1); # NB: the 1!!!
1472
1473                 $chkcat[$entrychk{$symb}] = 'DONE ALREADY';
1474             }
1475             
1476         } elsif ( $chkcat[$i] eq 'vector' ) {
1477             $symb = $chksymb[$i];
1478
1479             # VECTOR TABLE
1480             if ( defined($vectorchk{$symb}) ) {
1481                 print OUTASM $T_HDR_vector;
1482                 print OUTASM &rev_tbl($symb, $chk[$vectorchk{$symb}], 0);
1483
1484                 # direct return code will be put here!
1485                 $chkcat[$vectorchk{$symb}] = 'DONE ALREADY';
1486
1487             } elsif ( $TargetPlatform =~ /^alpha-/m ) {
1488                 # Alphas: the commented nop is for the splitter, to ensure
1489                 # that no module ends with a label as the very last
1490                 # thing.  (The linker will adjust the label to point
1491                 # to the first code word of the next module linked in,
1492                 # even if alignment constraints cause the label to move!)
1493
1494                 print OUTASM "\t# nop\n";
1495             }
1496             
1497         } elsif ( $chkcat[$i] eq 'rodata' ) {
1498                 print OUTASM $T_HDR_rodata;
1499                 print OUTASM $chk[$i];
1500                 $chkcat[$i] = 'DONE ALREADY';
1501         } elsif ( $chkcat[$i] eq 'relrodata' ) {
1502                 print OUTASM $T_HDR_relrodata;
1503                 print OUTASM $chk[$i];
1504                 $chkcat[$i] = 'DONE ALREADY';
1505         } elsif ( $chkcat[$i] eq 'toc' ) {
1506             # silly optimisation to print tocs, since they come in groups...
1507             print OUTASM $T_HDR_toc;
1508             local($j)   = $i;
1509             while ($chkcat[$j] eq 'toc')
1510               { if (   $chk[$j] !~ /\.tc UpdatePAP\[TC\]/m # not needed: always turned into a jump.
1511                    ) 
1512                 {
1513                   print OUTASM $chk[$j];
1514                 }
1515                 $chkcat[$j] = 'DONE ALREADY';
1516                 $j++;
1517             }
1518             
1519         } elsif ( $TargetPlatform =~ /^.*-apple-darwin.*/m && $chkcat[$i] eq 'dyld' ) {
1520             # apple-darwin: dynamic linker stubs
1521             if($chk[$i] !~ /\.indirect_symbol ___DISCARD__/m)
1522             {   # print them out unchanged, but remove the stubs for __DISCARD__
1523                 print OUTASM $chk[$i];
1524             }
1525         } elsif ( $TargetPlatform =~ /^i386-apple-darwin.*/m && $chkcat[$i] eq 'get_pc_thunk' ) {
1526             # i386-apple-darwin: __i686.get_pc_thunk.[abcd]x
1527             print OUTASM ".section __TEXT,__textcoal_nt,coalesced,no_toc\n";
1528             print OUTASM $chk[$i];
1529         } else {
1530             &tidy_up_and_die(1,"$Pgm: unknown chkcat (ghc-asm: $TargetPlatform)\n$chkcat[$i]\n$chk[$i]\n");
1531         }
1532     }
1533
1534     print OUTASM $EXTERN_DECLS if $TargetPlatform =~ /^mips-/m;
1535
1536     # finished
1537     close(OUTASM) || &tidy_up_and_die(1,"Failed writing to $out_asmf\n");
1538     close(INASM)  || &tidy_up_and_die(1,"Failed reading from $in_asmf\n");
1539 }
1540 \end{code}
1541
1542 On IA64, tail calls are converted to branches at this point.  The mangler
1543 searches for function calls immediately followed by a '--- TAILCALL ---'
1544 token.  Since the compiler can put various combinations of labels, bundling
1545 directives, nop instructions, stops, and a move of the return value
1546 between the branch and the tail call, proper matching of the tail call
1547 gets a little hairy.  This subroutine does the mangling.
1548
1549 Here is an example of a tail call before mangling:
1550
1551 \begin{verbatim}
1552         br.call.sptk.many b0 = b6
1553 .L211
1554         ;;
1555         .mmi
1556         mov r1 = r32
1557         ;;
1558         nop.m 0
1559         nop.i 0
1560         ;;
1561         --- TAILCALL --
1562         ;;
1563 .L123
1564 \end{verbatim}
1565
1566 \begin{code}
1567 sub ia64_mangle_tailcalls {
1568     # Function input and output are in $c
1569
1570     # Construct the tailcall-mangling expression the first time this function
1571     # is called.
1572     if (!defined($IA64_MATCH_TAILCALL)) {
1573         # One-line pattern matching constructs.  None of these
1574         # should bind references; all parenthesized terms
1575         # should be (?:) terms.
1576         my $stop       = q/(?:\t;;\n)/;
1577         my $bundle     = q/(?:\t\.(?:mii|mib|mmi|mmb|mfi|mfb|mbb|bbb)\n)/;
1578         my $nop        = q/(?:\tnop(?:\.[mifb])?\s+\d+\n)/;
1579         my $movgp      = q/(?:\tmov r1 = r\d+\n)/;
1580         my $postbr     = q/(?:\tbr \.L\d+\n)/;
1581
1582         my $noeffect   = "(?:$stop$bundle?|$nop)*";
1583         my $postbundle = "(?:$bundle?$nop?$nop?$postbr)?";
1584
1585         # Important parts of the pattern match.  The branch target
1586         # and subsequent jump label are bound to $1 and $2
1587         # respectively.  Sometimes there is no label.
1588         my $callbr    = q/^\tbr\.call\.sptk\.many b0 = (.*)\n/;
1589         my $label     = q/(?:^\.L([0-9]*):\n)/;
1590         my $tailcall  = q/\t--- TAILCALL ---\n/;
1591
1592         $IA64_MATCH_TAILCALL =
1593           $callbr . $label . '?' . $noeffect . $movgp . '?' . $noeffect .
1594           $tailcall . $stop . '?' . '(?:' . $postbundle . ')?';
1595     }
1596
1597     # Find and mangle tailcalls
1598     while ($c =~ s/$IA64_MATCH_TAILCALL/\tbr\.few $1\n/om) {
1599         # Eek, the gcc optimiser is getting smarter... if we see a jump to the
1600         # --- TAILCALL --- marker then we reapply the substitution at the source sites
1601         $c =~ s/^\tbr \.L$2\n/\t--- TAILCALL ---\n/gm if ($2);
1602     }
1603
1604     # Verify that all instances of TAILCALL were processed
1605     if ($c =~ /^\t--- TAILCALL ---\n/m) {
1606         die "Unmangled TAILCALL tokens remain after mangling"
1607     }
1608 }
1609 \end{code}
1610
1611 The number of registers allocated on the IA64 register stack is set
1612 upon entry to the runtime with an `alloc' instruction at the entry
1613 point of \verb+StgRun()+.  Gcc uses its own `alloc' to allocate
1614 however many registers it likes in each function.  When we discard
1615 gcc's alloc, we have to reconcile its register assignment with what
1616 the STG uses.
1617
1618 There are three stack areas: fixed registers, input/local registers,
1619 and output registers.  We move the output registers to the output
1620 register space and leave the other registers where they are.
1621
1622 \begin{code}
1623 sub ia64_rename_registers() {
1624     # The text to be mangled is in $c
1625     # Find number of registers in each stack area
1626     my ($loc, $out) = @_;
1627     my $cout;
1628     my $first_out_reg;
1629     my $regnum;
1630     my $fragment;
1631
1632     # These are the register numbers used in the STG runtime
1633     my $STG_FIRST_OUT_REG = 32 + 34;
1634     my $STG_LAST_OUT_REG = $STG_FIRST_OUT_REG + 7;
1635
1636     $first_out_reg = 32 + $loc;
1637
1638     if ($first_out_reg > $STG_FIRST_OUT_REG) {
1639         die "Too many local registers allocated by gcc";
1640     }
1641
1642     # Split the string into fragments containing one register name each.
1643     # Rename the register in each fragment and concatenate.
1644     $cout = "";
1645     foreach $fragment (split(/(?=r\d+[^a-zA-Z0-9_.])/sm, $c)) {
1646         if ($fragment =~ /^r(\d+)((?:[^a-zA-Z0-9_.].*)?)$/sm) {
1647             $regnum = $1;
1648
1649             if ($regnum < $first_out_reg) {
1650                 # This is a local or fixed register
1651
1652                 # Local registers 32 and 33 (r64 and r65) are
1653                 # used to hold saved state; they shouldn't be touched
1654                 if ($regnum == 64 || $regnum == 65) {
1655                    die "Reserved register $regnum is in use";
1656                 }
1657             }
1658             else {
1659                 # This is an output register
1660                 $regnum = $regnum - $first_out_reg + $STG_FIRST_OUT_REG;
1661                 if ($regnum > $STG_LAST_OUT_REG) {
1662                     die "Register number ($regnum) is out of expected range";
1663                 }
1664             }
1665
1666             # Update this fragment
1667             $fragment = "r" . $regnum . $2;
1668         }
1669         $cout .= $fragment;
1670     }
1671
1672     $c = $cout;
1673 }
1674
1675 \end{code}
1676
1677 \begin{code}
1678 sub hppa_mash_prologue { # OK, epilogue, too
1679     local($_) = @_;
1680
1681     # toss all prologue stuff
1682     s/^\s+\.ENTRY[^\0]*--- BEGIN ---/\t.ENTRY/m;
1683
1684     # Lie about our .CALLINFO
1685     s/^\s+\.CALLINFO.*$/\t.CALLINFO NO_CALLS,NO_UNWIND/m;
1686
1687     # Get rid of P'
1688
1689     s/LP'/L'/gm;
1690     s/RP'/R'/gm;
1691
1692     # toss all epilogue stuff
1693     s/^\s+--- END ---[^\0]*\.EXIT/\t.EXIT/m;
1694
1695     # Sorry; we moved the _info stuff to the code segment.
1696     s/_info,DATA/_info,CODE/gm;
1697
1698     return($_);
1699 }
1700 \end{code}
1701
1702 \begin{code}
1703 sub print_doctored {
1704     local($_, $need_fallthru_patch) = @_;
1705
1706     if ( $TargetPlatform =~ /^x86_64-/m ) {
1707             # Catch things like
1708             #   
1709             #    movq -4(%ebp), %rax
1710             #    jmp  *%rax
1711             # 
1712             # and optimise:
1713             #
1714             s/^\tmovq\s+(-?\d*\(\%r(bx|bp|13)\)),\s*(\%r(ax|cx|dx|10|11))\n\tjmp\s+\*\3/\tjmp\t\*$1/gm;
1715             s/^\tmovl\s+\$${T_US}(.*),\s*(\%e(ax|cx|si|di))\n\tjmp\s+\*\%r\3/\tjmp\t$T_US$1/gm;
1716     }
1717
1718     if ( $TargetPlatform !~ /^i386-/m 
1719       || ! /^\t[a-z]/m  # no instructions in here, apparently
1720       || /^${T_US}__stginit_[A-Za-z0-9_]+${T_POST_LBL}/m) {
1721         print OUTASM $_;
1722         return;
1723     }
1724
1725     # OK, must do some x86 **HACKING**
1726
1727     local($entry_patch) = '';
1728     local($exit_patch)  = '';
1729
1730     # gotta watch out for weird instructions that
1731     # invisibly smash various regs:
1732     #   rep*    %ecx used for counting
1733     #   scas*   %edi used for destination index
1734     #   cmps*   %e[sd]i used for indices
1735     #   loop*   %ecx used for counting
1736     #
1737     # SIGH.
1738
1739     # We cater for:
1740     #  * use of STG reg [ nn(%ebx) ] where no machine reg avail
1741     #
1742     #  * GCC used an "STG reg" for its own purposes
1743     #
1744     #  * some secret uses of machine reg, requiring STG reg
1745     #    to be saved/restored
1746
1747     # The most dangerous "GCC uses" of an "STG reg" are when
1748     # the reg holds the target of a jmp -- it's tricky to
1749     # insert the patch-up code before we get to the target!
1750     # So here we change the jmps:
1751
1752     # --------------------------------------------------------
1753     # it can happen that we have jumps of the form...
1754     #   jmp *<something involving %esp>
1755     # or
1756     #   jmp <something involving another naughty register...>
1757     #
1758     # a reasonably-common case is:
1759     #
1760     #   movl $_blah,<bad-reg>
1761     #   jmp  *<bad-reg>
1762     #
1763     s/^\tmovl\s+\$${T_US}(.*),\s*(\%e[acd]x)\n\tjmp\s+\*\2/\tjmp $T_US$1/gm;
1764
1765     # Catch things like
1766     #
1767     #    movl -4(%ebx), %eax
1768     #    jmp  *%eax
1769     # 
1770     # and optimise:
1771     #
1772     s/^\tmovl\s+(-?\d*\(\%e(bx|si)\)),\s*(\%e[acd]x)\n\tjmp\s+\*\3/\tjmp\t\*$1/gm;
1773
1774     if ($StolenX86Regs <= 2 ) { # YURGH! spurious uses of esi?
1775         s/^\tmovl\s+(.*),\s*\%esi\n\tjmp\s+\*%esi\n/\tmovl $1,\%eax\n\tjmp \*\%eax\n/gm;
1776         s/^\tjmp\s+\*(.*\(.*\%esi.*\))\n/\tmovl $1,\%eax\n\tjmp \*\%eax\n/gm;
1777         s/^\tjmp\s+\*\%esi\n/\tmovl \%esi,\%eax\n\tjmp \*\%eax\n/gm;
1778         die "$Pgm: (mangler) still have jump involving \%esi!\n$_"
1779             if /(jmp|call)\s+.*\%esi/m;
1780     }
1781     if ($StolenX86Regs <= 3 ) { # spurious uses of edi?
1782         s/^\tmovl\s+(.*),\s*\%edi\n\tjmp\s+\*%edi\n/\tmovl $1,\%eax\n\tjmp \*\%eax\n/gm;
1783         s/^\tjmp\s+\*(.*\(.*\%edi.*\))\n/\tmovl $1,\%eax\n\tjmp \*\%eax\n/gm;
1784         s/^\tjmp\s+\*\%edi\n/\tmovl \%edi,\%eax\n\tjmp \*\%eax\n/gm;
1785         die "$Pgm: (mangler) still have jump involving \%edi!\n$_"
1786             if /(jmp|call)\s+.*\%edi/m;
1787     }
1788
1789     # OK, now we can decide what our patch-up code is going to
1790     # be:
1791
1792     # Offsets into register table - you'd better update these magic
1793     # numbers should you change its contents!
1794     # local($OFFSET_R1)=0;  No offset for R1 in new RTS.
1795     local($OFFSET_Hp)=88;
1796
1797         # Note funky ".=" stuff; we're *adding* to these _patch guys
1798     if ( $StolenX86Regs <= 2
1799          && ( /[^0-9]\(\%ebx\)/m || /\%esi/m || /^\tcmps/m ) ) { # R1 (esi)
1800         $entry_patch .= "\tmovl \%esi,(\%ebx)\n";
1801         $exit_patch  .= "\tmovl (\%ebx),\%esi\n";
1802
1803         # nothing for call_{entry,exit} because %esi is callee-save
1804     }
1805     if ( $StolenX86Regs <= 3
1806          && ( /${OFFSET_Hp}\(\%ebx\)/m || /\%edi/m || /^\t(scas|cmps)/m ) ) { # Hp (edi)
1807         $entry_patch .= "\tmovl \%edi,${OFFSET_Hp}(\%ebx)\n";
1808         $exit_patch  .= "\tmovl ${OFFSET_Hp}(\%ebx),\%edi\n";
1809
1810         # nothing for call_{entry,exit} because %edi is callee-save
1811     }
1812
1813     # --------------------------------------------------------
1814     # next, here we go with non-%esp patching!
1815     #
1816     s/^(\t[a-z])/$entry_patch$1/m; # before first instruction
1817
1818 # Before calling GC we must set up the exit condition before the call
1819 # and entry condition when we come back
1820
1821     # fix _all_ non-local jumps:
1822
1823     if ( $TargetPlatform =~ /^.*-apple-darwin.*/m ) {
1824         # On Darwin, we've got local-looking jumps that are
1825         # actually global (i.e. jumps to Lfoo$stub or via
1826         # Lfoo$non_lazy_ptr), so we fix those first.
1827         # In fact, we just fix everything that contains a dollar
1828         # because false positives don't hurt here.
1829
1830         s/^(\tjmp\s+\*?L.*\$.*\n)/$exit_patch$1/gm;
1831     }
1832
1833     s/^\tjmp\s+\*${T_X86_PRE_LLBL_PAT}/\tJMP___SL/gom;
1834     s/^\tjmp\s+${T_X86_PRE_LLBL_PAT}/\tJMP___L/gom;
1835
1836     s/^(\tjmp\s+.*\n)/$exit_patch$1/gm; # here's the fix...
1837
1838     s/^\tJMP___SL/\tjmp \*${T_X86_PRE_LLBL}/gom;
1839     s/^\tJMP___L/\tjmp ${T_X86_PRE_LLBL}/gom;
1840
1841     if ($StolenX86Regs == 2 ) {
1842         die "ARGH! Jump uses \%esi or \%edi with -monly-2-regs:\n$_" 
1843             if /^\t(jmp|call)\s+.*\%e(si|di)/m;
1844     } elsif ($StolenX86Regs == 3 ) {
1845         die "ARGH! Jump uses \%edi with -monly-3-regs:\n$_" 
1846             if /^\t(jmp|call)\s+.*\%edi/m;
1847     }
1848
1849     # --------------------------------------------------------
1850     # that's it -- print it
1851     #
1852     #die "Funny jumps?\n$_" if /${T_X86_BADJMP}/o; # paranoia
1853
1854     print OUTASM $_;
1855
1856     if ( $need_fallthru_patch ) { # exit patch for end of slow entry code
1857         print OUTASM $exit_patch;
1858         # ToDo: make it not print if there is a "jmp" at the end
1859     }
1860 }
1861 \end{code}
1862
1863 \begin{code}
1864 sub init_FUNNY_THINGS {
1865     # use vars '%KNOWN_FUNNY_THING'; # Unused?
1866     %KNOWN_FUNNY_THING = (
1867         # example
1868         # "${T_US}stg_.*{T_POST_LBL}", 1,  
1869     );
1870 }
1871 \end{code}
1872
1873 The following table reversal is used for both info tables and return
1874 vectors.  In both cases, we remove the first entry from the table,
1875 reverse the table, put the label at the end, and paste some code
1876 (that which is normally referred to by the first entry in the table)
1877 right after the table itself.  (The code pasting is done elsewhere.)
1878
1879 \begin{code}
1880 sub rev_tbl {
1881     # use vars '$discard1';   # Unused?
1882     local($symb, $tbl, $discard1) = @_;
1883
1884     return ($tbl) if ($TargetPlatform =~ /^ia64-/m
1885                       || $TABLES_NEXT_TO_CODE ~~ "NO");
1886
1887     local($before) = '';
1888     local($label) = '';
1889     local(@imports) = (); # hppa only
1890     local(@words) = ();
1891     local($after) = '';
1892     local(@lines) = split(/\n/m, $tbl);
1893     local($i, $j);
1894
1895     # Deal with the header...
1896     for ($i = 0; $i <= $#lines && $lines[$i] !~ /^\t?${T_DOT_WORD}\s+/om; $i++) {
1897         $label .= $lines[$i] . "\n",
1898             next if $lines[$i] =~ /^[A-Za-z0-9_]+_info${T_POST_LBL}$/om
1899                  || $lines[$i] =~ /${T_DOT_GLOBAL}/om
1900                  || $lines[$i] =~ /^${T_US}\S+_vtbl${T_POST_LBL}$/om;
1901
1902         $before .= $lines[$i] . "\n"; # otherwise...
1903     }
1904
1905     $infoname = $label;
1906     $infoname =~ s/(.|\n)*^([A-Za-z0-9_]+_info)${T_POST_LBL}$(.|\n)*/$2/m;
1907     
1908     # Grab the table data...
1909     if ( $TargetPlatform !~ /^hppa/m ) {
1910         for ( ; $i <= $#lines && $lines[$i] =~ /^\t?${T_DOT_WORD}\s+/om; $i++) {
1911             $line = $lines[$i];
1912             # Convert addresses of SRTs, slow entrypoints and large bitmaps
1913             # to offsets (relative to the info label),
1914             # in order to support position independent code.
1915             $line =~ s/$infoname/0/m
1916             || $line =~ s/([A-Za-z0-9_]+_srtd)$/$1 - $infoname/m
1917             || $line =~ s/([A-Za-z0-9_]+_srt(\+\d+)?)$/$1 - $infoname/m
1918             || $line =~ s/([A-Za-z0-9_]+_str)$/$1 - $infoname/m
1919             || $line =~ s/([A-Za-z0-9_]+_slow)$/$1 - $infoname/m
1920             || $line =~ s/([A-Za-z0-9_]+_btm)$/$1 - $infoname/m
1921             || $line =~ s/([A-Za-z0-9_]+_alt)$/$1 - $infoname/m
1922             || $line =~ s/([A-Za-z0-9_]+_dflt)$/$1 - $infoname/m
1923             || $line =~ s/([A-Za-z0-9_]+_ret)$/$1 - $infoname/m;
1924             push(@words, $line);
1925         }
1926     } else { # hppa weirdness
1927         for ( ; $i <= $#lines && $lines[$i] =~ /^\s+(${T_DOT_WORD}|\.IMPORT)/m; $i++) {
1928             # FIXME: the RTS now expects offsets instead of addresses
1929             # for all labels in info tables.
1930             if ($lines[$i] =~ /^\s+\.IMPORT/m) {
1931                 push(@imports, $lines[$i]);
1932             } else {
1933                 # We don't use HP's ``function pointers''
1934                 # We just use labels in code space, like normal people
1935                 $lines[$i] =~ s/P%//m;
1936                 push(@words, $lines[$i]);
1937             }
1938         }
1939     }
1940
1941     # Now throw away any initial zero word from the table.  This is a hack
1942     # that lets us reduce the size of info tables when the SRT field is not
1943     # needed: see comments StgFunInfoTable in InfoTables.h.
1944     #
1945     # The .zero business is for Linux/ELF.
1946     # The .skip business is for Sparc/Solaris/ELF.
1947     # The .blockz business is for HPPA.
1948 #    if ($discard1) {
1949 #       if ($words[0] =~ /^\t?(${T_DOT_WORD}\s+0|\.zero\s+4|\.skip\s+4|\.blockz\s+4)/) {
1950 #               shift(@words);
1951 #       }
1952 #    }
1953
1954     for (; $i <= $#lines; $i++) {
1955         $after .= $lines[$i] . "\n";
1956     }
1957
1958     # Alphas: If we have anonymous text (not part of a procedure), the
1959     # linker may complain about missing exception information.  Bleh.
1960     # To suppress this, we place a .ent/.end pair around the code.
1961     # At the same time, we have to be careful and not enclose any leading
1962     # .file/.loc directives.
1963     if ( $TargetPlatform =~ /^alpha-/m && $label =~ /^([A-Za-z0-9_]+):$/m) {
1964         local ($ident) = $1;
1965         $before =~ s/^((\s*\.(file|loc)\s+[^\n]*\n)*)/$1\t.ent $ident\n/m;
1966         $after .= "\t.end $ident\n";
1967     }
1968
1969     # Alphas: The heroic Simon Marlow found a bug in the Digital UNIX
1970     # assembler (!) wherein .quad constants inside .text sections are
1971     # first narrowed to 32 bits then sign-extended back to 64 bits.
1972     # This obviously screws up our 64-bit bitmaps, so we work around
1973     # the bug by replacing .quad with .align 3 + .long + .long [ccshan]
1974     if ( $TargetPlatform =~ /^alpha-/m ) {
1975         foreach (@words) {
1976             if (/^\s*\.quad\s+([-+0-9].*\S)\s*$/m && length $1 >= 10) {
1977                 local ($number) = $1;
1978                 if ($number =~ /^([-+])?(0x?)?([0-9]+)$/m) {
1979                     local ($sign, $base, $digits) = ($1, $2, $3);
1980                     $base = (10, 8, 16)[length $base];
1981                     local ($hi, $lo) = (0, 0);
1982                     foreach $i (split(//, $digits)) {
1983                         $j = $lo * $base + $i;
1984                         $lo = $j % 4294967296;
1985                         $hi = $hi * $base + ($j - $lo) / 4294967296;
1986                     }
1987                     ($hi, $lo) = (4294967295 - $hi, 4294967296 - $lo)
1988                         if $sign eq "-";
1989                     $_ = "\t.align 3\n\t.long $lo\n\t.long $hi\n";
1990                     # printf STDERR "TURNING %s into 0x %08x %08x\n", $number, $hi, $lo;
1991                 } else {
1992                     print STDERR "Cannot handle \".quad $number\" in info table\n";
1993                     exit 1;
1994                 }
1995             }
1996         }
1997     }
1998
1999     if ( $TargetPlatform =~ /x86_64-apple-darwin/m ) {
2000         # Tack a label to the front of the info table, too.
2001         # For now, this just serves to work around a crash in Apple's new
2002         # 64-bit linker (it seems to assume that there is no data before the
2003         # first label in a section).
2004         
2005         # The plan for the future is to do this on all Darwin platforms, and
2006         # to add a reference to this label after the entry code, just as the
2007         # NCG does, so we can enable dead-code-stripping in the linker without
2008         # losing our info tables. (Hence the name _dsp, for dead-strip preventer)
2009         
2010         $before .= "\n${infoname}_dsp:\n";    
2011     }
2012
2013     $tbl = $before
2014          . (($TargetPlatform !~ /^hppa/m) ? '' : join("\n", @imports) . "\n")
2015          . join("\n", @words) . "\n"
2016          . $label . $after;
2017
2018 #   print STDERR "before=$before\n";
2019 #   print STDERR "label=$label\n";
2020 #   print STDERR "words=",(reverse @words),"\n";
2021 #   print STDERR "after=$after\n";
2022
2023     $tbl;
2024 }
2025 \end{code}
2026
2027 The HP is a major nuisance.  The threaded code mangler moved info
2028 tables from data space to code space, but unthreaded code in the RTS
2029 still has references to info tables in data space.  Since the HP
2030 linker is very precise about where symbols live, we need to patch the
2031 references in the unthreaded RTS as well.
2032
2033 \begin{code}
2034 sub mini_mangle_asm_hppa {
2035     local($in_asmf, $out_asmf) = @_;
2036
2037     open(INASM, "< $in_asmf")
2038         || &tidy_up_and_die(1,"$Pgm: failed to open `$in_asmf' (to read)\n");
2039     open(OUTASM,"> $out_asmf")
2040         || &tidy_up_and_die(1,"$Pgm: failed to open `$out_asmf' (to write)\n");
2041
2042     while (<INASM>) {
2043         s/_info,DATA/_info,CODE/m;   # Move _info references to code space
2044         s/P%_PR/_PR/m;
2045         print OUTASM;
2046     }
2047
2048     # finished:
2049     close(OUTASM) || &tidy_up_and_die(1,"Failed writing to $out_asmf\n");
2050     close(INASM)  || &tidy_up_and_die(1,"Failed reading from $in_asmf\n");
2051 }
2052
2053 \end{code}
2054
2055 \begin{code}
2056 sub tidy_up_and_die {
2057     local($return_val, $msg) = @_;
2058     print STDERR $msg;
2059     exit (($return_val == 0) ? 0 : 1);
2060 }
2061 \end{code}