简体   繁体   English

使用尾调用优化打印换行符

[英]print a newline using tail call optimization

There's this unanswered question in the Igor Zhirkov's book Low-Level Programming : Igor Zhirkov 的《低级编程》一书中有一个未回答的问题:

"Try to rewrite print_newline without calling print_char or copying its code. Hint: read about tail call optimization.". “尝试在不调用 print_char 或复制其代码的情况下重写 print_newline。提示:阅读有关尾调用优化的信息。”。

I've spent some times reading about tail call optimization, but I can't figure out what would be the proper way of doing it.我花了一些时间阅读关于尾调用优化的文章,但我不知道什么是正确的做法。

Original code (without tail-call): print_newline => print_char => print_string=>string_length=>print_string原始代码(无尾调用): print_newline => print_char => print_string=>string_length=>print_string

string_length:
    xor rax, rax
.loop:
    cmp byte [rdi+rax], 0   ; if rdi =  0 (not an address), then seg fault
    je .end 
    inc rax
    jmp .loop 
.end:
    ret
print_string:
    push rdi
    call string_length
    pop rsi
    mov rdx, rax
    mov rax, 1
    mov rdi, 1
    syscall
    ret
print_char:
    push rdi
    mov rdi, rsp 
    call print_string 
    pop rdi
    ret
print_newline:
    mov rdi, 10
    jmp print_char

What could be a tail-call optimization of that?什么是尾调用优化?

For the sake of reference I will provide the solution in this thread too.为了参考,我也会在这个线程中提供解决方案。

  1. Without optimizations没有优化
print_newline:
    mov rdi, 10
    call print_char
    ret
print_char:
    push rdi
    mov rdi, rsp 
    call print_string 
    pop rdi
    ret
  1. A tail call optimization.尾调用优化。 A sequence of instructions call X and ret can always be substituted by jmp X .一系列指令call Xret总是可以用jmp X代替。
print_newline:
    mov rdi, 10
    jmp print_char
print_char:
    push rdi
    mov rdi, rsp 
    call print_string 
    pop rdi
    ret
  1. Just falling into print_char ;刚刚落入print_char basically making a subroutine with two entry points.基本上制作一个有两个入口点的子程序。
print_newline:
    mov rdi, 10
print_char:
    push rdi
    mov rdi, rsp 
    call print_string 
    pop rdi
    ret

Here is a more in-depth explanation in my blog 这是我的博客中更深入的解释

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM