blob: 770cd44d75f7e8a0b1220fb1a32203a055f6556e [file] [log] [blame]
Chris Lattnere9412912003-03-31 19:55:43 +00001//===- PRE.cpp - Partial Redundancy Elimination ---------------------------===//
John Criswellb576c942003-10-20 19:43:21 +00002//
3// The LLVM Compiler Infrastructure
4//
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.
7//
8//===----------------------------------------------------------------------===//
Chris Lattnere9412912003-03-31 19:55:43 +00009//
Misha Brukmandfa5f832003-09-09 21:54:45 +000010// This file implements the well-known Partial Redundancy Elimination
Chris Lattnere9412912003-03-31 19:55:43 +000011// optimization, using an SSA formulation based on e-paths. See this paper for
12// more information:
13//
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
17//
18// This file actually implements a sparse version of the algorithm, using SSA
19// and CFG properties instead of bit-vectors.
20//
21//===----------------------------------------------------------------------===//
22
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"
Chris Lattner6806f562003-08-01 22:15:03 +000033#include "Support/Debug.h"
Chris Lattnere9412912003-03-31 19:55:43 +000034#include "Support/DepthFirstIterator.h"
35#include "Support/PostOrderIterator.h"
36#include "Support/Statistic.h"
37#include "Support/hash_set"
38
Brian Gaeked0fde302003-11-11 22:41:34 +000039namespace llvm {
40
Chris Lattnere9412912003-03-31 19:55:43 +000041namespace {
42 Statistic<> NumExprsEliminated("pre", "Number of expressions constantified");
43 Statistic<> NumRedundant ("pre", "Number of redundant exprs eliminated");
Brian Gaeked0fde302003-11-11 22:41:34 +000044 static Statistic<> NumInserted ("pre", "Number of expressions inserted");
Chris Lattnere9412912003-03-31 19:55:43 +000045
46 struct PRE : public FunctionPass {
47 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
48 AU.addRequiredID(BreakCriticalEdgesID); // No critical edges for now!
49 AU.addRequired<PostDominatorTree>();
50 AU.addRequired<PostDominanceFrontier>();
51 AU.addRequired<DominatorSet>();
52 AU.addRequired<DominatorTree>();
53 AU.addRequired<DominanceFrontier>();
54 AU.addRequired<ValueNumbering>();
55 }
56 virtual bool runOnFunction(Function &F);
57
58 private:
59 // Block information - Map basic blocks in a function back and forth to
60 // unsigned integers.
61 std::vector<BasicBlock*> BlockMapping;
62 hash_map<BasicBlock*, unsigned> BlockNumbering;
63
64 // ProcessedExpressions - Keep track of which expressions have already been
65 // processed.
66 hash_set<Instruction*> ProcessedExpressions;
67
68 // Provide access to the various analyses used...
69 DominatorSet *DS;
70 DominatorTree *DT; PostDominatorTree *PDT;
71 DominanceFrontier *DF; PostDominanceFrontier *PDF;
72 ValueNumbering *VN;
73
74 // AvailableBlocks - Contain a mapping of blocks with available expression
75 // values to the expression value itself. This can be used as an efficient
76 // way to find out if the expression is available in the block, and if so,
77 // which version to use. This map is only used while processing a single
78 // expression.
79 //
80 typedef hash_map<BasicBlock*, Instruction*> AvailableBlocksTy;
81 AvailableBlocksTy AvailableBlocks;
82
83 bool ProcessBlock(BasicBlock *BB);
84
85 // Anticipatibility calculation...
86 void MarkPostDominatingBlocksAnticipatible(PostDominatorTree::Node *N,
87 std::vector<char> &AntBlocks,
Misha Brukmandfa5f832003-09-09 21:54:45 +000088 Instruction *Occurrence);
89 void CalculateAnticipatiblityForOccurrence(unsigned BlockNo,
Chris Lattnere9412912003-03-31 19:55:43 +000090 std::vector<char> &AntBlocks,
Misha Brukmandfa5f832003-09-09 21:54:45 +000091 Instruction *Occurrence);
Chris Lattnere9412912003-03-31 19:55:43 +000092 void CalculateAnticipatibleBlocks(const std::map<unsigned, Instruction*> &D,
93 std::vector<char> &AnticipatibleBlocks);
94
95 // PRE for an expression
Misha Brukmandfa5f832003-09-09 21:54:45 +000096 void MarkOccurrenceAvailableInAllDominatedBlocks(Instruction *Occurrence,
97 BasicBlock *StartBlock);
98 void ReplaceDominatedAvailableOccurrencesWith(Instruction *NewOcc,
99 DominatorTree::Node *N);
Chris Lattnere9412912003-03-31 19:55:43 +0000100 bool ProcessExpression(Instruction *I);
101 };
102
103 RegisterOpt<PRE> Z("pre", "Partial Redundancy Elimination");
104}
105
106
107bool PRE::runOnFunction(Function &F) {
108 VN = &getAnalysis<ValueNumbering>();
109 DS = &getAnalysis<DominatorSet>();
110 DT = &getAnalysis<DominatorTree>();
111 DF = &getAnalysis<DominanceFrontier>();
112 PDT = &getAnalysis<PostDominatorTree>();
113 PDF = &getAnalysis<PostDominanceFrontier>();
114
115 DEBUG(std::cerr << "\n*** Running PRE on func '" << F.getName() << "'...\n");
116
117 // Number the basic blocks based on a reverse post-order traversal of the CFG
118 // so that all predecessors of a block (ignoring back edges) are visited
119 // before a block is visited.
120 //
121 BlockMapping.reserve(F.size());
122 {
123 ReversePostOrderTraversal<Function*> RPOT(&F);
124 DEBUG(std::cerr << "Block order: ");
125 for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
126 E = RPOT.end(); I != E; ++I) {
127 // Keep track of mapping...
128 BasicBlock *BB = *I;
129 BlockNumbering.insert(std::make_pair(BB, BlockMapping.size()));
130 BlockMapping.push_back(BB);
131 DEBUG(std::cerr << BB->getName() << " ");
132 }
133 DEBUG(std::cerr << "\n");
134 }
135
136 // Traverse the current function depth-first in dominator-tree order. This
137 // ensures that we see all definitions before their uses (except for PHI
138 // nodes), allowing us to hoist dependent expressions correctly.
139 bool Changed = false;
140 for (unsigned i = 0, e = BlockMapping.size(); i != e; ++i)
141 Changed |= ProcessBlock(BlockMapping[i]);
142
143 // Free memory
144 BlockMapping.clear();
145 BlockNumbering.clear();
146 ProcessedExpressions.clear();
147 return Changed;
148}
149
150
151// ProcessBlock - Process any expressions first seen in this block...
152//
153bool PRE::ProcessBlock(BasicBlock *BB) {
154 bool Changed = false;
155
156 // PRE expressions first defined in this block...
157 Instruction *PrevInst = 0;
158 for (BasicBlock::iterator I = BB->begin(); I != BB->end(); )
159 if (ProcessExpression(I)) {
160 // The current instruction may have been deleted, make sure to back up to
161 // PrevInst instead.
162 if (PrevInst)
163 I = PrevInst;
164 else
165 I = BB->begin();
166 Changed = true;
167 } else {
168 PrevInst = I++;
169 }
170
171 return Changed;
172}
173
174void PRE::MarkPostDominatingBlocksAnticipatible(PostDominatorTree::Node *N,
175 std::vector<char> &AntBlocks,
Misha Brukmandfa5f832003-09-09 21:54:45 +0000176 Instruction *Occurrence) {
Chris Lattnerc444a422003-09-11 16:26:13 +0000177 unsigned BlockNo = BlockNumbering[N->getBlock()];
Chris Lattnere9412912003-03-31 19:55:43 +0000178
179 if (AntBlocks[BlockNo]) return; // Already known to be anticipatible??
180
181 // Check to see if any of the operands are defined in this block, if so, the
182 // entry of this block does not anticipate the expression. This computes
183 // "transparency".
Misha Brukmandfa5f832003-09-09 21:54:45 +0000184 for (unsigned i = 0, e = Occurrence->getNumOperands(); i != e; ++i)
185 if (Instruction *I = dyn_cast<Instruction>(Occurrence->getOperand(i)))
Chris Lattnerc444a422003-09-11 16:26:13 +0000186 if (I->getParent() == N->getBlock()) // Operand is defined in this block!
Chris Lattnere9412912003-03-31 19:55:43 +0000187 return;
188
Misha Brukmandfa5f832003-09-09 21:54:45 +0000189 if (isa<LoadInst>(Occurrence))
Chris Lattnere9412912003-03-31 19:55:43 +0000190 return; // FIXME: compute transparency for load instructions using AA
191
192 // Insert block into AntBlocks list...
193 AntBlocks[BlockNo] = true;
194
195 for (PostDominatorTree::Node::iterator I = N->begin(), E = N->end(); I != E;
196 ++I)
Misha Brukmandfa5f832003-09-09 21:54:45 +0000197 MarkPostDominatingBlocksAnticipatible(*I, AntBlocks, Occurrence);
Chris Lattnere9412912003-03-31 19:55:43 +0000198}
199
Misha Brukmandfa5f832003-09-09 21:54:45 +0000200void PRE::CalculateAnticipatiblityForOccurrence(unsigned BlockNo,
201 std::vector<char> &AntBlocks,
202 Instruction *Occurrence) {
Chris Lattnere9412912003-03-31 19:55:43 +0000203 if (AntBlocks[BlockNo]) return; // Block already anticipatible!
204
205 BasicBlock *BB = BlockMapping[BlockNo];
206
Misha Brukmandfa5f832003-09-09 21:54:45 +0000207 // For each occurrence, mark all post-dominated blocks as anticipatible...
Chris Lattnere9412912003-03-31 19:55:43 +0000208 MarkPostDominatingBlocksAnticipatible(PDT->getNode(BB), AntBlocks,
Misha Brukmandfa5f832003-09-09 21:54:45 +0000209 Occurrence);
Chris Lattnere9412912003-03-31 19:55:43 +0000210
211 // Next, mark any blocks in the post-dominance frontier as anticipatible iff
212 // all successors are anticipatible.
213 //
214 PostDominanceFrontier::iterator PDFI = PDF->find(BB);
215 if (PDFI != DF->end())
216 for (std::set<BasicBlock*>::iterator DI = PDFI->second.begin();
217 DI != PDFI->second.end(); ++DI) {
218 BasicBlock *PDFBlock = *DI;
219 bool AllSuccessorsAnticipatible = true;
220 for (succ_iterator SI = succ_begin(PDFBlock), SE = succ_end(PDFBlock);
221 SI != SE; ++SI)
222 if (!AntBlocks[BlockNumbering[*SI]]) {
223 AllSuccessorsAnticipatible = false;
224 break;
225 }
226
227 if (AllSuccessorsAnticipatible)
Misha Brukmandfa5f832003-09-09 21:54:45 +0000228 CalculateAnticipatiblityForOccurrence(BlockNumbering[PDFBlock],
229 AntBlocks, Occurrence);
Chris Lattnere9412912003-03-31 19:55:43 +0000230 }
231}
232
233
234void PRE::CalculateAnticipatibleBlocks(const std::map<unsigned,
235 Instruction*> &Defs,
236 std::vector<char> &AntBlocks) {
237 // Initialize to zeros...
238 AntBlocks.resize(BlockMapping.size());
239
240 // Loop over all of the expressions...
241 for (std::map<unsigned, Instruction*>::const_iterator I = Defs.begin(),
242 E = Defs.end(); I != E; ++I)
Misha Brukmandfa5f832003-09-09 21:54:45 +0000243 CalculateAnticipatiblityForOccurrence(I->first, AntBlocks, I->second);
Chris Lattnere9412912003-03-31 19:55:43 +0000244}
245
Misha Brukmandfa5f832003-09-09 21:54:45 +0000246/// MarkOccurrenceAvailableInAllDominatedBlocks - Add entries to AvailableBlocks
247/// for all nodes dominated by the occurrence to indicate that it is now the
248/// available occurrence to use in any of these blocks.
Chris Lattnere9412912003-03-31 19:55:43 +0000249///
Misha Brukmandfa5f832003-09-09 21:54:45 +0000250void PRE::MarkOccurrenceAvailableInAllDominatedBlocks(Instruction *Occurrence,
251 BasicBlock *BB) {
Chris Lattnere9412912003-03-31 19:55:43 +0000252 // FIXME: There are much more efficient ways to get the blocks dominated
253 // by a block. Use them.
254 //
Misha Brukmandfa5f832003-09-09 21:54:45 +0000255 DominatorTree::Node *N = DT->getNode(Occurrence->getParent());
Chris Lattnere9412912003-03-31 19:55:43 +0000256 for (df_iterator<DominatorTree::Node*> DI = df_begin(N), E = df_end(N);
257 DI != E; ++DI)
Chris Lattnerc444a422003-09-11 16:26:13 +0000258 AvailableBlocks[(*DI)->getBlock()] = Occurrence;
Chris Lattnere9412912003-03-31 19:55:43 +0000259}
260
Misha Brukmandfa5f832003-09-09 21:54:45 +0000261/// ReplaceDominatedAvailableOccurrencesWith - This loops over the region
Chris Lattnere9412912003-03-31 19:55:43 +0000262/// dominated by N, replacing any available expressions with NewOcc.
Misha Brukmandfa5f832003-09-09 21:54:45 +0000263void PRE::ReplaceDominatedAvailableOccurrencesWith(Instruction *NewOcc,
264 DominatorTree::Node *N) {
Chris Lattnerc444a422003-09-11 16:26:13 +0000265 BasicBlock *BB = N->getBlock();
Chris Lattnere9412912003-03-31 19:55:43 +0000266 Instruction *&ExistingAvailableVal = AvailableBlocks[BB];
267
268 // If there isn't a definition already active in this node, make this the new
269 // active definition...
270 if (ExistingAvailableVal == 0) {
271 ExistingAvailableVal = NewOcc;
272
273 for (DominatorTree::Node::iterator I = N->begin(), E = N->end(); I != E;++I)
Misha Brukmandfa5f832003-09-09 21:54:45 +0000274 ReplaceDominatedAvailableOccurrencesWith(NewOcc, *I);
Chris Lattnere9412912003-03-31 19:55:43 +0000275 } else {
276 // If there is already an active definition in this block, replace it with
277 // NewOcc, and force it into all dominated blocks.
278 DEBUG(std::cerr << " Replacing dominated occ %"
279 << ExistingAvailableVal->getName() << " with %" << NewOcc->getName()
280 << "\n");
281 assert(ExistingAvailableVal != NewOcc && "NewOcc already inserted??");
282 ExistingAvailableVal->replaceAllUsesWith(NewOcc);
283 ++NumRedundant;
284
285 assert(ExistingAvailableVal->getParent() == BB &&
286 "OldOcc not defined in current block?");
287 BB->getInstList().erase(ExistingAvailableVal);
288
289 // Mark NewOCC as the Available expression in all blocks dominated by BB
290 for (df_iterator<DominatorTree::Node*> DI = df_begin(N), E = df_end(N);
291 DI != E; ++DI)
Chris Lattnerc444a422003-09-11 16:26:13 +0000292 AvailableBlocks[(*DI)->getBlock()] = NewOcc;
Chris Lattnere9412912003-03-31 19:55:43 +0000293 }
294}
295
296
297/// ProcessExpression - Given an expression (instruction) process the
298/// instruction to remove any partial redundancies induced by equivalent
299/// computations. Note that we only need to PRE each expression once, so we
300/// keep track of whether an expression has been PRE'd already, and don't PRE an
301/// expression again. Expressions may be seen multiple times because process
302/// the entire equivalence class at once, which may leave expressions later in
303/// the control path.
304///
305bool PRE::ProcessExpression(Instruction *Expr) {
306 if (Expr->mayWriteToMemory() || Expr->getType() == Type::VoidTy ||
307 isa<PHINode>(Expr))
308 return false; // Cannot move expression
309 if (ProcessedExpressions.count(Expr)) return false; // Already processed.
310
311 // Ok, this is the first time we have seen the expression. Build a set of
312 // equivalent expressions using SSA def/use information. We consider
313 // expressions to be equivalent if they are the same opcode and have
314 // equivalent operands. As a special case for SSA, values produced by PHI
315 // nodes are considered to be equivalent to all of their operands.
316 //
317 std::vector<Value*> Values;
318 VN->getEqualNumberNodes(Expr, Values);
319
Chris Lattnerfaf4cc22003-05-29 20:26:30 +0000320#if 0
321 // FIXME: This should handle PHI nodes correctly. To do this, we need to
322 // consider expressions of the following form equivalent to this set of
323 // expressions:
324 //
Misha Brukmandfa5f832003-09-09 21:54:45 +0000325 // If an operand is a PHI node, add any occurrences of the expression with the
Chris Lattnerfaf4cc22003-05-29 20:26:30 +0000326 // PHI operand replaced with the PHI node operands. This is only valid if the
Misha Brukmandfa5f832003-09-09 21:54:45 +0000327 // PHI operand occurrences exist in blocks post-dominated by the incoming edge
Chris Lattnerfaf4cc22003-05-29 20:26:30 +0000328 // of the PHI node.
329#endif
330
Chris Lattnere9412912003-03-31 19:55:43 +0000331 // We have to be careful to handle expression definitions which dominated by
332 // other expressions. These can be directly eliminated in favor of their
333 // dominating value. Keep track of which blocks contain definitions (the key)
334 // and if a block contains a definition, which instruction it is.
335 //
336 std::map<unsigned, Instruction*> Definitions;
337 Definitions.insert(std::make_pair(BlockNumbering[Expr->getParent()], Expr));
338
339 bool Changed = false;
340
341 // Look at all of the equal values. If any of the values is not an
342 // instruction, replace all other expressions immediately with it (it must be
343 // an argument or a constant or something). Otherwise, convert the list of
344 // values into a list of expression (instruction) definitions ordering
345 // according to their dominator tree ordering.
346 //
347 Value *NonInstValue = 0;
348 for (unsigned i = 0, e = Values.size(); i != e; ++i)
349 if (Instruction *I = dyn_cast<Instruction>(Values[i])) {
350 Instruction *&BlockInst = Definitions[BlockNumbering[I->getParent()]];
351 if (BlockInst && BlockInst != I) { // Eliminate direct redundancy
352 if (DS->dominates(I, BlockInst)) { // I dom BlockInst
353 BlockInst->replaceAllUsesWith(I);
354 BlockInst->getParent()->getInstList().erase(BlockInst);
355 } else { // BlockInst dom I
356 I->replaceAllUsesWith(BlockInst);
357 I->getParent()->getInstList().erase(I);
358 I = BlockInst;
359 }
360 ++NumRedundant;
361 }
362 BlockInst = I;
363 } else {
364 NonInstValue = Values[i];
365 }
366
367 std::vector<Value*>().swap(Values); // Done with the values list
368
369 if (NonInstValue) {
370 // This is the good, though unlikely, case where we find out that this
371 // expression is equal to a constant or argument directly. We can replace
372 // this and all of the other equivalent instructions with the value
373 // directly.
374 //
375 for (std::map<unsigned, Instruction*>::iterator I = Definitions.begin(),
376 E = Definitions.end(); I != E; ++I) {
377 Instruction *Inst = I->second;
378 // Replace the value with the specified non-instruction value.
379 Inst->replaceAllUsesWith(NonInstValue); // Fixup any uses
380 Inst->getParent()->getInstList().erase(Inst); // Erase the instruction
381 }
382 NumExprsEliminated += Definitions.size();
383 return true; // Program modified!
384 }
385
386 // There are no expressions equal to this one. Exit early.
387 assert(!Definitions.empty() && "no equal expressions??");
388#if 0
389 if (Definitions.size() == 1) {
390 ProcessedExpressions.insert(Definitions.begin()->second);
391 return Changed;
392 }
393#endif
394 DEBUG(std::cerr << "\n====--- Expression: " << Expr);
395 const Type *ExprType = Expr->getType();
396
397 // AnticipatibleBlocks - Blocks where the current expression is anticipatible.
398 // This is logically std::vector<bool> but using 'char' for performance.
399 std::vector<char> AnticipatibleBlocks;
400
401 // Calculate all of the blocks which the current expression is anticipatible.
402 CalculateAnticipatibleBlocks(Definitions, AnticipatibleBlocks);
403
404 // Print out anticipatible blocks...
405 DEBUG(std::cerr << "AntBlocks: ";
406 for (unsigned i = 0, e = AnticipatibleBlocks.size(); i != e; ++i)
407 if (AnticipatibleBlocks[i])
408 std::cerr << BlockMapping[i]->getName() <<" ";
409 std::cerr << "\n";);
410
411
412
413 // AvailabilityFrontier - Calculates the availability frontier for the current
414 // expression. The availability frontier contains the blocks on the dominance
415 // frontier of the current available expressions, iff they anticipate a
416 // definition of the expression.
417 hash_set<unsigned> AvailabilityFrontier;
418
Misha Brukmandfa5f832003-09-09 21:54:45 +0000419 Instruction *NonPHIOccurrence = 0;
Chris Lattnere9412912003-03-31 19:55:43 +0000420
421 while (!Definitions.empty() || !AvailabilityFrontier.empty()) {
422 if (!Definitions.empty() &&
423 (AvailabilityFrontier.empty() ||
424 Definitions.begin()->first < *AvailabilityFrontier.begin())) {
Misha Brukmandfa5f832003-09-09 21:54:45 +0000425 Instruction *Occurrence = Definitions.begin()->second;
426 BasicBlock *BB = Occurrence->getParent();
Chris Lattnere9412912003-03-31 19:55:43 +0000427 Definitions.erase(Definitions.begin());
428
Misha Brukmandfa5f832003-09-09 21:54:45 +0000429 DEBUG(std::cerr << "PROCESSING Occurrence: " << Occurrence);
Chris Lattnere9412912003-03-31 19:55:43 +0000430
431 // Check to see if there is already an incoming value for this block...
432 AvailableBlocksTy::iterator LBI = AvailableBlocks.find(BB);
433 if (LBI != AvailableBlocks.end()) {
434 // Yes, there is a dominating definition for this block. Replace this
Misha Brukmandfa5f832003-09-09 21:54:45 +0000435 // occurrence with the incoming value.
436 if (LBI->second != Occurrence) {
Chris Lattnere9412912003-03-31 19:55:43 +0000437 DEBUG(std::cerr << " replacing with: " << LBI->second);
Misha Brukmandfa5f832003-09-09 21:54:45 +0000438 Occurrence->replaceAllUsesWith(LBI->second);
439 BB->getInstList().erase(Occurrence); // Delete instruction
Chris Lattnere9412912003-03-31 19:55:43 +0000440 ++NumRedundant;
441 }
Chris Lattnere9412912003-03-31 19:55:43 +0000442 } else {
Misha Brukmandfa5f832003-09-09 21:54:45 +0000443 ProcessedExpressions.insert(Occurrence);
444 if (!isa<PHINode>(Occurrence))
445 NonPHIOccurrence = Occurrence; // Keep an occurrence of this expr
Chris Lattnere9412912003-03-31 19:55:43 +0000446
447 // Okay, there is no incoming value for this block, so this expression
448 // is a new definition that is good for this block and all blocks
449 // dominated by it. Add this information to the AvailableBlocks map.
450 //
Misha Brukmandfa5f832003-09-09 21:54:45 +0000451 MarkOccurrenceAvailableInAllDominatedBlocks(Occurrence, BB);
Chris Lattnere9412912003-03-31 19:55:43 +0000452
453 // Update the dominance frontier for the definitions so far... if a node
454 // in the dominator frontier now has all of its predecessors available,
455 // and the block is in an anticipatible region, we can insert a PHI node
456 // in that block.
457 DominanceFrontier::iterator DFI = DF->find(BB);
458 if (DFI != DF->end()) {
459 for (std::set<BasicBlock*>::iterator DI = DFI->second.begin();
460 DI != DFI->second.end(); ++DI) {
461 BasicBlock *DFBlock = *DI;
462 unsigned DFBlockID = BlockNumbering[DFBlock];
463 if (AnticipatibleBlocks[DFBlockID]) {
464 // Check to see if any of the predecessors of this block on the
465 // frontier are not available...
466 bool AnyNotAvailable = false;
467 for (pred_iterator PI = pred_begin(DFBlock),
468 PE = pred_end(DFBlock); PI != PE; ++PI)
469 if (!AvailableBlocks.count(*PI)) {
470 AnyNotAvailable = true;
471 break;
472 }
473
474 // If any predecessor blocks are not available, add the node to
475 // the current expression dominance frontier.
476 if (AnyNotAvailable) {
477 AvailabilityFrontier.insert(DFBlockID);
478 } else {
479 // This block is no longer in the availability frontier, it IS
480 // available.
481 AvailabilityFrontier.erase(DFBlockID);
482
483 // If all of the predecessor blocks are available (and the block
484 // anticipates a definition along the path to the exit), we need
485 // to insert a new PHI node in this block. This block serves as
486 // a new definition for the expression, extending the available
487 // region.
488 //
489 PHINode *PN = new PHINode(ExprType, Expr->getName()+".pre",
490 DFBlock->begin());
491 ProcessedExpressions.insert(PN);
492
493 DEBUG(std::cerr << " INSERTING PHI on frontier: " << PN);
494
495 // Add the incoming blocks for the PHI node
496 for (pred_iterator PI = pred_begin(DFBlock),
497 PE = pred_end(DFBlock); PI != PE; ++PI)
498 if (*PI != DFBlock)
499 PN->addIncoming(AvailableBlocks[*PI], *PI);
500 else // edge from the current block
501 PN->addIncoming(PN, DFBlock);
502
503 Instruction *&BlockOcc = Definitions[DFBlockID];
504 if (BlockOcc) {
Misha Brukmandfa5f832003-09-09 21:54:45 +0000505 DEBUG(std::cerr <<" PHI superceeds occurrence: "<<BlockOcc);
Chris Lattnere9412912003-03-31 19:55:43 +0000506 BlockOcc->replaceAllUsesWith(PN);
507 BlockOcc->getParent()->getInstList().erase(BlockOcc);
508 ++NumRedundant;
509 }
510 BlockOcc = PN;
511 }
512 }
513 }
514 }
515 }
516
517 } else {
518 // Otherwise we must be looking at a node in the availability frontier!
519 unsigned AFBlockID = *AvailabilityFrontier.begin();
520 AvailabilityFrontier.erase(AvailabilityFrontier.begin());
521 BasicBlock *AFBlock = BlockMapping[AFBlockID];
522
523 // We eliminate the partial redundancy on this frontier by inserting a PHI
524 // node into this block, merging any incoming available versions into the
525 // PHI and inserting a new computation into predecessors without an
526 // incoming value. Note that we would have to insert the expression on
527 // the edge if the predecessor didn't anticipate the expression and we
528 // didn't break critical edges.
529 //
530 PHINode *PN = new PHINode(ExprType, Expr->getName()+".PRE",
531 AFBlock->begin());
532 DEBUG(std::cerr << "INSERTING PHI for PR: " << PN);
533
Misha Brukmandfa5f832003-09-09 21:54:45 +0000534 // If there is a pending occurrence in this block, make sure to replace it
Chris Lattnere9412912003-03-31 19:55:43 +0000535 // with the PHI node...
536 std::map<unsigned, Instruction*>::iterator EDFI =
537 Definitions.find(AFBlockID);
538 if (EDFI != Definitions.end()) {
Misha Brukmandfa5f832003-09-09 21:54:45 +0000539 // There is already an occurrence in this block. Replace it with PN and
Chris Lattnere9412912003-03-31 19:55:43 +0000540 // remove it.
541 Instruction *OldOcc = EDFI->second;
Misha Brukmandfa5f832003-09-09 21:54:45 +0000542 DEBUG(std::cerr << " Replaces occurrence: " << OldOcc);
Chris Lattnere9412912003-03-31 19:55:43 +0000543 OldOcc->replaceAllUsesWith(PN);
544 AFBlock->getInstList().erase(OldOcc);
545 Definitions.erase(EDFI);
546 ++NumRedundant;
547 }
548
549 for (pred_iterator PI = pred_begin(AFBlock), PE = pred_end(AFBlock);
550 PI != PE; ++PI) {
551 BasicBlock *Pred = *PI;
552 AvailableBlocksTy::iterator LBI = AvailableBlocks.find(Pred);
553 if (LBI != AvailableBlocks.end()) { // If there is a available value
554 PN->addIncoming(LBI->second, Pred); // for this pred, use it.
555 } else { // No available value yet...
556 unsigned PredID = BlockNumbering[Pred];
557
558 // Is the predecessor the same block that we inserted the PHI into?
559 // (self loop)
560 if (Pred == AFBlock) {
561 // Yes, reuse the incoming value here...
562 PN->addIncoming(PN, Pred);
563 } else {
564 // No, we must insert a new computation into this block and add it
565 // to the definitions list...
Misha Brukmandfa5f832003-09-09 21:54:45 +0000566 assert(NonPHIOccurrence && "No non-phi occurrences seen so far???");
567 Instruction *New = NonPHIOccurrence->clone();
568 New->setName(NonPHIOccurrence->getName() + ".PRE-inserted");
Chris Lattnere9412912003-03-31 19:55:43 +0000569 ProcessedExpressions.insert(New);
570
Misha Brukmandfa5f832003-09-09 21:54:45 +0000571 DEBUG(std::cerr << " INSERTING OCCURRRENCE: " << New);
Chris Lattnere9412912003-03-31 19:55:43 +0000572
573 // Insert it into the bottom of the predecessor, right before the
574 // terminator instruction...
575 Pred->getInstList().insert(Pred->getTerminator(), New);
576
577 // Make this block be the available definition for any blocks it
578 // dominates. The ONLY case that this can affect more than just the
579 // block itself is when we are moving a computation to a loop
580 // header. In all other cases, because we don't have critical
581 // edges, the node is guaranteed to only dominate itself.
582 //
Misha Brukmandfa5f832003-09-09 21:54:45 +0000583 ReplaceDominatedAvailableOccurrencesWith(New, DT->getNode(Pred));
Chris Lattnere9412912003-03-31 19:55:43 +0000584
585 // Add it as an incoming value on this edge to the PHI node
586 PN->addIncoming(New, Pred);
Misha Brukmandfa5f832003-09-09 21:54:45 +0000587 NonPHIOccurrence = New;
Chris Lattnere9412912003-03-31 19:55:43 +0000588 NumInserted++;
589 }
590 }
591 }
592
593 // Find out if there is already an available value in this block. If so,
594 // we need to replace the available value with the PHI node. This can
595 // only happen when we just inserted a PHI node on a backedge.
596 //
597 AvailableBlocksTy::iterator LBBlockAvailableValIt =
598 AvailableBlocks.find(AFBlock);
599 if (LBBlockAvailableValIt != AvailableBlocks.end()) {
600 if (LBBlockAvailableValIt->second->getParent() == AFBlock) {
601 Instruction *OldVal = LBBlockAvailableValIt->second;
602 OldVal->replaceAllUsesWith(PN); // Use the new PHI node now
603 ++NumRedundant;
604 DEBUG(std::cerr << " PHI replaces available value: %"
605 << OldVal->getName() << "\n");
606
607 // Loop over all of the blocks dominated by this PHI node, and change
608 // the AvailableBlocks entries to be the PHI node instead of the old
609 // instruction.
Misha Brukmandfa5f832003-09-09 21:54:45 +0000610 MarkOccurrenceAvailableInAllDominatedBlocks(PN, AFBlock);
Chris Lattnere9412912003-03-31 19:55:43 +0000611
612 AFBlock->getInstList().erase(OldVal); // Delete old instruction!
613
614 // The resultant PHI node is a new definition of the value!
615 Definitions.insert(std::make_pair(AFBlockID, PN));
616 } else {
617 // If the value is not defined in this block, that means that an
Misha Brukmandfa5f832003-09-09 21:54:45 +0000618 // inserted occurrence in a predecessor is now the live value for the
Chris Lattnere9412912003-03-31 19:55:43 +0000619 // region (occurs when hoisting loop invariants, f.e.). In this case,
620 // the PHI node should actually just be removed.
621 assert(PN->use_empty() && "No uses should exist for dead PHI node!");
622 PN->getParent()->getInstList().erase(PN);
623 }
624 } else {
625 // The resultant PHI node is a new definition of the value!
626 Definitions.insert(std::make_pair(AFBlockID, PN));
627 }
628 }
629 }
630
631 AvailableBlocks.clear();
632
633 return Changed;
634}
Brian Gaeked0fde302003-11-11 22:41:34 +0000635
636} // End llvm namespace