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/iPHINode.h"
27 #include "llvm/iMemory.h"
28 #include "llvm/Support/CFG.h"
29 #include "llvm/Analysis/Dominators.h"
30 #include "llvm/Analysis/PostDominators.h"
31 #include "llvm/Analysis/ValueNumbering.h"
32 #include "llvm/Transforms/Scalar.h"
33 #include "Support/Debug.h"
34 #include "Support/DepthFirstIterator.h"
35 #include "Support/PostOrderIterator.h"
36 #include "Support/Statistic.h"
37 #include "Support/hash_set"
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 // PRE expressions first defined in this block...
156 Instruction *PrevInst = 0;
157 for (BasicBlock::iterator I = BB->begin(); I != BB->end(); )
158 if (ProcessExpression(I)) {
159 // The current instruction may have been deleted, make sure to back up to
173 void PRE::MarkPostDominatingBlocksAnticipatible(PostDominatorTree::Node *N,
174 std::vector<char> &AntBlocks,
175 Instruction *Occurrence) {
176 unsigned BlockNo = BlockNumbering[N->getBlock()];
178 if (AntBlocks[BlockNo]) return; // Already known to be anticipatible??
180 // Check to see if any of the operands are defined in this block, if so, the
181 // entry of this block does not anticipate the expression. This computes
183 for (unsigned i = 0, e = Occurrence->getNumOperands(); i != e; ++i)
184 if (Instruction *I = dyn_cast<Instruction>(Occurrence->getOperand(i)))
185 if (I->getParent() == N->getBlock()) // Operand is defined in this block!
188 if (isa<LoadInst>(Occurrence))
189 return; // FIXME: compute transparency for load instructions using AA
191 // Insert block into AntBlocks list...
192 AntBlocks[BlockNo] = true;
194 for (PostDominatorTree::Node::iterator I = N->begin(), E = N->end(); I != E;
196 MarkPostDominatingBlocksAnticipatible(*I, AntBlocks, Occurrence);
199 void PRE::CalculateAnticipatiblityForOccurrence(unsigned BlockNo,
200 std::vector<char> &AntBlocks,
201 Instruction *Occurrence) {
202 if (AntBlocks[BlockNo]) return; // Block already anticipatible!
204 BasicBlock *BB = BlockMapping[BlockNo];
206 // For each occurrence, mark all post-dominated blocks as anticipatible...
207 MarkPostDominatingBlocksAnticipatible(PDT->getNode(BB), AntBlocks,
210 // Next, mark any blocks in the post-dominance frontier as anticipatible iff
211 // all successors are anticipatible.
213 PostDominanceFrontier::iterator PDFI = PDF->find(BB);
214 if (PDFI != DF->end())
215 for (std::set<BasicBlock*>::iterator DI = PDFI->second.begin();
216 DI != PDFI->second.end(); ++DI) {
217 BasicBlock *PDFBlock = *DI;
218 bool AllSuccessorsAnticipatible = true;
219 for (succ_iterator SI = succ_begin(PDFBlock), SE = succ_end(PDFBlock);
221 if (!AntBlocks[BlockNumbering[*SI]]) {
222 AllSuccessorsAnticipatible = false;
226 if (AllSuccessorsAnticipatible)
227 CalculateAnticipatiblityForOccurrence(BlockNumbering[PDFBlock],
228 AntBlocks, Occurrence);
233 void PRE::CalculateAnticipatibleBlocks(const std::map<unsigned,
235 std::vector<char> &AntBlocks) {
236 // Initialize to zeros...
237 AntBlocks.resize(BlockMapping.size());
239 // Loop over all of the expressions...
240 for (std::map<unsigned, Instruction*>::const_iterator I = Defs.begin(),
241 E = Defs.end(); I != E; ++I)
242 CalculateAnticipatiblityForOccurrence(I->first, AntBlocks, I->second);
245 /// MarkOccurrenceAvailableInAllDominatedBlocks - Add entries to AvailableBlocks
246 /// for all nodes dominated by the occurrence to indicate that it is now the
247 /// available occurrence to use in any of these blocks.
249 void PRE::MarkOccurrenceAvailableInAllDominatedBlocks(Instruction *Occurrence,
251 // FIXME: There are much more efficient ways to get the blocks dominated
252 // by a block. Use them.
254 DominatorTree::Node *N = DT->getNode(Occurrence->getParent());
255 for (df_iterator<DominatorTree::Node*> DI = df_begin(N), E = df_end(N);
257 AvailableBlocks[(*DI)->getBlock()] = Occurrence;
260 /// ReplaceDominatedAvailableOccurrencesWith - This loops over the region
261 /// dominated by N, replacing any available expressions with NewOcc.
262 void PRE::ReplaceDominatedAvailableOccurrencesWith(Instruction *NewOcc,
263 DominatorTree::Node *N) {
264 BasicBlock *BB = N->getBlock();
265 Instruction *&ExistingAvailableVal = AvailableBlocks[BB];
267 // If there isn't a definition already active in this node, make this the new
268 // active definition...
269 if (ExistingAvailableVal == 0) {
270 ExistingAvailableVal = NewOcc;
272 for (DominatorTree::Node::iterator I = N->begin(), E = N->end(); I != E;++I)
273 ReplaceDominatedAvailableOccurrencesWith(NewOcc, *I);
275 // If there is already an active definition in this block, replace it with
276 // NewOcc, and force it into all dominated blocks.
277 DEBUG(std::cerr << " Replacing dominated occ %"
278 << ExistingAvailableVal->getName() << " with %" << NewOcc->getName()
280 assert(ExistingAvailableVal != NewOcc && "NewOcc already inserted??");
281 ExistingAvailableVal->replaceAllUsesWith(NewOcc);
284 assert(ExistingAvailableVal->getParent() == BB &&
285 "OldOcc not defined in current block?");
286 BB->getInstList().erase(ExistingAvailableVal);
288 // Mark NewOCC as the Available expression in all blocks dominated by BB
289 for (df_iterator<DominatorTree::Node*> DI = df_begin(N), E = df_end(N);
291 AvailableBlocks[(*DI)->getBlock()] = NewOcc;
296 /// ProcessExpression - Given an expression (instruction) process the
297 /// instruction to remove any partial redundancies induced by equivalent
298 /// computations. Note that we only need to PRE each expression once, so we
299 /// keep track of whether an expression has been PRE'd already, and don't PRE an
300 /// expression again. Expressions may be seen multiple times because process
301 /// the entire equivalence class at once, which may leave expressions later in
302 /// the control path.
304 bool PRE::ProcessExpression(Instruction *Expr) {
305 if (Expr->mayWriteToMemory() || Expr->getType() == Type::VoidTy ||
307 return false; // Cannot move expression
308 if (ProcessedExpressions.count(Expr)) return false; // Already processed.
310 // Ok, this is the first time we have seen the expression. Build a set of
311 // equivalent expressions using SSA def/use information. We consider
312 // expressions to be equivalent if they are the same opcode and have
313 // equivalent operands. As a special case for SSA, values produced by PHI
314 // nodes are considered to be equivalent to all of their operands.
316 std::vector<Value*> Values;
317 VN->getEqualNumberNodes(Expr, Values);
320 // FIXME: This should handle PHI nodes correctly. To do this, we need to
321 // consider expressions of the following form equivalent to this set of
324 // If an operand is a PHI node, add any occurrences of the expression with the
325 // PHI operand replaced with the PHI node operands. This is only valid if the
326 // PHI operand occurrences exist in blocks post-dominated by the incoming edge
330 // We have to be careful to handle expression definitions which dominated by
331 // other expressions. These can be directly eliminated in favor of their
332 // dominating value. Keep track of which blocks contain definitions (the key)
333 // and if a block contains a definition, which instruction it is.
335 std::map<unsigned, Instruction*> Definitions;
336 Definitions.insert(std::make_pair(BlockNumbering[Expr->getParent()], Expr));
338 bool Changed = false;
340 // Look at all of the equal values. If any of the values is not an
341 // instruction, replace all other expressions immediately with it (it must be
342 // an argument or a constant or something). Otherwise, convert the list of
343 // values into a list of expression (instruction) definitions ordering
344 // according to their dominator tree ordering.
346 Value *NonInstValue = 0;
347 for (unsigned i = 0, e = Values.size(); i != e; ++i)
348 if (Instruction *I = dyn_cast<Instruction>(Values[i])) {
349 Instruction *&BlockInst = Definitions[BlockNumbering[I->getParent()]];
350 if (BlockInst && BlockInst != I) { // Eliminate direct redundancy
351 if (DS->dominates(I, BlockInst)) { // I dom BlockInst
352 BlockInst->replaceAllUsesWith(I);
353 BlockInst->getParent()->getInstList().erase(BlockInst);
354 } else { // BlockInst dom I
355 I->replaceAllUsesWith(BlockInst);
356 I->getParent()->getInstList().erase(I);
363 NonInstValue = Values[i];
366 std::vector<Value*>().swap(Values); // Done with the values list
369 // This is the good, though unlikely, case where we find out that this
370 // expression is equal to a constant or argument directly. We can replace
371 // this and all of the other equivalent instructions with the value
374 for (std::map<unsigned, Instruction*>::iterator I = Definitions.begin(),
375 E = Definitions.end(); I != E; ++I) {
376 Instruction *Inst = I->second;
377 // Replace the value with the specified non-instruction value.
378 Inst->replaceAllUsesWith(NonInstValue); // Fixup any uses
379 Inst->getParent()->getInstList().erase(Inst); // Erase the instruction
381 NumExprsEliminated += Definitions.size();
382 return true; // Program modified!
385 // There are no expressions equal to this one. Exit early.
386 assert(!Definitions.empty() && "no equal expressions??");
388 if (Definitions.size() == 1) {
389 ProcessedExpressions.insert(Definitions.begin()->second);
393 DEBUG(std::cerr << "\n====--- Expression: " << Expr);
394 const Type *ExprType = Expr->getType();
396 // AnticipatibleBlocks - Blocks where the current expression is anticipatible.
397 // This is logically std::vector<bool> but using 'char' for performance.
398 std::vector<char> AnticipatibleBlocks;
400 // Calculate all of the blocks which the current expression is anticipatible.
401 CalculateAnticipatibleBlocks(Definitions, AnticipatibleBlocks);
403 // Print out anticipatible blocks...
404 DEBUG(std::cerr << "AntBlocks: ";
405 for (unsigned i = 0, e = AnticipatibleBlocks.size(); i != e; ++i)
406 if (AnticipatibleBlocks[i])
407 std::cerr << BlockMapping[i]->getName() <<" ";
412 // AvailabilityFrontier - Calculates the availability frontier for the current
413 // expression. The availability frontier contains the blocks on the dominance
414 // frontier of the current available expressions, iff they anticipate a
415 // definition of the expression.
416 hash_set<unsigned> AvailabilityFrontier;
418 Instruction *NonPHIOccurrence = 0;
420 while (!Definitions.empty() || !AvailabilityFrontier.empty()) {
421 if (!Definitions.empty() &&
422 (AvailabilityFrontier.empty() ||
423 Definitions.begin()->first < *AvailabilityFrontier.begin())) {
424 Instruction *Occurrence = Definitions.begin()->second;
425 BasicBlock *BB = Occurrence->getParent();
426 Definitions.erase(Definitions.begin());
428 DEBUG(std::cerr << "PROCESSING Occurrence: " << Occurrence);
430 // Check to see if there is already an incoming value for this block...
431 AvailableBlocksTy::iterator LBI = AvailableBlocks.find(BB);
432 if (LBI != AvailableBlocks.end()) {
433 // Yes, there is a dominating definition for this block. Replace this
434 // occurrence with the incoming value.
435 if (LBI->second != Occurrence) {
436 DEBUG(std::cerr << " replacing with: " << LBI->second);
437 Occurrence->replaceAllUsesWith(LBI->second);
438 BB->getInstList().erase(Occurrence); // Delete instruction
442 ProcessedExpressions.insert(Occurrence);
443 if (!isa<PHINode>(Occurrence))
444 NonPHIOccurrence = Occurrence; // Keep an occurrence of this expr
446 // Okay, there is no incoming value for this block, so this expression
447 // is a new definition that is good for this block and all blocks
448 // dominated by it. Add this information to the AvailableBlocks map.
450 MarkOccurrenceAvailableInAllDominatedBlocks(Occurrence, BB);
452 // Update the dominance frontier for the definitions so far... if a node
453 // in the dominator frontier now has all of its predecessors available,
454 // and the block is in an anticipatible region, we can insert a PHI node
456 DominanceFrontier::iterator DFI = DF->find(BB);
457 if (DFI != DF->end()) {
458 for (std::set<BasicBlock*>::iterator DI = DFI->second.begin();
459 DI != DFI->second.end(); ++DI) {
460 BasicBlock *DFBlock = *DI;
461 unsigned DFBlockID = BlockNumbering[DFBlock];
462 if (AnticipatibleBlocks[DFBlockID]) {
463 // Check to see if any of the predecessors of this block on the
464 // frontier are not available...
465 bool AnyNotAvailable = false;
466 for (pred_iterator PI = pred_begin(DFBlock),
467 PE = pred_end(DFBlock); PI != PE; ++PI)
468 if (!AvailableBlocks.count(*PI)) {
469 AnyNotAvailable = true;
473 // If any predecessor blocks are not available, add the node to
474 // the current expression dominance frontier.
475 if (AnyNotAvailable) {
476 AvailabilityFrontier.insert(DFBlockID);
478 // This block is no longer in the availability frontier, it IS
480 AvailabilityFrontier.erase(DFBlockID);
482 // If all of the predecessor blocks are available (and the block
483 // anticipates a definition along the path to the exit), we need
484 // to insert a new PHI node in this block. This block serves as
485 // a new definition for the expression, extending the available
488 PHINode *PN = new PHINode(ExprType, Expr->getName()+".pre",
490 ProcessedExpressions.insert(PN);
492 DEBUG(std::cerr << " INSERTING PHI on frontier: " << PN);
494 // Add the incoming blocks for the PHI node
495 for (pred_iterator PI = pred_begin(DFBlock),
496 PE = pred_end(DFBlock); PI != PE; ++PI)
498 PN->addIncoming(AvailableBlocks[*PI], *PI);
499 else // edge from the current block
500 PN->addIncoming(PN, DFBlock);
502 Instruction *&BlockOcc = Definitions[DFBlockID];
504 DEBUG(std::cerr <<" PHI superceeds occurrence: "<<BlockOcc);
505 BlockOcc->replaceAllUsesWith(PN);
506 BlockOcc->getParent()->getInstList().erase(BlockOcc);
517 // Otherwise we must be looking at a node in the availability frontier!
518 unsigned AFBlockID = *AvailabilityFrontier.begin();
519 AvailabilityFrontier.erase(AvailabilityFrontier.begin());
520 BasicBlock *AFBlock = BlockMapping[AFBlockID];
522 // We eliminate the partial redundancy on this frontier by inserting a PHI
523 // node into this block, merging any incoming available versions into the
524 // PHI and inserting a new computation into predecessors without an
525 // incoming value. Note that we would have to insert the expression on
526 // the edge if the predecessor didn't anticipate the expression and we
527 // didn't break critical edges.
529 PHINode *PN = new PHINode(ExprType, Expr->getName()+".PRE",
531 DEBUG(std::cerr << "INSERTING PHI for PR: " << PN);
533 // If there is a pending occurrence in this block, make sure to replace it
534 // with the PHI node...
535 std::map<unsigned, Instruction*>::iterator EDFI =
536 Definitions.find(AFBlockID);
537 if (EDFI != Definitions.end()) {
538 // There is already an occurrence in this block. Replace it with PN and
540 Instruction *OldOcc = EDFI->second;
541 DEBUG(std::cerr << " Replaces occurrence: " << OldOcc);
542 OldOcc->replaceAllUsesWith(PN);
543 AFBlock->getInstList().erase(OldOcc);
544 Definitions.erase(EDFI);
548 for (pred_iterator PI = pred_begin(AFBlock), PE = pred_end(AFBlock);
550 BasicBlock *Pred = *PI;
551 AvailableBlocksTy::iterator LBI = AvailableBlocks.find(Pred);
552 if (LBI != AvailableBlocks.end()) { // If there is a available value
553 PN->addIncoming(LBI->second, Pred); // for this pred, use it.
554 } else { // No available value yet...
555 unsigned PredID = BlockNumbering[Pred];
557 // Is the predecessor the same block that we inserted the PHI into?
559 if (Pred == AFBlock) {
560 // Yes, reuse the incoming value here...
561 PN->addIncoming(PN, Pred);
563 // No, we must insert a new computation into this block and add it
564 // to the definitions list...
565 assert(NonPHIOccurrence && "No non-phi occurrences seen so far???");
566 Instruction *New = NonPHIOccurrence->clone();
567 New->setName(NonPHIOccurrence->getName() + ".PRE-inserted");
568 ProcessedExpressions.insert(New);
570 DEBUG(std::cerr << " INSERTING OCCURRRENCE: " << New);
572 // Insert it into the bottom of the predecessor, right before the
573 // terminator instruction...
574 Pred->getInstList().insert(Pred->getTerminator(), New);
576 // Make this block be the available definition for any blocks it
577 // dominates. The ONLY case that this can affect more than just the
578 // block itself is when we are moving a computation to a loop
579 // header. In all other cases, because we don't have critical
580 // edges, the node is guaranteed to only dominate itself.
582 ReplaceDominatedAvailableOccurrencesWith(New, DT->getNode(Pred));
584 // Add it as an incoming value on this edge to the PHI node
585 PN->addIncoming(New, Pred);
586 NonPHIOccurrence = New;
592 // Find out if there is already an available value in this block. If so,
593 // we need to replace the available value with the PHI node. This can
594 // only happen when we just inserted a PHI node on a backedge.
596 AvailableBlocksTy::iterator LBBlockAvailableValIt =
597 AvailableBlocks.find(AFBlock);
598 if (LBBlockAvailableValIt != AvailableBlocks.end()) {
599 if (LBBlockAvailableValIt->second->getParent() == AFBlock) {
600 Instruction *OldVal = LBBlockAvailableValIt->second;
601 OldVal->replaceAllUsesWith(PN); // Use the new PHI node now
603 DEBUG(std::cerr << " PHI replaces available value: %"
604 << OldVal->getName() << "\n");
606 // Loop over all of the blocks dominated by this PHI node, and change
607 // the AvailableBlocks entries to be the PHI node instead of the old
609 MarkOccurrenceAvailableInAllDominatedBlocks(PN, AFBlock);
611 AFBlock->getInstList().erase(OldVal); // Delete old instruction!
613 // The resultant PHI node is a new definition of the value!
614 Definitions.insert(std::make_pair(AFBlockID, PN));
616 // If the value is not defined in this block, that means that an
617 // inserted occurrence in a predecessor is now the live value for the
618 // region (occurs when hoisting loop invariants, f.e.). In this case,
619 // the PHI node should actually just be removed.
620 assert(PN->use_empty() && "No uses should exist for dead PHI node!");
621 PN->getParent()->getInstList().erase(PN);
624 // The resultant PHI node is a new definition of the value!
625 Definitions.insert(std::make_pair(AFBlockID, PN));
630 AvailableBlocks.clear();