Hello.cpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. //===- Hello.cpp - Example code from "Writing an LLVM Pass" ---------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements two versions of the LLVM "Hello World" pass described
  11. // in docs/WritingAnLLVMPass.html
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/ADT/Statistic.h"
  15. #include "llvm/IR/Function.h"
  16. #include "llvm/Pass.h"
  17. #include "llvm/Support/raw_ostream.h"
  18. using namespace llvm;
  19. #define DEBUG_TYPE "hello"
  20. STATISTIC(HelloCounter, "Counts number of functions greeted");
  21. namespace {
  22. // Hello - The first implementation, without getAnalysisUsage.
  23. struct Hello : public FunctionPass {
  24. static char ID; // Pass identification, replacement for typeid
  25. Hello() : FunctionPass(ID) {}
  26. bool runOnFunction(Function &F) override {
  27. ++HelloCounter;
  28. errs() << "Hello: ";
  29. errs().write_escaped(F.getName()) << '\n';
  30. return false;
  31. }
  32. };
  33. }
  34. char Hello::ID = 0;
  35. static RegisterPass<Hello> X("hello", "Hello World Pass");
  36. namespace {
  37. // Hello2 - The second implementation with getAnalysisUsage implemented.
  38. struct Hello2 : public FunctionPass {
  39. static char ID; // Pass identification, replacement for typeid
  40. Hello2() : FunctionPass(ID) {}
  41. bool runOnFunction(Function &F) override {
  42. ++HelloCounter;
  43. errs() << "Hello: ";
  44. errs().write_escaped(F.getName()) << '\n';
  45. return false;
  46. }
  47. // We don't modify the program, so we preserve all analyses.
  48. void getAnalysisUsage(AnalysisUsage &AU) const override {
  49. AU.setPreservesAll();
  50. }
  51. };
  52. }
  53. char Hello2::ID = 0;
  54. static RegisterPass<Hello2>
  55. Y("hello2", "Hello World Pass (with getAnalysisUsage implemented)");