xref: /llvm-project/llvm/include/llvm/IR/PredIteratorCache.h (revision 6676f794dcdab9ad78d59e044dfdc355dc0916a2)
1 //===- PredIteratorCache.h - pred_iterator Cache ----------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the PredIteratorCache class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_IR_PREDITERATORCACHE_H
14 #define LLVM_IR_PREDITERATORCACHE_H
15 
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/IR/CFG.h"
20 #include "llvm/Support/Allocator.h"
21 
22 namespace llvm {
23 
24 /// PredIteratorCache - This class is an extremely trivial cache for
25 /// predecessor iterator queries.  This is useful for code that repeatedly
26 /// wants the predecessor list for the same blocks.
27 class PredIteratorCache {
28   /// Cached list of predecessors, allocated in Memory.
29   DenseMap<BasicBlock *, ArrayRef<BasicBlock *>> BlockToPredsMap;
30 
31   /// Memory - This is the space that holds cached preds.
32   BumpPtrAllocator Memory;
33 
34 public:
35   size_t size(BasicBlock *BB) { return get(BB).size(); }
36   ArrayRef<BasicBlock *> get(BasicBlock *BB) {
37     ArrayRef<BasicBlock *> &Entry = BlockToPredsMap[BB];
38     if (Entry.data())
39       return Entry;
40 
41     SmallVector<BasicBlock *, 32> PredCache(predecessors(BB));
42     BasicBlock **Data = Memory.Allocate<BasicBlock *>(PredCache.size());
43     std::copy(PredCache.begin(), PredCache.end(), Data);
44     Entry = ArrayRef(Data, PredCache.size());
45     return Entry;
46   }
47 
48   /// clear - Remove all information.
49   void clear() {
50     BlockToPredsMap.clear();
51     Memory.Reset();
52   }
53 };
54 
55 } // end namespace llvm
56 
57 #endif
58