Constants propagation into printf format string


I was thinking about a new possible simplification in InstCombine which would transform code like this:

const char * NAME = “Prog”;

void printer(char **arr, int len) {
for (int i = 0; i < len; ++i) {
printf(“%s: %s”, NAME, arr[i]);


void printer(char **arr, int len) {
for (int i = 0; i < len; ++i) {
printf(“Prog: %s”, arr[i]);

This transformation would take constant strings/integers/chars and put them to the format string.

In the example I used “printf” but it could be applied also for fprintf and sprintf.

Do you consider this as good to be implemented? Or not worth to do at all?

I implemented it some time ago personally just for fun to try it. I would reimplement it and send a patch to LLVM if any interest.

Ideas? Complains? Suggestions?


This is not a peephole optimization, therefore it doesn't belong to instcombine.
If you want to try to implement something like this, I'd recommend
taking a look at ConstantFolding or SCCP (and try to understand why
the value doesn't get propagated).


Thanks, I will look at it.

What? Transforming `printf("FOO: %s", "BAR")` to `printf("FOO: BAR")` looks like a peephole to me.


Apologies, I read the example incorrectly. I think you can probably
peephole easy cases like this.