Function Pass does not recognize IR built using -O0 optimization level but recognizes -O3 IR

I wrote a simple pass that should print the function body, basic blocks, and all instructions. When I compile my code (clang -O0 -emit-llvm globalVariablesInteger.c -S -o globalVariablesInteger.ll) , and run my pass on the IR, it does not print anything. However, when I do change the optimization level to -O3 it functions like its supposed to(prints Function body, basic block, etc.). Am I doing something wrong?

Here is my simple code

#include "llvm/Transforms/Utils/SafeRegion.h"
#include "llvm/Pass.h"
#include "llvm/IR/Function.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/IR/InstrTypes.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"

#include <map>

using namespace llvm;

namespace {
static bool safeRegion(Function &F) {

  bool changed = false;
  errs() << "Function body:\n" << F << "\n";
  for (auto& B : F) {
    errs() << "Basic block:\n" << B << "\n";
    for (auto& I : B) {
      errs() << "Instruction: " << I << "\n";
    }
  }
  return changed;
}
}

PreservedAnalyses SafeRegionPass::run(Function &F,
                                      FunctionAnalysisManager &AM) {
  if(!safeRegion(F))
    return PreservedAnalyses::all();
  return PreservedAnalyses::none();
}

The IR of functions generated by Clang at -O0 are annotated with optnone which prevents any optimizations / Passes from running. You can add -Xclang -disable-O0-optnone to disable this behavior.

1 Like

That worked!! Thank you so much