2
0

SparsePropagation.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. //===- SparsePropagation.cpp - Sparse Conditional Property Propagation ----===//
  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 an abstract sparse conditional propagation algorithm,
  11. // modeled after SCCP, but with a customizable lattice function.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/Analysis/SparsePropagation.h"
  15. #include "llvm/IR/Constants.h"
  16. #include "llvm/IR/Function.h"
  17. #include "llvm/IR/Instructions.h"
  18. #include "llvm/Support/Debug.h"
  19. #include "llvm/Support/raw_ostream.h"
  20. using namespace llvm;
  21. #define DEBUG_TYPE "sparseprop"
  22. //===----------------------------------------------------------------------===//
  23. // AbstractLatticeFunction Implementation
  24. //===----------------------------------------------------------------------===//
  25. AbstractLatticeFunction::~AbstractLatticeFunction() {}
  26. /// PrintValue - Render the specified lattice value to the specified stream.
  27. void AbstractLatticeFunction::PrintValue(LatticeVal V, raw_ostream &OS) {
  28. if (V == UndefVal)
  29. OS << "undefined";
  30. else if (V == OverdefinedVal)
  31. OS << "overdefined";
  32. else if (V == UntrackedVal)
  33. OS << "untracked";
  34. else
  35. OS << "unknown lattice value";
  36. }
  37. //===----------------------------------------------------------------------===//
  38. // SparseSolver Implementation
  39. //===----------------------------------------------------------------------===//
  40. /// getOrInitValueState - Return the LatticeVal object that corresponds to the
  41. /// value, initializing the value's state if it hasn't been entered into the
  42. /// map yet. This function is necessary because not all values should start
  43. /// out in the underdefined state... Arguments should be overdefined, and
  44. /// constants should be marked as constants.
  45. ///
  46. SparseSolver::LatticeVal SparseSolver::getOrInitValueState(Value *V) {
  47. DenseMap<Value*, LatticeVal>::iterator I = ValueState.find(V);
  48. if (I != ValueState.end()) return I->second; // Common case, in the map
  49. LatticeVal LV;
  50. if (LatticeFunc->IsUntrackedValue(V))
  51. return LatticeFunc->getUntrackedVal();
  52. else if (Constant *C = dyn_cast<Constant>(V))
  53. LV = LatticeFunc->ComputeConstant(C);
  54. else if (Argument *A = dyn_cast<Argument>(V))
  55. LV = LatticeFunc->ComputeArgument(A);
  56. else if (!isa<Instruction>(V))
  57. // All other non-instructions are overdefined.
  58. LV = LatticeFunc->getOverdefinedVal();
  59. else
  60. // All instructions are underdefined by default.
  61. LV = LatticeFunc->getUndefVal();
  62. // If this value is untracked, don't add it to the map.
  63. if (LV == LatticeFunc->getUntrackedVal())
  64. return LV;
  65. return ValueState[V] = LV;
  66. }
  67. /// UpdateState - When the state for some instruction is potentially updated,
  68. /// this function notices and adds I to the worklist if needed.
  69. void SparseSolver::UpdateState(Instruction &Inst, LatticeVal V) {
  70. DenseMap<Value*, LatticeVal>::iterator I = ValueState.find(&Inst);
  71. if (I != ValueState.end() && I->second == V)
  72. return; // No change.
  73. // An update. Visit uses of I.
  74. ValueState[&Inst] = V;
  75. InstWorkList.push_back(&Inst);
  76. }
  77. /// MarkBlockExecutable - This method can be used by clients to mark all of
  78. /// the blocks that are known to be intrinsically live in the processed unit.
  79. void SparseSolver::MarkBlockExecutable(BasicBlock *BB) {
  80. DEBUG(dbgs() << "Marking Block Executable: " << BB->getName() << "\n");
  81. BBExecutable.insert(BB); // Basic block is executable!
  82. BBWorkList.push_back(BB); // Add the block to the work list!
  83. }
  84. /// markEdgeExecutable - Mark a basic block as executable, adding it to the BB
  85. /// work list if it is not already executable...
  86. void SparseSolver::markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
  87. if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
  88. return; // This edge is already known to be executable!
  89. DEBUG(dbgs() << "Marking Edge Executable: " << Source->getName()
  90. << " -> " << Dest->getName() << "\n");
  91. if (BBExecutable.count(Dest)) {
  92. // The destination is already executable, but we just made an edge
  93. // feasible that wasn't before. Revisit the PHI nodes in the block
  94. // because they have potentially new operands.
  95. for (BasicBlock::iterator I = Dest->begin(); isa<PHINode>(I); ++I)
  96. visitPHINode(*cast<PHINode>(I));
  97. } else {
  98. MarkBlockExecutable(Dest);
  99. }
  100. }
  101. /// getFeasibleSuccessors - Return a vector of booleans to indicate which
  102. /// successors are reachable from a given terminator instruction.
  103. void SparseSolver::getFeasibleSuccessors(TerminatorInst &TI,
  104. SmallVectorImpl<bool> &Succs,
  105. bool AggressiveUndef) {
  106. Succs.resize(TI.getNumSuccessors());
  107. if (TI.getNumSuccessors() == 0) return;
  108. if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
  109. if (BI->isUnconditional()) {
  110. Succs[0] = true;
  111. return;
  112. }
  113. LatticeVal BCValue;
  114. if (AggressiveUndef)
  115. BCValue = getOrInitValueState(BI->getCondition());
  116. else
  117. BCValue = getLatticeState(BI->getCondition());
  118. if (BCValue == LatticeFunc->getOverdefinedVal() ||
  119. BCValue == LatticeFunc->getUntrackedVal()) {
  120. // Overdefined condition variables can branch either way.
  121. Succs[0] = Succs[1] = true;
  122. return;
  123. }
  124. // If undefined, neither is feasible yet.
  125. if (BCValue == LatticeFunc->getUndefVal())
  126. return;
  127. Constant *C = LatticeFunc->GetConstant(BCValue, BI->getCondition(), *this);
  128. if (!C || !isa<ConstantInt>(C)) {
  129. // Non-constant values can go either way.
  130. Succs[0] = Succs[1] = true;
  131. return;
  132. }
  133. // Constant condition variables mean the branch can only go a single way
  134. Succs[C->isNullValue()] = true;
  135. return;
  136. }
  137. if (isa<InvokeInst>(TI)) {
  138. // Invoke instructions successors are always executable.
  139. // TODO: Could ask the lattice function if the value can throw.
  140. Succs[0] = Succs[1] = true;
  141. return;
  142. }
  143. if (isa<IndirectBrInst>(TI)) {
  144. Succs.assign(Succs.size(), true);
  145. return;
  146. }
  147. SwitchInst &SI = cast<SwitchInst>(TI);
  148. LatticeVal SCValue;
  149. if (AggressiveUndef)
  150. SCValue = getOrInitValueState(SI.getCondition());
  151. else
  152. SCValue = getLatticeState(SI.getCondition());
  153. if (SCValue == LatticeFunc->getOverdefinedVal() ||
  154. SCValue == LatticeFunc->getUntrackedVal()) {
  155. // All destinations are executable!
  156. Succs.assign(TI.getNumSuccessors(), true);
  157. return;
  158. }
  159. // If undefined, neither is feasible yet.
  160. if (SCValue == LatticeFunc->getUndefVal())
  161. return;
  162. Constant *C = LatticeFunc->GetConstant(SCValue, SI.getCondition(), *this);
  163. if (!C || !isa<ConstantInt>(C)) {
  164. // All destinations are executable!
  165. Succs.assign(TI.getNumSuccessors(), true);
  166. return;
  167. }
  168. SwitchInst::CaseIt Case = SI.findCaseValue(cast<ConstantInt>(C));
  169. Succs[Case.getSuccessorIndex()] = true;
  170. }
  171. /// isEdgeFeasible - Return true if the control flow edge from the 'From'
  172. /// basic block to the 'To' basic block is currently feasible...
  173. bool SparseSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To,
  174. bool AggressiveUndef) {
  175. SmallVector<bool, 16> SuccFeasible;
  176. TerminatorInst *TI = From->getTerminator();
  177. getFeasibleSuccessors(*TI, SuccFeasible, AggressiveUndef);
  178. for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
  179. if (TI->getSuccessor(i) == To && SuccFeasible[i])
  180. return true;
  181. return false;
  182. }
  183. void SparseSolver::visitTerminatorInst(TerminatorInst &TI) {
  184. SmallVector<bool, 16> SuccFeasible;
  185. getFeasibleSuccessors(TI, SuccFeasible, true);
  186. BasicBlock *BB = TI.getParent();
  187. // Mark all feasible successors executable...
  188. for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
  189. if (SuccFeasible[i])
  190. markEdgeExecutable(BB, TI.getSuccessor(i));
  191. }
  192. void SparseSolver::visitPHINode(PHINode &PN) {
  193. // The lattice function may store more information on a PHINode than could be
  194. // computed from its incoming values. For example, SSI form stores its sigma
  195. // functions as PHINodes with a single incoming value.
  196. if (LatticeFunc->IsSpecialCasedPHI(&PN)) {
  197. LatticeVal IV = LatticeFunc->ComputeInstructionState(PN, *this);
  198. if (IV != LatticeFunc->getUntrackedVal())
  199. UpdateState(PN, IV);
  200. return;
  201. }
  202. LatticeVal PNIV = getOrInitValueState(&PN);
  203. LatticeVal Overdefined = LatticeFunc->getOverdefinedVal();
  204. // If this value is already overdefined (common) just return.
  205. if (PNIV == Overdefined || PNIV == LatticeFunc->getUntrackedVal())
  206. return; // Quick exit
  207. // Super-extra-high-degree PHI nodes are unlikely to ever be interesting,
  208. // and slow us down a lot. Just mark them overdefined.
  209. if (PN.getNumIncomingValues() > 64) {
  210. UpdateState(PN, Overdefined);
  211. return;
  212. }
  213. // Look at all of the executable operands of the PHI node. If any of them
  214. // are overdefined, the PHI becomes overdefined as well. Otherwise, ask the
  215. // transfer function to give us the merge of the incoming values.
  216. for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
  217. // If the edge is not yet known to be feasible, it doesn't impact the PHI.
  218. if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent(), true))
  219. continue;
  220. // Merge in this value.
  221. LatticeVal OpVal = getOrInitValueState(PN.getIncomingValue(i));
  222. if (OpVal != PNIV)
  223. PNIV = LatticeFunc->MergeValues(PNIV, OpVal);
  224. if (PNIV == Overdefined)
  225. break; // Rest of input values don't matter.
  226. }
  227. // Update the PHI with the compute value, which is the merge of the inputs.
  228. UpdateState(PN, PNIV);
  229. }
  230. void SparseSolver::visitInst(Instruction &I) {
  231. // PHIs are handled by the propagation logic, they are never passed into the
  232. // transfer functions.
  233. if (PHINode *PN = dyn_cast<PHINode>(&I))
  234. return visitPHINode(*PN);
  235. // Otherwise, ask the transfer function what the result is. If this is
  236. // something that we care about, remember it.
  237. LatticeVal IV = LatticeFunc->ComputeInstructionState(I, *this);
  238. if (IV != LatticeFunc->getUntrackedVal())
  239. UpdateState(I, IV);
  240. if (TerminatorInst *TI = dyn_cast<TerminatorInst>(&I))
  241. visitTerminatorInst(*TI);
  242. }
  243. void SparseSolver::Solve(Function &F) {
  244. MarkBlockExecutable(&F.getEntryBlock());
  245. // Process the work lists until they are empty!
  246. while (!BBWorkList.empty() || !InstWorkList.empty()) {
  247. // Process the instruction work list.
  248. while (!InstWorkList.empty()) {
  249. Instruction *I = InstWorkList.back();
  250. InstWorkList.pop_back();
  251. DEBUG(dbgs() << "\nPopped off I-WL: " << *I << "\n");
  252. // "I" got into the work list because it made a transition. See if any
  253. // users are both live and in need of updating.
  254. for (User *U : I->users()) {
  255. Instruction *UI = cast<Instruction>(U);
  256. if (BBExecutable.count(UI->getParent())) // Inst is executable?
  257. visitInst(*UI);
  258. }
  259. }
  260. // Process the basic block work list.
  261. while (!BBWorkList.empty()) {
  262. BasicBlock *BB = BBWorkList.back();
  263. BBWorkList.pop_back();
  264. DEBUG(dbgs() << "\nPopped off BBWL: " << *BB);
  265. // Notify all instructions in this basic block that they are newly
  266. // executable.
  267. for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
  268. visitInst(*I);
  269. }
  270. }
  271. }
  272. void SparseSolver::Print(Function &F, raw_ostream &OS) const {
  273. OS << "\nFUNCTION: " << F.getName() << "\n";
  274. for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
  275. if (!BBExecutable.count(BB))
  276. OS << "INFEASIBLE: ";
  277. OS << "\t";
  278. if (BB->hasName())
  279. OS << BB->getName() << ":\n";
  280. else
  281. OS << "; anon bb\n";
  282. for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
  283. LatticeFunc->PrintValue(getLatticeState(I), OS);
  284. OS << *I << "\n";
  285. }
  286. OS << "\n";
  287. }
  288. }