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