Codegen overload

Some new features to improve the flexibility of code generation.

@mstimberg could you check this and merge into master asap? The changes are small and I think safe.