Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimizer optimizes and breaks hand-written assembly code #880

Open
zzarko opened this issue Feb 23, 2025 · 4 comments
Open

Optimizer optimizes and breaks hand-written assembly code #880

zzarko opened this issue Feb 23, 2025 · 4 comments

Comments

@zzarko
Copy link
Collaborator

zzarko commented Feb 23, 2025

When writing this function, I came to a weird bug where optimizer changes my ASM code and makes something that does not work.

function ChangeByte(value: byte):byte;
var temp: byte;
begin
	asm("
		lda localVariable_ScreenUtil_ChangeByte_ScreenUtil_value
		nop ; added just to fool TRSE's optimization that messes up above LDA instruction
		tay
		lsr
		tya
		ror
		tay
		lsr
		tya
		ror
		and #$CC
		tax

		lda localVariable_ScreenUtil_ChangeByte_ScreenUtil_value
		nop ; added just to fool TRSE's optimization that messes up above LDA instruction
		tay
		asl
		tya
		rol
		tay
		asl
		tya
		rol
		and #$33
		sta localVariable_ScreenUtil_ChangeByte_ScreenUtil_temp
		txa
		ora localVariable_ScreenUtil_ChangeByte_ScreenUtil_temp
	");
end;

I have added two NOPs to stop optimizer from messing up the code. If NOPs are removed, previous LDA instructions are changed to LDY and code does not work as intended anymore.

@AndyHOvine
Copy link
Collaborator

AndyHOvine commented Feb 23, 2025

Try adding ;keep to the end of the lines you don't want trse to optimise away...

Lda var;keep
Or
Lda var ;keep

Tay;keep

Etc

@zzarko
Copy link
Collaborator Author

zzarko commented Feb 23, 2025

@AndyHOvine I just tried to put ";keep", but unfortunately it still changes the instruction to LDY. I'm keeping NOP for now.

@AndyHOvine
Copy link
Collaborator

Try it with, or without a space. I can't remember which.

@AndyHOvine
Copy link
Collaborator

AndyHOvine commented Feb 24, 2025

I've had time to test it, hope this helps :)

	asm ; problem example
		
		lda i
		tax
		lsr
		txa
		ror
		
	end;

produces:

		ldx i ; optimized, look out for bugs
		lsr
		txa
		ror

Whereas,

	asm ; fixed example
		
		lda i
		tax;keep
		lsr
		txa
		ror
		
	end;

produces:

		lda i
		tax;keep
		lsr
		txa
		ror

tax has not been removed and lda is preserved.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants