Advertisement
Fare9

BasicBlockExtractorFromIR.cpp

Apr 22nd, 2020
478
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.28 KB | None | 0 0
  1. #include "llvm/Bitcode/ReaderWriter.h"
  2. #include "llvm/IR/LLVMContext.h" // added to fix LLVMContext problem
  3. #include "llvm/IR/Function.h"
  4. #include "llvm/IR/Module.h"
  5. #include "llvm/Support/CommandLine.h"
  6. #include "llvm/Support/ErrorOr.h"
  7. #include "llvm/Support/MemoryBuffer.h"
  8. #include "llvm/Support/raw_ostream.h"
  9.  
  10. using namespace llvm;
  11.  
  12. // use of cl namespace (command line) for setting
  13. // a variable we need
  14. static cl::opt<std::string> FileName(cl::Positional, cl::desc("Bitcode file"), cl::Required);
  15.  
  16. int
  17. main(int argc, char **argv)
  18. {
  19.     // Parse the command line
  20.     cl::ParseCommandLineOptions(argc, argv, "LLVM Hello World\n");
  21.     LLVMContext context;
  22.  
  23.     // obtain the file to a MemoryBuffer
  24.     ErrorOr<std::unique_ptr<MemoryBuffer>> mb = MemoryBuffer::getFile(FileName);
  25.  
  26.     if (std::error_code ec = mb.getError())
  27.     {
  28.         errs() << ec.message();
  29.         return -1;
  30.     }
  31.  
  32.     // get the memory buffer and parse its bitcode (the compiled IR).
  33.     ErrorOr<Module *> m = parseBitcodeFile(mb->get(), context);
  34.     if (std::error_code ec = m.getError())
  35.     {
  36.         errs() << "Error reading bitcode: " << ec.message() << "\n";
  37.         return -1;
  38.     }
  39.  
  40.     // The module now contain all the functions
  41.     // from the code, and from each function
  42.     // we can extract name and basic blocks
  43.     for (Module::const_iterator I = (*m)->getFunctionList().begin(),
  44.          E = (*m)->getFunctionList().end(); I != E; ++I)
  45.     {
  46.         outs() << "Function: " << I->getName() << "(";  
  47.         for (Function::const_arg_iterator arg = I->getArgumentList().begin(),
  48.                 arg_end = I->getArgumentList().end(); arg != arg_end; ++arg)
  49.         {
  50.             arg->getType()->print(outs());
  51.             outs() << " %" << arg->getName();
  52.             if (arg->getNextNode() != arg_end)
  53.                 outs() << ",";
  54.         }
  55.         outs() << ")";
  56.  
  57.         if (!I->isDeclaration())
  58.         // if it's an internal declaration LLVM
  59.         // has analyzed how many basic blocks contain
  60.         {
  61.             outs() << " has " << I->size() << " basic blocks.\n";
  62.         }
  63.         // in other case is an external function
  64.         else
  65.         {
  66.             outs() << " is used but it's external to this code.\n";
  67.         }
  68.     }
  69.  
  70.     return 0;
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement