2017-07-30 95 views
0

看看C++內聯優化

func(int): 
    imul edi, edi 
    mov eax, edi 
    ret 
main: 
    push rbx 
    mov rdi, QWORD PTR [rsi+8] 
    mov rbx, rsi 
    mov edx, 10 
    xor esi, esi 
    call strtol 
    imul eax, eax 
    mov edi, OFFSET FLAT:std::cout 
    mov esi, eax 
    call std::basic_ostream<char, std::char_traits<char> >::operator<<(int) 
    mov rdi, QWORD PTR [rbx+16] 
    mov edx, 10 
    xor esi, esi 
    call strtol 
    imul eax, eax 
    mov edi, OFFSET FLAT:std::cout 
    mov esi, eax 
    call std::basic_ostream<char, std::char_traits<char> >::operator<<(int) 
    mov eax, 1 
    pop rbx 
    ret 
_GLOBAL__sub_I__Z4funci: 
    sub rsp, 8 
    mov edi, OFFSET FLAT:std::__ioinit 
    call std::ios_base::Init::Init() 
    mov edx, OFFSET FLAT:__dso_handle 
    mov esi, OFFSET FLAT:std::__ioinit 
    mov edi, OFFSET FLAT:std::ios_base::Init::~Init() 
    add rsp, 8 
    jmp __cxa_atexit 

顯INLINE我的例子here OR 以下C++ &匹配組件

IMPLICIT INLINE

#include <iostream> 

int func(int i) 
{ 
    return i * i; 
} 

int main(int argc, char *argv[]) { 

    auto value = atoi(argv[1]); 
    std::cout << func(value); 


    value = atoi(argv[2]); 
    std::cout << func(value); 

    return 1; 
} 

結果

#include <iostream> 

inline int func(int i) 
{ 
    return i * i; 
} 

int main(int argc, char *argv[]) { 

    auto value = atoi(argv[1]); 
    std::cout << func(value); 


    value = atoi(argv[2]); 
    std::cout << func(value); 

    return 1; 
} 

導致

main: 
    push rbx 
    mov rdi, QWORD PTR [rsi+8] 
    mov rbx, rsi 
    mov edx, 10 
    xor esi, esi 
    call strtol 
    imul eax, eax 
    mov edi, OFFSET FLAT:std::cout 
    mov esi, eax 
    call std::basic_ostream<char, std::char_traits<char> >::operator<<(int) 
    mov rdi, QWORD PTR [rbx+16] 
    mov edx, 10 
    xor esi, esi 
    call strtol 
    imul eax, eax 
    mov edi, OFFSET FLAT:std::cout 
    mov esi, eax 
    call std::basic_ostream<char, std::char_traits<char> >::operator<<(int) 
    mov eax, 1 
    pop rbx 
    ret 
_GLOBAL__sub_I_main: 
    sub rsp, 8 
    mov edi, OFFSET FLAT:std::__ioinit 
    call std::ios_base::Init::Init() 
    mov edx, OFFSET FLAT:__dso_handle 
    mov esi, OFFSET FLAT:std::__ioinit 
    mov edi, OFFSET FLAT:std::ios_base::Init::~Init() 
    add rsp, 8 
    jmp __cxa_atexit 

在該示例中,如果線路5被註釋的那樣,碼的最優化內聯函數「FUNC」在兩個調用點,但它留下的組件在生成的二進制文件中的func。但是,如果'func'被明確內聯,則該函數在輸出程序集中不存在。

爲什麼GCC的優化器離開隱含內聯函數在編譯的程序集,即使內聯函數的操作是真正與調用代碼內聯?

+0

在這裏發表您的代碼中的問題,請。如果你想得到我們的幫助,你應該盡我們的方便。 –

+0

裝配體如何?我使用Godbolt的原因是因爲它很容易證明發生的事情。 – tuskcode

+0

直接在問題中發佈代碼。像Godbolt這樣的外部資源鏈接是很好的演員。發佈一段代碼和一個鏈接都沒有問題。 –

回答

0

,如果它被標記static功能將完全消失。因爲它目前沒有標記爲static,所以它可能被另一個編譯單元引用,所以它不能被消除。