PredIteratorCache.h 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. //===- PredIteratorCache.h - pred_iterator Cache ----------------*- C++ -*-===//
  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 defines the PredIteratorCache class.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #ifndef LLVM_IR_PREDITERATORCACHE_H
  14. #define LLVM_IR_PREDITERATORCACHE_H
  15. #include "llvm/ADT/ArrayRef.h"
  16. #include "llvm/ADT/DenseMap.h"
  17. #include "llvm/ADT/SmallVector.h"
  18. #include "llvm/IR/CFG.h"
  19. #include "llvm/Support/Allocator.h"
  20. namespace llvm {
  21. /// PredIteratorCache - This class is an extremely trivial cache for
  22. /// predecessor iterator queries. This is useful for code that repeatedly
  23. /// wants the predecessor list for the same blocks.
  24. class PredIteratorCache {
  25. /// BlockToPredsMap - Pointer to null-terminated list.
  26. DenseMap<BasicBlock *, BasicBlock **> BlockToPredsMap;
  27. DenseMap<BasicBlock *, unsigned> BlockToPredCountMap;
  28. /// Memory - This is the space that holds cached preds.
  29. BumpPtrAllocator Memory;
  30. private:
  31. /// GetPreds - Get a cached list for the null-terminated predecessor list of
  32. /// the specified block. This can be used in a loop like this:
  33. /// for (BasicBlock **PI = PredCache->GetPreds(BB); *PI; ++PI)
  34. /// use(*PI);
  35. /// instead of:
  36. /// for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
  37. BasicBlock **GetPreds(BasicBlock *BB) {
  38. BasicBlock **&Entry = BlockToPredsMap[BB];
  39. if (Entry)
  40. return Entry;
  41. SmallVector<BasicBlock *, 32> PredCache(pred_begin(BB), pred_end(BB));
  42. PredCache.push_back(nullptr); // null terminator.
  43. BlockToPredCountMap[BB] = PredCache.size() - 1;
  44. Entry = Memory.Allocate<BasicBlock *>(PredCache.size());
  45. std::copy(PredCache.begin(), PredCache.end(), Entry);
  46. return Entry;
  47. }
  48. unsigned GetNumPreds(BasicBlock *BB) {
  49. GetPreds(BB);
  50. return BlockToPredCountMap[BB];
  51. }
  52. public:
  53. size_t size(BasicBlock *BB) { return GetNumPreds(BB); }
  54. ArrayRef<BasicBlock *> get(BasicBlock *BB) {
  55. return makeArrayRef(GetPreds(BB), GetNumPreds(BB));
  56. }
  57. /// clear - Remove all information.
  58. void clear() {
  59. BlockToPredsMap.clear();
  60. BlockToPredCountMap.clear();
  61. Memory.Reset();
  62. }
  63. };
  64. } // end namespace llvm
  65. #endif