LLVM  7.0.0
PhiValues.cpp
Go to the documentation of this file.
1 //===- PhiValues.cpp - Phi Value Analysis ---------------------------------===//
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 
11 #include "llvm/ADT/SmallPtrSet.h"
12 #include "llvm/ADT/SmallVector.h"
13 #include "llvm/IR/Instructions.h"
14 
15 using namespace llvm;
16 
19  // PhiValues is invalidated if it isn't preserved.
20  auto PAC = PA.getChecker<PhiValuesAnalysis>();
21  return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>());
22 }
23 
24 // The goal here is to find all of the non-phi values reachable from this phi,
25 // and to do the same for all of the phis reachable from this phi, as doing so
26 // is necessary anyway in order to get the values for this phi. We do this using
27 // Tarjan's algorithm with Nuutila's improvements to find the strongly connected
28 // components of the phi graph rooted in this phi:
29 // * All phis in a strongly connected component will have the same reachable
30 // non-phi values. The SCC may not be the maximal subgraph for that set of
31 // reachable values, but finding out that isn't really necessary (it would
32 // only reduce the amount of memory needed to store the values).
33 // * Tarjan's algorithm completes components in a bottom-up manner, i.e. it
34 // never completes a component before the components reachable from it have
35 // been completed. This means that when we complete a component we have
36 // everything we need to collect the values reachable from that component.
37 // * We collect both the non-phi values reachable from each SCC, as that's what
38 // we're ultimately interested in, and all of the reachable values, i.e.
39 // including phis, as that makes invalidateValue easier.
40 void PhiValues::processPhi(const PHINode *Phi,
42  // Initialize the phi with the next depth number.
43  assert(DepthMap.lookup(Phi) == 0);
44  assert(NextDepthNumber != UINT_MAX);
45  unsigned int DepthNumber = ++NextDepthNumber;
46  DepthMap[Phi] = DepthNumber;
47 
48  // Recursively process the incoming phis of this phi.
49  for (Value *PhiOp : Phi->incoming_values()) {
50  if (PHINode *PhiPhiOp = dyn_cast<PHINode>(PhiOp)) {
51  // Recurse if the phi has not yet been visited.
52  if (DepthMap.lookup(PhiPhiOp) == 0)
53  processPhi(PhiPhiOp, Stack);
54  assert(DepthMap.lookup(PhiPhiOp) != 0);
55  // If the phi did not become part of a component then this phi and that
56  // phi are part of the same component, so adjust the depth number.
57  if (!ReachableMap.count(DepthMap[PhiPhiOp]))
58  DepthMap[Phi] = std::min(DepthMap[Phi], DepthMap[PhiPhiOp]);
59  }
60  }
61 
62  // Now that incoming phis have been handled, push this phi to the stack.
63  Stack.push_back(Phi);
64 
65  // If the depth number has not changed then we've finished collecting the phis
66  // of a strongly connected component.
67  if (DepthMap[Phi] == DepthNumber) {
68  // Collect the reachable values for this component. The phis of this
69  // component will be those on top of the depth stach with the same or
70  // greater depth number.
71  ConstValueSet Reachable;
72  while (!Stack.empty() && DepthMap[Stack.back()] >= DepthNumber) {
73  const PHINode *ComponentPhi = Stack.pop_back_val();
74  Reachable.insert(ComponentPhi);
75  DepthMap[ComponentPhi] = DepthNumber;
76  for (Value *Op : ComponentPhi->incoming_values()) {
77  if (PHINode *PhiOp = dyn_cast<PHINode>(Op)) {
78  // If this phi is not part of the same component then that component
79  // is guaranteed to have been completed before this one. Therefore we
80  // can just add its reachable values to the reachable values of this
81  // component.
82  auto It = ReachableMap.find(DepthMap[PhiOp]);
83  if (It != ReachableMap.end())
84  Reachable.insert(It->second.begin(), It->second.end());
85  } else {
86  Reachable.insert(Op);
87  }
88  }
89  }
90  ReachableMap.insert({DepthNumber,Reachable});
91 
92  // Filter out phis to get the non-phi reachable values.
93  ValueSet NonPhi;
94  for (const Value *V : Reachable)
95  if (!isa<PHINode>(V))
96  NonPhi.insert(const_cast<Value*>(V));
97  NonPhiReachableMap.insert({DepthNumber,NonPhi});
98  }
99 }
100 
102  if (DepthMap.count(PN) == 0) {
104  processPhi(PN, Stack);
105  assert(Stack.empty());
106  }
107  assert(DepthMap.lookup(PN) != 0);
108  return NonPhiReachableMap[DepthMap[PN]];
109 }
110 
112  // Components that can reach V are invalid.
113  SmallVector<unsigned int, 8> InvalidComponents;
114  for (auto &Pair : ReachableMap)
115  if (Pair.second.count(V))
116  InvalidComponents.push_back(Pair.first);
117 
118  for (unsigned int N : InvalidComponents) {
119  for (const Value *V : ReachableMap[N])
120  if (const PHINode *PN = dyn_cast<PHINode>(V))
121  DepthMap.erase(PN);
122  NonPhiReachableMap.erase(N);
123  ReachableMap.erase(N);
124  }
125 }
126 
128  DepthMap.clear();
129  NonPhiReachableMap.clear();
130  ReachableMap.clear();
131 }
132 
133 void PhiValues::print(raw_ostream &OS) const {
134  // Iterate through the phi nodes of the function rather than iterating through
135  // DepthMap in order to get predictable ordering.
136  for (const BasicBlock &BB : F) {
137  for (const PHINode &PN : BB.phis()) {
138  OS << "PHI ";
139  PN.printAsOperand(OS, false);
140  OS << " has values:\n";
141  unsigned int N = DepthMap.lookup(&PN);
142  auto It = NonPhiReachableMap.find(N);
143  if (It == NonPhiReachableMap.end())
144  OS << " UNKNOWN\n";
145  else if (It->second.empty())
146  OS << " NONE\n";
147  else
148  for (Value *V : It->second)
149  // Printing of an instruction prints two spaces at the start, so
150  // handle instructions and everything else slightly differently in
151  // order to get consistent indenting.
152  if (Instruction *I = dyn_cast<Instruction>(V))
153  OS << *I << "\n";
154  else
155  OS << " " << *V << "\n";
156  }
157  }
158 }
159 
160 AnalysisKey PhiValuesAnalysis::Key;
162  return PhiValues(F);
163 }
164 
167  OS << "PHI Values for function: " << F.getName() << "\n";
169  for (const BasicBlock &BB : F)
170  for (const PHINode &PN : BB.phis())
171  PI.getValuesForPhi(&PN);
172  PI.print(OS);
173  return PreservedAnalyses::all();
174 }
175 
178 }
179 
181  Result.reset(new PhiValues(F));
182  return false;
183 }
184 
186  Result->releaseMemory();
187 }
188 
190  AU.setPreservesAll();
191 }
192 
193 char PhiValuesWrapperPass::ID = 0;
194 
195 INITIALIZE_PASS(PhiValuesWrapperPass, "phi-values", "Phi Values Analysis", false,
196  true)
void releaseMemory()
Free the memory used by this class.
Definition: PhiValues.cpp:127
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:687
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
void releaseMemory() override
releaseMemory() - This member can be implemented by a pass if it wants to be able to release its memo...
Definition: PhiValues.cpp:185
F(f)
const ValueSet & getValuesForPhi(const PHINode *PN)
Get the underlying values of a phi.
Definition: PhiValues.cpp:101
The analysis pass which yields a PhiValues.
Definition: PhiValues.h:103
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
Definition: PassManager.h:304
Wrapper pass for the legacy pass manager.
Definition: PhiValues.h:126
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Definition: PhiValues.cpp:189
bool invalidate(Function &, const PreservedAnalyses &, FunctionAnalysisManager::Invalidator &)
Handle invalidation events in the new pass manager.
Definition: PhiValues.cpp:17
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:153
LLVM Basic Block Representation.
Definition: BasicBlock.h:59
void invalidateValue(const Value *V)
Notify PhiValues that the cached information using V is no longer valid.
Definition: PhiValues.cpp:111
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:371
Represent the analysis usage information of a pass.
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:285
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:159
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:34
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:418
PhiValues run(Function &F, FunctionAnalysisManager &)
Definition: PhiValues.cpp:161
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:847
bool runOnFunction(Function &F) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass...
Definition: PhiValues.cpp:180
LLVM_NODISCARD T pop_back_val()
Definition: SmallVector.h:381
void setPreservesAll()
Set by analyses that do not transform their input at all.
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Definition: PhiValues.cpp:165
void print(raw_ostream &OS) const
Print out the values currently in the cache.
Definition: PhiValues.cpp:133
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:56
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:224
Class for calculating and caching the underlying values of phis in a function.
Definition: PhiValues.h:43
#define I(x, y, z)
Definition: MD5.cpp:58
#define N
API to communicate dependencies between analyses during invalidation.
Definition: PassManager.h:559
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This templated class represents "all analyses that operate over <a particular IR unit>" (e...
Definition: PassManager.h:91
LLVM Value Representation.
Definition: Value.h:73
void initializePhiValuesWrapperPassPass(PassRegistry &)
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:46
A container for analyses that lazily runs them and caches their results.
op_range incoming_values()
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition: PassManager.h:70
PhiValues(const Function &F)
Construct an empty PhiValues.
Definition: PhiValues.h:48