I’m working on a whole program optimizer that uses LLVM as a library, and one of the things I want to do is eliminate dead global functions and variables even when they are not local to a module. (This understandably doesn’t happen by default because the optimizer has to assume it could be compiling a library rather than a program.)
I’ve actually written a function to do this, but then I came across InternalizePass which seems like it could allow my code to be discarded because it could flag globals as internal (in the presence of a main function, according to the documentation) which would allow the existing dead global elimination optimization pass to do the job.
It seems that InternalizePass is, again understandably, not enabled by default even when you select optimization level 3. How do you turn it on? I tried setting PrepareForLTO but that doesn’t seem to do anything. Here’s what I have so far:
legacy::FunctionPassManager FPM(&M);
legacy::PassManager MPM;
PassManagerBuilder Builder;
Builder.OptLevel = 3;
Builder.PrepareForLTO = true;
Builder.VerifyInput = true;
Builder.VerifyOutput = true;
Builder.populateFunctionPassManager(FPM);
Builder.populateModulePassManager(MPM);
FPM.doInitialization();
for (Function &F : M)
FPM.run(F);
FPM.doFinalization();
MPM.run(M);