Skip to content

Instantly share code, notes, and snippets.

@zamabuvaraeu
Last active February 12, 2024 15:15
Show Gist options
  • Select an option

  • Save zamabuvaraeu/f7edeacaabbdcbada579bf9e18958d5f to your computer and use it in GitHub Desktop.

Select an option

Save zamabuvaraeu/f7edeacaabbdcbada579bf9e18958d5f to your computer and use it in GitHub Desktop.
Оптимизирующий компилятор удалил вызов функции

Оптимизации

Как компилятор удаляет вызовы функций.

Исходный код

Посмотрим код на бейсике, который вычисляет факториал числа:

' Для использования форматированного вывода
#include once "crt.bi"

Private Function FactorialTailRecursive(ByVal X As Integer, ByVal Accumulator As Integer)As Integer
	
	If X = 0 Then
		Return Accumulator
	End If
	
	Dim Steps As Integer = X - 1
	Dim Prod As Integer = Accumulator * X
	
	Return FactorialTailRecursive(Steps, Prod)
	
End Function

Private Function Factorial(ByVal X As Integer)As Integer
	
	Dim Prod As Integer = FactorialTailRecursive(X, 1)
	
	Return Prod
	
End Function

Dim argument As Integer = 8
Dim fact As Integer = Factorial(argument)

' Выводим на консоль:
printf(!"%d! = %d\r\n", argument, fact)

Вывод программы

8! =  40320

Ассемблерный код

Как видно, никаких вызовов функций в ассемблерном коде не осталось, компилятор вычислил факториал числа 8 и подставил его в выражение (Lorem Ipsum удалён):

	.intel_syntax noprefix
	.text
	.def	__main;	.scl	2;	.type	32;	.endef
	.section .rdata,"dr"
.LC0:
	.ascii "%d! = %d\15\12\0"
	.section	.text.startup,"x"
	.p2align 4
	.globl	main
	.def	main;	.scl	2;	.type	32;	.endef
main:
# компиляторные подготовления 
	push	r13
	push	r12
	sub	rsp, 40
	mov	r12d, ecx
	mov	r13, rdx
	call	__main
	xor	r8d, r8d
	mov	rdx, r13
	mov	ecx, r12d
	call	fb_Init

# вывод на консоль
	mov	r8d, 40320
	mov	edx, 8
	lea	rcx, .LC0[rip]
	call	printf

# выход из программы
	xor	ecx, ecx
	call	fb_End
	xor	eax, eax
	add	rsp, 40
	pop	r12
	pop	r13
	ret

Параметры компиляции

fbc64.exe -gen gcc -O 3 file.bas
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment