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