LLVM API Documentation

InstVisitor.h
Go to the documentation of this file.
00001 //===- InstVisitor.h - Instruction visitor templates ------------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 
00010 
00011 #ifndef LLVM_IR_INSTVISITOR_H
00012 #define LLVM_IR_INSTVISITOR_H
00013 
00014 #include "llvm/IR/CallSite.h"
00015 #include "llvm/IR/Function.h"
00016 #include "llvm/IR/Instructions.h"
00017 #include "llvm/IR/IntrinsicInst.h"
00018 #include "llvm/IR/Intrinsics.h"
00019 #include "llvm/IR/Module.h"
00020 #include "llvm/Support/ErrorHandling.h"
00021 
00022 namespace llvm {
00023 
00024 // We operate on opaque instruction classes, so forward declare all instruction
00025 // types now...
00026 //
00027 #define HANDLE_INST(NUM, OPCODE, CLASS)   class CLASS;
00028 #include "llvm/IR/Instruction.def"
00029 
00030 #define DELEGATE(CLASS_TO_VISIT) \
00031   return static_cast<SubClass*>(this)-> \
00032                visit##CLASS_TO_VISIT(static_cast<CLASS_TO_VISIT&>(I))
00033 
00034 
00035 /// @brief Base class for instruction visitors
00036 ///
00037 /// Instruction visitors are used when you want to perform different actions
00038 /// for different kinds of instructions without having to use lots of casts
00039 /// and a big switch statement (in your code, that is).
00040 ///
00041 /// To define your own visitor, inherit from this class, specifying your
00042 /// new type for the 'SubClass' template parameter, and "override" visitXXX
00043 /// functions in your class. I say "override" because this class is defined
00044 /// in terms of statically resolved overloading, not virtual functions.
00045 ///
00046 /// For example, here is a visitor that counts the number of malloc
00047 /// instructions processed:
00048 ///
00049 ///  /// Declare the class.  Note that we derive from InstVisitor instantiated
00050 ///  /// with _our new subclasses_ type.
00051 ///  ///
00052 ///  struct CountAllocaVisitor : public InstVisitor<CountAllocaVisitor> {
00053 ///    unsigned Count;
00054 ///    CountAllocaVisitor() : Count(0) {}
00055 ///
00056 ///    void visitAllocaInst(AllocaInst &AI) { ++Count; }
00057 ///  };
00058 ///
00059 ///  And this class would be used like this:
00060 ///    CountAllocaVisitor CAV;
00061 ///    CAV.visit(function);
00062 ///    NumAllocas = CAV.Count;
00063 ///
00064 /// The defined has 'visit' methods for Instruction, and also for BasicBlock,
00065 /// Function, and Module, which recursively process all contained instructions.
00066 ///
00067 /// Note that if you don't implement visitXXX for some instruction type,
00068 /// the visitXXX method for instruction superclass will be invoked. So
00069 /// if instructions are added in the future, they will be automatically
00070 /// supported, if you handle one of their superclasses.
00071 ///
00072 /// The optional second template argument specifies the type that instruction
00073 /// visitation functions should return. If you specify this, you *MUST* provide
00074 /// an implementation of visitInstruction though!.
00075 ///
00076 /// Note that this class is specifically designed as a template to avoid
00077 /// virtual function call overhead.  Defining and using an InstVisitor is just
00078 /// as efficient as having your own switch statement over the instruction
00079 /// opcode.
00080 template<typename SubClass, typename RetTy=void>
00081 class InstVisitor {
00082   //===--------------------------------------------------------------------===//
00083   // Interface code - This is the public interface of the InstVisitor that you
00084   // use to visit instructions...
00085   //
00086 
00087 public:
00088   // Generic visit method - Allow visitation to all instructions in a range
00089   template<class Iterator>
00090   void visit(Iterator Start, Iterator End) {
00091     while (Start != End)
00092       static_cast<SubClass*>(this)->visit(*Start++);
00093   }
00094 
00095   // Define visitors for functions and basic blocks...
00096   //
00097   void visit(Module &M) {
00098     static_cast<SubClass*>(this)->visitModule(M);
00099     visit(M.begin(), M.end());
00100   }
00101   void visit(Function &F) {
00102     static_cast<SubClass*>(this)->visitFunction(F);
00103     visit(F.begin(), F.end());
00104   }
00105   void visit(BasicBlock &BB) {
00106     static_cast<SubClass*>(this)->visitBasicBlock(BB);
00107     visit(BB.begin(), BB.end());
00108   }
00109 
00110   // Forwarding functions so that the user can visit with pointers AND refs.
00111   void visit(Module       *M)  { visit(*M); }
00112   void visit(Function     *F)  { visit(*F); }
00113   void visit(BasicBlock   *BB) { visit(*BB); }
00114   RetTy visit(Instruction *I)  { return visit(*I); }
00115 
00116   // visit - Finally, code to visit an instruction...
00117   //
00118   RetTy visit(Instruction &I) {
00119     switch (I.getOpcode()) {
00120     default: llvm_unreachable("Unknown instruction type encountered!");
00121       // Build the switch statement using the Instruction.def file...
00122 #define HANDLE_INST(NUM, OPCODE, CLASS) \
00123     case Instruction::OPCODE: return \
00124            static_cast<SubClass*>(this)-> \
00125                       visit##OPCODE(static_cast<CLASS&>(I));
00126 #include "llvm/IR/Instruction.def"
00127     }
00128   }
00129 
00130   //===--------------------------------------------------------------------===//
00131   // Visitation functions... these functions provide default fallbacks in case
00132   // the user does not specify what to do for a particular instruction type.
00133   // The default behavior is to generalize the instruction type to its subtype
00134   // and try visiting the subtype.  All of this should be inlined perfectly,
00135   // because there are no virtual functions to get in the way.
00136   //
00137 
00138   // When visiting a module, function or basic block directly, these methods get
00139   // called to indicate when transitioning into a new unit.
00140   //
00141   void visitModule    (Module &M) {}
00142   void visitFunction  (Function &F) {}
00143   void visitBasicBlock(BasicBlock &BB) {}
00144 
00145   // Define instruction specific visitor functions that can be overridden to
00146   // handle SPECIFIC instructions.  These functions automatically define
00147   // visitMul to proxy to visitBinaryOperator for instance in case the user does
00148   // not need this generality.
00149   //
00150   // These functions can also implement fan-out, when a single opcode and
00151   // instruction have multiple more specific Instruction subclasses. The Call
00152   // instruction currently supports this. We implement that by redirecting that
00153   // instruction to a special delegation helper.
00154 #define HANDLE_INST(NUM, OPCODE, CLASS) \
00155     RetTy visit##OPCODE(CLASS &I) { \
00156       if (NUM == Instruction::Call) \
00157         return delegateCallInst(I); \
00158       else \
00159         DELEGATE(CLASS); \
00160     }
00161 #include "llvm/IR/Instruction.def"
00162 
00163   // Specific Instruction type classes... note that all of the casts are
00164   // necessary because we use the instruction classes as opaque types...
00165   //
00166   RetTy visitReturnInst(ReturnInst &I)            { DELEGATE(TerminatorInst);}
00167   RetTy visitBranchInst(BranchInst &I)            { DELEGATE(TerminatorInst);}
00168   RetTy visitSwitchInst(SwitchInst &I)            { DELEGATE(TerminatorInst);}
00169   RetTy visitIndirectBrInst(IndirectBrInst &I)    { DELEGATE(TerminatorInst);}
00170   RetTy visitResumeInst(ResumeInst &I)            { DELEGATE(TerminatorInst);}
00171   RetTy visitUnreachableInst(UnreachableInst &I)  { DELEGATE(TerminatorInst);}
00172   RetTy visitICmpInst(ICmpInst &I)                { DELEGATE(CmpInst);}
00173   RetTy visitFCmpInst(FCmpInst &I)                { DELEGATE(CmpInst);}
00174   RetTy visitAllocaInst(AllocaInst &I)            { DELEGATE(UnaryInstruction);}
00175   RetTy visitLoadInst(LoadInst     &I)            { DELEGATE(UnaryInstruction);}
00176   RetTy visitStoreInst(StoreInst   &I)            { DELEGATE(Instruction);}
00177   RetTy visitAtomicCmpXchgInst(AtomicCmpXchgInst &I) { DELEGATE(Instruction);}
00178   RetTy visitAtomicRMWInst(AtomicRMWInst &I)      { DELEGATE(Instruction);}
00179   RetTy visitFenceInst(FenceInst   &I)            { DELEGATE(Instruction);}
00180   RetTy visitGetElementPtrInst(GetElementPtrInst &I){ DELEGATE(Instruction);}
00181   RetTy visitPHINode(PHINode       &I)            { DELEGATE(Instruction);}
00182   RetTy visitTruncInst(TruncInst &I)              { DELEGATE(CastInst);}
00183   RetTy visitZExtInst(ZExtInst &I)                { DELEGATE(CastInst);}
00184   RetTy visitSExtInst(SExtInst &I)                { DELEGATE(CastInst);}
00185   RetTy visitFPTruncInst(FPTruncInst &I)          { DELEGATE(CastInst);}
00186   RetTy visitFPExtInst(FPExtInst &I)              { DELEGATE(CastInst);}
00187   RetTy visitFPToUIInst(FPToUIInst &I)            { DELEGATE(CastInst);}
00188   RetTy visitFPToSIInst(FPToSIInst &I)            { DELEGATE(CastInst);}
00189   RetTy visitUIToFPInst(UIToFPInst &I)            { DELEGATE(CastInst);}
00190   RetTy visitSIToFPInst(SIToFPInst &I)            { DELEGATE(CastInst);}
00191   RetTy visitPtrToIntInst(PtrToIntInst &I)        { DELEGATE(CastInst);}
00192   RetTy visitIntToPtrInst(IntToPtrInst &I)        { DELEGATE(CastInst);}
00193   RetTy visitBitCastInst(BitCastInst &I)          { DELEGATE(CastInst);}
00194   RetTy visitAddrSpaceCastInst(AddrSpaceCastInst &I) { DELEGATE(CastInst);}
00195   RetTy visitSelectInst(SelectInst &I)            { DELEGATE(Instruction);}
00196   RetTy visitVAArgInst(VAArgInst   &I)            { DELEGATE(UnaryInstruction);}
00197   RetTy visitExtractElementInst(ExtractElementInst &I) { DELEGATE(Instruction);}
00198   RetTy visitInsertElementInst(InsertElementInst &I) { DELEGATE(Instruction);}
00199   RetTy visitShuffleVectorInst(ShuffleVectorInst &I) { DELEGATE(Instruction);}
00200   RetTy visitExtractValueInst(ExtractValueInst &I){ DELEGATE(UnaryInstruction);}
00201   RetTy visitInsertValueInst(InsertValueInst &I)  { DELEGATE(Instruction); }
00202   RetTy visitLandingPadInst(LandingPadInst &I)    { DELEGATE(Instruction); }
00203 
00204   // Handle the special instrinsic instruction classes.
00205   RetTy visitDbgDeclareInst(DbgDeclareInst &I)    { DELEGATE(DbgInfoIntrinsic);}
00206   RetTy visitDbgValueInst(DbgValueInst &I)        { DELEGATE(DbgInfoIntrinsic);}
00207   RetTy visitDbgInfoIntrinsic(DbgInfoIntrinsic &I) { DELEGATE(IntrinsicInst); }
00208   RetTy visitMemSetInst(MemSetInst &I)            { DELEGATE(MemIntrinsic); }
00209   RetTy visitMemCpyInst(MemCpyInst &I)            { DELEGATE(MemTransferInst); }
00210   RetTy visitMemMoveInst(MemMoveInst &I)          { DELEGATE(MemTransferInst); }
00211   RetTy visitMemTransferInst(MemTransferInst &I)  { DELEGATE(MemIntrinsic); }
00212   RetTy visitMemIntrinsic(MemIntrinsic &I)        { DELEGATE(IntrinsicInst); }
00213   RetTy visitVAStartInst(VAStartInst &I)          { DELEGATE(IntrinsicInst); }
00214   RetTy visitVAEndInst(VAEndInst &I)              { DELEGATE(IntrinsicInst); }
00215   RetTy visitVACopyInst(VACopyInst &I)            { DELEGATE(IntrinsicInst); }
00216   RetTy visitIntrinsicInst(IntrinsicInst &I)      { DELEGATE(CallInst); }
00217 
00218   // Call and Invoke are slightly different as they delegate first through
00219   // a generic CallSite visitor.
00220   RetTy visitCallInst(CallInst &I) {
00221     return static_cast<SubClass*>(this)->visitCallSite(&I);
00222   }
00223   RetTy visitInvokeInst(InvokeInst &I) {
00224     return static_cast<SubClass*>(this)->visitCallSite(&I);
00225   }
00226 
00227   // Next level propagators: If the user does not overload a specific
00228   // instruction type, they can overload one of these to get the whole class
00229   // of instructions...
00230   //
00231   RetTy visitCastInst(CastInst &I)                { DELEGATE(UnaryInstruction);}
00232   RetTy visitBinaryOperator(BinaryOperator &I)    { DELEGATE(Instruction);}
00233   RetTy visitCmpInst(CmpInst &I)                  { DELEGATE(Instruction);}
00234   RetTy visitTerminatorInst(TerminatorInst &I)    { DELEGATE(Instruction);}
00235   RetTy visitUnaryInstruction(UnaryInstruction &I){ DELEGATE(Instruction);}
00236 
00237   // Provide a special visitor for a 'callsite' that visits both calls and
00238   // invokes. When unimplemented, properly delegates to either the terminator or
00239   // regular instruction visitor.
00240   RetTy visitCallSite(CallSite CS) {
00241     assert(CS);
00242     Instruction &I = *CS.getInstruction();
00243     if (CS.isCall())
00244       DELEGATE(Instruction);
00245 
00246     assert(CS.isInvoke());
00247     DELEGATE(TerminatorInst);
00248   }
00249 
00250   // If the user wants a 'default' case, they can choose to override this
00251   // function.  If this function is not overloaded in the user's subclass, then
00252   // this instruction just gets ignored.
00253   //
00254   // Note that you MUST override this function if your return type is not void.
00255   //
00256   void visitInstruction(Instruction &I) {}  // Ignore unhandled instructions
00257 
00258 private:
00259   // Special helper function to delegate to CallInst subclass visitors.
00260   RetTy delegateCallInst(CallInst &I) {
00261     if (const Function *F = I.getCalledFunction()) {
00262       switch ((Intrinsic::ID)F->getIntrinsicID()) {
00263       default:                     DELEGATE(IntrinsicInst);
00264       case Intrinsic::dbg_declare: DELEGATE(DbgDeclareInst);
00265       case Intrinsic::dbg_value:   DELEGATE(DbgValueInst);
00266       case Intrinsic::memcpy:      DELEGATE(MemCpyInst);
00267       case Intrinsic::memmove:     DELEGATE(MemMoveInst);
00268       case Intrinsic::memset:      DELEGATE(MemSetInst);
00269       case Intrinsic::vastart:     DELEGATE(VAStartInst);
00270       case Intrinsic::vaend:       DELEGATE(VAEndInst);
00271       case Intrinsic::vacopy:      DELEGATE(VACopyInst);
00272       case Intrinsic::not_intrinsic: break;
00273       }
00274     }
00275     DELEGATE(CallInst);
00276   }
00277 
00278   // An overload that will never actually be called, it is used only from dead
00279   // code in the dispatching from opcodes to instruction subclasses.
00280   RetTy delegateCallInst(Instruction &I) {
00281     llvm_unreachable("delegateCallInst called for non-CallInst");
00282   }
00283 };
00284 
00285 #undef DELEGATE
00286 
00287 } // End llvm namespace
00288 
00289 #endif