Compile time macro trouble.

Lass Safin via digitalmars-d-ldc digitalmars-d-ldc at puremagic.com
Sun Mar 13 05:52:01 PDT 2016


On Sunday, 13 March 2016 at 06:15:34 UTC, Taylor Hillegeist wrote:
>
> So here: https://dlang.org/pretod.html
> there is a lovely section about how doing normal functions is 
> basically a processor macro.
>
> The C Preprocessor Way:
> #define X(i)	((i) = (i) / 3)
>
> The D Way:
> int X(ref int i) { return i = i / 3; }
>
> However I am running into troubles with the truthfulness of 
> this on LDC for thumb cortex-m0plus.
>
> MKL25Z.d
> line 5243:
> uint32_t SIM_SOPT2_TPMSRC(uint32_t x)  {return ((x << 
> SIM_SOPT2_TPMSRC_SHIFT) & SIM_SOPT2_TPMSRC_MASK);}
> [...]
> Is this an error on ldc's part or do i need to do something 
> more to get the correct result?

Try using DMD, it may just be a bug in LDC.
In DMD you can also force inline with the attribute 
pragma(inline, true) (or force it not to with pragma(inline, 
false).

Another thing: I wouldn't use ref here. Do it like this instead:

int X(int i) { return i = i / 3; }

int i = 491;
i = X(i);

If you look at the assembly which LDC generates you see this:

mangled_name:
movl    (%rdi), %eax
shll    $2, %eax
retq

As you can see, it dereferences a pointer inside %rdi, which 
means when you call the function, a pointer gets send to it. This 
means a the caller has to push the value onto the stack (or 
heap). This costs precious cycles. The callee also has to load 
the value from memory.

This may also be why it isn't inlined. Perhaps LLVM detects that 
inlining it won't improve performance, so it refrains from 
increasing the code size.


More information about the digitalmars-d-ldc mailing list