LLVM 源码分析(五)BasicBlockPass
namespace{ struct Hello1 : public BasicBlockPass { static char ID; // Pass identification, replacement for typeid Hello1() : BasicBlockPass(ID) {} virtual bool runOnBasicBlock(BasicBlock &BB) { errs() << "Hello1: "; errs().write_escaped(BB.getName()) << '\n'; return false; } bool doInitialization(Function &F){ // By default, don't do anything. errs()<<"BB doInitialization test"; return false; } };}char Hello1::ID = 0;static RegisterPass<Hello1> Z("hello1", "Hello World Pass");
下面是一段著名的dead code 删除代码
//===- DCE.cpp - Code to perform dead code elimination --------------------===////// The LLVM Compiler Infrastructure//// This file is distributed under the University of Illinois Open Source// License. See LICENSE.TXT for details.////===----------------------------------===////// This file implements dead inst elimination and dead code elimination.//// Dead Inst Elimination performs a single pass over the function removing// instructions that are obviously dead. Dead Code Elimination is similar, but// it rechecks instructions that were used by removed instructions to see if// they are newly dead.////===----------------------------------===//#define DEBUG_TYPE "dce"#include "llvm/Transforms/Scalar.h"#include "llvm/Transforms/Utils/Local.h"#include "llvm/Instruction.h"#include "llvm/Pass.h"#include "llvm/Support/InstIterator.h"#include "llvm/Target/TargetLibraryInfo.h"#include "llvm/ADT/Statistic.h"using namespace llvm;STATISTIC(DIEEliminated, "Number of insts removed by DIE pass");STATISTIC(DCEEliminated, "Number of insts removed");namespace { //===--------------------------------===// // DeadInstElimination pass implementation // struct DeadInstElimination : public BasicBlockPass { static char ID; // Pass identification, replacement for typeid DeadInstElimination() : BasicBlockPass(ID) { initializeDeadInstEliminationPass(*PassRegistry::getPassRegistry()); } virtual bool runOnBasicBlock(BasicBlock &BB) { TargetLibraryInfo *TLI = getAnalysisIfAvailable<TargetLibraryInfo>(); bool Changed = false; for (BasicBlock::iterator DI = BB.begin(); DI != BB.end(); ) { Instruction *Inst = DI++; if (isInstructionTriviallyDead(Inst, TLI)) { Inst->eraseFromParent(); Changed = true; ++DIEEliminated; } } return Changed; } virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesCFG(); } };}char DeadInstElimination::ID = 0;INITIALIZE_PASS(DeadInstElimination, "die", "Dead Instruction Elimination", false, false)Pass *llvm::createDeadInstEliminationPass() { return new DeadInstElimination();}