On Friday, January 05, 2018 04:16:48 Adam D. Ruppe via Digitalmars-d-learn wrote: > On Friday, 5 January 2018 at 04:10:54 UTC, Steven Schveighoffer > > wrote: > > The compiler assumes x is going to be 5 forever, so instead of > > loading the value at that address, it just loads 5 into a > > register (or maybe it just folds x == 5 into true). > > I was curious what dmd did, and the disassembly indeed shows it > just loads 5 into the register and leaves it there - assuming > since it is immutable, it will never change through any pointer > and thus never reloads it from memory at any time. > > Interestingly, dmd -O just stubs out the whole function. I guess > it assumes all the defined behavior actually accomplishes nothing > and it is free to optimize out undefined behavior... thus the > function needs no code. Similarly, if the last assert is changed > to x != 5, dmd -O doesn't even actually do a comparison (the > value 5 never appears in the generated code!), it just outputs > the direct call to assertion failure.
Well, it's certainly nice to see some evidence that the compiler really is taking advantage of the guarantees that immutable is supposed to provide. - Jonathan M Davis