x86_64-xlate.pl commentary section update.
[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 open STDOUT,">$output" || die "can't open $output: $!";
61
62 my $masm=1 if ($output =~ /\.asm/);
63
64 my $current_segment;
65 my $current_function;
66
67 { package opcode;       # pick up opcodes
68     sub re {
69         my      $self = shift;  # single instance in enough...
70         local   *line = shift;
71         undef   $ret;
72
73         if ($line =~ /^([a-z]+)/i) {
74             $self->{op} = $1;
75             $ret = $self;
76             $line = substr($line,@+[0]); $line =~ s/^\s+//;
77
78             undef $self->{sz};
79             if ($self->{op} =~ /(movz)b.*/) {   # movz is pain...
80                 $self->{op} = $1;
81                 $self->{sz} = "b";
82             } elsif ($self->{op} =~ /([a-z]{3,})([qlwb])/) {
83                 $self->{op} = $1;
84                 $self->{sz} = $2;
85             }
86         }
87         $ret;
88     }
89     sub size {
90         my $self = shift;
91         my $sz   = shift;
92         $self->{sz} = $sz if (defined($sz) && !defined($self->{sz}));
93         $self->{sz};
94     }
95     sub out {
96         my $self = shift;
97         if (!$masm) {
98             if ($self->{op} eq "movz") {        # movz in pain...
99                 sprintf "%s%s%s",$self->{op},$self->{sz},shift;
100             } elsif ($self->{op} eq "ret") {
101                 ".byte  0xf3,0xc3";
102             } else {
103                 "$self->{op}$self->{sz}";
104             }
105         } else {
106             $self->{op} =~ s/movz/movzx/;
107             if ($self->{op} eq "ret") {
108                 $self->{op} = "";
109                 if ($current_function->{abi} eq "svr4") {
110                     $self->{op} = "mov  rdi,QWORD PTR 8[rsp]\t;WIN64 epilogue\n\t".
111                                   "mov  rsi,QWORD PTR 16[rsp]\n\t";
112                 }
113                 $self->{op} .= "DB\t0F3h,0C3h\t\t;repret";
114             }
115             $self->{op};
116         }
117     }
118 }
119 { package const;        # pick up constants, which start with $
120     sub re {
121         my      $self = shift;  # single instance in enough...
122         local   *line = shift;
123         undef   $ret;
124
125         if ($line =~ /^\$([^,]+)/) {
126             $self->{value} = $1;
127             $ret = $self;
128             $line = substr($line,@+[0]); $line =~ s/^\s+//;
129         }
130         $ret;
131     }
132     sub out {
133         my $self = shift;
134
135         if (!$masm) {
136             # Solaris /usr/ccs/bin/as can't handle multiplications
137             # in $self->{value}
138             $self->{value} =~ s/(?<![0-9a-f])(0[x0-9a-f]+)/oct($1)/egi;
139             $self->{value} =~ s/([0-9]+\s*[\*\/\%]\s*[0-9]+)/eval($1)/eg;
140             sprintf "\$%s",$self->{value};
141         } else {
142             $self->{value} =~ s/0x([0-9a-f]+)/0$1h/ig;
143             sprintf "%s",$self->{value};
144         }
145     }
146 }
147 { package ea;           # pick up effective addresses: expr(%reg,%reg,scale)
148     sub re {
149         my      $self = shift;  # single instance in enough...
150         local   *line = shift;
151         undef   $ret;
152
153         if ($line =~ /^([^\(,]*)\(([%\w,]+)\)/) {
154             $self->{label} = $1;
155             ($self->{base},$self->{index},$self->{scale})=split(/,/,$2);
156             $self->{scale} = 1 if (!defined($self->{scale}));
157             $ret = $self;
158             $line = substr($line,@+[0]); $line =~ s/^\s+//;
159
160             $self->{base}  =~ s/^%//;
161             $self->{index} =~ s/^%// if (defined($self->{index}));
162         }
163         $ret;
164     }
165     sub size {}
166     sub out {
167         my $self = shift;
168         my $sz = shift;
169
170         # Silently convert all EAs to 64-bit. This is required for
171         # elder GNU assembler and results in more compact code,
172         # *but* most importantly AES module depends on this feature!
173         $self->{index} =~ s/^[er](.?[0-9xpi])[d]?$/r\1/;
174         $self->{base}  =~ s/^[er](.?[0-9xpi])[d]?$/r\1/;
175
176         if (!$masm) {
177             # Solaris /usr/ccs/bin/as can't handle multiplications
178             # in $self->{label}
179             $self->{label} =~ s/(?<![0-9a-f])(0[x0-9a-f]+)/oct($1)/egi;
180             $self->{label} =~ s/([0-9]+\s*[\*\/\%]\s*[0-9]+)/eval($1)/eg;
181
182             if (defined($self->{index})) {
183                 sprintf "%s(%%%s,%%%s,%d)",
184                                         $self->{label},$self->{base},
185                                         $self->{index},$self->{scale};
186             } else {
187                 sprintf "%s(%%%s)",     $self->{label},$self->{base};
188             }
189         } else {
190             %szmap = ( b=>"BYTE", w=>"WORD", l=>"DWORD", q=>"QWORD" );
191
192             $self->{label} =~ s/\./\$/g;
193             $self->{label} =~ s/0x([0-9a-f]+)/0$1h/ig;
194             $self->{label} = "($self->{label})" if ($self->{label} =~ /[\*\+\-\/]/);
195
196             if (defined($self->{index})) {
197                 sprintf "%s PTR %s[%s*%d+%s]",$szmap{$sz},
198                                         $self->{label},
199                                         $self->{index},$self->{scale},
200                                         $self->{base};
201             } else {
202                 sprintf "%s PTR %s[%s]",$szmap{$sz},
203                                         $self->{label},$self->{base};
204             }
205         }
206     }
207 }
208 { package register;     # pick up registers, which start with %.
209     sub re {
210         my      $class = shift; # muliple instances...
211         my      $self = {};
212         local   *line = shift;
213         undef   $ret;
214
215         if ($line =~ /^%(\w+)/) {
216             bless $self,$class;
217             $self->{value} = $1;
218             $ret = $self;
219             $line = substr($line,@+[0]); $line =~ s/^\s+//;
220         }
221         $ret;
222     }
223     sub size {
224         my      $self = shift;
225         undef   $ret;
226
227         if    ($self->{value} =~ /^r[\d]+b$/i)  { $ret="b"; }
228         elsif ($self->{value} =~ /^r[\d]+w$/i)  { $ret="w"; }
229         elsif ($self->{value} =~ /^r[\d]+d$/i)  { $ret="l"; }
230         elsif ($self->{value} =~ /^r[\w]+$/i)   { $ret="q"; }
231         elsif ($self->{value} =~ /^[a-d][hl]$/i){ $ret="b"; }
232         elsif ($self->{value} =~ /^[\w]{2}l$/i) { $ret="b"; }
233         elsif ($self->{value} =~ /^[\w]{2}$/i)  { $ret="w"; }
234         elsif ($self->{value} =~ /^e[a-z]{2}$/i){ $ret="l"; }
235
236         $ret;
237     }
238     sub out {
239         my $self = shift;
240         sprintf $masm?"%s":"%%%s",$self->{value};
241     }
242 }
243 { package label;        # pick up labels, which end with :
244     sub re {
245         my      $self = shift;  # single instance is enough...
246         local   *line = shift;
247         undef   $ret;
248
249         if ($line =~ /(^[\.\w]+\:)/) {
250             $self->{value} = $1;
251             $ret = $self;
252             $line = substr($line,@+[0]); $line =~ s/^\s+//;
253
254             $self->{value} =~ s/\.L/\$L/ if ($masm);
255         }
256         $ret;
257     }
258     sub out {
259         my $self = shift;
260
261         if (!$masm) {
262             $self->{value};
263         } elsif ($self->{value} ne "$current_function->{name}:") {
264             $self->{value};
265         } elsif ($current_function->{abi} eq "svr4") {
266             my $func =  "$current_function->{name}      PROC\n".
267                         "       mov     QWORD PTR 8[rsp],rdi\t;WIN64 prologue\n".
268                         "       mov     QWORD PTR 16[rsp],rsi\n";
269             my $narg = $current_function->{narg};
270             $narg=6 if (!defined($narg));
271             $func .= "  mov     rdi,rcx\n" if ($narg>0);
272             $func .= "  mov     rsi,rdx\n" if ($narg>1);
273             $func .= "  mov     rdx,r8\n"  if ($narg>2);
274             $func .= "  mov     rcx,r9\n"  if ($narg>3);
275             $func .= "  mov     r8,QWORD PTR 40[rsp]\n" if ($narg>4);
276             $func .= "  mov     r9,QWORD PTR 48[rsp]\n" if ($narg>5);
277             $func .= "\n";
278         } else {
279            "$current_function->{name}   PROC";
280         }
281     }
282 }
283 { package expr;         # pick up expressioins
284     sub re {
285         my      $self = shift;  # single instance is enough...
286         local   *line = shift;
287         undef   $ret;
288
289         if ($line =~ /(^[^,]+)/) {
290             $self->{value} = $1;
291             $ret = $self;
292             $line = substr($line,@+[0]); $line =~ s/^\s+//;
293
294             $self->{value} =~ s/\.L/\$L/g if ($masm);
295         }
296         $ret;
297     }
298     sub out {
299         my $self = shift;
300         $self->{value};
301     }
302 }
303 { package directive;    # pick up directives, which start with .
304     sub re {
305         my      $self = shift;  # single instance is enough...
306         local   *line = shift;
307         undef   $ret;
308         my      $dir;
309         my      %opcode =       # lea 2f-1f(%rip),%dst; 1: nop; 2:
310                 (       "%rax"=>0x01058d48,     "%rcx"=>0x010d8d48,
311                         "%rdx"=>0x01158d48,     "%rbx"=>0x011d8d48,
312                         "%rsp"=>0x01258d48,     "%rbp"=>0x012d8d48,
313                         "%rsi"=>0x01358d48,     "%rdi"=>0x013d8d48,
314                         "%r8" =>0x01058d4c,     "%r9" =>0x010d8d4c,
315                         "%r10"=>0x01158d4c,     "%r11"=>0x011d8d4c,
316                         "%r12"=>0x01258d4c,     "%r13"=>0x012d8d4c,
317                         "%r14"=>0x01358d4c,     "%r15"=>0x013d8d4c      );
318
319         if ($line =~ /^\s*(\.\w+)/) {
320             if (!$masm) {
321                 $self->{value} = $1;
322                 $line =~ s/\@abi\-omnipotent/\@function/;
323                 $line =~ s/\@function.*/\@function/;
324                 if ($line =~ /\.picmeup\s+(%r[\w]+)/i) {
325                     $self->{value} = sprintf "\t.long\t0x%x,0x90000000",$opcode{$1};
326                 } else {
327                     $self->{value} = $line;
328                 }
329                 $line = "";
330                 return $self;
331             }
332
333             $dir = $1;
334             $ret = $self;
335             undef $self->{value};
336             $line = substr($line,@+[0]); $line =~ s/^\s+//;
337             SWITCH: for ($dir) {
338                 /\.(text)/
339                             && do { my $v=undef;
340                                     $v="$current_segment\tENDS\n" if ($current_segment);
341                                     $current_segment = "_$1\$";
342                                     $current_segment =~ tr/[a-z]/[A-Z]/;
343                                     $v.="$current_segment\tSEGMENT ALIGN(64) 'CODE'";
344                                     $self->{value} = $v;
345                                     last;
346                                   };
347                 /\.globl/   && do { $self->{value} = "PUBLIC\t".$line; last; };
348                 /\.type/    && do { ($sym,$type,$narg) = split(',',$line);
349                                     if ($type eq "\@function") {
350                                         undef $current_function;
351                                         $current_function->{name} = $sym;
352                                         $current_function->{abi}  = "svr4";
353                                         $current_function->{narg} = $narg;
354                                     } elsif ($type eq "\@abi-omnipotent") {
355                                         undef $current_function;
356                                         $current_function->{name} = $sym;
357                                     }
358                                     last;
359                                   };
360                 /\.size/    && do { if (defined($current_function)) {
361                                         $self->{value}="$current_function->{name}\tENDP";
362                                         undef $current_function;
363                                     }
364                                     last;
365                                   };
366                 /\.align/   && do { $self->{value} = "ALIGN\t".$line; last; };
367                 /\.(byte|value|long|quad)/
368                             && do { my @arr = split(',',$line);
369                                     my $sz  = substr($1,0,1);
370                                     my $last = pop(@arr);
371
372                                     $sz =~ tr/bvlq/BWDQ/;
373                                     $self->{value} = "\tD$sz\t";
374                                     for (@arr) { $self->{value} .= sprintf"0%Xh,",oct; }
375                                     $self->{value} .= sprintf"0%Xh",oct($last);
376                                     last;
377                                   };
378                 /\.picmeup/ && do { $self->{value} = sprintf"\tDD\t 0%Xh,090000000h",$opcode{$line};
379                                     last;
380                                   };
381             }
382             $line = "";
383         }
384
385         $ret;
386     }
387     sub out {
388         my $self = shift;
389         $self->{value};
390     }
391 }
392
393 while($line=<>) {
394
395     chomp($line);
396
397     $line =~ s|[#!].*$||;       # get rid of asm-style comments...
398     $line =~ s|/\*.*\*/||;      # ... and C-style comments...
399     $line =~ s|^\s+||;          # ... and skip white spaces in beginning
400
401     undef $label;
402     undef $opcode;
403     undef $dst;
404     undef $src;
405     undef $sz;
406
407     if ($label=label->re(\$line))       { print $label->out(); }
408
409     if (directive->re(\$line)) {
410         printf "%s",directive->out();
411     } elsif ($opcode=opcode->re(\$line)) { ARGUMENT: {
412
413         if ($src=register->re(\$line))  { opcode->size($src->size()); }
414         elsif ($src=const->re(\$line))  { }
415         elsif ($src=ea->re(\$line))     { }
416         elsif ($src=expr->re(\$line))   { }
417
418         last ARGUMENT if ($line !~ /^,/);
419
420         $line = substr($line,1); $line =~ s/^\s+//;
421
422         if ($dst=register->re(\$line))  { opcode->size($dst->size()); }
423         elsif ($dst=const->re(\$line))  { }
424         elsif ($dst=ea->re(\$line))     { }
425
426         } # ARGUMENT:
427
428         $sz=opcode->size();
429
430         if (defined($dst)) {
431             if (!$masm) {
432                 printf "\t%s\t%s,%s",   $opcode->out($dst->size()),
433                                         $src->out($sz),$dst->out($sz);
434             } else {
435                 printf "\t%s\t%s,%s",   $opcode->out(),
436                                         $dst->out($sz),$src->out($sz);
437             }
438         } elsif (defined($src)) {
439             printf "\t%s\t%s",$opcode->out(),$src->out($sz);
440         } else {
441             printf "\t%s",$opcode->out();
442         }
443     }
444
445     print $line,"\n";
446 }
447
448 print "\n$current_segment\tENDS\nEND\n" if ($masm);
449
450 close STDOUT;
451
452 #################################################
453 # Cross-reference x86_64 ABI "card"
454 #
455 #               Unix            Win64
456 # %rax          *               *
457 # %rbx          -               -
458 # %rcx          #4              #1
459 # %rdx          #3              #2
460 # %rsi          #2              -
461 # %rdi          #1              -
462 # %rbp          -               -
463 # %rsp          -               -
464 # %r8           #5              #3
465 # %r9           #6              #4
466 # %r10          *               *
467 # %r11          *               *
468 # %r12          -               -
469 # %r13          -               -
470 # %r14          -               -
471 # %r15          -               -
472
473 # (*)   volatile register
474 # (-)   preserved by callee
475 # (#)   Nth argument, volatile
476 #
477 # In Unix terms top of stack is argument transfer area for arguments
478 # which could not be accomodated in registers. Or in other words 7th
479 # [integer] argument resides at 8(%rsp) upon function entry point.
480 # 128 bytes above %rsp constitute a "red zone" which is not touched
481 # by signal handlers and can be used as temporal storage without
482 # allocating a frame.
483 #
484 # In Win64 terms N*8 bytes on top of stack is argument transfer area,
485 # which belongs to/can be overwritten by callee. N is the number of
486 # arguments passed to callee, *but* not less than 4! This means that
487 # upon function entry point 5th argument resides at 40(%rsp), as well
488 # as that 32 bytes from 8(%rsp) can always be used as temporal
489 # storage [without allocating a frame]. One can actually argue that
490 # one can assume a "red zone" above stack pointer under Win64 as well.
491 # Point is that at apparently no accasion Windows would alter the area
492 # above stack pointer in true asynchronous manner...
493 #
494 # All the above means that if assembler programmer adheres to Unix
495 # register and stack layout, but disregards the "red zone" existense,
496 # it's possible to use following prologue and epilogue to "gear" from
497 # Unix to Win64 ABI in leaf functions with not more than 6 arguments.
498 #
499 # omnipotent_function:
500 # ifdef WIN64
501 #       movq    %rdi,8(%rsp)
502 #       movq    %rsi,16(%rsp)
503 #       movq    %rcx,%rdi       ; if 1st argument is actually present
504 #       movq    %rdx,%rsi       ; if 2nd argument is actually ...
505 #       movq    %r8,%rdx        ; if 3rd argument is ...
506 #       movq    %r9,%rcx        ; if 4th argument ...
507 #       movq    40(%rsp),%r8    ; if 5th ...
508 #       movq    48(%rsp),%r9    ; if 6th ...
509 # endif
510 #       ...
511 # ifdef WIN64
512 #       movq    8(%rsp),%rdi
513 #       movq    16(%rsp),%rsi
514 # endif
515 #       ret