[Mono-dev] Inline assembly in C#

Jonathan Pryor jonpryor at vt.edu
Tue May 30 16:16:41 UTC 2017


Reply inline:

On May 28, 2017, at 10:42 AM, Miguel de Icaza via Mono-devel-list <mono-devel-list at lists.dot.net> wrote:
...
> This would require some changes to the language, but it would look something like this:
> 
> public int ReturnOne ()  {
>    x86 {
>       mov $1, rax
>    }
>    ppc {
>       li r3, 1
>    }
> }

Much as I’d hate to start syntax bikeshedding, I don’t like this syntax:

1. It makes it hard to easily grep for uses of inline assembly
2. I think it would require too much “architecture hardcoding” into the compiler
3. As-is, I don’t see how I could provide an “IL fallback” path

(1) and (2) could be solved by using `asm “architecture”` instead:

	asm “x86” {mov $1, rax}

but that leaves (3): how do you support conditional code flow between inline-assembly and “normal” code? How could you have a “fallback” codepath?

The original class-based design supported this:

	if (asm.x64supported) { asm.x64 (“mov $1, rax”);
	else if (asm.x86supported) {asm.x86 (“mov $1, eax”);
	else if (asm.ppcsupported) {asm.ppc (“li r3, 1”);
	else {
		// new/unknown architecture; write the code in IL
	}

I can think of two ways to support IL fallbacks:

1. Treat “asm architecture” as an `if`, allowing `else asm:

	asm “x86” { mov $1, rax }
	else asm “ppc” {li r3, 1}
	else { /* IL */ }

2. Instead of `asm architecture`, rely on conditional compilation:

	#if x86
		asm { mov $1, rax }
	#elif ppc
		asm { li r3, 1 }
	#else
		/* new/unknown arch; default IL fallback */
	#endif

This could get ugly quick, but perhaps such ugliness is a *good* thing?

Additionally, “IL fallback” isn’t *just* for IL fallbacks; it’s for *intermixing* inline assembly with normal code within the same body.

Finally, methods should be marked as `unsafe` in order to use inline assembly.

 - Jon



More information about the Mono-devel-list mailing list