1 //===- PRE.cpp - Partial Redundancy Elimination ---------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the well-known Partial Redundancy Elimination
11 // optimization, using an SSA formulation based on e-paths. See this paper for
14 // E-path_PRE: partial redundancy elimination made easy
15 // By: Dhananjay M. Dhamdhere In: ACM SIGPLAN Notices. Vol 37, #8, 2002
16 // http://doi.acm.org/10.1145/596992.597004
18 // This file actually implements a sparse version of the algorithm, using SSA
19 // and CFG properties instead of bit-vectors.
21 //===----------------------------------------------------------------------===//
23 #include "llvm/Pass.h"
24 #include "llvm/Function.h"
25 #include "llvm/Type.h"
26 #include "llvm/Instructions.h"
27 #include "llvm/Support/CFG.h"
28 #include "llvm/Analysis/Dominators.h"
29 #include "llvm/Analysis/PostDominators.h"
30 #include "llvm/Analysis/ValueNumbering.h"
31 #include "llvm/Transforms/Scalar.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/ADT/DepthFirstIterator.h"
34 #include "llvm/ADT/PostOrderIterator.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/ADT/hash_set"
37 #include "llvm/ADT/hash_map"
41 Statistic<> NumExprsEliminated("pre", "Number of expressions constantified");
42 Statistic<> NumRedundant ("pre", "Number of redundant exprs eliminated");
43 Statistic<> NumInserted ("pre", "Number of expressions inserted");
45 struct PRE : public FunctionPass {
46 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
47 AU.addRequiredID(BreakCriticalEdgesID); // No critical edges for now!
48 AU.addRequired<PostDominatorTree>();
49 AU.addRequired<PostDominanceFrontier>();
50 AU.addRequired<DominatorSet>();
51 AU.addRequired<DominatorTree>();
52 AU.addRequired<DominanceFrontier>();
53 AU.addRequired<ValueNumbering>();
55 virtual bool runOnFunction(Function &F);
58 // Block information - Map basic blocks in a function back and forth to
60 std::vector<BasicBlock*> BlockMapping;
61 hash_map<BasicBlock*, unsigned> BlockNumbering;
63 // ProcessedExpressions - Keep track of which expressions have already been
65 hash_set<Instruction*> ProcessedExpressions;
67 // Provide access to the various analyses used...
69 DominatorTree *DT; PostDominatorTree *PDT;
70 DominanceFrontier *DF; PostDominanceFrontier *PDF;
73 // AvailableBlocks - Contain a mapping of blocks with available expression
74 // values to the expression value itself. This can be used as an efficient
75 // way to find out if the expression is available in the block, and if so,
76 // which version to use. This map is only used while processing a single
79 typedef hash_map<BasicBlock*, Instruction*> AvailableBlocksTy;
80 AvailableBlocksTy AvailableBlocks;
82 bool ProcessBlock(BasicBlock *BB);
84 // Anticipatibility calculation...
85 void MarkPostDominatingBlocksAnticipatible(PostDominatorTree::Node *N,
86 std::vector<char> &AntBlocks,
87 Instruction *Occurrence);
88 void CalculateAnticipatiblityForOccurrence(unsigned BlockNo,
89 std::vector<char> &AntBlocks,
90 Instruction *Occurrence);
91 void CalculateAnticipatibleBlocks(const std::map<unsigned, Instruction*> &D,
92 std::vector<char> &AnticipatibleBlocks);
94 // PRE for an expression
95 void MarkOccurrenceAvailableInAllDominatedBlocks(Instruction *Occurrence,
96 BasicBlock *StartBlock);
97 void ReplaceDominatedAvailableOccurrencesWith(Instruction *NewOcc,
98 DominatorTree::Node *N);
99 bool ProcessExpression(Instruction *I);
102 RegisterOpt<PRE> Z("pre", "Partial Redundancy Elimination");
106 bool PRE::runOnFunction(Function &F) {
107 VN = &getAnalysis<ValueNumbering>();
108 DS = &getAnalysis<DominatorSet>();
109 DT = &getAnalysis<DominatorTree>();
110 DF = &getAnalysis<DominanceFrontier>();
111 PDT = &getAnalysis<PostDominatorTree>();
112 PDF = &getAnalysis<PostDominanceFrontier>();
114 DEBUG(std::cerr << "\n*** Running PRE on func '" << F.getName() << "'...\n");
116 // Number the basic blocks based on a reverse post-order traversal of the CFG
117 // so that all predecessors of a block (ignoring back edges) are visited
118 // before a block is visited.
120 BlockMapping.reserve(F.size());
122 ReversePostOrderTraversal<Function*> RPOT(&F);
123 DEBUG(std::cerr << "Block order: ");
124 for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
125 E = RPOT.end(); I != E; ++I) {
126 // Keep track of mapping...
128 BlockNumbering.insert(std::make_pair(BB, BlockMapping.size()));
129 BlockMapping.push_back(BB);
130 DEBUG(std::cerr << BB->getName() << " ");
132 DEBUG(std::cerr << "\n");
135 // Traverse the current function depth-first in dominator-tree order. This
136 // ensures that we see all definitions before their uses (except for PHI
137 // nodes), allowing us to hoist dependent expressions correctly.
138 bool Changed = false;
139 for (unsigned i = 0, e = BlockMapping.size(); i != e; ++i)
140 Changed |= ProcessBlock(BlockMapping[i]);
143 BlockMapping.clear();
144 BlockNumbering.clear();
145 ProcessedExpressions.clear();
150 // ProcessBlock - Process any expressions first seen in this block...
152 bool PRE::ProcessBlock(BasicBlock *BB) {
153 bool Changed = false;
155 // DISABLED: This pass invalidates iterators and then uses them.
158 // PRE expressions first defined in this block...
159 for (BasicBlock::iterator I = BB->begin(); I != BB->end(); )
160 if (ProcessExpression(I++))
166 void PRE::MarkPostDominatingBlocksAnticipatible(PostDominatorTree::Node *N,
167 std::vector<char> &AntBlocks,
168 Instruction *Occurrence) {
169 unsigned BlockNo = BlockNumbering[N->getBlock()];
171 if (AntBlocks[BlockNo]) return; // Already known to be anticipatible??
173 // Check to see if any of the operands are defined in this block, if so, the
174 // entry of this block does not anticipate the expression. This computes
176 for (unsigned i = 0, e = Occurrence->getNumOperands(); i != e; ++i)
177 if (Instruction *I = dyn_cast<Instruction>(Occurrence->getOperand(i)))
178 if (I->getParent() == N->getBlock()) // Operand is defined in this block!
181 if (isa<LoadInst>(Occurrence))
182 return; // FIXME: compute transparency for load instructions using AA
184 // Insert block into AntBlocks list...
185 AntBlocks[BlockNo] = true;
187 for (PostDominatorTree::Node::iterator I = N->begin(), E = N->end(); I != E;
189 MarkPostDominatingBlocksAnticipatible(*I, AntBlocks, Occurrence);
192 void PRE::CalculateAnticipatiblityForOccurrence(unsigned BlockNo,
193 std::vector<char> &AntBlocks,
194 Instruction *Occurrence) {
195 if (AntBlocks[BlockNo]) return; // Block already anticipatible!
197 BasicBlock *BB = BlockMapping[BlockNo];
199 // For each occurrence, mark all post-dominated blocks as anticipatible...
200 MarkPostDominatingBlocksAnticipatible(PDT->getNode(BB), AntBlocks,
203 // Next, mark any blocks in the post-dominance frontier as anticipatible iff
204 // all successors are anticipatible.
206 PostDominanceFrontier::iterator PDFI = PDF->find(BB);
207 if (PDFI != DF->end())
208 for (std::set<BasicBlock*>::iterator DI = PDFI->second.begin();
209 DI != PDFI->second.end(); ++DI) {
210 BasicBlock *PDFBlock = *DI;
211 bool AllSuccessorsAnticipatible = true;
212 for (succ_iterator SI = succ_begin(PDFBlock), SE = succ_end(PDFBlock);
214 if (!AntBlocks[BlockNumbering[*SI]]) {
215 AllSuccessorsAnticipatible = false;
219 if (AllSuccessorsAnticipatible)
220 CalculateAnticipatiblityForOccurrence(BlockNumbering[PDFBlock],
221 AntBlocks, Occurrence);
226 void PRE::CalculateAnticipatibleBlocks(const std::map<unsigned,
228 std::vector<char> &AntBlocks) {
229 // Initialize to zeros...
230 AntBlocks.resize(BlockMapping.size());
232 // Loop over all of the expressions...
233 for (std::map<unsigned, Instruction*>::const_iterator I = Defs.begin(),
234 E = Defs.end(); I != E; ++I)
235 CalculateAnticipatiblityForOccurrence(I->first, AntBlocks, I->second);
238 /// MarkOccurrenceAvailableInAllDominatedBlocks - Add entries to AvailableBlocks
239 /// for all nodes dominated by the occurrence to indicate that it is now the
240 /// available occurrence to use in any of these blocks.
242 void PRE::MarkOccurrenceAvailableInAllDominatedBlocks(Instruction *Occurrence,
244 // FIXME: There are much more efficient ways to get the blocks dominated
245 // by a block. Use them.
247 DominatorTree::Node *N = DT->getNode(Occurrence->getParent());
248 for (df_iterator<DominatorTree::Node*> DI = df_begin(N), E = df_end(N);
250 AvailableBlocks[(*DI)->getBlock()] = Occurrence;
253 /// ReplaceDominatedAvailableOccurrencesWith - This loops over the region
254 /// dominated by N, replacing any available expressions with NewOcc.
255 void PRE::ReplaceDominatedAvailableOccurrencesWith(Instruction *NewOcc,
256 DominatorTree::Node *N) {
257 BasicBlock *BB = N->getBlock();
258 Instruction *&ExistingAvailableVal = AvailableBlocks[BB];
260 // If there isn't a definition already active in this node, make this the new
261 // active definition...
262 if (ExistingAvailableVal == 0) {
263 ExistingAvailableVal = NewOcc;
265 for (DominatorTree::Node::iterator I = N->begin(), E = N->end(); I != E;++I)
266 ReplaceDominatedAvailableOccurrencesWith(NewOcc, *I);
268 // If there is already an active definition in this block, replace it with
269 // NewOcc, and force it into all dominated blocks.
270 DEBUG(std::cerr << " Replacing dominated occ %"
271 << ExistingAvailableVal->getName() << " with %" << NewOcc->getName()
273 assert(ExistingAvailableVal != NewOcc && "NewOcc already inserted??");
274 ExistingAvailableVal->replaceAllUsesWith(NewOcc);
277 assert(ExistingAvailableVal->getParent() == BB &&
278 "OldOcc not defined in current block?");
279 BB->getInstList().erase(ExistingAvailableVal);
281 // Mark NewOCC as the Available expression in all blocks dominated by BB
282 for (df_iterator<DominatorTree::Node*> DI = df_begin(N), E = df_end(N);
284 AvailableBlocks[(*DI)->getBlock()] = NewOcc;
289 /// ProcessExpression - Given an expression (instruction) process the
290 /// instruction to remove any partial redundancies induced by equivalent
291 /// computations. Note that we only need to PRE each expression once, so we
292 /// keep track of whether an expression has been PRE'd already, and don't PRE an
293 /// expression again. Expressions may be seen multiple times because process
294 /// the entire equivalence class at once, which may leave expressions later in
295 /// the control path.
297 bool PRE::ProcessExpression(Instruction *Expr) {
298 if (Expr->mayWriteToMemory() || Expr->getType() == Type::VoidTy ||
300 return false; // Cannot move expression
301 if (ProcessedExpressions.count(Expr)) return false; // Already processed.
303 // Ok, this is the first time we have seen the expression. Build a set of
304 // equivalent expressions using SSA def/use information. We consider
305 // expressions to be equivalent if they are the same opcode and have
306 // equivalent operands. As a special case for SSA, values produced by PHI
307 // nodes are considered to be equivalent to all of their operands.
309 std::vector<Value*> Values;
310 VN->getEqualNumberNodes(Expr, Values);
313 // FIXME: This should handle PHI nodes correctly. To do this, we need to
314 // consider expressions of the following form equivalent to this set of
317 // If an operand is a PHI node, add any occurrences of the expression with the
318 // PHI operand replaced with the PHI node operands. This is only valid if the
319 // PHI operand occurrences exist in blocks post-dominated by the incoming edge
323 // We have to be careful to handle expression definitions which dominated by
324 // other expressions. These can be directly eliminated in favor of their
325 // dominating value. Keep track of which blocks contain definitions (the key)
326 // and if a block contains a definition, which instruction it is.
328 std::map<unsigned, Instruction*> Definitions;
329 Definitions.insert(std::make_pair(BlockNumbering[Expr->getParent()], Expr));
331 bool Changed = false;
333 // Look at all of the equal values. If any of the values is not an
334 // instruction, replace all other expressions immediately with it (it must be
335 // an argument or a constant or something). Otherwise, convert the list of
336 // values into a list of expression (instruction) definitions ordering
337 // according to their dominator tree ordering.
339 Value *NonInstValue = 0;
340 for (unsigned i = 0, e = Values.size(); i != e; ++i)
341 if (Instruction *I = dyn_cast<Instruction>(Values[i])) {
342 Instruction *&BlockInst = Definitions[BlockNumbering[I->getParent()]];
343 if (BlockInst && BlockInst != I) { // Eliminate direct redundancy
344 if (DS->dominates(I, BlockInst)) { // I dom BlockInst
345 BlockInst->replaceAllUsesWith(I);
346 BlockInst->getParent()->getInstList().erase(BlockInst);
347 } else { // BlockInst dom I
348 I->replaceAllUsesWith(BlockInst);
349 I->getParent()->getInstList().erase(I);
356 NonInstValue = Values[i];
359 std::vector<Value*>().swap(Values); // Done with the values list
362 // This is the good, though unlikely, case where we find out that this
363 // expression is equal to a constant or argument directly. We can replace
364 // this and all of the other equivalent instructions with the value
367 for (std::map<unsigned, Instruction*>::iterator I = Definitions.begin(),
368 E = Definitions.end(); I != E; ++I) {
369 Instruction *Inst = I->second;
370 // Replace the value with the specified non-instruction value.
371 Inst->replaceAllUsesWith(NonInstValue); // Fixup any uses
372 Inst->getParent()->getInstList().erase(Inst); // Erase the instruction
374 NumExprsEliminated += Definitions.size();
375 return true; // Program modified!
378 // There are no expressions equal to this one. Exit early.
379 assert(!Definitions.empty() && "no equal expressions??");
381 if (Definitions.size() == 1) {
382 ProcessedExpressions.insert(Definitions.begin()->second);
386 DEBUG(std::cerr << "\n====--- Expression: " << *Expr);
387 const Type *ExprType = Expr->getType();
389 // AnticipatibleBlocks - Blocks where the current expression is anticipatible.
390 // This is logically std::vector<bool> but using 'char' for performance.
391 std::vector<char> AnticipatibleBlocks;
393 // Calculate all of the blocks which the current expression is anticipatible.
394 CalculateAnticipatibleBlocks(Definitions, AnticipatibleBlocks);
396 // Print out anticipatible blocks...
397 DEBUG(std::cerr << "AntBlocks: ";
398 for (unsigned i = 0, e = AnticipatibleBlocks.size(); i != e; ++i)
399 if (AnticipatibleBlocks[i])
400 std::cerr << BlockMapping[i]->getName() <<" ";
405 // AvailabilityFrontier - Calculates the availability frontier for the current
406 // expression. The availability frontier contains the blocks on the dominance
407 // frontier of the current available expressions, iff they anticipate a
408 // definition of the expression.
409 hash_set<unsigned> AvailabilityFrontier;
411 Instruction *NonPHIOccurrence = 0;
413 while (!Definitions.empty() || !AvailabilityFrontier.empty()) {
414 if (!Definitions.empty() &&
415 (AvailabilityFrontier.empty() ||
416 Definitions.begin()->first < *AvailabilityFrontier.begin())) {
417 Instruction *Occurrence = Definitions.begin()->second;
418 BasicBlock *BB = Occurrence->getParent();
419 Definitions.erase(Definitions.begin());
421 DEBUG(std::cerr << "PROCESSING Occurrence: " << *Occurrence);
423 // Check to see if there is already an incoming value for this block...
424 AvailableBlocksTy::iterator LBI = AvailableBlocks.find(BB);
425 if (LBI != AvailableBlocks.end()) {
426 // Yes, there is a dominating definition for this block. Replace this
427 // occurrence with the incoming value.
428 if (LBI->second != Occurrence) {
429 DEBUG(std::cerr << " replacing with: " << *LBI->second);
430 Occurrence->replaceAllUsesWith(LBI->second);
431 BB->getInstList().erase(Occurrence); // Delete instruction
435 ProcessedExpressions.insert(Occurrence);
436 if (!isa<PHINode>(Occurrence))
437 NonPHIOccurrence = Occurrence; // Keep an occurrence of this expr
439 // Okay, there is no incoming value for this block, so this expression
440 // is a new definition that is good for this block and all blocks
441 // dominated by it. Add this information to the AvailableBlocks map.
443 MarkOccurrenceAvailableInAllDominatedBlocks(Occurrence, BB);
445 // Update the dominance frontier for the definitions so far... if a node
446 // in the dominator frontier now has all of its predecessors available,
447 // and the block is in an anticipatible region, we can insert a PHI node
449 DominanceFrontier::iterator DFI = DF->find(BB);
450 if (DFI != DF->end()) {
451 for (std::set<BasicBlock*>::iterator DI = DFI->second.begin();
452 DI != DFI->second.end(); ++DI) {
453 BasicBlock *DFBlock = *DI;
454 unsigned DFBlockID = BlockNumbering[DFBlock];
455 if (AnticipatibleBlocks[DFBlockID]) {
456 // Check to see if any of the predecessors of this block on the
457 // frontier are not available...
458 bool AnyNotAvailable = false;
459 for (pred_iterator PI = pred_begin(DFBlock),
460 PE = pred_end(DFBlock); PI != PE; ++PI)
461 if (!AvailableBlocks.count(*PI)) {
462 AnyNotAvailable = true;
466 // If any predecessor blocks are not available, add the node to
467 // the current expression dominance frontier.
468 if (AnyNotAvailable) {
469 AvailabilityFrontier.insert(DFBlockID);
471 // This block is no longer in the availability frontier, it IS
473 AvailabilityFrontier.erase(DFBlockID);
475 // If all of the predecessor blocks are available (and the block
476 // anticipates a definition along the path to the exit), we need
477 // to insert a new PHI node in this block. This block serves as
478 // a new definition for the expression, extending the available
481 PHINode *PN = new PHINode(ExprType, Expr->getName()+".pre",
483 ProcessedExpressions.insert(PN);
485 DEBUG(std::cerr << " INSERTING PHI on frontier: " << *PN);
487 // Add the incoming blocks for the PHI node
488 for (pred_iterator PI = pred_begin(DFBlock),
489 PE = pred_end(DFBlock); PI != PE; ++PI)
491 PN->addIncoming(AvailableBlocks[*PI], *PI);
492 else // edge from the current block
493 PN->addIncoming(PN, DFBlock);
495 Instruction *&BlockOcc = Definitions[DFBlockID];
497 DEBUG(std::cerr <<" PHI superceeds occurrence: "<<
499 BlockOcc->replaceAllUsesWith(PN);
500 BlockOcc->getParent()->getInstList().erase(BlockOcc);
511 // Otherwise we must be looking at a node in the availability frontier!
512 unsigned AFBlockID = *AvailabilityFrontier.begin();
513 AvailabilityFrontier.erase(AvailabilityFrontier.begin());
514 BasicBlock *AFBlock = BlockMapping[AFBlockID];
516 // We eliminate the partial redundancy on this frontier by inserting a PHI
517 // node into this block, merging any incoming available versions into the
518 // PHI and inserting a new computation into predecessors without an
519 // incoming value. Note that we would have to insert the expression on
520 // the edge if the predecessor didn't anticipate the expression and we
521 // didn't break critical edges.
523 PHINode *PN = new PHINode(ExprType, Expr->getName()+".PRE",
525 DEBUG(std::cerr << "INSERTING PHI for PR: " << *PN);
527 // If there is a pending occurrence in this block, make sure to replace it
528 // with the PHI node...
529 std::map<unsigned, Instruction*>::iterator EDFI =
530 Definitions.find(AFBlockID);
531 if (EDFI != Definitions.end()) {
532 // There is already an occurrence in this block. Replace it with PN and
534 Instruction *OldOcc = EDFI->second;
535 DEBUG(std::cerr << " Replaces occurrence: " << *OldOcc);
536 OldOcc->replaceAllUsesWith(PN);
537 AFBlock->getInstList().erase(OldOcc);
538 Definitions.erase(EDFI);
542 for (pred_iterator PI = pred_begin(AFBlock), PE = pred_end(AFBlock);
544 BasicBlock *Pred = *PI;
545 AvailableBlocksTy::iterator LBI = AvailableBlocks.find(Pred);
546 if (LBI != AvailableBlocks.end()) { // If there is a available value
547 PN->addIncoming(LBI->second, Pred); // for this pred, use it.
548 } else { // No available value yet...
549 unsigned PredID = BlockNumbering[Pred];
551 // Is the predecessor the same block that we inserted the PHI into?
553 if (Pred == AFBlock) {
554 // Yes, reuse the incoming value here...
555 PN->addIncoming(PN, Pred);
557 // No, we must insert a new computation into this block and add it
558 // to the definitions list...
559 assert(NonPHIOccurrence && "No non-phi occurrences seen so far???");
560 Instruction *New = NonPHIOccurrence->clone();
561 New->setName(NonPHIOccurrence->getName() + ".PRE-inserted");
562 ProcessedExpressions.insert(New);
564 DEBUG(std::cerr << " INSERTING OCCURRRENCE: " << *New);
566 // Insert it into the bottom of the predecessor, right before the
567 // terminator instruction...
568 Pred->getInstList().insert(Pred->getTerminator(), New);
570 // Make this block be the available definition for any blocks it
571 // dominates. The ONLY case that this can affect more than just the
572 // block itself is when we are moving a computation to a loop
573 // header. In all other cases, because we don't have critical
574 // edges, the node is guaranteed to only dominate itself.
576 ReplaceDominatedAvailableOccurrencesWith(New, DT->getNode(Pred));
578 // Add it as an incoming value on this edge to the PHI node
579 PN->addIncoming(New, Pred);
580 NonPHIOccurrence = New;
586 // Find out if there is already an available value in this block. If so,
587 // we need to replace the available value with the PHI node. This can
588 // only happen when we just inserted a PHI node on a backedge.
590 AvailableBlocksTy::iterator LBBlockAvailableValIt =
591 AvailableBlocks.find(AFBlock);
592 if (LBBlockAvailableValIt != AvailableBlocks.end()) {
593 if (LBBlockAvailableValIt->second->getParent() == AFBlock) {
594 Instruction *OldVal = LBBlockAvailableValIt->second;
595 OldVal->replaceAllUsesWith(PN); // Use the new PHI node now
597 DEBUG(std::cerr << " PHI replaces available value: %"
598 << OldVal->getName() << "\n");
600 // Loop over all of the blocks dominated by this PHI node, and change
601 // the AvailableBlocks entries to be the PHI node instead of the old
603 MarkOccurrenceAvailableInAllDominatedBlocks(PN, AFBlock);
605 AFBlock->getInstList().erase(OldVal); // Delete old instruction!
607 // The resultant PHI node is a new definition of the value!
608 Definitions.insert(std::make_pair(AFBlockID, PN));
610 // If the value is not defined in this block, that means that an
611 // inserted occurrence in a predecessor is now the live value for the
612 // region (occurs when hoisting loop invariants, f.e.). In this case,
613 // the PHI node should actually just be removed.
614 assert(PN->use_empty() && "No uses should exist for dead PHI node!");
615 PN->getParent()->getInstList().erase(PN);
618 // The resultant PHI node is a new definition of the value!
619 Definitions.insert(std::make_pair(AFBlockID, PN));
624 AvailableBlocks.clear();