Adding IR optimization support

LLVM provides a wide variety of optimization passes. LLVM allows a compiler implementation to decide which optimizations to use, their order, and so on. In this recipe, you will learn how to add IR optimization support.

How to do it…

Do the following steps:

  1. To start with the addition of IR optimization support, first of all a static variable for function manager has to be defined as follows:
    static FunctionPassManager *Global_FP;
  2. Then, a function pass manager needs to be defined for the Module object used previously. This can be done in the main() function as follows:
    FunctionPassManager My_FP(TheModule);
  3. Now a pipeline of various optimizer passes can be added in the main() function as follows:
    My_FP.add(createBasicAliasAnalysisPass());
    My_FP.add(createInstructionCombiningPass());
    My_FP.add(createReassociatePass());
    My_FP.add(createGVNPass());
    My_FP.doInitialization();
  4. Now the static global function Pass Manager is assigned to this pipeline as follows:
    Global_FP = &My_FP;
    Driver();

    This PassManager has a run method, which we can run on the function IR generated before returning from Codegen() of the function definition. This is demonstrated as follows:

    Function* FunctionDefnAST::Codegen() {
      Named_Values.clear();
      Function *TheFunction = Func_Decl->Codegen();
      if (!TheFunction) return 0;
      BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
      Builder.SetInsertPoint(BB);
      if (Value* Return_Value = Body->Codegen()) {
        Builder.CreateRet(Return_Value);
        verifyFunction(*TheFunction);
        Global_FP->run(*TheFunction);
        returnTheFunction;
      }
      TheFunction->eraseFromParent();
      return 0;
    }

This is a lot more beneficial as it optimizes the function in place, improving the code generated for the function body.

See also

  • How to add our own optimization pass and its run method will be demonstrated in the later chapters
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.163.62