PhiValues.cpp 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. //===- PhiValues.cpp - Phi Value Analysis ---------------------------------===//
  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. #include "llvm/Analysis/PhiValues.h"
  9. #include "llvm/ADT/SmallVector.h"
  10. #include "llvm/IR/Instructions.h"
  11. #include "llvm/InitializePasses.h"
  12. using namespace llvm;
  13. void PhiValues::PhiValuesCallbackVH::deleted() {
  14. PV->invalidateValue(getValPtr());
  15. }
  16. void PhiValues::PhiValuesCallbackVH::allUsesReplacedWith(Value *) {
  17. // We could potentially update the cached values we have with the new value,
  18. // but it's simpler to just treat the old value as invalidated.
  19. PV->invalidateValue(getValPtr());
  20. }
  21. bool PhiValues::invalidate(Function &, const PreservedAnalyses &PA,
  22. FunctionAnalysisManager::Invalidator &) {
  23. // PhiValues is invalidated if it isn't preserved.
  24. auto PAC = PA.getChecker<PhiValuesAnalysis>();
  25. return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>());
  26. }
  27. // The goal here is to find all of the non-phi values reachable from this phi,
  28. // and to do the same for all of the phis reachable from this phi, as doing so
  29. // is necessary anyway in order to get the values for this phi. We do this using
  30. // Tarjan's algorithm with Nuutila's improvements to find the strongly connected
  31. // components of the phi graph rooted in this phi:
  32. // * All phis in a strongly connected component will have the same reachable
  33. // non-phi values. The SCC may not be the maximal subgraph for that set of
  34. // reachable values, but finding out that isn't really necessary (it would
  35. // only reduce the amount of memory needed to store the values).
  36. // * Tarjan's algorithm completes components in a bottom-up manner, i.e. it
  37. // never completes a component before the components reachable from it have
  38. // been completed. This means that when we complete a component we have
  39. // everything we need to collect the values reachable from that component.
  40. // * We collect both the non-phi values reachable from each SCC, as that's what
  41. // we're ultimately interested in, and all of the reachable values, i.e.
  42. // including phis, as that makes invalidateValue easier.
  43. void PhiValues::processPhi(const PHINode *Phi,
  44. SmallVectorImpl<const PHINode *> &Stack) {
  45. // Initialize the phi with the next depth number.
  46. assert(DepthMap.lookup(Phi) == 0);
  47. assert(NextDepthNumber != UINT_MAX);
  48. unsigned int RootDepthNumber = ++NextDepthNumber;
  49. DepthMap[Phi] = RootDepthNumber;
  50. // Recursively process the incoming phis of this phi.
  51. TrackedValues.insert(PhiValuesCallbackVH(const_cast<PHINode *>(Phi), this));
  52. for (Value *PhiOp : Phi->incoming_values()) {
  53. if (PHINode *PhiPhiOp = dyn_cast<PHINode>(PhiOp)) {
  54. // Recurse if the phi has not yet been visited.
  55. unsigned int OpDepthNumber = DepthMap.lookup(PhiPhiOp);
  56. if (OpDepthNumber == 0) {
  57. processPhi(PhiPhiOp, Stack);
  58. OpDepthNumber = DepthMap.lookup(PhiPhiOp);
  59. assert(OpDepthNumber != 0);
  60. }
  61. // If the phi did not become part of a component then this phi and that
  62. // phi are part of the same component, so adjust the depth number.
  63. if (!ReachableMap.count(OpDepthNumber))
  64. DepthMap[Phi] = std::min(DepthMap[Phi], OpDepthNumber);
  65. } else {
  66. TrackedValues.insert(PhiValuesCallbackVH(PhiOp, this));
  67. }
  68. }
  69. // Now that incoming phis have been handled, push this phi to the stack.
  70. Stack.push_back(Phi);
  71. // If the depth number has not changed then we've finished collecting the phis
  72. // of a strongly connected component.
  73. if (DepthMap[Phi] == RootDepthNumber) {
  74. // Collect the reachable values for this component. The phis of this
  75. // component will be those on top of the depth stack with the same or
  76. // greater depth number.
  77. ConstValueSet &Reachable = ReachableMap[RootDepthNumber];
  78. while (true) {
  79. const PHINode *ComponentPhi = Stack.pop_back_val();
  80. Reachable.insert(ComponentPhi);
  81. for (Value *Op : ComponentPhi->incoming_values()) {
  82. if (PHINode *PhiOp = dyn_cast<PHINode>(Op)) {
  83. // If this phi is not part of the same component then that component
  84. // is guaranteed to have been completed before this one. Therefore we
  85. // can just add its reachable values to the reachable values of this
  86. // component.
  87. unsigned int OpDepthNumber = DepthMap[PhiOp];
  88. if (OpDepthNumber != RootDepthNumber) {
  89. auto It = ReachableMap.find(OpDepthNumber);
  90. if (It != ReachableMap.end())
  91. Reachable.insert(It->second.begin(), It->second.end());
  92. }
  93. } else
  94. Reachable.insert(Op);
  95. }
  96. if (Stack.empty())
  97. break;
  98. unsigned int &ComponentDepthNumber = DepthMap[Stack.back()];
  99. if (ComponentDepthNumber < RootDepthNumber)
  100. break;
  101. ComponentDepthNumber = RootDepthNumber;
  102. }
  103. // Filter out phis to get the non-phi reachable values.
  104. ValueSet &NonPhi = NonPhiReachableMap[RootDepthNumber];
  105. for (const Value *V : Reachable)
  106. if (!isa<PHINode>(V))
  107. NonPhi.insert(const_cast<Value *>(V));
  108. }
  109. }
  110. const PhiValues::ValueSet &PhiValues::getValuesForPhi(const PHINode *PN) {
  111. unsigned int DepthNumber = DepthMap.lookup(PN);
  112. if (DepthNumber == 0) {
  113. SmallVector<const PHINode *, 8> Stack;
  114. processPhi(PN, Stack);
  115. DepthNumber = DepthMap.lookup(PN);
  116. assert(Stack.empty());
  117. assert(DepthNumber != 0);
  118. }
  119. return NonPhiReachableMap[DepthNumber];
  120. }
  121. void PhiValues::invalidateValue(const Value *V) {
  122. // Components that can reach V are invalid.
  123. SmallVector<unsigned int, 8> InvalidComponents;
  124. for (auto &Pair : ReachableMap)
  125. if (Pair.second.count(V))
  126. InvalidComponents.push_back(Pair.first);
  127. for (unsigned int N : InvalidComponents) {
  128. for (const Value *V : ReachableMap[N])
  129. if (const PHINode *PN = dyn_cast<PHINode>(V))
  130. DepthMap.erase(PN);
  131. NonPhiReachableMap.erase(N);
  132. ReachableMap.erase(N);
  133. }
  134. // This value is no longer tracked
  135. auto It = TrackedValues.find_as(V);
  136. if (It != TrackedValues.end())
  137. TrackedValues.erase(It);
  138. }
  139. void PhiValues::releaseMemory() {
  140. DepthMap.clear();
  141. NonPhiReachableMap.clear();
  142. ReachableMap.clear();
  143. }
  144. void PhiValues::print(raw_ostream &OS) const {
  145. // Iterate through the phi nodes of the function rather than iterating through
  146. // DepthMap in order to get predictable ordering.
  147. for (const BasicBlock &BB : F) {
  148. for (const PHINode &PN : BB.phis()) {
  149. OS << "PHI ";
  150. PN.printAsOperand(OS, false);
  151. OS << " has values:\n";
  152. unsigned int N = DepthMap.lookup(&PN);
  153. auto It = NonPhiReachableMap.find(N);
  154. if (It == NonPhiReachableMap.end())
  155. OS << " UNKNOWN\n";
  156. else if (It->second.empty())
  157. OS << " NONE\n";
  158. else
  159. for (Value *V : It->second)
  160. // Printing of an instruction prints two spaces at the start, so
  161. // handle instructions and everything else slightly differently in
  162. // order to get consistent indenting.
  163. if (Instruction *I = dyn_cast<Instruction>(V))
  164. OS << *I << "\n";
  165. else
  166. OS << " " << *V << "\n";
  167. }
  168. }
  169. }
  170. AnalysisKey PhiValuesAnalysis::Key;
  171. PhiValues PhiValuesAnalysis::run(Function &F, FunctionAnalysisManager &) {
  172. return PhiValues(F);
  173. }
  174. PreservedAnalyses PhiValuesPrinterPass::run(Function &F,
  175. FunctionAnalysisManager &AM) {
  176. OS << "PHI Values for function: " << F.getName() << "\n";
  177. PhiValues &PI = AM.getResult<PhiValuesAnalysis>(F);
  178. for (const BasicBlock &BB : F)
  179. for (const PHINode &PN : BB.phis())
  180. PI.getValuesForPhi(&PN);
  181. PI.print(OS);
  182. return PreservedAnalyses::all();
  183. }
  184. PhiValuesWrapperPass::PhiValuesWrapperPass() : FunctionPass(ID) {
  185. initializePhiValuesWrapperPassPass(*PassRegistry::getPassRegistry());
  186. }
  187. bool PhiValuesWrapperPass::runOnFunction(Function &F) {
  188. Result.reset(new PhiValues(F));
  189. return false;
  190. }
  191. void PhiValuesWrapperPass::releaseMemory() {
  192. Result->releaseMemory();
  193. }
  194. void PhiValuesWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
  195. AU.setPreservesAll();
  196. }
  197. char PhiValuesWrapperPass::ID = 0;
  198. INITIALIZE_PASS(PhiValuesWrapperPass, "phi-values", "Phi Values Analysis", false,
  199. true)