This fixes the bug(s) originally described on llvm-dev in November (with some more discussion in the last couple of days):
http://lists.llvm.org/pipermail/llvm-dev/2016-November/106955.html
As described by @mehdi_amini in his reply, the approach here is to recursively propagate the address space of the global through the allocas uses, instead of introducing a potentially illegal addrspacecast.
Apologies for any obvious issues with either the approach or the style, I'm a first time contributor to LLVM. One thing in particular I'm not sure about is where I had to modify test2 to check for the nonnull attribute as well - I couldn't work out how to correctly retain the original function attributes.
Nit: Don't repeat the name of the function in the comment, we use to do this but we changed the doxygen settings some time ago and this is deprecated.