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"
40 Statistic<> NumExprsEliminated("pre", "Number of expressions constantified");
41 Statistic<> NumRedundant ("pre", "Number of redundant exprs eliminated");
42 Statistic<> NumInserted ("pre", "Number of expressions inserted");
44 struct PRE : public FunctionPass {
45 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
46 AU.addRequiredID(BreakCriticalEdgesID); // No critical edges for now!
47 AU.addRequired<PostDominatorTree>();
48 AU.addRequired<PostDominanceFrontier>();
49 AU.addRequired<DominatorSet>();
50 AU.addRequired<DominatorTree>();
51 AU.addRequired<DominanceFrontier>();
52 AU.addRequired<ValueNumbering>();
54 virtual bool runOnFunction(Function &F);
57 // Block information - Map basic blocks in a function back and forth to
59 std::vector<BasicBlock*> BlockMapping;
60 hash_map<BasicBlock*, unsigned> BlockNumbering;
62 // ProcessedExpressions - Keep track of which expressions have already been
64 hash_set<Instruction*> ProcessedExpressions;
66 // Provide access to the various analyses used...
68 DominatorTree *DT; PostDominatorTree *PDT;
69 DominanceFrontier *DF; PostDominanceFrontier *PDF;
72 // AvailableBlocks - Contain a mapping of blocks with available expression
73 // values to the expression value itself. This can be used as an efficient
74 // way to find out if the expression is available in the block, and if so,
75 // which version to use. This map is only used while processing a single
78 typedef hash_map<BasicBlock*, Instruction*> AvailableBlocksTy;
79 AvailableBlocksTy AvailableBlocks;
81 bool ProcessBlock(BasicBlock *BB);
83 // Anticipatibility calculation...
84 void MarkPostDominatingBlocksAnticipatible(PostDominatorTree::Node *N,
85 std::vector<char> &AntBlocks,
86 Instruction *Occurrence);
87 void CalculateAnticipatiblityForOccurrence(unsigned BlockNo,
88 std::vector<char> &AntBlocks,
89 Instruction *Occurrence);
90 void CalculateAnticipatibleBlocks(const std::map<unsigned, Instruction*> &D,
91 std::vector<char> &AnticipatibleBlocks);
93 // PRE for an expression
94 void MarkOccurrenceAvailableInAllDominatedBlocks(Instruction *Occurrence,
95 BasicBlock *StartBlock);
96 void ReplaceDominatedAvailableOccurrencesWith(Instruction *NewOcc,
97 DominatorTree::Node *N);
98 bool ProcessExpression(Instruction *I);
101 RegisterOpt<PRE> Z("pre", "Partial Redundancy Elimination");
105 bool PRE::runOnFunction(Function &F) {
106 VN = &getAnalysis<ValueNumbering>();
107 DS = &getAnalysis<DominatorSet>();
108 DT = &getAnalysis<DominatorTree>();
109 DF = &getAnalysis<DominanceFrontier>();
110 PDT = &getAnalysis<PostDominatorTree>();
111 PDF = &getAnalysis<PostDominanceFrontier>();
113 DEBUG(std::cerr << "\n*** Running PRE on func '" << F.getName() << "'...\n");
115 // Number the basic blocks based on a reverse post-order traversal of the CFG
116 // so that all predecessors of a block (ignoring back edges) are visited
117 // before a block is visited.
119 BlockMapping.reserve(F.size());
121 ReversePostOrderTraversal<Function*> RPOT(&F);
122 DEBUG(std::cerr << "Block order: ");
123 for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
124 E = RPOT.end(); I != E; ++I) {
125 // Keep track of mapping...
127 BlockNumbering.insert(std::make_pair(BB, BlockMapping.size()));
128 BlockMapping.push_back(BB);
129 DEBUG(std::cerr << BB->getName() << " ");
131 DEBUG(std::cerr << "\n");
134 // Traverse the current function depth-first in dominator-tree order. This
135 // ensures that we see all definitions before their uses (except for PHI
136 // nodes), allowing us to hoist dependent expressions correctly.
137 bool Changed = false;
138 for (unsigned i = 0, e = BlockMapping.size(); i != e; ++i)
139 Changed |= ProcessBlock(BlockMapping[i]);
142 BlockMapping.clear();
143 BlockNumbering.clear();
144 ProcessedExpressions.clear();
149 // ProcessBlock - Process any expressions first seen in this block...
151 bool PRE::ProcessBlock(BasicBlock *BB) {
152 bool Changed = false;
154 // PRE expressions first defined in this block...
155 Instruction *PrevInst = 0;
156 for (BasicBlock::iterator I = BB->begin(); I != BB->end(); )
157 if (ProcessExpression(I)) {
158 // The current instruction may have been deleted, make sure to back up to
172 void PRE::MarkPostDominatingBlocksAnticipatible(PostDominatorTree::Node *N,
173 std::vector<char> &AntBlocks,
174 Instruction *Occurrence) {
175 unsigned BlockNo = BlockNumbering[N->getBlock()];
177 if (AntBlocks[BlockNo]) return; // Already known to be anticipatible??
179 // Check to see if any of the operands are defined in this block, if so, the
180 // entry of this block does not anticipate the expression. This computes
182 for (unsigned i = 0, e = Occurrence->getNumOperands(); i != e; ++i)
183 if (Instruction *I = dyn_cast<Instruction>(Occurrence->getOperand(i)))
184 if (I->getParent() == N->getBlock()) // Operand is defined in this block!
187 if (isa<LoadInst>(Occurrence))
188 return; // FIXME: compute transparency for load instructions using AA
190 // Insert block into AntBlocks list...
191 AntBlocks[BlockNo] = true;
193 for (PostDominatorTree::Node::iterator I = N->begin(), E = N->end(); I != E;
195 MarkPostDominatingBlocksAnticipatible(*I, AntBlocks, Occurrence);
198 void PRE::CalculateAnticipatiblityForOccurrence(unsigned BlockNo,
199 std::vector<char> &AntBlocks,
200 Instruction *Occurrence) {
201 if (AntBlocks[BlockNo]) return; // Block already anticipatible!
203 BasicBlock *BB = BlockMapping[BlockNo];
205 // For each occurrence, mark all post-dominated blocks as anticipatible...
206 MarkPostDominatingBlocksAnticipatible(PDT->getNode(BB), AntBlocks,
209 // Next, mark any blocks in the post-dominance frontier as anticipatible iff
210 // all successors are anticipatible.
212 PostDominanceFrontier::iterator PDFI = PDF->find(BB);
213 if (PDFI != DF->end())
214 for (std::set<BasicBlock*>::iterator DI = PDFI->second.begin();
215 DI != PDFI->second.end(); ++DI) {
216 BasicBlock *PDFBlock = *DI;
217 bool AllSuccessorsAnticipatible = true;
218 for (succ_iterator SI = succ_begin(PDFBlock), SE = succ_end(PDFBlock);
220 if (!AntBlocks[BlockNumbering[*SI]]) {
221 AllSuccessorsAnticipatible = false;
225 if (AllSuccessorsAnticipatible)
226 CalculateAnticipatiblityForOccurrence(BlockNumbering[PDFBlock],
227 AntBlocks, Occurrence);
232 void PRE::CalculateAnticipatibleBlocks(const std::map<unsigned,
234 std::vector<char> &AntBlocks) {
235 // Initialize to zeros...
236 AntBlocks.resize(BlockMapping.size());
238 // Loop over all of the expressions...
239 for (std::map<unsigned, Instruction*>::const_iterator I = Defs.begin(),
240 E = Defs.end(); I != E; ++I)
241 CalculateAnticipatiblityForOccurrence(I->first, AntBlocks, I->second);
244 /// MarkOccurrenceAvailableInAllDominatedBlocks - Add entries to AvailableBlocks
245 /// for all nodes dominated by the occurrence to indicate that it is now the
246 /// available occurrence to use in any of these blocks.
248 void PRE::MarkOccurrenceAvailableInAllDominatedBlocks(Instruction *Occurrence,
250 // FIXME: There are much more efficient ways to get the blocks dominated
251 // by a block. Use them.
253 DominatorTree::Node *N = DT->getNode(Occurrence->getParent());
254 for (df_iterator<DominatorTree::Node*> DI = df_begin(N), E = df_end(N);
256 AvailableBlocks[(*DI)->getBlock()] = Occurrence;
259 /// ReplaceDominatedAvailableOccurrencesWith - This loops over the region
260 /// dominated by N, replacing any available expressions with NewOcc.
261 void PRE::ReplaceDominatedAvailableOccurrencesWith(Instruction *NewOcc,
262 DominatorTree::Node *N) {
263 BasicBlock *BB = N->getBlock();
264 Instruction *&ExistingAvailableVal = AvailableBlocks[BB];
266 // If there isn't a definition already active in this node, make this the new
267 // active definition...
268 if (ExistingAvailableVal == 0) {
269 ExistingAvailableVal = NewOcc;
271 for (DominatorTree::Node::iterator I = N->begin(), E = N->end(); I != E;++I)
272 ReplaceDominatedAvailableOccurrencesWith(NewOcc, *I);
274 // If there is already an active definition in this block, replace it with
275 // NewOcc, and force it into all dominated blocks.
276 DEBUG(std::cerr << " Replacing dominated occ %"
277 << ExistingAvailableVal->getName() << " with %" << NewOcc->getName()
279 assert(ExistingAvailableVal != NewOcc && "NewOcc already inserted??");
280 ExistingAvailableVal->replaceAllUsesWith(NewOcc);
283 assert(ExistingAvailableVal->getParent() == BB &&
284 "OldOcc not defined in current block?");
285 BB->getInstList().erase(ExistingAvailableVal);
287 // Mark NewOCC as the Available expression in all blocks dominated by BB
288 for (df_iterator<DominatorTree::Node*> DI = df_begin(N), E = df_end(N);
290 AvailableBlocks[(*DI)->getBlock()] = NewOcc;
295 /// ProcessExpression - Given an expression (instruction) process the
296 /// instruction to remove any partial redundancies induced by equivalent
297 /// computations. Note that we only need to PRE each expression once, so we
298 /// keep track of whether an expression has been PRE'd already, and don't PRE an
299 /// expression again. Expressions may be seen multiple times because process
300 /// the entire equivalence class at once, which may leave expressions later in
301 /// the control path.
303 bool PRE::ProcessExpression(Instruction *Expr) {
304 if (Expr->mayWriteToMemory() || Expr->getType() == Type::VoidTy ||
306 return false; // Cannot move expression
307 if (ProcessedExpressions.count(Expr)) return false; // Already processed.
309 // Ok, this is the first time we have seen the expression. Build a set of
310 // equivalent expressions using SSA def/use information. We consider
311 // expressions to be equivalent if they are the same opcode and have
312 // equivalent operands. As a special case for SSA, values produced by PHI
313 // nodes are considered to be equivalent to all of their operands.
315 std::vector<Value*> Values;
316 VN->getEqualNumberNodes(Expr, Values);
319 // FIXME: This should handle PHI nodes correctly. To do this, we need to
320 // consider expressions of the following form equivalent to this set of
323 // If an operand is a PHI node, add any occurrences of the expression with the
324 // PHI operand replaced with the PHI node operands. This is only valid if the
325 // PHI operand occurrences exist in blocks post-dominated by the incoming edge
329 // We have to be careful to handle expression definitions which dominated by
330 // other expressions. These can be directly eliminated in favor of their
331 // dominating value. Keep track of which blocks contain definitions (the key)
332 // and if a block contains a definition, which instruction it is.
334 std::map<unsigned, Instruction*> Definitions;
335 Definitions.insert(std::make_pair(BlockNumbering[Expr->getParent()], Expr));
337 bool Changed = false;
339 // Look at all of the equal values. If any of the values is not an
340 // instruction, replace all other expressions immediately with it (it must be
341 // an argument or a constant or something). Otherwise, convert the list of
342 // values into a list of expression (instruction) definitions ordering
343 // according to their dominator tree ordering.
345 Value *NonInstValue = 0;
346 for (unsigned i = 0, e = Values.size(); i != e; ++i)
347 if (Instruction *I = dyn_cast<Instruction>(Values[i])) {
348 Instruction *&BlockInst = Definitions[BlockNumbering[I->getParent()]];
349 if (BlockInst && BlockInst != I) { // Eliminate direct redundancy
350 if (DS->dominates(I, BlockInst)) { // I dom BlockInst
351 BlockInst->replaceAllUsesWith(I);
352 BlockInst->getParent()->getInstList().erase(BlockInst);
353 } else { // BlockInst dom I
354 I->replaceAllUsesWith(BlockInst);
355 I->getParent()->getInstList().erase(I);
362 NonInstValue = Values[i];
365 std::vector<Value*>().swap(Values); // Done with the values list
368 // This is the good, though unlikely, case where we find out that this
369 // expression is equal to a constant or argument directly. We can replace
370 // this and all of the other equivalent instructions with the value
373 for (std::map<unsigned, Instruction*>::iterator I = Definitions.begin(),
374 E = Definitions.end(); I != E; ++I) {
375 Instruction *Inst = I->second;
376 // Replace the value with the specified non-instruction value.
377 Inst->replaceAllUsesWith(NonInstValue); // Fixup any uses
378 Inst->getParent()->getInstList().erase(Inst); // Erase the instruction
380 NumExprsEliminated += Definitions.size();
381 return true; // Program modified!
384 // There are no expressions equal to this one. Exit early.
385 assert(!Definitions.empty() && "no equal expressions??");
387 if (Definitions.size() == 1) {
388 ProcessedExpressions.insert(Definitions.begin()->second);
392 DEBUG(std::cerr << "\n====--- Expression: " << Expr);
393 const Type *ExprType = Expr->getType();
395 // AnticipatibleBlocks - Blocks where the current expression is anticipatible.
396 // This is logically std::vector<bool> but using 'char' for performance.
397 std::vector<char> AnticipatibleBlocks;
399 // Calculate all of the blocks which the current expression is anticipatible.
400 CalculateAnticipatibleBlocks(Definitions, AnticipatibleBlocks);
402 // Print out anticipatible blocks...
403 DEBUG(std::cerr << "AntBlocks: ";
404 for (unsigned i = 0, e = AnticipatibleBlocks.size(); i != e; ++i)
405 if (AnticipatibleBlocks[i])
406 std::cerr << BlockMapping[i]->getName() <<" ";
411 // AvailabilityFrontier - Calculates the availability frontier for the current
412 // expression. The availability frontier contains the blocks on the dominance
413 // frontier of the current available expressions, iff they anticipate a
414 // definition of the expression.
415 hash_set<unsigned> AvailabilityFrontier;
417 Instruction *NonPHIOccurrence = 0;
419 while (!Definitions.empty() || !AvailabilityFrontier.empty()) {
420 if (!Definitions.empty() &&
421 (AvailabilityFrontier.empty() ||
422 Definitions.begin()->first < *AvailabilityFrontier.begin())) {
423 Instruction *Occurrence = Definitions.begin()->second;
424 BasicBlock *BB = Occurrence->getParent();
425 Definitions.erase(Definitions.begin());
427 DEBUG(std::cerr << "PROCESSING Occurrence: " << Occurrence);
429 // Check to see if there is already an incoming value for this block...
430 AvailableBlocksTy::iterator LBI = AvailableBlocks.find(BB);
431 if (LBI != AvailableBlocks.end()) {
432 // Yes, there is a dominating definition for this block. Replace this
433 // occurrence with the incoming value.
434 if (LBI->second != Occurrence) {
435 DEBUG(std::cerr << " replacing with: " << LBI->second);
436 Occurrence->replaceAllUsesWith(LBI->second);
437 BB->getInstList().erase(Occurrence); // Delete instruction
441 ProcessedExpressions.insert(Occurrence);
442 if (!isa<PHINode>(Occurrence))
443 NonPHIOccurrence = Occurrence; // Keep an occurrence of this expr
445 // Okay, there is no incoming value for this block, so this expression
446 // is a new definition that is good for this block and all blocks
447 // dominated by it. Add this information to the AvailableBlocks map.
449 MarkOccurrenceAvailableInAllDominatedBlocks(Occurrence, BB);
451 // Update the dominance frontier for the definitions so far... if a node
452 // in the dominator frontier now has all of its predecessors available,
453 // and the block is in an anticipatible region, we can insert a PHI node
455 DominanceFrontier::iterator DFI = DF->find(BB);
456 if (DFI != DF->end()) {
457 for (std::set<BasicBlock*>::iterator DI = DFI->second.begin();
458 DI != DFI->second.end(); ++DI) {
459 BasicBlock *DFBlock = *DI;
460 unsigned DFBlockID = BlockNumbering[DFBlock];
461 if (AnticipatibleBlocks[DFBlockID]) {
462 // Check to see if any of the predecessors of this block on the
463 // frontier are not available...
464 bool AnyNotAvailable = false;
465 for (pred_iterator PI = pred_begin(DFBlock),
466 PE = pred_end(DFBlock); PI != PE; ++PI)
467 if (!AvailableBlocks.count(*PI)) {
468 AnyNotAvailable = true;
472 // If any predecessor blocks are not available, add the node to
473 // the current expression dominance frontier.
474 if (AnyNotAvailable) {
475 AvailabilityFrontier.insert(DFBlockID);
477 // This block is no longer in the availability frontier, it IS
479 AvailabilityFrontier.erase(DFBlockID);
481 // If all of the predecessor blocks are available (and the block
482 // anticipates a definition along the path to the exit), we need
483 // to insert a new PHI node in this block. This block serves as
484 // a new definition for the expression, extending the available
487 PHINode *PN = new PHINode(ExprType, Expr->getName()+".pre",
489 ProcessedExpressions.insert(PN);
491 DEBUG(std::cerr << " INSERTING PHI on frontier: " << PN);
493 // Add the incoming blocks for the PHI node
494 for (pred_iterator PI = pred_begin(DFBlock),
495 PE = pred_end(DFBlock); PI != PE; ++PI)
497 PN->addIncoming(AvailableBlocks[*PI], *PI);
498 else // edge from the current block
499 PN->addIncoming(PN, DFBlock);
501 Instruction *&BlockOcc = Definitions[DFBlockID];
503 DEBUG(std::cerr <<" PHI superceeds occurrence: "<<BlockOcc);
504 BlockOcc->replaceAllUsesWith(PN);
505 BlockOcc->getParent()->getInstList().erase(BlockOcc);
516 // Otherwise we must be looking at a node in the availability frontier!
517 unsigned AFBlockID = *AvailabilityFrontier.begin();
518 AvailabilityFrontier.erase(AvailabilityFrontier.begin());
519 BasicBlock *AFBlock = BlockMapping[AFBlockID];
521 // We eliminate the partial redundancy on this frontier by inserting a PHI
522 // node into this block, merging any incoming available versions into the
523 // PHI and inserting a new computation into predecessors without an
524 // incoming value. Note that we would have to insert the expression on
525 // the edge if the predecessor didn't anticipate the expression and we
526 // didn't break critical edges.
528 PHINode *PN = new PHINode(ExprType, Expr->getName()+".PRE",
530 DEBUG(std::cerr << "INSERTING PHI for PR: " << PN);
532 // If there is a pending occurrence in this block, make sure to replace it
533 // with the PHI node...
534 std::map<unsigned, Instruction*>::iterator EDFI =
535 Definitions.find(AFBlockID);
536 if (EDFI != Definitions.end()) {
537 // There is already an occurrence in this block. Replace it with PN and
539 Instruction *OldOcc = EDFI->second;
540 DEBUG(std::cerr << " Replaces occurrence: " << OldOcc);
541 OldOcc->replaceAllUsesWith(PN);
542 AFBlock->getInstList().erase(OldOcc);
543 Definitions.erase(EDFI);
547 for (pred_iterator PI = pred_begin(AFBlock), PE = pred_end(AFBlock);
549 BasicBlock *Pred = *PI;
550 AvailableBlocksTy::iterator LBI = AvailableBlocks.find(Pred);
551 if (LBI != AvailableBlocks.end()) { // If there is a available value
552 PN->addIncoming(LBI->second, Pred); // for this pred, use it.
553 } else { // No available value yet...
554 unsigned PredID = BlockNumbering[Pred];
556 // Is the predecessor the same block that we inserted the PHI into?
558 if (Pred == AFBlock) {
559 // Yes, reuse the incoming value here...
560 PN->addIncoming(PN, Pred);
562 // No, we must insert a new computation into this block and add it
563 // to the definitions list...
564 assert(NonPHIOccurrence && "No non-phi occurrences seen so far???");
565 Instruction *New = NonPHIOccurrence->clone();
566 New->setName(NonPHIOccurrence->getName() + ".PRE-inserted");
567 ProcessedExpressions.insert(New);
569 DEBUG(std::cerr << " INSERTING OCCURRRENCE: " << New);
571 // Insert it into the bottom of the predecessor, right before the
572 // terminator instruction...
573 Pred->getInstList().insert(Pred->getTerminator(), New);
575 // Make this block be the available definition for any blocks it
576 // dominates. The ONLY case that this can affect more than just the
577 // block itself is when we are moving a computation to a loop
578 // header. In all other cases, because we don't have critical
579 // edges, the node is guaranteed to only dominate itself.
581 ReplaceDominatedAvailableOccurrencesWith(New, DT->getNode(Pred));
583 // Add it as an incoming value on this edge to the PHI node
584 PN->addIncoming(New, Pred);
585 NonPHIOccurrence = New;
591 // Find out if there is already an available value in this block. If so,
592 // we need to replace the available value with the PHI node. This can
593 // only happen when we just inserted a PHI node on a backedge.
595 AvailableBlocksTy::iterator LBBlockAvailableValIt =
596 AvailableBlocks.find(AFBlock);
597 if (LBBlockAvailableValIt != AvailableBlocks.end()) {
598 if (LBBlockAvailableValIt->second->getParent() == AFBlock) {
599 Instruction *OldVal = LBBlockAvailableValIt->second;
600 OldVal->replaceAllUsesWith(PN); // Use the new PHI node now
602 DEBUG(std::cerr << " PHI replaces available value: %"
603 << OldVal->getName() << "\n");
605 // Loop over all of the blocks dominated by this PHI node, and change
606 // the AvailableBlocks entries to be the PHI node instead of the old
608 MarkOccurrenceAvailableInAllDominatedBlocks(PN, AFBlock);
610 AFBlock->getInstList().erase(OldVal); // Delete old instruction!
612 // The resultant PHI node is a new definition of the value!
613 Definitions.insert(std::make_pair(AFBlockID, PN));
615 // If the value is not defined in this block, that means that an
616 // inserted occurrence in a predecessor is now the live value for the
617 // region (occurs when hoisting loop invariants, f.e.). In this case,
618 // the PHI node should actually just be removed.
619 assert(PN->use_empty() && "No uses should exist for dead PHI node!");
620 PN->getParent()->getInstList().erase(PN);
623 // The resultant PHI node is a new definition of the value!
624 Definitions.insert(std::make_pair(AFBlockID, PN));
629 AvailableBlocks.clear();