x86_64-xlate.pl: new gas requires sign extention in lea instruction
[openssl.git] / crypto / perlasm / x86_64-xlate.pl
1 #!/usr/bin/env perl
2
3 # Ascetic x86_64 AT&T to MASM 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 # - indirect calls and jumps are not supported;
24 #
25 # Dual-ABI styling rules.
26 #
27 # 1. Adhere to Unix register and stack layout [see the end for
28 #    explanation].
29 # 2. Forget about "red zone," stick to more traditional blended
30 #    stack frame allocation. If volatile storage is actually required
31 #    that is. If not, just leave the stack as is.
32 # 3. Functions tagged with ".type name,@function" get crafted with
33 #    unified Win64 prologue and epilogue automatically. If you want
34 #    to take care of ABI differences yourself, tag functions as
35 #    ".type name,@abi-omnipotent" instead.
36 # 4. To optimize the Win64 prologue you can specify number of input
37 #    arguments as ".type name,@function,N." Keep in mind that if N is
38 #    larger than 6, then you *have to* write "abi-omnipotent" code,
39 #    because >6 cases can't be addressed with unified prologue.
40 # 5. Name local labels as .L*, do *not* use dynamic labels such as 1:
41 #    (sorry about latter).
42 # 6. Don't use [or hand-code with .byte] "rep ret." "ret" mnemonic is
43 #    required to identify the spots, where to inject Win64 epilogue!
44 #    But on the pros, it's then prefixed with rep automatically:-)
45 # 7. Due to MASM limitations [and certain general counter-intuitivity
46 #    of ip-relative addressing] generation of position-independent
47 #    code is assisted by synthetic directive, .picmeup, which puts
48 #    address of the *next* instruction into target register.
49 #
50 #    Example 1:
51 #               .picmeup        %rax
52 #               lea             .Label-.(%rax),%rax
53 #    Example 2:
54 #               .picmeup        %rcx
55 #       .Lpic_point:
56 #               ...
57 #               lea             .Label-.Lpic_point(%rcx),%rbp
58
59 my $output = shift;
60
61 { my ($stddev,$stdino,@junk)=stat(STDOUT);
62   my ($outdev,$outino,@junk)=stat($output);
63
64     open STDOUT,">$output" || die "can't open $output: $!"
65         if ($stddev!=$outdev || $stdino!=$outino);
66 }
67
68 my $masmref=8 + 50727*2**-32;   # 8.00.50727 shipped with VS2005
69 my $masm=$masmref if ($output =~ /\.asm/);
70 if ($masm && `ml64 2>&1` =~ m/Version ([0-9]+)\.([0-9]+)(\.([0-9]+))?/)
71 {   $masm=$1 + $2*2**-16 + $4*2**-32;   }
72
73 my $current_segment;
74 my $current_function;
75
76 { package opcode;       # pick up opcodes
77     sub re {
78         my      $self = shift;  # single instance in enough...
79         local   *line = shift;
80         undef   $ret;
81
82         if ($line =~ /^([a-z][a-z0-9]*)/i) {
83             $self->{op} = $1;
84             $ret = $self;
85             $line = substr($line,@+[0]); $line =~ s/^\s+//;
86
87             undef $self->{sz};
88             if ($self->{op} =~ /^(movz)b.*/) {  # movz is pain...
89                 $self->{op} = $1;
90                 $self->{sz} = "b";
91             } elsif ($self->{op} =~ /call/) {
92                 $self->{sz} = ""
93             } elsif ($self->{op} =~ /([a-z]{3,})([qlwb])$/) {
94                 $self->{op} = $1;
95                 $self->{sz} = $2;
96             }
97         }
98         $ret;
99     }
100     sub size {
101         my $self = shift;
102         my $sz   = shift;
103         $self->{sz} = $sz if (defined($sz) && !defined($self->{sz}));
104         $self->{sz};
105     }
106     sub out {
107         my $self = shift;
108         if (!$masm) {
109             if ($self->{op} eq "movz") {        # movz is pain...
110                 sprintf "%s%s%s",$self->{op},$self->{sz},shift;
111             } elsif ($self->{op} =~ /^set/) { 
112                 "$self->{op}";
113             } elsif ($self->{op} eq "ret") {
114                 ".byte  0xf3,0xc3";
115             } else {
116                 "$self->{op}$self->{sz}";
117             }
118         } else {
119             $self->{op} =~ s/^movz/movzx/;
120             if ($self->{op} eq "ret") {
121                 $self->{op} = "";
122                 if ($current_function->{abi} eq "svr4") {
123                     $self->{op} = "mov  rdi,QWORD PTR 8[rsp]\t;WIN64 epilogue\n\t".
124                                   "mov  rsi,QWORD PTR 16[rsp]\n\t";
125                 }
126                 $self->{op} .= "DB\t0F3h,0C3h\t\t;repret";
127             }
128             $self->{op};
129         }
130     }
131 }
132 { package const;        # pick up constants, which start with $
133     sub re {
134         my      $self = shift;  # single instance in enough...
135         local   *line = shift;
136         undef   $ret;
137
138         if ($line =~ /^\$([^,]+)/) {
139             $self->{value} = $1;
140             $ret = $self;
141             $line = substr($line,@+[0]); $line =~ s/^\s+//;
142         }
143         $ret;
144     }
145     sub out {
146         my $self = shift;
147
148         if (!$masm) {
149             # Solaris /usr/ccs/bin/as can't handle multiplications
150             # in $self->{value}
151             $self->{value} =~ s/(?<![0-9a-f])(0[x0-9a-f]+)/oct($1)/egi;
152             $self->{value} =~ s/([0-9]+\s*[\*\/\%]\s*[0-9]+)/eval($1)/eg;
153             sprintf "\$%s",$self->{value};
154         } else {
155             $self->{value} =~ s/0x([0-9a-f]+)/0$1h/ig;
156             sprintf "%s",$self->{value};
157         }
158     }
159 }
160 { package ea;           # pick up effective addresses: expr(%reg,%reg,scale)
161     sub re {
162         my      $self = shift;  # single instance in enough...
163         local   *line = shift;
164         undef   $ret;
165
166         if ($line =~ /^([^\(,]*)\(([%\w,]+)\)/) {
167             $self->{label} = $1;
168             ($self->{base},$self->{index},$self->{scale})=split(/,/,$2);
169             $self->{scale} = 1 if (!defined($self->{scale}));
170             $ret = $self;
171             $line = substr($line,@+[0]); $line =~ s/^\s+//;
172
173             $self->{base}  =~ s/^%//;
174             $self->{index} =~ s/^%// if (defined($self->{index}));
175         }
176         $ret;
177     }
178     sub size {}
179     sub out {
180         my $self = shift;
181         my $sz = shift;
182
183         # Silently convert all EAs to 64-bit. This is required for
184         # elder GNU assembler and results in more compact code,
185         # *but* most importantly AES module depends on this feature!
186         $self->{index} =~ s/^[er](.?[0-9xpi])[d]?$/r\1/;
187         $self->{base}  =~ s/^[er](.?[0-9xpi])[d]?$/r\1/;
188
189         if (!$masm) {
190             # Solaris /usr/ccs/bin/as can't handle multiplications
191             # in $self->{label}
192             use integer;
193             $self->{label} =~ s/(?<![0-9a-f])(0[x0-9a-f]+)/oct($1)<<32>>32/egi;
194             $self->{label} =~ s/([0-9]+\s*[\*\/\%]\s*[0-9]+)/eval($1)/eg;
195
196             if (defined($self->{index})) {
197                 sprintf "%s(%%%s,%%%s,%d)",
198                                         $self->{label},$self->{base},
199                                         $self->{index},$self->{scale};
200             } else {
201                 sprintf "%s(%%%s)",     $self->{label},$self->{base};
202             }
203         } else {
204             %szmap = ( b=>"BYTE", w=>"WORD", l=>"DWORD", q=>"QWORD" );
205
206             $self->{label} =~ s/\./\$/g;
207             $self->{label} =~ s/0x([0-9a-f]+)/0$1h/ig;
208             $self->{label} = "($self->{label})" if ($self->{label} =~ /[\*\+\-\/]/);
209
210             if (defined($self->{index})) {
211                 sprintf "%s PTR %s[%s*%d+%s]",$szmap{$sz},
212                                         $self->{label},
213                                         $self->{index},$self->{scale},
214                                         $self->{base};
215             } elsif ($self->{base} eq "rip") {
216                 sprintf "%s PTR %s",$szmap{$sz},$self->{label};
217             } else {
218                 sprintf "%s PTR %s[%s]",$szmap{$sz},
219                                         $self->{label},$self->{base};
220             }
221         }
222     }
223 }
224 { package register;     # pick up registers, which start with %.
225     sub re {
226         my      $class = shift; # muliple instances...
227         my      $self = {};
228         local   *line = shift;
229         undef   $ret;
230
231         if ($line =~ /^%(\w+)/) {
232             bless $self,$class;
233             $self->{value} = $1;
234             $ret = $self;
235             $line = substr($line,@+[0]); $line =~ s/^\s+//;
236         }
237         $ret;
238     }
239     sub size {
240         my      $self = shift;
241         undef   $ret;
242
243         if    ($self->{value} =~ /^r[\d]+b$/i)  { $ret="b"; }
244         elsif ($self->{value} =~ /^r[\d]+w$/i)  { $ret="w"; }
245         elsif ($self->{value} =~ /^r[\d]+d$/i)  { $ret="l"; }
246         elsif ($self->{value} =~ /^r[\w]+$/i)   { $ret="q"; }
247         elsif ($self->{value} =~ /^[a-d][hl]$/i){ $ret="b"; }
248         elsif ($self->{value} =~ /^[\w]{2}l$/i) { $ret="b"; }
249         elsif ($self->{value} =~ /^[\w]{2}$/i)  { $ret="w"; }
250         elsif ($self->{value} =~ /^e[a-z]{2}$/i){ $ret="l"; }
251
252         $ret;
253     }
254     sub out {
255         my $self = shift;
256         sprintf $masm?"%s":"%%%s",$self->{value};
257     }
258 }
259 { package label;        # pick up labels, which end with :
260     sub re {
261         my      $self = shift;  # single instance is enough...
262         local   *line = shift;
263         undef   $ret;
264
265         if ($line =~ /(^[\.\w]+\:)/) {
266             $self->{value} = $1;
267             $ret = $self;
268             $line = substr($line,@+[0]); $line =~ s/^\s+//;
269
270             $self->{value} =~ s/\.L/\$L/ if ($masm);
271         }
272         $ret;
273     }
274     sub out {
275         my $self = shift;
276
277         if (!$masm) {
278             $self->{value};
279         } elsif ($self->{value} ne "$current_function->{name}:") {
280             $self->{value};
281         } elsif ($current_function->{abi} eq "svr4") {
282             my $func =  "$current_function->{name}      PROC\n".
283                         "       mov     QWORD PTR 8[rsp],rdi\t;WIN64 prologue\n".
284                         "       mov     QWORD PTR 16[rsp],rsi\n";
285             my $narg = $current_function->{narg};
286             $narg=6 if (!defined($narg));
287             $func .= "  mov     rdi,rcx\n" if ($narg>0);
288             $func .= "  mov     rsi,rdx\n" if ($narg>1);
289             $func .= "  mov     rdx,r8\n"  if ($narg>2);
290             $func .= "  mov     rcx,r9\n"  if ($narg>3);
291             $func .= "  mov     r8,QWORD PTR 40[rsp]\n" if ($narg>4);
292             $func .= "  mov     r9,QWORD PTR 48[rsp]\n" if ($narg>5);
293             $func .= "\n";
294         } else {
295            "$current_function->{name}   PROC";
296         }
297     }
298 }
299 { package expr;         # pick up expressioins
300     sub re {
301         my      $self = shift;  # single instance is enough...
302         local   *line = shift;
303         undef   $ret;
304
305         if ($line =~ /(^[^,]+)/) {
306             $self->{value} = $1;
307             $ret = $self;
308             $line = substr($line,@+[0]); $line =~ s/^\s+//;
309
310             $self->{value} =~ s/\.L/\$L/g if ($masm);
311         }
312         $ret;
313     }
314     sub out {
315         my $self = shift;
316         $self->{value};
317     }
318 }
319 { package directive;    # pick up directives, which start with .
320     sub re {
321         my      $self = shift;  # single instance is enough...
322         local   *line = shift;
323         undef   $ret;
324         my      $dir;
325         my      %opcode =       # lea 2f-1f(%rip),%dst; 1: nop; 2:
326                 (       "%rax"=>0x01058d48,     "%rcx"=>0x010d8d48,
327                         "%rdx"=>0x01158d48,     "%rbx"=>0x011d8d48,
328                         "%rsp"=>0x01258d48,     "%rbp"=>0x012d8d48,
329                         "%rsi"=>0x01358d48,     "%rdi"=>0x013d8d48,
330                         "%r8" =>0x01058d4c,     "%r9" =>0x010d8d4c,
331                         "%r10"=>0x01158d4c,     "%r11"=>0x011d8d4c,
332                         "%r12"=>0x01258d4c,     "%r13"=>0x012d8d4c,
333                         "%r14"=>0x01358d4c,     "%r15"=>0x013d8d4c      );
334
335         if ($line =~ /^\s*(\.\w+)/) {
336             if (!$masm) {
337                 $self->{value} = $1;
338                 $line =~ s/\@abi\-omnipotent/\@function/;
339                 $line =~ s/\@function.*/\@function/;
340                 if ($line =~ /\.picmeup\s+(%r[\w]+)/i) {
341                     $self->{value} = sprintf "\t.long\t0x%x,0x90000000",$opcode{$1};
342                 } elsif ($line =~ /\.asciz\s+"(.*)"$/) {
343                     $self->{value} = ".byte\t".join(",",unpack("C*",$1),0);
344                 } elsif ($line =~ /\.extern/) {
345                     $self->{value} = ""; # swallow extern
346                 } else {
347                     $self->{value} = $line;
348                 }
349                 $line = "";
350                 return $self;
351             }
352
353             $dir = $1;
354             $ret = $self;
355             undef $self->{value};
356             $line = substr($line,@+[0]); $line =~ s/^\s+//;
357             SWITCH: for ($dir) {
358                 /\.(text)/
359                             && do { my $v=undef;
360                                     $v="$current_segment\tENDS\n" if ($current_segment);
361                                     $current_segment = "_$1\$";
362                                     $current_segment =~ tr/[a-z]/[A-Z]/;
363                                     $v.="$current_segment\tSEGMENT ";
364                                     $v.=$masm>=$masmref ? "ALIGN(64)" : "PAGE";
365                                     $v.=" 'CODE'";
366                                     $self->{value} = $v;
367                                     last;
368                                   };
369                 /\.extern/  && do { $self->{value} = "EXTRN\t".$line.":BYTE"; last;  };
370                 /\.globl/   && do { $self->{value} = "PUBLIC\t".$line; last; };
371                 /\.type/    && do { ($sym,$type,$narg) = split(',',$line);
372                                     if ($type eq "\@function") {
373                                         undef $current_function;
374                                         $current_function->{name} = $sym;
375                                         $current_function->{abi}  = "svr4";
376                                         $current_function->{narg} = $narg;
377                                     } elsif ($type eq "\@abi-omnipotent") {
378                                         undef $current_function;
379                                         $current_function->{name} = $sym;
380                                     }
381                                     last;
382                                   };
383                 /\.size/    && do { if (defined($current_function)) {
384                                         $self->{value}="$current_function->{name}\tENDP";
385                                         undef $current_function;
386                                     }
387                                     last;
388                                   };
389                 /\.align/   && do { $self->{value} = "ALIGN\t".$line; last; };
390                 /\.(byte|value|long|quad)/
391                             && do { my @arr = split(',',$line);
392                                     my $sz  = substr($1,0,1);
393                                     my $last = pop(@arr);
394                                     my $conv = sub  {   my $var=shift;
395                                                         if ($var=~s/0x([0-9a-f]+)/0$1h/i) { $var; }
396                                                         else { sprintf"0%Xh",$var; }
397                                                     };  
398
399                                     $sz =~ tr/bvlq/BWDQ/;
400                                     $self->{value} = "\tD$sz\t";
401                                     for (@arr) { $self->{value} .= &$conv($_).","; }
402                                     $self->{value} .= &$conv($last);
403                                     last;
404                                   };
405                 /\.picmeup/ && do { $self->{value} = sprintf"\tDD\t 0%Xh,090000000h",$opcode{$line};
406                                     last;
407                                   };
408                 /\.asciz/   && do { if ($line =~ /^"(.*)"$/) {
409                                         my @str=unpack("C*",$1);
410                                         push @str,0;
411                                         while ($#str>15) {
412                                             $self->{value}.="DB\t"
413                                                 .join(",",@str[0..15])."\n";
414                                             foreach (0..15) { shift @str; }
415                                         }
416                                         $self->{value}.="DB\t"
417                                                 .join(",",@str) if (@str);
418                                     }
419                                     last;
420                                   };
421             }
422             $line = "";
423         }
424
425         $ret;
426     }
427     sub out {
428         my $self = shift;
429         $self->{value};
430     }
431 }
432
433 while($line=<>) {
434
435     chomp($line);
436
437     $line =~ s|[#!].*$||;       # get rid of asm-style comments...
438     $line =~ s|/\*.*\*/||;      # ... and C-style comments...
439     $line =~ s|^\s+||;          # ... and skip white spaces in beginning
440
441     undef $label;
442     undef $opcode;
443     undef $dst;
444     undef $src;
445     undef $sz;
446
447     if ($label=label->re(\$line))       { print $label->out(); }
448
449     if (directive->re(\$line)) {
450         printf "%s",directive->out();
451     } elsif ($opcode=opcode->re(\$line)) { ARGUMENT: {
452
453         if ($src=register->re(\$line))  { opcode->size($src->size()); }
454         elsif ($src=const->re(\$line))  { }
455         elsif ($src=ea->re(\$line))     { }
456         elsif ($src=expr->re(\$line))   { }
457
458         last ARGUMENT if ($line !~ /^,/);
459
460         $line = substr($line,1); $line =~ s/^\s+//;
461
462         if ($dst=register->re(\$line))  { opcode->size($dst->size()); }
463         elsif ($dst=const->re(\$line))  { }
464         elsif ($dst=ea->re(\$line))     { }
465
466         } # ARGUMENT:
467
468         $sz=opcode->size();
469
470         if (defined($dst)) {
471             if (!$masm) {
472                 printf "\t%s\t%s,%s",   $opcode->out($dst->size()),
473                                         $src->out($sz),$dst->out($sz);
474             } else {
475                 printf "\t%s\t%s,%s",   $opcode->out(),
476                                         $dst->out($sz),$src->out($sz);
477             }
478         } elsif (defined($src)) {
479             printf "\t%s\t%s",$opcode->out(),$src->out($sz);
480         } else {
481             printf "\t%s",$opcode->out();
482         }
483     }
484
485     print $line,"\n";
486 }
487
488 print "\n$current_segment\tENDS\nEND\n" if ($masm);
489
490 close STDOUT;
491
492 #################################################
493 # Cross-reference x86_64 ABI "card"
494 #
495 #               Unix            Win64
496 # %rax          *               *
497 # %rbx          -               -
498 # %rcx          #4              #1
499 # %rdx          #3              #2
500 # %rsi          #2              -
501 # %rdi          #1              -
502 # %rbp          -               -
503 # %rsp          -               -
504 # %r8           #5              #3
505 # %r9           #6              #4
506 # %r10          *               *
507 # %r11          *               *
508 # %r12          -               -
509 # %r13          -               -
510 # %r14          -               -
511 # %r15          -               -
512
513 # (*)   volatile register
514 # (-)   preserved by callee
515 # (#)   Nth argument, volatile
516 #
517 # In Unix terms top of stack is argument transfer area for arguments
518 # which could not be accomodated in registers. Or in other words 7th
519 # [integer] argument resides at 8(%rsp) upon function entry point.
520 # 128 bytes above %rsp constitute a "red zone" which is not touched
521 # by signal handlers and can be used as temporal storage without
522 # allocating a frame.
523 #
524 # In Win64 terms N*8 bytes on top of stack is argument transfer area,
525 # which belongs to/can be overwritten by callee. N is the number of
526 # arguments passed to callee, *but* not less than 4! This means that
527 # upon function entry point 5th argument resides at 40(%rsp), as well
528 # as that 32 bytes from 8(%rsp) can always be used as temporal
529 # storage [without allocating a frame]. One can actually argue that
530 # one can assume a "red zone" above stack pointer under Win64 as well.
531 # Point is that at apparently no occasion Windows kernel would alter
532 # the area above user stack pointer in true asynchronous manner...
533 #
534 # All the above means that if assembler programmer adheres to Unix
535 # register and stack layout, but disregards the "red zone" existense,
536 # it's possible to use following prologue and epilogue to "gear" from
537 # Unix to Win64 ABI in leaf functions with not more than 6 arguments.
538 #
539 # omnipotent_function:
540 # ifdef WIN64
541 #       movq    %rdi,8(%rsp)
542 #       movq    %rsi,16(%rsp)
543 #       movq    %rcx,%rdi       ; if 1st argument is actually present
544 #       movq    %rdx,%rsi       ; if 2nd argument is actually ...
545 #       movq    %r8,%rdx        ; if 3rd argument is ...
546 #       movq    %r9,%rcx        ; if 4th argument ...
547 #       movq    40(%rsp),%r8    ; if 5th ...
548 #       movq    48(%rsp),%r9    ; if 6th ...
549 # endif
550 #       ...
551 # ifdef WIN64
552 #       movq    8(%rsp),%rdi
553 #       movq    16(%rsp),%rsi
554 # endif
555 #       ret