x86_64-xlate.pl: minor size/performance improvement.
[openssl.git] / crypto / perlasm / x86_64-xlate.pl
1 #!/usr/bin/env perl
2
3 # Ascetic x86_64 AT&T to MASM/NASM assembler translator by <appro>.
4 #
5 # Why AT&T to MASM and not vice versa? Several reasons. Because AT&T
6 # format is way easier to parse. Because it's simpler to "gear" from
7 # Unix ABI to Windows one [see cross-reference "card" at the end of
8 # file]. Because Linux targets were available first...
9 #
10 # In addition the script also "distills" code suitable for GNU
11 # assembler, so that it can be compiled with more rigid assemblers,
12 # such as Solaris /usr/ccs/bin/as.
13 #
14 # This translator is not designed to convert *arbitrary* assembler
15 # code from AT&T format to MASM one. It's designed to convert just
16 # enough to provide for dual-ABI OpenSSL modules development...
17 # There *are* limitations and you might have to modify your assembler
18 # code or this script to achieve the desired result...
19 #
20 # Currently recognized limitations:
21 #
22 # - can't use multiple ops per line;
23 #
24 # Dual-ABI styling rules.
25 #
26 # 1. Adhere to Unix register and stack layout [see cross-reference
27 #    ABI "card" at the end for explanation].
28 # 2. Forget about "red zone," stick to more traditional blended
29 #    stack frame allocation. If volatile storage is actually required
30 #    that is. If not, just leave the stack as is.
31 # 3. Functions tagged with ".type name,@function" get crafted with
32 #    unified Win64 prologue and epilogue automatically. If you want
33 #    to take care of ABI differences yourself, tag functions as
34 #    ".type name,@abi-omnipotent" instead.
35 # 4. To optimize the Win64 prologue you can specify number of input
36 #    arguments as ".type name,@function,N." Keep in mind that if N is
37 #    larger than 6, then you *have to* write "abi-omnipotent" code,
38 #    because >6 cases can't be addressed with unified prologue.
39 # 5. Name local labels as .L*, do *not* use dynamic labels such as 1:
40 #    (sorry about latter).
41 # 6. Don't use [or hand-code with .byte] "rep ret." "ret" mnemonic is
42 #    required to identify the spots, where to inject Win64 epilogue!
43 #    But on the pros, it's then prefixed with rep automatically:-)
44 # 7. Stick to explicit ip-relative addressing. If you have to use
45 #    GOTPCREL addressing, stick to mov symbol@GOTPCREL(%rip),%r??.
46 #    Both are recognized and translated to proper Win64 addressing
47 #    modes. To support legacy code a synthetic directive, .picmeup,
48 #    is implemented. It puts address of the *next* instruction into
49 #    target register, e.g.:
50 #
51 #               .picmeup        %rax
52 #               lea             .Label-.(%rax),%rax
53 #
54 # 8. In order to provide for structured exception handling unified
55 #    Win64 prologue copies %rsp value to %rax. For further details
56 #    see SEH paragraph at the end.
57 # 9. .init segment is allowed to contain calls to functions only.
58 # a. If function accepts more than 4 arguments *and* >4th argument
59 #    is declared as non 64-bit value, do clear its upper part.
60 \f
61 my $flavour = shift;
62 my $output  = shift;
63 if ($flavour =~ /\./) { $output = $flavour; undef $flavour; }
64
65 open STDOUT,">$output" || die "can't open $output: $!"
66         if (defined($output));
67
68 my $gas=1;      $gas=0 if ($output =~ /\.asm$/);
69 my $elf=1;      $elf=0 if (!$gas);
70 my $win64=0;
71 my $prefix="";
72 my $decor=".L";
73
74 my $masmref=8 + 50727*2**-32;   # 8.00.50727 shipped with VS2005
75 my $masm=0;
76 my $PTR=" PTR";
77
78 my $nasmref=2.03;
79 my $nasm=0;
80
81 if    ($flavour eq "mingw64")   { $gas=1; $elf=0; $win64=1;
82                                   $prefix=`echo __USER_LABEL_PREFIX__ | $ENV{CC} -E -P -`;
83                                   chomp($prefix);
84                                 }
85 elsif ($flavour eq "macosx")    { $gas=1; $elf=0; $prefix="_"; $decor="L\$"; }
86 elsif ($flavour eq "masm")      { $gas=0; $elf=0; $masm=$masmref; $win64=1; $decor="\$L\$"; }
87 elsif ($flavour eq "nasm")      { $gas=0; $elf=0; $nasm=$nasmref; $win64=1; $decor="\$L\$"; $PTR=""; }
88 elsif (!$gas)
89 {   if ($ENV{ASM} =~ m/nasm/ && `nasm -v` =~ m/version ([0-9]+)\.([0-9]+)/i)
90     {   $nasm = $1 + $2*0.01; $PTR="";  }
91     elsif (`ml64 2>&1` =~ m/Version ([0-9]+)\.([0-9]+)(\.([0-9]+))?/)
92     {   $masm = $1 + $2*2**-16 + $4*2**-32;   }
93     die "no assembler found on %PATH" if (!($nasm || $masm));
94     $win64=1;
95     $elf=0;
96     $decor="\$L\$";
97 }
98
99 my $current_segment;
100 my $current_function;
101 my %globals;
102
103 { package opcode;       # pick up opcodes
104     sub re {
105         my      $self = shift;  # single instance in enough...
106         local   *line = shift;
107         undef   $ret;
108
109         if ($line =~ /^([a-z][a-z0-9]*)/i) {
110             $self->{op} = $1;
111             $ret = $self;
112             $line = substr($line,@+[0]); $line =~ s/^\s+//;
113
114             undef $self->{sz};
115             if ($self->{op} =~ /^(movz)x?([bw]).*/) {   # movz is pain...
116                 $self->{op} = $1;
117                 $self->{sz} = $2;
118             } elsif ($self->{op} =~ /call|jmp/) {
119                 $self->{sz} = "";
120             } elsif ($self->{op} =~ /^p/ && $' !~ /^(ush|op|insrw)/) { # SSEn
121                 $self->{sz} = "";
122             } elsif ($self->{op} =~ /^v/) { # VEX
123                 $self->{sz} = "";
124             } elsif ($self->{op} =~ /movq/ && $line =~ /%xmm/) {
125                 $self->{sz} = "";
126             } elsif ($self->{op} =~ /([a-z]{3,})([qlwb])$/) {
127                 $self->{op} = $1;
128                 $self->{sz} = $2;
129             }
130         }
131         $ret;
132     }
133     sub size {
134         my $self = shift;
135         my $sz   = shift;
136         $self->{sz} = $sz if (defined($sz) && !defined($self->{sz}));
137         $self->{sz};
138     }
139     sub out {
140         my $self = shift;
141         if ($gas) {
142             if ($self->{op} eq "movz") {        # movz is pain...
143                 sprintf "%s%s%s",$self->{op},$self->{sz},shift;
144             } elsif ($self->{op} =~ /^set/) { 
145                 "$self->{op}";
146             } elsif ($self->{op} eq "ret") {
147                 my $epilogue = "";
148                 if ($win64 && $current_function->{abi} eq "svr4") {
149                     $epilogue = "movq   8(%rsp),%rdi\n\t" .
150                                 "movq   16(%rsp),%rsi\n\t";
151                 }
152                 $epilogue . ".byte      0xf3,0xc3";
153             } elsif ($self->{op} eq "call" && !$elf && $current_segment eq ".init") {
154                 ".p2align\t3\n\t.quad";
155             } else {
156                 "$self->{op}$self->{sz}";
157             }
158         } else {
159             $self->{op} =~ s/^movz/movzx/;
160             if ($self->{op} eq "ret") {
161                 $self->{op} = "";
162                 if ($win64 && $current_function->{abi} eq "svr4") {
163                     $self->{op} = "mov  rdi,QWORD${PTR}[8+rsp]\t;WIN64 epilogue\n\t".
164                                   "mov  rsi,QWORD${PTR}[16+rsp]\n\t";
165                 }
166                 $self->{op} .= "DB\t0F3h,0C3h\t\t;repret";
167             } elsif ($self->{op} =~ /^(pop|push)f/) {
168                 $self->{op} .= $self->{sz};
169             } elsif ($self->{op} eq "call" && $current_segment eq ".CRT\$XCU") {
170                 $self->{op} = "\tDQ";
171             } 
172             $self->{op};
173         }
174     }
175     sub mnemonic {
176         my $self=shift;
177         my $op=shift;
178         $self->{op}=$op if (defined($op));
179         $self->{op};
180     }
181 }
182 { package const;        # pick up constants, which start with $
183     sub re {
184         my      $self = shift;  # single instance in enough...
185         local   *line = shift;
186         undef   $ret;
187
188         if ($line =~ /^\$([^,]+)/) {
189             $self->{value} = $1;
190             $ret = $self;
191             $line = substr($line,@+[0]); $line =~ s/^\s+//;
192         }
193         $ret;
194     }
195     sub out {
196         my $self = shift;
197
198         if ($gas) {
199             # Solaris /usr/ccs/bin/as can't handle multiplications
200             # in $self->{value}
201             $self->{value} =~ s/(?<![\w\$\.])(0x?[0-9a-f]+)/oct($1)/egi;
202             $self->{value} =~ s/([0-9]+\s*[\*\/\%]\s*[0-9]+)/eval($1)/eg;
203             sprintf "\$%s",$self->{value};
204         } else {
205             $self->{value} =~ s/(0b[0-1]+)/oct($1)/eig;
206             $self->{value} =~ s/0x([0-9a-f]+)/0$1h/ig if ($masm);
207             sprintf "%s",$self->{value};
208         }
209     }
210 }
211 { package ea;           # pick up effective addresses: expr(%reg,%reg,scale)
212     sub re {
213         my      $self = shift;  # single instance in enough...
214         local   *line = shift;
215         undef   $ret;
216
217         # optional * ---vvv--- appears in indirect jmp/call
218         if ($line =~ /^(\*?)([^\(,]*)\(([%\w,]+)\)/) {
219             $self->{asterisk} = $1;
220             $self->{label} = $2;
221             ($self->{base},$self->{index},$self->{scale})=split(/,/,$3);
222             $self->{scale} = 1 if (!defined($self->{scale}));
223             $ret = $self;
224             $line = substr($line,@+[0]); $line =~ s/^\s+//;
225
226             if ($win64 && $self->{label} =~ s/\@GOTPCREL//) {
227                 die if (opcode->mnemonic() ne "mov");
228                 opcode->mnemonic("lea");
229             }
230             $self->{base}  =~ s/^%//;
231             $self->{index} =~ s/^%// if (defined($self->{index}));
232         }
233         $ret;
234     }
235     sub size {}
236     sub out {
237         my $self = shift;
238         my $sz = shift;
239
240         $self->{label} =~ s/([_a-z][_a-z0-9]*)/$globals{$1} or $1/gei;
241         $self->{label} =~ s/\.L/$decor/g;
242
243         # Silently convert all EAs to 64-bit. This is required for
244         # elder GNU assembler and results in more compact code,
245         # *but* most importantly AES module depends on this feature!
246         $self->{index} =~ s/^[er](.?[0-9xpi])[d]?$/r\1/;
247         $self->{base}  =~ s/^[er](.?[0-9xpi])[d]?$/r\1/;
248
249         # Solaris /usr/ccs/bin/as can't handle multiplications
250         # in $self->{label}, new gas requires sign extension...
251         use integer;
252         $self->{label} =~ s/(?<![\w\$\.])(0x?[0-9a-f]+)/oct($1)/egi;
253         $self->{label} =~ s/([0-9]+\s*[\*\/\%]\s*[0-9]+)/eval($1)/eg;
254         $self->{label} =~ s/([0-9]+)/$1<<32>>32/eg;
255
256         if (!$self->{label} && $self->{index} && $self->{scale}==1 &&
257             $self->{base} =~ /(rbp|r13)/) {
258                 $self->{base} = $self->{index}; $self->{index} = $1;
259         }
260
261         if ($gas) {
262             $self->{label} =~ s/^___imp_/__imp__/   if ($flavour eq "mingw64");
263
264             if (defined($self->{index})) {
265                 sprintf "%s%s(%s,%%%s,%d)",$self->{asterisk},
266                                         $self->{label},
267                                         $self->{base}?"%$self->{base}":"",
268                                         $self->{index},$self->{scale};
269             } else {
270                 sprintf "%s%s(%%%s)",   $self->{asterisk},$self->{label},$self->{base};
271             }
272         } else {
273             %szmap = (  b=>"BYTE$PTR", w=>"WORD$PTR", l=>"DWORD$PTR",
274                         q=>"QWORD$PTR",o=>"OWORD$PTR",x=>"XMMWORD$PTR" );
275
276             $self->{label} =~ s/\./\$/g;
277             $self->{label} =~ s/(?<![\w\$\.])0x([0-9a-f]+)/0$1h/ig;
278             $self->{label} = "($self->{label})" if ($self->{label} =~ /[\*\+\-\/]/);
279             $sz="q" if ($self->{asterisk} || opcode->mnemonic() eq "movq");
280             $sz="l" if (opcode->mnemonic() eq "movd");
281
282             if (defined($self->{index})) {
283                 sprintf "%s[%s%s*%d%s]",$szmap{$sz},
284                                         $self->{label}?"$self->{label}+":"",
285                                         $self->{index},$self->{scale},
286                                         $self->{base}?"+$self->{base}":"";
287             } elsif ($self->{base} eq "rip") {
288                 sprintf "%s[%s]",$szmap{$sz},$self->{label};
289             } else {
290                 sprintf "%s[%s%s]",$szmap{$sz},
291                                         $self->{label}?"$self->{label}+":"",
292                                         $self->{base};
293             }
294         }
295     }
296 }
297 { package register;     # pick up registers, which start with %.
298     sub re {
299         my      $class = shift; # muliple instances...
300         my      $self = {};
301         local   *line = shift;
302         undef   $ret;
303
304         # optional * ---vvv--- appears in indirect jmp/call
305         if ($line =~ /^(\*?)%(\w+)/) {
306             bless $self,$class;
307             $self->{asterisk} = $1;
308             $self->{value} = $2;
309             $ret = $self;
310             $line = substr($line,@+[0]); $line =~ s/^\s+//;
311         }
312         $ret;
313     }
314     sub size {
315         my      $self = shift;
316         undef   $ret;
317
318         if    ($self->{value} =~ /^r[\d]+b$/i)  { $ret="b"; }
319         elsif ($self->{value} =~ /^r[\d]+w$/i)  { $ret="w"; }
320         elsif ($self->{value} =~ /^r[\d]+d$/i)  { $ret="l"; }
321         elsif ($self->{value} =~ /^r[\w]+$/i)   { $ret="q"; }
322         elsif ($self->{value} =~ /^[a-d][hl]$/i){ $ret="b"; }
323         elsif ($self->{value} =~ /^[\w]{2}l$/i) { $ret="b"; }
324         elsif ($self->{value} =~ /^[\w]{2}$/i)  { $ret="w"; }
325         elsif ($self->{value} =~ /^e[a-z]{2}$/i){ $ret="l"; }
326
327         $ret;
328     }
329     sub out {
330         my $self = shift;
331         if ($gas)       { sprintf "%s%%%s",$self->{asterisk},$self->{value}; }
332         else            { $self->{value}; }
333     }
334 }
335 { package label;        # pick up labels, which end with :
336     sub re {
337         my      $self = shift;  # single instance is enough...
338         local   *line = shift;
339         undef   $ret;
340
341         if ($line =~ /(^[\.\w]+)\:/) {
342             $self->{value} = $1;
343             $ret = $self;
344             $line = substr($line,@+[0]); $line =~ s/^\s+//;
345
346             $self->{value} =~ s/^\.L/$decor/;
347         }
348         $ret;
349     }
350     sub out {
351         my $self = shift;
352
353         if ($gas) {
354             my $func = ($globals{$self->{value}} or $self->{value}) . ":";
355             if ($win64  &&
356                         $current_function->{name} eq $self->{value} &&
357                         $current_function->{abi} eq "svr4") {
358                 $func .= "\n";
359                 $func .= "      movq    %rdi,8(%rsp)\n";
360                 $func .= "      movq    %rsi,16(%rsp)\n";
361                 $func .= "      movq    %rsp,%rax\n";
362                 $func .= "${decor}SEH_begin_$current_function->{name}:\n";
363                 my $narg = $current_function->{narg};
364                 $narg=6 if (!defined($narg));
365                 $func .= "      movq    %rcx,%rdi\n" if ($narg>0);
366                 $func .= "      movq    %rdx,%rsi\n" if ($narg>1);
367                 $func .= "      movq    %r8,%rdx\n"  if ($narg>2);
368                 $func .= "      movq    %r9,%rcx\n"  if ($narg>3);
369                 $func .= "      movq    40(%rsp),%r8\n" if ($narg>4);
370                 $func .= "      movq    48(%rsp),%r9\n" if ($narg>5);
371             }
372             $func;
373         } elsif ($self->{value} ne "$current_function->{name}") {
374             $self->{value} .= ":" if ($masm && $ret!~m/^\$/);
375             $self->{value} . ":";
376         } elsif ($win64 && $current_function->{abi} eq "svr4") {
377             my $func =  "$current_function->{name}" .
378                         ($nasm ? ":" : "\tPROC $current_function->{scope}") .
379                         "\n";
380             $func .= "  mov     QWORD${PTR}[8+rsp],rdi\t;WIN64 prologue\n";
381             $func .= "  mov     QWORD${PTR}[16+rsp],rsi\n";
382             $func .= "  mov     rax,rsp\n";
383             $func .= "${decor}SEH_begin_$current_function->{name}:";
384             $func .= ":" if ($masm);
385             $func .= "\n";
386             my $narg = $current_function->{narg};
387             $narg=6 if (!defined($narg));
388             $func .= "  mov     rdi,rcx\n" if ($narg>0);
389             $func .= "  mov     rsi,rdx\n" if ($narg>1);
390             $func .= "  mov     rdx,r8\n"  if ($narg>2);
391             $func .= "  mov     rcx,r9\n"  if ($narg>3);
392             $func .= "  mov     r8,QWORD${PTR}[40+rsp]\n" if ($narg>4);
393             $func .= "  mov     r9,QWORD${PTR}[48+rsp]\n" if ($narg>5);
394             $func .= "\n";
395         } else {
396            "$current_function->{name}".
397                         ($nasm ? ":" : "\tPROC $current_function->{scope}");
398         }
399     }
400 }
401 { package expr;         # pick up expressioins
402     sub re {
403         my      $self = shift;  # single instance is enough...
404         local   *line = shift;
405         undef   $ret;
406
407         if ($line =~ /(^[^,]+)/) {
408             $self->{value} = $1;
409             $ret = $self;
410             $line = substr($line,@+[0]); $line =~ s/^\s+//;
411
412             $self->{value} =~ s/\@PLT// if (!$elf);
413             $self->{value} =~ s/([_a-z][_a-z0-9]*)/$globals{$1} or $1/gei;
414             $self->{value} =~ s/\.L/$decor/g;
415         }
416         $ret;
417     }
418     sub out {
419         my $self = shift;
420         if ($nasm && opcode->mnemonic()=~m/^j/) {
421             "NEAR ".$self->{value};
422         } else {
423             $self->{value};
424         }
425     }
426 }
427 { package directive;    # pick up directives, which start with .
428     sub re {
429         my      $self = shift;  # single instance is enough...
430         local   *line = shift;
431         undef   $ret;
432         my      $dir;
433         my      %opcode =       # lea 2f-1f(%rip),%dst; 1: nop; 2:
434                 (       "%rax"=>0x01058d48,     "%rcx"=>0x010d8d48,
435                         "%rdx"=>0x01158d48,     "%rbx"=>0x011d8d48,
436                         "%rsp"=>0x01258d48,     "%rbp"=>0x012d8d48,
437                         "%rsi"=>0x01358d48,     "%rdi"=>0x013d8d48,
438                         "%r8" =>0x01058d4c,     "%r9" =>0x010d8d4c,
439                         "%r10"=>0x01158d4c,     "%r11"=>0x011d8d4c,
440                         "%r12"=>0x01258d4c,     "%r13"=>0x012d8d4c,
441                         "%r14"=>0x01358d4c,     "%r15"=>0x013d8d4c      );
442
443         if ($line =~ /^\s*(\.\w+)/) {
444             $dir = $1;
445             $ret = $self;
446             undef $self->{value};
447             $line = substr($line,@+[0]); $line =~ s/^\s+//;
448
449             SWITCH: for ($dir) {
450                 /\.picmeup/ && do { if ($line =~ /(%r[\w]+)/i) {
451                                         $dir="\t.long";
452                                         $line=sprintf "0x%x,0x90000000",$opcode{$1};
453                                     }
454                                     last;
455                                   };
456                 /\.global|\.globl|\.extern/
457                             && do { $globals{$line} = $prefix . $line;
458                                     $line = $globals{$line} if ($prefix);
459                                     last;
460                                   };
461                 /\.type/    && do { ($sym,$type,$narg) = split(',',$line);
462                                     if ($type eq "\@function") {
463                                         undef $current_function;
464                                         $current_function->{name} = $sym;
465                                         $current_function->{abi}  = "svr4";
466                                         $current_function->{narg} = $narg;
467                                         $current_function->{scope} = defined($globals{$sym})?"PUBLIC":"PRIVATE";
468                                     } elsif ($type eq "\@abi-omnipotent") {
469                                         undef $current_function;
470                                         $current_function->{name} = $sym;
471                                         $current_function->{scope} = defined($globals{$sym})?"PUBLIC":"PRIVATE";
472                                     }
473                                     $line =~ s/\@abi\-omnipotent/\@function/;
474                                     $line =~ s/\@function.*/\@function/;
475                                     last;
476                                   };
477                 /\.asciz/   && do { if ($line =~ /^"(.*)"$/) {
478                                         $dir  = ".byte";
479                                         $line = join(",",unpack("C*",$1),0);
480                                     }
481                                     last;
482                                   };
483                 /\.rva|\.long|\.quad/
484                             && do { $line =~ s/([_a-z][_a-z0-9]*)/$globals{$1} or $1/gei;
485                                     $line =~ s/\.L/$decor/g;
486                                     last;
487                                   };
488             }
489
490             if ($gas) {
491                 $self->{value} = $dir . "\t" . $line;
492
493                 if ($dir =~ /\.extern/) {
494                     $self->{value} = ""; # swallow extern
495                 } elsif (!$elf && $dir =~ /\.type/) {
496                     $self->{value} = "";
497                     $self->{value} = ".def\t" . ($globals{$1} or $1) . ";\t" .
498                                 (defined($globals{$1})?".scl 2;":".scl 3;") .
499                                 "\t.type 32;\t.endef"
500                                 if ($win64 && $line =~ /([^,]+),\@function/);
501                 } elsif (!$elf && $dir =~ /\.size/) {
502                     $self->{value} = "";
503                     if (defined($current_function)) {
504                         $self->{value} .= "${decor}SEH_end_$current_function->{name}:"
505                                 if ($win64 && $current_function->{abi} eq "svr4");
506                         undef $current_function;
507                     }
508                 } elsif (!$elf && $dir =~ /\.align/) {
509                     $self->{value} = ".p2align\t" . (log($line)/log(2));
510                 } elsif ($dir eq ".section") {
511                     $current_segment=$line;
512                     if (!$elf && $current_segment eq ".init") {
513                         if      ($flavour eq "macosx")  { $self->{value} = ".mod_init_func"; }
514                         elsif   ($flavour eq "mingw64") { $self->{value} = ".section\t.ctors"; }
515                     }
516                 } elsif ($dir =~ /\.(text|data)/) {
517                     $current_segment=".$1";
518                 } elsif ($dir =~ /\.hidden/) {
519                     if    ($flavour eq "macosx")  { $self->{value} = ".private_extern\t$prefix$line"; }
520                     elsif ($flavour eq "mingw64") { $self->{value} = ""; }
521                 } elsif ($dir =~ /\.comm/) {
522                     $self->{value} = "$dir\t$prefix$line";
523                     $self->{value} =~ s|,([0-9]+),([0-9]+)$|",$1,".log($2)/log(2)|e if ($flavour eq "macosx");
524                 }
525                 $line = "";
526                 return $self;
527             }
528
529             # non-gas case or nasm/masm
530             SWITCH: for ($dir) {
531                 /\.text/    && do { my $v=undef;
532                                     if ($nasm) {
533                                         $v="section     .text code align=64\n";
534                                     } else {
535                                         $v="$current_segment\tENDS\n" if ($current_segment);
536                                         $current_segment = ".text\$";
537                                         $v.="$current_segment\tSEGMENT ";
538                                         $v.=$masm>=$masmref ? "ALIGN(64)" : "PAGE";
539                                         $v.=" 'CODE'";
540                                     }
541                                     $self->{value} = $v;
542                                     last;
543                                   };
544                 /\.data/    && do { my $v=undef;
545                                     if ($nasm) {
546                                         $v="section     .data data align=8\n";
547                                     } else {
548                                         $v="$current_segment\tENDS\n" if ($current_segment);
549                                         $current_segment = "_DATA";
550                                         $v.="$current_segment\tSEGMENT";
551                                     }
552                                     $self->{value} = $v;
553                                     last;
554                                   };
555                 /\.section/ && do { my $v=undef;
556                                     $line =~ s/([^,]*).*/$1/;
557                                     $line = ".CRT\$XCU" if ($line eq ".init");
558                                     if ($nasm) {
559                                         $v="section     $line";
560                                         if ($line=~/\.([px])data/) {
561                                             $v.=" rdata align=";
562                                             $v.=$1 eq "p"? 4 : 8;
563                                         } elsif ($line=~/\.CRT\$/i) {
564                                             $v.=" rdata align=8";
565                                         }
566                                     } else {
567                                         $v="$current_segment\tENDS\n" if ($current_segment);
568                                         $v.="$line\tSEGMENT";
569                                         if ($line=~/\.([px])data/) {
570                                             $v.=" READONLY";
571                                             $v.=" ALIGN(".($1 eq "p" ? 4 : 8).")" if ($masm>=$masmref);
572                                         } elsif ($line=~/\.CRT\$/i) {
573                                             $v.=" READONLY ";
574                                             $v.=$masm>=$masmref ? "ALIGN(8)" : "DWORD";
575                                         }
576                                     }
577                                     $current_segment = $line;
578                                     $self->{value} = $v;
579                                     last;
580                                   };
581                 /\.extern/  && do { $self->{value}  = "EXTERN\t".$line;
582                                     $self->{value} .= ":NEAR" if ($masm);
583                                     last;
584                                   };
585                 /\.globl|.global/
586                             && do { $self->{value}  = $masm?"PUBLIC":"global";
587                                     $self->{value} .= "\t".$line;
588                                     last;
589                                   };
590                 /\.size/    && do { if (defined($current_function)) {
591                                         undef $self->{value};
592                                         if ($current_function->{abi} eq "svr4") {
593                                             $self->{value}="${decor}SEH_end_$current_function->{name}:";
594                                             $self->{value}.=":\n" if($masm);
595                                         }
596                                         $self->{value}.="$current_function->{name}\tENDP" if($masm && $current_function->{name});
597                                         undef $current_function;
598                                     }
599                                     last;
600                                   };
601                 /\.align/   && do { $self->{value} = "ALIGN\t".$line; last; };
602                 /\.(value|long|rva|quad)/
603                             && do { my $sz  = substr($1,0,1);
604                                     my @arr = split(/,\s*/,$line);
605                                     my $last = pop(@arr);
606                                     my $conv = sub  {   my $var=shift;
607                                                         $var=~s/^(0b[0-1]+)/oct($1)/eig;
608                                                         $var=~s/^0x([0-9a-f]+)/0$1h/ig if ($masm);
609                                                         if ($sz eq "D" && ($current_segment=~/.[px]data/ || $dir eq ".rva"))
610                                                         { $var=~s/([_a-z\$\@][_a-z0-9\$\@]*)/$nasm?"$1 wrt ..imagebase":"imagerel $1"/egi; }
611                                                         $var;
612                                                     };  
613
614                                     $sz =~ tr/bvlrq/BWDDQ/;
615                                     $self->{value} = "\tD$sz\t";
616                                     for (@arr) { $self->{value} .= &$conv($_).","; }
617                                     $self->{value} .= &$conv($last);
618                                     last;
619                                   };
620                 /\.byte/    && do { my @str=split(/,\s*/,$line);
621                                     map(s/(0b[0-1]+)/oct($1)/eig,@str);
622                                     map(s/0x([0-9a-f]+)/0$1h/ig,@str) if ($masm);       
623                                     while ($#str>15) {
624                                         $self->{value}.="DB\t"
625                                                 .join(",",@str[0..15])."\n";
626                                         foreach (0..15) { shift @str; }
627                                     }
628                                     $self->{value}.="DB\t"
629                                                 .join(",",@str) if (@str);
630                                     last;
631                                   };
632                 /\.comm/    && do { my @str=split(/,\s*/,$line);
633                                     my $v=undef;
634                                     if ($nasm) {
635                                         $v.="common     $prefix@str[0] @str[1]";
636                                     } else {
637                                         $v="$current_segment\tENDS\n" if ($current_segment);
638                                         $current_segment = "_DATA";
639                                         $v.="$current_segment\tSEGMENT\n";
640                                         $v.="COMM       @str[0]:DWORD:".@str[1]/4;
641                                     }
642                                     $self->{value} = $v;
643                                     last;
644                                   };
645             }
646             $line = "";
647         }
648
649         $ret;
650     }
651     sub out {
652         my $self = shift;
653         $self->{value};
654     }
655 }
656
657 sub rex {
658  local *opcode=shift;
659  my ($dst,$src,$rex)=@_;
660
661    $rex|=0x04 if($dst>=8);
662    $rex|=0x01 if($src>=8);
663    push @opcode,($rex|0x40) if ($rex);
664 }
665
666 # older gas and ml64 don't handle SSE>2 instructions
667 my %regrm = (   "%eax"=>0, "%ecx"=>1, "%edx"=>2, "%ebx"=>3,
668                 "%esp"=>4, "%ebp"=>5, "%esi"=>6, "%edi"=>7      );
669
670 my $movq = sub {        # elderly gas can't handle inter-register movq
671   my $arg = shift;
672   my @opcode=(0x66);
673     if ($arg =~ /%xmm([0-9]+),\s*%r(\w+)/) {
674         my ($src,$dst)=($1,$2);
675         if ($dst !~ /[0-9]+/)   { $dst = $regrm{"%e$dst"}; }
676         rex(\@opcode,$src,$dst,0x8);
677         push @opcode,0x0f,0x7e;
678         push @opcode,0xc0|(($src&7)<<3)|($dst&7);       # ModR/M
679         @opcode;
680     } elsif ($arg =~ /%r(\w+),\s*%xmm([0-9]+)/) {
681         my ($src,$dst)=($2,$1);
682         if ($dst !~ /[0-9]+/)   { $dst = $regrm{"%e$dst"}; }
683         rex(\@opcode,$src,$dst,0x8);
684         push @opcode,0x0f,0x6e;
685         push @opcode,0xc0|(($src&7)<<3)|($dst&7);       # ModR/M
686         @opcode;
687     } else {
688         ();
689     }
690 };
691
692 my $pextrd = sub {
693     if (shift =~ /\$([0-9]+),\s*%xmm([0-9]+),\s*(%\w+)/) {
694       my @opcode=(0x66);
695         $imm=$1;
696         $src=$2;
697         $dst=$3;
698         if ($dst =~ /%r([0-9]+)d/)      { $dst = $1; }
699         elsif ($dst =~ /%e/)            { $dst = $regrm{$dst}; }
700         rex(\@opcode,$src,$dst);
701         push @opcode,0x0f,0x3a,0x16;
702         push @opcode,0xc0|(($src&7)<<3)|($dst&7);       # ModR/M
703         push @opcode,$imm;
704         @opcode;
705     } else {
706         ();
707     }
708 };
709
710 my $pinsrd = sub {
711     if (shift =~ /\$([0-9]+),\s*(%\w+),\s*%xmm([0-9]+)/) {
712       my @opcode=(0x66);
713         $imm=$1;
714         $src=$2;
715         $dst=$3;
716         if ($src =~ /%r([0-9]+)/)       { $src = $1; }
717         elsif ($src =~ /%e/)            { $src = $regrm{$src}; }
718         rex(\@opcode,$dst,$src);
719         push @opcode,0x0f,0x3a,0x22;
720         push @opcode,0xc0|(($dst&7)<<3)|($src&7);       # ModR/M
721         push @opcode,$imm;
722         @opcode;
723     } else {
724         ();
725     }
726 };
727
728 my $pshufb = sub {
729     if (shift =~ /%xmm([0-9]+),\s*%xmm([0-9]+)/) {
730       my @opcode=(0x66);
731         rex(\@opcode,$2,$1);
732         push @opcode,0x0f,0x38,0x00;
733         push @opcode,0xc0|($1&7)|(($2&7)<<3);           # ModR/M
734         @opcode;
735     } else {
736         ();
737     }
738 };
739
740 my $palignr = sub {
741     if (shift =~ /\$([0-9]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
742       my @opcode=(0x66);
743         rex(\@opcode,$3,$2);
744         push @opcode,0x0f,0x3a,0x0f;
745         push @opcode,0xc0|($2&7)|(($3&7)<<3);           # ModR/M
746         push @opcode,$1;
747         @opcode;
748     } else {
749         ();
750     }
751 };
752
753 my $pclmulqdq = sub {
754     if (shift =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
755       my @opcode=(0x66);
756         rex(\@opcode,$3,$2);
757         push @opcode,0x0f,0x3a,0x44;
758         push @opcode,0xc0|($2&7)|(($3&7)<<3);           # ModR/M
759         my $c=$1;
760         push @opcode,$c=~/^0/?oct($c):$c;
761         @opcode;
762     } else {
763         ();
764     }
765 };
766
767 my $rdrand = sub {
768     if (shift =~ /%[er](\w+)/) {
769       my @opcode=();
770       my $dst=$1;
771         if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
772         rex(\@opcode,0,$1,8);
773         push @opcode,0x0f,0xc7,0xf0|($dst&7);
774         @opcode;
775     } else {
776         ();
777     }
778 };
779
780 sub rxb {
781  local *opcode=shift;
782  my ($dst,$src1,$src2,$rxb)=@_;
783
784    $rxb|=0x7<<5;
785    $rxb&=~(0x04<<5) if($dst>=8);
786    $rxb&=~(0x01<<5) if($src1>=8);
787    $rxb&=~(0x02<<5) if($src2>=8);
788    push @opcode,$rxb;
789 }
790
791 my $vprotd = sub {
792     if (shift =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
793       my @opcode=(0x8f);
794         rxb(\@opcode,$3,$2,-1,0x08);
795         push @opcode,0x78,0xc2;
796         push @opcode,0xc0|($2&7)|(($3&7)<<3);           # ModR/M
797         my $c=$1;
798         push @opcode,$c=~/^0/?oct($c):$c;
799         @opcode;
800     } else {
801         ();
802     }
803 };
804
805 my $vprotq = sub {
806     if (shift =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
807       my @opcode=(0x8f);
808         rxb(\@opcode,$3,$2,-1,0x08);
809         push @opcode,0x78,0xc3;
810         push @opcode,0xc0|($2&7)|(($3&7)<<3);           # ModR/M
811         my $c=$1;
812         push @opcode,$c=~/^0/?oct($c):$c;
813         @opcode;
814     } else {
815         ();
816     }
817 };
818
819 if ($nasm) {
820     print <<___;
821 default rel
822 %define XMMWORD
823 ___
824 } elsif ($masm) {
825     print <<___;
826 OPTION  DOTNAME
827 ___
828 }
829 while($line=<>) {
830
831     chomp($line);
832
833     $line =~ s|[#!].*$||;       # get rid of asm-style comments...
834     $line =~ s|/\*.*\*/||;      # ... and C-style comments...
835     $line =~ s|^\s+||;          # ... and skip white spaces in beginning
836
837     undef $label;
838     undef $opcode;
839     undef @args;
840
841     if ($label=label->re(\$line))       { print $label->out(); }
842
843     if (directive->re(\$line)) {
844         printf "%s",directive->out();
845     } elsif ($opcode=opcode->re(\$line)) {
846         my $asm = eval("\$".$opcode->mnemonic());
847         undef @bytes;
848         
849         if ((ref($asm) eq 'CODE') && scalar(@bytes=&$asm($line))) {
850             print $gas?".byte\t":"DB\t",join(',',@bytes),"\n";
851             next;
852         }
853
854         ARGUMENT: while (1) {
855         my $arg;
856
857         if ($arg=register->re(\$line))  { opcode->size($arg->size()); }
858         elsif ($arg=const->re(\$line))  { }
859         elsif ($arg=ea->re(\$line))     { }
860         elsif ($arg=expr->re(\$line))   { }
861         else                            { last ARGUMENT; }
862
863         push @args,$arg;
864
865         last ARGUMENT if ($line !~ /^,/);
866
867         $line =~ s/^,\s*//;
868         } # ARGUMENT:
869
870         if ($#args>=0) {
871             my $insn;
872             my $sz=opcode->size();
873
874             if ($gas) {
875                 $insn = $opcode->out($#args>=1?$args[$#args]->size():$sz);
876                 @args = map($_->out($sz),@args);
877                 printf "\t%s\t%s",$insn,join(",",@args);
878             } else {
879                 $insn = $opcode->out();
880                 foreach (@args) {
881                     my $arg = $_->out();
882                     # $insn.=$sz compensates for movq, pinsrw, ...
883                     if ($arg =~ /^xmm[0-9]+$/) { $insn.=$sz; $sz="x" if(!$sz); last; }
884                     if ($arg =~ /^mm[0-9]+$/)  { $insn.=$sz; $sz="q" if(!$sz); last; }
885                 }
886                 @args = reverse(@args);
887                 undef $sz if ($nasm && $opcode->mnemonic() eq "lea");
888                 printf "\t%s\t%s",$insn,join(",",map($_->out($sz),@args));
889             }
890         } else {
891             printf "\t%s",$opcode->out();
892         }
893     }
894
895     print $line,"\n";
896 }
897
898 print "\n$current_segment\tENDS\n"      if ($current_segment && $masm);
899 print "END\n"                           if ($masm);
900
901 close STDOUT;
902
903 \f#################################################
904 # Cross-reference x86_64 ABI "card"
905 #
906 #               Unix            Win64
907 # %rax          *               *
908 # %rbx          -               -
909 # %rcx          #4              #1
910 # %rdx          #3              #2
911 # %rsi          #2              -
912 # %rdi          #1              -
913 # %rbp          -               -
914 # %rsp          -               -
915 # %r8           #5              #3
916 # %r9           #6              #4
917 # %r10          *               *
918 # %r11          *               *
919 # %r12          -               -
920 # %r13          -               -
921 # %r14          -               -
922 # %r15          -               -
923
924 # (*)   volatile register
925 # (-)   preserved by callee
926 # (#)   Nth argument, volatile
927 #
928 # In Unix terms top of stack is argument transfer area for arguments
929 # which could not be accomodated in registers. Or in other words 7th
930 # [integer] argument resides at 8(%rsp) upon function entry point.
931 # 128 bytes above %rsp constitute a "red zone" which is not touched
932 # by signal handlers and can be used as temporal storage without
933 # allocating a frame.
934 #
935 # In Win64 terms N*8 bytes on top of stack is argument transfer area,
936 # which belongs to/can be overwritten by callee. N is the number of
937 # arguments passed to callee, *but* not less than 4! This means that
938 # upon function entry point 5th argument resides at 40(%rsp), as well
939 # as that 32 bytes from 8(%rsp) can always be used as temporal
940 # storage [without allocating a frame]. One can actually argue that
941 # one can assume a "red zone" above stack pointer under Win64 as well.
942 # Point is that at apparently no occasion Windows kernel would alter
943 # the area above user stack pointer in true asynchronous manner...
944 #
945 # All the above means that if assembler programmer adheres to Unix
946 # register and stack layout, but disregards the "red zone" existense,
947 # it's possible to use following prologue and epilogue to "gear" from
948 # Unix to Win64 ABI in leaf functions with not more than 6 arguments.
949 #
950 # omnipotent_function:
951 # ifdef WIN64
952 #       movq    %rdi,8(%rsp)
953 #       movq    %rsi,16(%rsp)
954 #       movq    %rcx,%rdi       ; if 1st argument is actually present
955 #       movq    %rdx,%rsi       ; if 2nd argument is actually ...
956 #       movq    %r8,%rdx        ; if 3rd argument is ...
957 #       movq    %r9,%rcx        ; if 4th argument ...
958 #       movq    40(%rsp),%r8    ; if 5th ...
959 #       movq    48(%rsp),%r9    ; if 6th ...
960 # endif
961 #       ...
962 # ifdef WIN64
963 #       movq    8(%rsp),%rdi
964 #       movq    16(%rsp),%rsi
965 # endif
966 #       ret
967 #
968 \f#################################################
969 # Win64 SEH, Structured Exception Handling.
970 #
971 # Unlike on Unix systems(*) lack of Win64 stack unwinding information
972 # has undesired side-effect at run-time: if an exception is raised in
973 # assembler subroutine such as those in question (basically we're
974 # referring to segmentation violations caused by malformed input
975 # parameters), the application is briskly terminated without invoking
976 # any exception handlers, most notably without generating memory dump
977 # or any user notification whatsoever. This poses a problem. It's
978 # possible to address it by registering custom language-specific
979 # handler that would restore processor context to the state at
980 # subroutine entry point and return "exception is not handled, keep
981 # unwinding" code. Writing such handler can be a challenge... But it's
982 # doable, though requires certain coding convention. Consider following
983 # snippet:
984 #
985 # .type function,@function
986 # function:
987 #       movq    %rsp,%rax       # copy rsp to volatile register
988 #       pushq   %r15            # save non-volatile registers
989 #       pushq   %rbx
990 #       pushq   %rbp
991 #       movq    %rsp,%r11
992 #       subq    %rdi,%r11       # prepare [variable] stack frame
993 #       andq    $-64,%r11
994 #       movq    %rax,0(%r11)    # check for exceptions
995 #       movq    %r11,%rsp       # allocate [variable] stack frame
996 #       movq    %rax,0(%rsp)    # save original rsp value
997 # magic_point:
998 #       ...
999 #       movq    0(%rsp),%rcx    # pull original rsp value
1000 #       movq    -24(%rcx),%rbp  # restore non-volatile registers
1001 #       movq    -16(%rcx),%rbx
1002 #       movq    -8(%rcx),%r15
1003 #       movq    %rcx,%rsp       # restore original rsp
1004 #       ret
1005 # .size function,.-function
1006 #
1007 # The key is that up to magic_point copy of original rsp value remains
1008 # in chosen volatile register and no non-volatile register, except for
1009 # rsp, is modified. While past magic_point rsp remains constant till
1010 # the very end of the function. In this case custom language-specific
1011 # exception handler would look like this:
1012 #
1013 # EXCEPTION_DISPOSITION handler (EXCEPTION_RECORD *rec,ULONG64 frame,
1014 #               CONTEXT *context,DISPATCHER_CONTEXT *disp)
1015 # {     ULONG64 *rsp = (ULONG64 *)context->Rax;
1016 #       if (context->Rip >= magic_point)
1017 #       {   rsp = ((ULONG64 **)context->Rsp)[0];
1018 #           context->Rbp = rsp[-3];
1019 #           context->Rbx = rsp[-2];
1020 #           context->R15 = rsp[-1];
1021 #       }
1022 #       context->Rsp = (ULONG64)rsp;
1023 #       context->Rdi = rsp[1];
1024 #       context->Rsi = rsp[2];
1025 #
1026 #       memcpy (disp->ContextRecord,context,sizeof(CONTEXT));
1027 #       RtlVirtualUnwind(UNW_FLAG_NHANDLER,disp->ImageBase,
1028 #               dips->ControlPc,disp->FunctionEntry,disp->ContextRecord,
1029 #               &disp->HandlerData,&disp->EstablisherFrame,NULL);
1030 #       return ExceptionContinueSearch;
1031 # }
1032 #
1033 # It's appropriate to implement this handler in assembler, directly in
1034 # function's module. In order to do that one has to know members'
1035 # offsets in CONTEXT and DISPATCHER_CONTEXT structures and some constant
1036 # values. Here they are:
1037 #
1038 #       CONTEXT.Rax                             120
1039 #       CONTEXT.Rcx                             128
1040 #       CONTEXT.Rdx                             136
1041 #       CONTEXT.Rbx                             144
1042 #       CONTEXT.Rsp                             152
1043 #       CONTEXT.Rbp                             160
1044 #       CONTEXT.Rsi                             168
1045 #       CONTEXT.Rdi                             176
1046 #       CONTEXT.R8                              184
1047 #       CONTEXT.R9                              192
1048 #       CONTEXT.R10                             200
1049 #       CONTEXT.R11                             208
1050 #       CONTEXT.R12                             216
1051 #       CONTEXT.R13                             224
1052 #       CONTEXT.R14                             232
1053 #       CONTEXT.R15                             240
1054 #       CONTEXT.Rip                             248
1055 #       CONTEXT.Xmm6                            512
1056 #       sizeof(CONTEXT)                         1232
1057 #       DISPATCHER_CONTEXT.ControlPc            0
1058 #       DISPATCHER_CONTEXT.ImageBase            8
1059 #       DISPATCHER_CONTEXT.FunctionEntry        16
1060 #       DISPATCHER_CONTEXT.EstablisherFrame     24
1061 #       DISPATCHER_CONTEXT.TargetIp             32
1062 #       DISPATCHER_CONTEXT.ContextRecord        40
1063 #       DISPATCHER_CONTEXT.LanguageHandler      48
1064 #       DISPATCHER_CONTEXT.HandlerData          56
1065 #       UNW_FLAG_NHANDLER                       0
1066 #       ExceptionContinueSearch                 1
1067 #
1068 # In order to tie the handler to the function one has to compose
1069 # couple of structures: one for .xdata segment and one for .pdata.
1070 #
1071 # UNWIND_INFO structure for .xdata segment would be
1072 #
1073 # function_unwind_info:
1074 #       .byte   9,0,0,0
1075 #       .rva    handler
1076 #
1077 # This structure designates exception handler for a function with
1078 # zero-length prologue, no stack frame or frame register.
1079 #
1080 # To facilitate composing of .pdata structures, auto-generated "gear"
1081 # prologue copies rsp value to rax and denotes next instruction with
1082 # .LSEH_begin_{function_name} label. This essentially defines the SEH
1083 # styling rule mentioned in the beginning. Position of this label is
1084 # chosen in such manner that possible exceptions raised in the "gear"
1085 # prologue would be accounted to caller and unwound from latter's frame.
1086 # End of function is marked with respective .LSEH_end_{function_name}
1087 # label. To summarize, .pdata segment would contain
1088 #
1089 #       .rva    .LSEH_begin_function
1090 #       .rva    .LSEH_end_function
1091 #       .rva    function_unwind_info
1092 #
1093 # Reference to functon_unwind_info from .xdata segment is the anchor.
1094 # In case you wonder why references are 32-bit .rvas and not 64-bit
1095 # .quads. References put into these two segments are required to be
1096 # *relative* to the base address of the current binary module, a.k.a.
1097 # image base. No Win64 module, be it .exe or .dll, can be larger than
1098 # 2GB and thus such relative references can be and are accommodated in
1099 # 32 bits.
1100 #
1101 # Having reviewed the example function code, one can argue that "movq
1102 # %rsp,%rax" above is redundant. It is not! Keep in mind that on Unix
1103 # rax would contain an undefined value. If this "offends" you, use
1104 # another register and refrain from modifying rax till magic_point is
1105 # reached, i.e. as if it was a non-volatile register. If more registers
1106 # are required prior [variable] frame setup is completed, note that
1107 # nobody says that you can have only one "magic point." You can
1108 # "liberate" non-volatile registers by denoting last stack off-load
1109 # instruction and reflecting it in finer grade unwind logic in handler.
1110 # After all, isn't it why it's called *language-specific* handler...
1111 #
1112 # Attentive reader can notice that exceptions would be mishandled in
1113 # auto-generated "gear" epilogue. Well, exception effectively can't
1114 # occur there, because if memory area used by it was subject to
1115 # segmentation violation, then it would be raised upon call to the
1116 # function (and as already mentioned be accounted to caller, which is
1117 # not a problem). If you're still not comfortable, then define tail
1118 # "magic point" just prior ret instruction and have handler treat it...
1119 #
1120 # (*)   Note that we're talking about run-time, not debug-time. Lack of
1121 #       unwind information makes debugging hard on both Windows and
1122 #       Unix. "Unlike" referes to the fact that on Unix signal handler
1123 #       will always be invoked, core dumped and appropriate exit code
1124 #       returned to parent (for user notification).