How to register a pass at -O3 optimization level?

I want to register this pass - llvm-project/Hello.cpp at main · llvm/llvm-project · GitHub at -O3 i.e. it should run whenever -O3 is passed.

Where should I register Hello to be run at -O3?

The code you showed is a legacy Pass. There are two ways to do that:

  1. Use llvm::RegisterStandardPasses instead of RegisterPass. So you will do something like
static llvm::RegisterStandardPasses Y(
    llvm::PassManagerBuilder::EP_EarlyAsPossible,
    [](const llvm::PassManagerBuilder &Builder,
       llvm::legacy::PassManagerBase &PM) { 
         if (Builder.OptLevel >= 3)
           PM.add(new Hello());
       });
  1. Modify in-tree source code. More specifically, changing functions like PassManagerBuilder::populateFunctionPassManager in lib/Transforms/IPO/PassManagerBuilder.cpp to add Hello when OptLevel is greater or equal than 3.

If you’re working on a new PassManager Pass, you can achieve (1) by using callbacks in llvm::PassBuilder, for instance PassBuilder::registerOptimizerLastEPCallback, to register the Pass upon certain optimization level at a specific position in the Pass pipeline.

4 Likes

You can also take a look at the OpcodeCounter example from llvm-tutor. It’s not specifically for -O3, but close :slight_smile:

2 Likes

Hello @mshockwave

Thanks for the detailed reply. I want to register SeparateConstOffsetFromGEPPass at -O3 under new pass manager.

I could not understand pass registration under new PM PassBuilder::registerOptimizerLastEPCallback - llvm-project/NewPMDriver.cpp at 092601d4baab7c13c06b31eda2d5bed91d9a6b65 · llvm/llvm-project · GitHub as there is no opt level where I could do -

PM.add(createSeparateConstOffsetFromGEPPass(true));

Actually I want to register this pass at -O3 - llvm-project/SeparateConstOffsetFromGEP.cpp at main · llvm/llvm-project · GitHub

[2] seems for old pass manager.

Does this work?

    PB.registerOptimizerLastEPCallback(
        [&PB](ModulePassManager &PM, OptimizationLevel OptLevel) {
          if (OptLevel == OptimizationLevel::O3)
            PM.addPass(SeparateConstOffsetFromGEPPass(true));
        });
3 Likes

@aeubanks - Thanks for the suggestion. I could register the pass now but at different place since

I can add SeparateConstOffsetFromGEPPass just after AggressiveInstCombinePass in PassBuilderPipelines.cpp at this location - llvm-project/PassBuilderPipelines.cpp at 237df15c089d4d66ced7c5ba3b91eeda2d9b4fde · llvm/llvm-project · GitHub

I am getting regression due to it.

What is the ideal place in -O3 pipeline for SeparateConstOffsetFromGEPPass to be added? Should it be just after AggressiveInstCombinePass or should it be at the bottom of the pipeline?