Changes For Bug 352
[oota-llvm.git] / lib / Transforms / Scalar / CorrelatedExprs.cpp
1 //===- CorrelatedExprs.cpp - Pass to detect and eliminated c.e.'s ---------===//
2 // 
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 //===----------------------------------------------------------------------===//
9 //
10 // Correlated Expression Elimination propagates information from conditional
11 // branches to blocks dominated by destinations of the branch.  It propagates
12 // information from the condition check itself into the body of the branch,
13 // allowing transformations like these for example:
14 //
15 //  if (i == 7)
16 //    ... 4*i;  // constant propagation
17 //
18 //  M = i+1; N = j+1;
19 //  if (i == j)
20 //    X = M-N;  // = M-M == 0;
21 //
22 // This is called Correlated Expression Elimination because we eliminate or
23 // simplify expressions that are correlated with the direction of a branch.  In
24 // this way we use static information to give us some information about the
25 // dynamic value of a variable.
26 //
27 //===----------------------------------------------------------------------===//
28
29 #include "llvm/Transforms/Scalar.h"
30 #include "llvm/Constants.h"
31 #include "llvm/Pass.h"
32 #include "llvm/Function.h"
33 #include "llvm/Instructions.h"
34 #include "llvm/Type.h"
35 #include "llvm/Analysis/Dominators.h"
36 #include "llvm/Assembly/Writer.h"
37 #include "llvm/Transforms/Utils/Local.h"
38 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
39 #include "llvm/Support/ConstantRange.h"
40 #include "llvm/Support/CFG.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/ADT/PostOrderIterator.h"
43 #include "llvm/ADT/Statistic.h"
44 #include <algorithm>
45 using namespace llvm;
46
47 namespace {
48   Statistic<> NumSetCCRemoved("cee", "Number of setcc instruction eliminated");
49   Statistic<> NumOperandsCann("cee", "Number of operands canonicalized");
50   Statistic<> BranchRevectors("cee", "Number of branches revectored");
51
52   class ValueInfo;
53   class Relation {
54     Value *Val;                 // Relation to what value?
55     Instruction::BinaryOps Rel; // SetCC relation, or Add if no information
56   public:
57     Relation(Value *V) : Val(V), Rel(Instruction::Add) {}
58     bool operator<(const Relation &R) const { return Val < R.Val; }
59     Value *getValue() const { return Val; }
60     Instruction::BinaryOps getRelation() const { return Rel; }
61
62     // contradicts - Return true if the relationship specified by the operand
63     // contradicts already known information.
64     //
65     bool contradicts(Instruction::BinaryOps Rel, const ValueInfo &VI) const;
66
67     // incorporate - Incorporate information in the argument into this relation
68     // entry.  This assumes that the information doesn't contradict itself.  If
69     // any new information is gained, true is returned, otherwise false is
70     // returned to indicate that nothing was updated.
71     //
72     bool incorporate(Instruction::BinaryOps Rel, ValueInfo &VI);
73
74     // KnownResult - Whether or not this condition determines the result of a
75     // setcc in the program.  False & True are intentionally 0 & 1 so we can
76     // convert to bool by casting after checking for unknown.
77     //
78     enum KnownResult { KnownFalse = 0, KnownTrue = 1, Unknown = 2 };
79
80     // getImpliedResult - If this relationship between two values implies that
81     // the specified relationship is true or false, return that.  If we cannot
82     // determine the result required, return Unknown.
83     //
84     KnownResult getImpliedResult(Instruction::BinaryOps Rel) const;
85
86     // print - Output this relation to the specified stream
87     void print(std::ostream &OS) const;
88     void dump() const;
89   };
90
91
92   // ValueInfo - One instance of this record exists for every value with
93   // relationships between other values.  It keeps track of all of the
94   // relationships to other values in the program (specified with Relation) that
95   // are known to be valid in a region.
96   //
97   class ValueInfo {
98     // RelationShips - this value is know to have the specified relationships to
99     // other values.  There can only be one entry per value, and this list is
100     // kept sorted by the Val field.
101     std::vector<Relation> Relationships;
102
103     // If information about this value is known or propagated from constant
104     // expressions, this range contains the possible values this value may hold.
105     ConstantRange Bounds;
106
107     // If we find that this value is equal to another value that has a lower
108     // rank, this value is used as it's replacement.
109     //
110     Value *Replacement;
111   public:
112     ValueInfo(const Type *Ty)
113       : Bounds(Ty->isIntegral() ? Ty : Type::IntTy), Replacement(0) {}
114
115     // getBounds() - Return the constant bounds of the value...
116     const ConstantRange &getBounds() const { return Bounds; }
117     ConstantRange &getBounds() { return Bounds; }
118
119     const std::vector<Relation> &getRelationships() { return Relationships; }
120
121     // getReplacement - Return the value this value is to be replaced with if it
122     // exists, otherwise return null.
123     //
124     Value *getReplacement() const { return Replacement; }
125
126     // setReplacement - Used by the replacement calculation pass to figure out
127     // what to replace this value with, if anything.
128     //
129     void setReplacement(Value *Repl) { Replacement = Repl; }
130
131     // getRelation - return the relationship entry for the specified value.
132     // This can invalidate references to other Relations, so use it carefully.
133     //
134     Relation &getRelation(Value *V) {
135       // Binary search for V's entry...
136       std::vector<Relation>::iterator I =
137         std::lower_bound(Relationships.begin(), Relationships.end(), V);
138
139       // If we found the entry, return it...
140       if (I != Relationships.end() && I->getValue() == V)
141         return *I;
142
143       // Insert and return the new relationship...
144       return *Relationships.insert(I, V);
145     }
146
147     const Relation *requestRelation(Value *V) const {
148       // Binary search for V's entry...
149       std::vector<Relation>::const_iterator I =
150         std::lower_bound(Relationships.begin(), Relationships.end(), V);
151       if (I != Relationships.end() && I->getValue() == V)
152         return &*I;
153       return 0;
154     }
155
156     // print - Output information about this value relation...
157     void print(std::ostream &OS, Value *V) const;
158     void dump() const;
159   };
160
161   // RegionInfo - Keeps track of all of the value relationships for a region.  A
162   // region is the are dominated by a basic block.  RegionInfo's keep track of
163   // the RegionInfo for their dominator, because anything known in a dominator
164   // is known to be true in a dominated block as well.
165   //
166   class RegionInfo {
167     BasicBlock *BB;
168
169     // ValueMap - Tracks the ValueInformation known for this region
170     typedef std::map<Value*, ValueInfo> ValueMapTy;
171     ValueMapTy ValueMap;
172   public:
173     RegionInfo(BasicBlock *bb) : BB(bb) {}
174
175     // getEntryBlock - Return the block that dominates all of the members of
176     // this region.
177     BasicBlock *getEntryBlock() const { return BB; }
178
179     // empty - return true if this region has no information known about it.
180     bool empty() const { return ValueMap.empty(); }
181     
182     const RegionInfo &operator=(const RegionInfo &RI) {
183       ValueMap = RI.ValueMap;
184       return *this;
185     }
186
187     // print - Output information about this region...
188     void print(std::ostream &OS) const;
189     void dump() const;
190
191     // Allow external access.
192     typedef ValueMapTy::iterator iterator;
193     iterator begin() { return ValueMap.begin(); }
194     iterator end() { return ValueMap.end(); }
195
196     ValueInfo &getValueInfo(Value *V) {
197       ValueMapTy::iterator I = ValueMap.lower_bound(V);
198       if (I != ValueMap.end() && I->first == V) return I->second;
199       return ValueMap.insert(I, std::make_pair(V, V->getType()))->second;
200     }
201
202     const ValueInfo *requestValueInfo(Value *V) const {
203       ValueMapTy::const_iterator I = ValueMap.find(V);
204       if (I != ValueMap.end()) return &I->second;
205       return 0;
206     }
207     
208     /// removeValueInfo - Remove anything known about V from our records.  This
209     /// works whether or not we know anything about V.
210     ///
211     void removeValueInfo(Value *V) {
212       ValueMap.erase(V);
213     }
214   };
215
216   /// CEE - Correlated Expression Elimination
217   class CEE : public FunctionPass {
218     std::map<Value*, unsigned> RankMap;
219     std::map<BasicBlock*, RegionInfo> RegionInfoMap;
220     DominatorSet *DS;
221     DominatorTree *DT;
222   public:
223     virtual bool runOnFunction(Function &F);
224
225     // We don't modify the program, so we preserve all analyses
226     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
227       AU.addRequired<DominatorSet>();
228       AU.addRequired<DominatorTree>();
229       AU.addRequiredID(BreakCriticalEdgesID);
230     };
231
232     // print - Implement the standard print form to print out analysis
233     // information.
234     virtual void print(std::ostream &O, const Module *M) const;
235
236   private:
237     RegionInfo &getRegionInfo(BasicBlock *BB) {
238       std::map<BasicBlock*, RegionInfo>::iterator I
239         = RegionInfoMap.lower_bound(BB);
240       if (I != RegionInfoMap.end() && I->first == BB) return I->second;
241       return RegionInfoMap.insert(I, std::make_pair(BB, BB))->second;
242     }
243
244     void BuildRankMap(Function &F);
245     unsigned getRank(Value *V) const {
246       if (isa<Constant>(V)) return 0;
247       std::map<Value*, unsigned>::const_iterator I = RankMap.find(V);
248       if (I != RankMap.end()) return I->second;
249       return 0; // Must be some other global thing
250     }
251
252     bool TransformRegion(BasicBlock *BB, std::set<BasicBlock*> &VisitedBlocks);
253
254     bool ForwardCorrelatedEdgeDestination(TerminatorInst *TI, unsigned SuccNo,
255                                           RegionInfo &RI);
256
257     void ForwardSuccessorTo(TerminatorInst *TI, unsigned Succ, BasicBlock *D,
258                             RegionInfo &RI);
259     void ReplaceUsesOfValueInRegion(Value *Orig, Value *New,
260                                     BasicBlock *RegionDominator);
261     void CalculateRegionExitBlocks(BasicBlock *BB, BasicBlock *OldSucc,
262                                    std::vector<BasicBlock*> &RegionExitBlocks);
263     void InsertRegionExitMerges(PHINode *NewPHI, Instruction *OldVal,
264                              const std::vector<BasicBlock*> &RegionExitBlocks);
265
266     void PropagateBranchInfo(BranchInst *BI);
267     void PropagateEquality(Value *Op0, Value *Op1, RegionInfo &RI);
268     void PropagateRelation(Instruction::BinaryOps Opcode, Value *Op0,
269                            Value *Op1, RegionInfo &RI);
270     void UpdateUsersOfValue(Value *V, RegionInfo &RI);
271     void IncorporateInstruction(Instruction *Inst, RegionInfo &RI);
272     void ComputeReplacements(RegionInfo &RI);
273
274
275     // getSetCCResult - Given a setcc instruction, determine if the result is
276     // determined by facts we already know about the region under analysis.
277     // Return KnownTrue, KnownFalse, or Unknown based on what we can determine.
278     //
279     Relation::KnownResult getSetCCResult(SetCondInst *SC, const RegionInfo &RI);
280
281
282     bool SimplifyBasicBlock(BasicBlock &BB, const RegionInfo &RI);
283     bool SimplifyInstruction(Instruction *Inst, const RegionInfo &RI);
284   }; 
285   RegisterOpt<CEE> X("cee", "Correlated Expression Elimination");
286 }
287
288 Pass *llvm::createCorrelatedExpressionEliminationPass() { return new CEE(); }
289
290
291 bool CEE::runOnFunction(Function &F) {
292   // Build a rank map for the function...
293   BuildRankMap(F);
294
295   // Traverse the dominator tree, computing information for each node in the
296   // tree.  Note that our traversal will not even touch unreachable basic
297   // blocks.
298   DS = &getAnalysis<DominatorSet>();
299   DT = &getAnalysis<DominatorTree>();
300   
301   std::set<BasicBlock*> VisitedBlocks;
302   bool Changed = TransformRegion(&F.getEntryBlock(), VisitedBlocks);
303
304   RegionInfoMap.clear();
305   RankMap.clear();
306   return Changed;
307 }
308
309 // TransformRegion - Transform the region starting with BB according to the
310 // calculated region information for the block.  Transforming the region
311 // involves analyzing any information this block provides to successors,
312 // propagating the information to successors, and finally transforming
313 // successors.
314 //
315 // This method processes the function in depth first order, which guarantees
316 // that we process the immediate dominator of a block before the block itself.
317 // Because we are passing information from immediate dominators down to
318 // dominatees, we obviously have to process the information source before the
319 // information consumer.
320 //
321 bool CEE::TransformRegion(BasicBlock *BB, std::set<BasicBlock*> &VisitedBlocks){
322   // Prevent infinite recursion...
323   if (VisitedBlocks.count(BB)) return false;
324   VisitedBlocks.insert(BB);
325
326   // Get the computed region information for this block...
327   RegionInfo &RI = getRegionInfo(BB);
328
329   // Compute the replacement information for this block...
330   ComputeReplacements(RI);
331
332   // If debugging, print computed region information...
333   DEBUG(RI.print(std::cerr));
334
335   // Simplify the contents of this block...
336   bool Changed = SimplifyBasicBlock(*BB, RI);
337
338   // Get the terminator of this basic block...
339   TerminatorInst *TI = BB->getTerminator();
340
341   // Loop over all of the blocks that this block is the immediate dominator for.
342   // Because all information known in this region is also known in all of the
343   // blocks that are dominated by this one, we can safely propagate the
344   // information down now.
345   //
346   DominatorTree::Node *BBN = (*DT)[BB];
347   if (!RI.empty())        // Time opt: only propagate if we can change something
348     for (unsigned i = 0, e = BBN->getChildren().size(); i != e; ++i) {
349       BasicBlock *Dominated = BBN->getChildren()[i]->getBlock();
350       assert(RegionInfoMap.find(Dominated) == RegionInfoMap.end() &&
351              "RegionInfo should be calculated in dominanace order!");
352       getRegionInfo(Dominated) = RI;
353     }
354
355   // Now that all of our successors have information if they deserve it,
356   // propagate any information our terminator instruction finds to our
357   // successors.
358   if (BranchInst *BI = dyn_cast<BranchInst>(TI))
359     if (BI->isConditional())
360       PropagateBranchInfo(BI);
361
362   // If this is a branch to a block outside our region that simply performs
363   // another conditional branch, one whose outcome is known inside of this
364   // region, then vector this outgoing edge directly to the known destination.
365   //
366   for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
367     while (ForwardCorrelatedEdgeDestination(TI, i, RI)) {
368       ++BranchRevectors;
369       Changed = true;
370     }
371
372   // Now that all of our successors have information, recursively process them.
373   for (unsigned i = 0, e = BBN->getChildren().size(); i != e; ++i)
374     Changed |= TransformRegion(BBN->getChildren()[i]->getBlock(),VisitedBlocks);
375
376   return Changed;
377 }
378
379 // isBlockSimpleEnoughForCheck to see if the block is simple enough for us to
380 // revector the conditional branch in the bottom of the block, do so now.
381 //
382 static bool isBlockSimpleEnough(BasicBlock *BB) {
383   assert(isa<BranchInst>(BB->getTerminator()));
384   BranchInst *BI = cast<BranchInst>(BB->getTerminator());
385   assert(BI->isConditional());
386
387   // Check the common case first: empty block, or block with just a setcc.
388   if (BB->size() == 1 ||
389       (BB->size() == 2 && &BB->front() == BI->getCondition() &&
390        BI->getCondition()->hasOneUse()))
391     return true;
392
393   // Check the more complex case now...
394   BasicBlock::iterator I = BB->begin();
395
396   // FIXME: This should be reenabled once the regression with SIM is fixed!
397 #if 0
398   // PHI Nodes are ok, just skip over them...
399   while (isa<PHINode>(*I)) ++I;
400 #endif
401
402   // Accept the setcc instruction...
403   if (&*I == BI->getCondition())
404     ++I;
405
406   // Nothing else is acceptable here yet.  We must not revector... unless we are
407   // at the terminator instruction.
408   if (&*I == BI)
409     return true;
410
411   return false;
412 }
413
414
415 bool CEE::ForwardCorrelatedEdgeDestination(TerminatorInst *TI, unsigned SuccNo,
416                                            RegionInfo &RI) {
417   // If this successor is a simple block not in the current region, which
418   // contains only a conditional branch, we decide if the outcome of the branch
419   // can be determined from information inside of the region.  Instead of going
420   // to this block, we can instead go to the destination we know is the right
421   // target.
422   //
423
424   // Check to see if we dominate the block. If so, this block will get the
425   // condition turned to a constant anyway.
426   //
427   //if (DS->dominates(RI.getEntryBlock(), BB))
428   // return 0;
429
430   BasicBlock *BB = TI->getParent();
431
432   // Get the destination block of this edge...
433   BasicBlock *OldSucc = TI->getSuccessor(SuccNo);
434
435   // Make sure that the block ends with a conditional branch and is simple
436   // enough for use to be able to revector over.
437   BranchInst *BI = dyn_cast<BranchInst>(OldSucc->getTerminator());
438   if (BI == 0 || !BI->isConditional() || !isBlockSimpleEnough(OldSucc))
439     return false;
440
441   // We can only forward the branch over the block if the block ends with a
442   // setcc we can determine the outcome for.
443   //
444   // FIXME: we can make this more generic.  Code below already handles more
445   // generic case.
446   SetCondInst *SCI = dyn_cast<SetCondInst>(BI->getCondition());
447   if (SCI == 0) return false;
448
449   // Make a new RegionInfo structure so that we can simulate the effect of the
450   // PHI nodes in the block we are skipping over...
451   //
452   RegionInfo NewRI(RI);
453
454   // Remove value information for all of the values we are simulating... to make
455   // sure we don't have any stale information.
456   for (BasicBlock::iterator I = OldSucc->begin(), E = OldSucc->end(); I!=E; ++I)
457     if (I->getType() != Type::VoidTy)
458       NewRI.removeValueInfo(I);
459     
460   // Put the newly discovered information into the RegionInfo...
461   for (BasicBlock::iterator I = OldSucc->begin(), E = OldSucc->end(); I!=E; ++I)
462     if (PHINode *PN = dyn_cast<PHINode>(I)) {
463       int OpNum = PN->getBasicBlockIndex(BB);
464       assert(OpNum != -1 && "PHI doesn't have incoming edge for predecessor!?");
465       PropagateEquality(PN, PN->getIncomingValue(OpNum), NewRI);      
466     } else if (SetCondInst *SCI = dyn_cast<SetCondInst>(I)) {
467       Relation::KnownResult Res = getSetCCResult(SCI, NewRI);
468       if (Res == Relation::Unknown) return false;
469       PropagateEquality(SCI, ConstantBool::get(Res), NewRI);
470     } else {
471       assert(isa<BranchInst>(*I) && "Unexpected instruction type!");
472     }
473   
474   // Compute the facts implied by what we have discovered...
475   ComputeReplacements(NewRI);
476
477   ValueInfo &PredicateVI = NewRI.getValueInfo(BI->getCondition());
478   if (PredicateVI.getReplacement() &&
479       isa<Constant>(PredicateVI.getReplacement()) &&
480       !isa<GlobalValue>(PredicateVI.getReplacement())) {
481     ConstantBool *CB = cast<ConstantBool>(PredicateVI.getReplacement());
482
483     // Forward to the successor that corresponds to the branch we will take.
484     ForwardSuccessorTo(TI, SuccNo, BI->getSuccessor(!CB->getValue()), NewRI);
485     return true;
486   }
487   
488   return false;
489 }
490
491 static Value *getReplacementOrValue(Value *V, RegionInfo &RI) {
492   if (const ValueInfo *VI = RI.requestValueInfo(V))
493     if (Value *Repl = VI->getReplacement())
494       return Repl;
495   return V;
496 }
497
498 /// ForwardSuccessorTo - We have found that we can forward successor # 'SuccNo'
499 /// of Terminator 'TI' to the 'Dest' BasicBlock.  This method performs the
500 /// mechanics of updating SSA information and revectoring the branch.
501 ///
502 void CEE::ForwardSuccessorTo(TerminatorInst *TI, unsigned SuccNo,
503                              BasicBlock *Dest, RegionInfo &RI) {
504   // If there are any PHI nodes in the Dest BB, we must duplicate the entry
505   // in the PHI node for the old successor to now include an entry from the
506   // current basic block.
507   //
508   BasicBlock *OldSucc = TI->getSuccessor(SuccNo);
509   BasicBlock *BB = TI->getParent();
510
511   DEBUG(std::cerr << "Forwarding branch in basic block %" << BB->getName()
512         << " from block %" << OldSucc->getName() << " to block %"
513         << Dest->getName() << "\n");
514
515   DEBUG(std::cerr << "Before forwarding: " << *BB->getParent());
516
517   // Because we know that there cannot be critical edges in the flow graph, and
518   // that OldSucc has multiple outgoing edges, this means that Dest cannot have
519   // multiple incoming edges.
520   //
521 #ifndef NDEBUG
522   pred_iterator DPI = pred_begin(Dest); ++DPI;
523   assert(DPI == pred_end(Dest) && "Critical edge found!!");
524 #endif
525
526   // Loop over any PHI nodes in the destination, eliminating them, because they
527   // may only have one input.
528   //
529   while (PHINode *PN = dyn_cast<PHINode>(&Dest->front())) {
530     assert(PN->getNumIncomingValues() == 1 && "Crit edge found!");
531     // Eliminate the PHI node
532     PN->replaceAllUsesWith(PN->getIncomingValue(0));
533     Dest->getInstList().erase(PN);
534   }
535
536   // If there are values defined in the "OldSucc" basic block, we need to insert
537   // PHI nodes in the regions we are dealing with to emulate them.  This can
538   // insert dead phi nodes, but it is more trouble to see if they are used than
539   // to just blindly insert them.
540   //
541   if (DS->dominates(OldSucc, Dest)) {
542     // RegionExitBlocks - Find all of the blocks that are not dominated by Dest,
543     // but have predecessors that are.  Additionally, prune down the set to only
544     // include blocks that are dominated by OldSucc as well.
545     //
546     std::vector<BasicBlock*> RegionExitBlocks;
547     CalculateRegionExitBlocks(Dest, OldSucc, RegionExitBlocks);
548
549     for (BasicBlock::iterator I = OldSucc->begin(), E = OldSucc->end();
550          I != E; ++I)
551       if (I->getType() != Type::VoidTy) {
552         // Create and insert the PHI node into the top of Dest.
553         PHINode *NewPN = new PHINode(I->getType(), I->getName()+".fw_merge",
554                                      Dest->begin());
555         // There is definitely an edge from OldSucc... add the edge now
556         NewPN->addIncoming(I, OldSucc);
557
558         // There is also an edge from BB now, add the edge with the calculated
559         // value from the RI.
560         NewPN->addIncoming(getReplacementOrValue(I, RI), BB);
561
562         // Make everything in the Dest region use the new PHI node now...
563         ReplaceUsesOfValueInRegion(I, NewPN, Dest);
564
565         // Make sure that exits out of the region dominated by NewPN get PHI
566         // nodes that merge the values as appropriate.
567         InsertRegionExitMerges(NewPN, I, RegionExitBlocks);
568       }
569   }
570
571   // If there were PHI nodes in OldSucc, we need to remove the entry for this
572   // edge from the PHI node, and we need to replace any references to the PHI
573   // node with a new value.
574   //
575   for (BasicBlock::iterator I = OldSucc->begin();
576        PHINode *PN = dyn_cast<PHINode>(I); ) {
577
578     // Get the value flowing across the old edge and remove the PHI node entry
579     // for this edge: we are about to remove the edge!  Don't remove the PHI
580     // node yet though if this is the last edge into it.
581     Value *EdgeValue = PN->removeIncomingValue(BB, false);
582
583     // Make sure that anything that used to use PN now refers to EdgeValue    
584     ReplaceUsesOfValueInRegion(PN, EdgeValue, Dest);
585
586     // If there is only one value left coming into the PHI node, replace the PHI
587     // node itself with the one incoming value left.
588     //
589     if (PN->getNumIncomingValues() == 1) {
590       assert(PN->getNumIncomingValues() == 1);
591       PN->replaceAllUsesWith(PN->getIncomingValue(0));
592       PN->getParent()->getInstList().erase(PN);
593       I = OldSucc->begin();
594     } else if (PN->getNumIncomingValues() == 0) {  // Nuke the PHI
595       // If we removed the last incoming value to this PHI, nuke the PHI node
596       // now.
597       PN->replaceAllUsesWith(Constant::getNullValue(PN->getType()));
598       PN->getParent()->getInstList().erase(PN);
599       I = OldSucc->begin();
600     } else {
601       ++I;  // Otherwise, move on to the next PHI node
602     }
603   }
604   
605   // Actually revector the branch now...
606   TI->setSuccessor(SuccNo, Dest);
607
608   // If we just introduced a critical edge in the flow graph, make sure to break
609   // it right away...
610   SplitCriticalEdge(TI, SuccNo, this);
611
612   // Make sure that we don't introduce critical edges from oldsucc now!
613   for (unsigned i = 0, e = OldSucc->getTerminator()->getNumSuccessors();
614        i != e; ++i)
615     if (isCriticalEdge(OldSucc->getTerminator(), i))
616       SplitCriticalEdge(OldSucc->getTerminator(), i, this);
617
618   // Since we invalidated the CFG, recalculate the dominator set so that it is
619   // useful for later processing!
620   // FIXME: This is much worse than it really should be!
621   //DS->recalculate();
622
623   DEBUG(std::cerr << "After forwarding: " << *BB->getParent());
624 }
625
626 /// ReplaceUsesOfValueInRegion - This method replaces all uses of Orig with uses
627 /// of New.  It only affects instructions that are defined in basic blocks that
628 /// are dominated by Head.
629 ///
630 void CEE::ReplaceUsesOfValueInRegion(Value *Orig, Value *New,
631                                      BasicBlock *RegionDominator) {
632   assert(Orig != New && "Cannot replace value with itself");
633   std::vector<Instruction*> InstsToChange;
634   std::vector<PHINode*>     PHIsToChange;
635   InstsToChange.reserve(Orig->use_size());
636
637   // Loop over instructions adding them to InstsToChange vector, this allows us
638   // an easy way to avoid invalidating the use_iterator at a bad time.
639   for (Value::use_iterator I = Orig->use_begin(), E = Orig->use_end();
640        I != E; ++I)
641     if (Instruction *User = dyn_cast<Instruction>(*I))
642       if (DS->dominates(RegionDominator, User->getParent()))
643         InstsToChange.push_back(User);
644       else if (PHINode *PN = dyn_cast<PHINode>(User)) {
645         PHIsToChange.push_back(PN);
646       }
647
648   // PHIsToChange contains PHI nodes that use Orig that do not live in blocks
649   // dominated by orig.  If the block the value flows in from is dominated by
650   // RegionDominator, then we rewrite the PHI
651   for (unsigned i = 0, e = PHIsToChange.size(); i != e; ++i) {
652     PHINode *PN = PHIsToChange[i];
653     for (unsigned j = 0, e = PN->getNumIncomingValues(); j != e; ++j)
654       if (PN->getIncomingValue(j) == Orig &&
655           DS->dominates(RegionDominator, PN->getIncomingBlock(j)))
656         PN->setIncomingValue(j, New);
657   }
658
659   // Loop over the InstsToChange list, replacing all uses of Orig with uses of
660   // New.  This list contains all of the instructions in our region that use
661   // Orig.
662   for (unsigned i = 0, e = InstsToChange.size(); i != e; ++i)
663     if (PHINode *PN = dyn_cast<PHINode>(InstsToChange[i])) {
664       // PHINodes must be handled carefully.  If the PHI node itself is in the
665       // region, we have to make sure to only do the replacement for incoming
666       // values that correspond to basic blocks in the region.
667       for (unsigned j = 0, e = PN->getNumIncomingValues(); j != e; ++j)
668         if (PN->getIncomingValue(j) == Orig &&
669             DS->dominates(RegionDominator, PN->getIncomingBlock(j)))
670           PN->setIncomingValue(j, New);
671
672     } else {
673       InstsToChange[i]->replaceUsesOfWith(Orig, New);
674     }
675 }
676
677 static void CalcRegionExitBlocks(BasicBlock *Header, BasicBlock *BB,
678                                  std::set<BasicBlock*> &Visited,
679                                  DominatorSet &DS,
680                                  std::vector<BasicBlock*> &RegionExitBlocks) {
681   if (Visited.count(BB)) return;
682   Visited.insert(BB);
683
684   if (DS.dominates(Header, BB)) {  // Block in the region, recursively traverse
685     for (succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I)
686       CalcRegionExitBlocks(Header, *I, Visited, DS, RegionExitBlocks);
687   } else {
688     // Header does not dominate this block, but we have a predecessor that does
689     // dominate us.  Add ourself to the list.
690     RegionExitBlocks.push_back(BB);    
691   }
692 }
693
694 /// CalculateRegionExitBlocks - Find all of the blocks that are not dominated by
695 /// BB, but have predecessors that are.  Additionally, prune down the set to
696 /// only include blocks that are dominated by OldSucc as well.
697 ///
698 void CEE::CalculateRegionExitBlocks(BasicBlock *BB, BasicBlock *OldSucc,
699                                     std::vector<BasicBlock*> &RegionExitBlocks){
700   std::set<BasicBlock*> Visited;  // Don't infinite loop
701
702   // Recursively calculate blocks we are interested in...
703   CalcRegionExitBlocks(BB, BB, Visited, *DS, RegionExitBlocks);
704   
705   // Filter out blocks that are not dominated by OldSucc...
706   for (unsigned i = 0; i != RegionExitBlocks.size(); ) {
707     if (DS->dominates(OldSucc, RegionExitBlocks[i]))
708       ++i;  // Block is ok, keep it.
709     else {
710       // Move to end of list...
711       std::swap(RegionExitBlocks[i], RegionExitBlocks.back());
712       RegionExitBlocks.pop_back();        // Nuke the end
713     }
714   }
715 }
716
717 void CEE::InsertRegionExitMerges(PHINode *BBVal, Instruction *OldVal,
718                              const std::vector<BasicBlock*> &RegionExitBlocks) {
719   assert(BBVal->getType() == OldVal->getType() && "Should be derived values!");
720   BasicBlock *BB = BBVal->getParent();
721   BasicBlock *OldSucc = OldVal->getParent();
722
723   // Loop over all of the blocks we have to place PHIs in, doing it.
724   for (unsigned i = 0, e = RegionExitBlocks.size(); i != e; ++i) {
725     BasicBlock *FBlock = RegionExitBlocks[i];  // Block on the frontier
726
727     // Create the new PHI node
728     PHINode *NewPN = new PHINode(BBVal->getType(),
729                                  OldVal->getName()+".fw_frontier",
730                                  FBlock->begin());
731
732     // Add an incoming value for every predecessor of the block...
733     for (pred_iterator PI = pred_begin(FBlock), PE = pred_end(FBlock);
734          PI != PE; ++PI) {
735       // If the incoming edge is from the region dominated by BB, use BBVal,
736       // otherwise use OldVal.
737       NewPN->addIncoming(DS->dominates(BB, *PI) ? BBVal : OldVal, *PI);
738     }
739     
740     // Now make everyone dominated by this block use this new value!
741     ReplaceUsesOfValueInRegion(OldVal, NewPN, FBlock);
742   }
743 }
744
745
746
747 // BuildRankMap - This method builds the rank map data structure which gives
748 // each instruction/value in the function a value based on how early it appears
749 // in the function.  We give constants and globals rank 0, arguments are
750 // numbered starting at one, and instructions are numbered in reverse post-order
751 // from where the arguments leave off.  This gives instructions in loops higher
752 // values than instructions not in loops.
753 //
754 void CEE::BuildRankMap(Function &F) {
755   unsigned Rank = 1;  // Skip rank zero.
756
757   // Number the arguments...
758   for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
759     RankMap[I] = Rank++;
760
761   // Number the instructions in reverse post order...
762   ReversePostOrderTraversal<Function*> RPOT(&F);
763   for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
764          E = RPOT.end(); I != E; ++I)
765     for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
766          BBI != E; ++BBI)
767       if (BBI->getType() != Type::VoidTy)
768         RankMap[BBI] = Rank++;
769 }
770
771
772 // PropagateBranchInfo - When this method is invoked, we need to propagate
773 // information derived from the branch condition into the true and false
774 // branches of BI.  Since we know that there aren't any critical edges in the
775 // flow graph, this can proceed unconditionally.
776 //
777 void CEE::PropagateBranchInfo(BranchInst *BI) {
778   assert(BI->isConditional() && "Must be a conditional branch!");
779
780   // Propagate information into the true block...
781   //
782   PropagateEquality(BI->getCondition(), ConstantBool::True,
783                     getRegionInfo(BI->getSuccessor(0)));
784   
785   // Propagate information into the false block...
786   //
787   PropagateEquality(BI->getCondition(), ConstantBool::False,
788                     getRegionInfo(BI->getSuccessor(1)));
789 }
790
791
792 // PropagateEquality - If we discover that two values are equal to each other in
793 // a specified region, propagate this knowledge recursively.
794 //
795 void CEE::PropagateEquality(Value *Op0, Value *Op1, RegionInfo &RI) {
796   if (Op0 == Op1) return;  // Gee whiz. Are these really equal each other?
797
798   if (isa<Constant>(Op0))  // Make sure the constant is always Op1
799     std::swap(Op0, Op1);
800
801   // Make sure we don't already know these are equal, to avoid infinite loops...
802   ValueInfo &VI = RI.getValueInfo(Op0);
803
804   // Get information about the known relationship between Op0 & Op1
805   Relation &KnownRelation = VI.getRelation(Op1);
806
807   // If we already know they're equal, don't reprocess...
808   if (KnownRelation.getRelation() == Instruction::SetEQ)
809     return;
810
811   // If this is boolean, check to see if one of the operands is a constant.  If
812   // it's a constant, then see if the other one is one of a setcc instruction,
813   // an AND, OR, or XOR instruction.
814   //
815   if (ConstantBool *CB = dyn_cast<ConstantBool>(Op1)) {
816
817     if (Instruction *Inst = dyn_cast<Instruction>(Op0)) {
818       // If we know that this instruction is an AND instruction, and the result
819       // is true, this means that both operands to the OR are known to be true
820       // as well.
821       //
822       if (CB->getValue() && Inst->getOpcode() == Instruction::And) {
823         PropagateEquality(Inst->getOperand(0), CB, RI);
824         PropagateEquality(Inst->getOperand(1), CB, RI);
825       }
826       
827       // If we know that this instruction is an OR instruction, and the result
828       // is false, this means that both operands to the OR are know to be false
829       // as well.
830       //
831       if (!CB->getValue() && Inst->getOpcode() == Instruction::Or) {
832         PropagateEquality(Inst->getOperand(0), CB, RI);
833         PropagateEquality(Inst->getOperand(1), CB, RI);
834       }
835       
836       // If we know that this instruction is a NOT instruction, we know that the
837       // operand is known to be the inverse of whatever the current value is.
838       //
839       if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(Inst))
840         if (BinaryOperator::isNot(BOp))
841           PropagateEquality(BinaryOperator::getNotArgument(BOp),
842                             ConstantBool::get(!CB->getValue()), RI);
843
844       // If we know the value of a SetCC instruction, propagate the information
845       // about the relation into this region as well.
846       //
847       if (SetCondInst *SCI = dyn_cast<SetCondInst>(Inst)) {
848         if (CB->getValue()) {  // If we know the condition is true...
849           // Propagate info about the LHS to the RHS & RHS to LHS
850           PropagateRelation(SCI->getOpcode(), SCI->getOperand(0),
851                             SCI->getOperand(1), RI);
852           PropagateRelation(SCI->getSwappedCondition(),
853                             SCI->getOperand(1), SCI->getOperand(0), RI);
854
855         } else {               // If we know the condition is false...
856           // We know the opposite of the condition is true...
857           Instruction::BinaryOps C = SCI->getInverseCondition();
858           
859           PropagateRelation(C, SCI->getOperand(0), SCI->getOperand(1), RI);
860           PropagateRelation(SetCondInst::getSwappedCondition(C),
861                             SCI->getOperand(1), SCI->getOperand(0), RI);
862         }
863       }
864     }
865   }
866
867   // Propagate information about Op0 to Op1 & visa versa
868   PropagateRelation(Instruction::SetEQ, Op0, Op1, RI);
869   PropagateRelation(Instruction::SetEQ, Op1, Op0, RI);
870 }
871
872
873 // PropagateRelation - We know that the specified relation is true in all of the
874 // blocks in the specified region.  Propagate the information about Op0 and
875 // anything derived from it into this region.
876 //
877 void CEE::PropagateRelation(Instruction::BinaryOps Opcode, Value *Op0,
878                             Value *Op1, RegionInfo &RI) {
879   assert(Op0->getType() == Op1->getType() && "Equal types expected!");
880
881   // Constants are already pretty well understood.  We will apply information
882   // about the constant to Op1 in another call to PropagateRelation.
883   //
884   if (isa<Constant>(Op0)) return;
885
886   // Get the region information for this block to update...
887   ValueInfo &VI = RI.getValueInfo(Op0);
888
889   // Get information about the known relationship between Op0 & Op1
890   Relation &Op1R = VI.getRelation(Op1);
891
892   // Quick bailout for common case if we are reprocessing an instruction...
893   if (Op1R.getRelation() == Opcode)
894     return;
895
896   // If we already have information that contradicts the current information we
897   // are propagating, ignore this info.  Something bad must have happened!
898   //
899   if (Op1R.contradicts(Opcode, VI)) {
900     Op1R.contradicts(Opcode, VI);
901     std::cerr << "Contradiction found for opcode: "
902               << Instruction::getOpcodeName(Opcode) << "\n";
903     Op1R.print(std::cerr);
904     return;
905   }
906
907   // If the information propagated is new, then we want process the uses of this
908   // instruction to propagate the information down to them.
909   //
910   if (Op1R.incorporate(Opcode, VI))
911     UpdateUsersOfValue(Op0, RI);
912 }
913
914
915 // UpdateUsersOfValue - The information about V in this region has been updated.
916 // Propagate this to all consumers of the value.
917 //
918 void CEE::UpdateUsersOfValue(Value *V, RegionInfo &RI) {
919   for (Value::use_iterator I = V->use_begin(), E = V->use_end();
920        I != E; ++I)
921     if (Instruction *Inst = dyn_cast<Instruction>(*I)) {
922       // If this is an instruction using a value that we know something about,
923       // try to propagate information to the value produced by the
924       // instruction.  We can only do this if it is an instruction we can
925       // propagate information for (a setcc for example), and we only WANT to
926       // do this if the instruction dominates this region.
927       //
928       // If the instruction doesn't dominate this region, then it cannot be
929       // used in this region and we don't care about it.  If the instruction
930       // is IN this region, then we will simplify the instruction before we
931       // get to uses of it anyway, so there is no reason to bother with it
932       // here.  This check is also effectively checking to make sure that Inst
933       // is in the same function as our region (in case V is a global f.e.).
934       //
935       if (DS->properlyDominates(Inst->getParent(), RI.getEntryBlock()))
936         IncorporateInstruction(Inst, RI);
937     }
938 }
939
940 // IncorporateInstruction - We just updated the information about one of the
941 // operands to the specified instruction.  Update the information about the
942 // value produced by this instruction
943 //
944 void CEE::IncorporateInstruction(Instruction *Inst, RegionInfo &RI) {
945   if (SetCondInst *SCI = dyn_cast<SetCondInst>(Inst)) {
946     // See if we can figure out a result for this instruction...
947     Relation::KnownResult Result = getSetCCResult(SCI, RI);
948     if (Result != Relation::Unknown) {
949       PropagateEquality(SCI, Result ? ConstantBool::True : ConstantBool::False,
950                         RI);
951     }
952   }
953 }
954
955
956 // ComputeReplacements - Some values are known to be equal to other values in a
957 // region.  For example if there is a comparison of equality between a variable
958 // X and a constant C, we can replace all uses of X with C in the region we are
959 // interested in.  We generalize this replacement to replace variables with
960 // other variables if they are equal and there is a variable with lower rank
961 // than the current one.  This offers a canonicalizing property that exposes
962 // more redundancies for later transformations to take advantage of.
963 //
964 void CEE::ComputeReplacements(RegionInfo &RI) {
965   // Loop over all of the values in the region info map...
966   for (RegionInfo::iterator I = RI.begin(), E = RI.end(); I != E; ++I) {
967     ValueInfo &VI = I->second;
968
969     // If we know that this value is a particular constant, set Replacement to
970     // the constant...
971     Value *Replacement = VI.getBounds().getSingleElement();
972
973     // If this value is not known to be some constant, figure out the lowest
974     // rank value that it is known to be equal to (if anything).
975     //
976     if (Replacement == 0) {
977       // Find out if there are any equality relationships with values of lower
978       // rank than VI itself...
979       unsigned MinRank = getRank(I->first);
980
981       // Loop over the relationships known about Op0.
982       const std::vector<Relation> &Relationships = VI.getRelationships();
983       for (unsigned i = 0, e = Relationships.size(); i != e; ++i)
984         if (Relationships[i].getRelation() == Instruction::SetEQ) {
985           unsigned R = getRank(Relationships[i].getValue());
986           if (R < MinRank) {
987             MinRank = R;
988             Replacement = Relationships[i].getValue();
989           }
990         }
991     }
992
993     // If we found something to replace this value with, keep track of it.
994     if (Replacement)
995       VI.setReplacement(Replacement);
996   }
997 }
998
999 // SimplifyBasicBlock - Given information about values in region RI, simplify
1000 // the instructions in the specified basic block.
1001 //
1002 bool CEE::SimplifyBasicBlock(BasicBlock &BB, const RegionInfo &RI) {
1003   bool Changed = false;
1004   for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ) {
1005     Instruction *Inst = I++;
1006
1007     // Convert instruction arguments to canonical forms...
1008     Changed |= SimplifyInstruction(Inst, RI);
1009
1010     if (SetCondInst *SCI = dyn_cast<SetCondInst>(Inst)) {
1011       // Try to simplify a setcc instruction based on inherited information
1012       Relation::KnownResult Result = getSetCCResult(SCI, RI);
1013       if (Result != Relation::Unknown) {
1014         DEBUG(std::cerr << "Replacing setcc with " << Result
1015                         << " constant: " << *SCI);
1016
1017         SCI->replaceAllUsesWith(ConstantBool::get((bool)Result));
1018         // The instruction is now dead, remove it from the program.
1019         SCI->getParent()->getInstList().erase(SCI);
1020         ++NumSetCCRemoved;
1021         Changed = true;
1022       }
1023     }
1024   }
1025
1026   return Changed;
1027 }
1028
1029 // SimplifyInstruction - Inspect the operands of the instruction, converting
1030 // them to their canonical form if possible.  This takes care of, for example,
1031 // replacing a value 'X' with a constant 'C' if the instruction in question is
1032 // dominated by a true seteq 'X', 'C'.
1033 //
1034 bool CEE::SimplifyInstruction(Instruction *I, const RegionInfo &RI) {
1035   bool Changed = false;
1036
1037   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1038     if (const ValueInfo *VI = RI.requestValueInfo(I->getOperand(i)))
1039       if (Value *Repl = VI->getReplacement()) {
1040         // If we know if a replacement with lower rank than Op0, make the
1041         // replacement now.
1042         DEBUG(std::cerr << "In Inst: " << *I << "  Replacing operand #" << i
1043                         << " with " << *Repl << "\n");
1044         I->setOperand(i, Repl);
1045         Changed = true;
1046         ++NumOperandsCann;
1047       }
1048
1049   return Changed;
1050 }
1051
1052
1053 // getSetCCResult - Try to simplify a setcc instruction based on information
1054 // inherited from a dominating setcc instruction.  V is one of the operands to
1055 // the setcc instruction, and VI is the set of information known about it.  We
1056 // take two cases into consideration here.  If the comparison is against a
1057 // constant value, we can use the constant range to see if the comparison is
1058 // possible to succeed.  If it is not a comparison against a constant, we check
1059 // to see if there is a known relationship between the two values.  If so, we
1060 // may be able to eliminate the check.
1061 //
1062 Relation::KnownResult CEE::getSetCCResult(SetCondInst *SCI,
1063                                           const RegionInfo &RI) {
1064   Value *Op0 = SCI->getOperand(0), *Op1 = SCI->getOperand(1);
1065   Instruction::BinaryOps Opcode = SCI->getOpcode();
1066   
1067   if (isa<Constant>(Op0)) {
1068     if (isa<Constant>(Op1)) {
1069       if (Constant *Result = ConstantFoldInstruction(SCI)) {
1070         // Wow, this is easy, directly eliminate the SetCondInst.
1071         DEBUG(std::cerr << "Replacing setcc with constant fold: " << *SCI);
1072         return cast<ConstantBool>(Result)->getValue()
1073           ? Relation::KnownTrue : Relation::KnownFalse;
1074       }
1075     } else {
1076       // We want to swap this instruction so that operand #0 is the constant.
1077       std::swap(Op0, Op1);
1078       Opcode = SCI->getSwappedCondition();
1079     }
1080   }
1081
1082   // Try to figure out what the result of this comparison will be...
1083   Relation::KnownResult Result = Relation::Unknown;
1084
1085   // We have to know something about the relationship to prove anything...
1086   if (const ValueInfo *Op0VI = RI.requestValueInfo(Op0)) {
1087
1088     // At this point, we know that if we have a constant argument that it is in
1089     // Op1.  Check to see if we know anything about comparing value with a
1090     // constant, and if we can use this info to fold the setcc.
1091     //
1092     if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(Op1)) {
1093       // Check to see if we already know the result of this comparison...
1094       ConstantRange R = ConstantRange(Opcode, C);
1095       ConstantRange Int = R.intersectWith(Op0VI->getBounds());
1096
1097       // If the intersection of the two ranges is empty, then the condition
1098       // could never be true!
1099       // 
1100       if (Int.isEmptySet()) {
1101         Result = Relation::KnownFalse;
1102
1103       // Otherwise, if VI.getBounds() (the possible values) is a subset of R
1104       // (the allowed values) then we know that the condition must always be
1105       // true!
1106       //
1107       } else if (Int == Op0VI->getBounds()) {
1108         Result = Relation::KnownTrue;
1109       }
1110     } else {
1111       // If we are here, we know that the second argument is not a constant
1112       // integral.  See if we know anything about Op0 & Op1 that allows us to
1113       // fold this anyway.
1114       //
1115       // Do we have value information about Op0 and a relation to Op1?
1116       if (const Relation *Op2R = Op0VI->requestRelation(Op1))
1117         Result = Op2R->getImpliedResult(Opcode);
1118     }
1119   }
1120   return Result;
1121 }
1122
1123 //===----------------------------------------------------------------------===//
1124 //  Relation Implementation
1125 //===----------------------------------------------------------------------===//
1126
1127 // CheckCondition - Return true if the specified condition is false.  Bound may
1128 // be null.
1129 static bool CheckCondition(Constant *Bound, Constant *C,
1130                            Instruction::BinaryOps BO) {
1131   assert(C != 0 && "C is not specified!");
1132   if (Bound == 0) return false;
1133
1134   Constant *Val = ConstantExpr::get(BO, Bound, C);
1135   if (ConstantBool *CB = dyn_cast<ConstantBool>(Val))
1136     return !CB->getValue();  // Return true if the condition is false...
1137   return false;
1138 }
1139
1140 // contradicts - Return true if the relationship specified by the operand
1141 // contradicts already known information.
1142 //
1143 bool Relation::contradicts(Instruction::BinaryOps Op,
1144                            const ValueInfo &VI) const {
1145   assert (Op != Instruction::Add && "Invalid relation argument!");
1146
1147   // If this is a relationship with a constant, make sure that this relationship
1148   // does not contradict properties known about the bounds of the constant.
1149   //
1150   if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(Val))
1151     if (ConstantRange(Op, C).intersectWith(VI.getBounds()).isEmptySet())
1152       return true;
1153
1154   switch (Rel) {
1155   default: assert(0 && "Unknown Relationship code!");
1156   case Instruction::Add: return false;  // Nothing known, nothing contradicts
1157   case Instruction::SetEQ:
1158     return Op == Instruction::SetLT || Op == Instruction::SetGT ||
1159            Op == Instruction::SetNE;
1160   case Instruction::SetNE: return Op == Instruction::SetEQ;
1161   case Instruction::SetLE: return Op == Instruction::SetGT;
1162   case Instruction::SetGE: return Op == Instruction::SetLT;
1163   case Instruction::SetLT:
1164     return Op == Instruction::SetEQ || Op == Instruction::SetGT ||
1165            Op == Instruction::SetGE;
1166   case Instruction::SetGT:
1167     return Op == Instruction::SetEQ || Op == Instruction::SetLT ||
1168            Op == Instruction::SetLE;
1169   }
1170 }
1171
1172 // incorporate - Incorporate information in the argument into this relation
1173 // entry.  This assumes that the information doesn't contradict itself.  If any
1174 // new information is gained, true is returned, otherwise false is returned to
1175 // indicate that nothing was updated.
1176 //
1177 bool Relation::incorporate(Instruction::BinaryOps Op, ValueInfo &VI) {
1178   assert(!contradicts(Op, VI) &&
1179          "Cannot incorporate contradictory information!");
1180
1181   // If this is a relationship with a constant, make sure that we update the
1182   // range that is possible for the value to have...
1183   //
1184   if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(Val))
1185     VI.getBounds() = ConstantRange(Op, C).intersectWith(VI.getBounds());
1186
1187   switch (Rel) {
1188   default: assert(0 && "Unknown prior value!");
1189   case Instruction::Add:   Rel = Op; return true;
1190   case Instruction::SetEQ: return false;  // Nothing is more precise
1191   case Instruction::SetNE: return false;  // Nothing is more precise
1192   case Instruction::SetLT: return false;  // Nothing is more precise
1193   case Instruction::SetGT: return false;  // Nothing is more precise
1194   case Instruction::SetLE:
1195     if (Op == Instruction::SetEQ || Op == Instruction::SetLT) {
1196       Rel = Op;
1197       return true;
1198     } else if (Op == Instruction::SetNE) {
1199       Rel = Instruction::SetLT;
1200       return true;
1201     }
1202     return false;
1203   case Instruction::SetGE: return Op == Instruction::SetLT;
1204     if (Op == Instruction::SetEQ || Op == Instruction::SetGT) {
1205       Rel = Op;
1206       return true;
1207     } else if (Op == Instruction::SetNE) {
1208       Rel = Instruction::SetGT;
1209       return true;
1210     }
1211     return false;
1212   }
1213 }
1214
1215 // getImpliedResult - If this relationship between two values implies that
1216 // the specified relationship is true or false, return that.  If we cannot
1217 // determine the result required, return Unknown.
1218 //
1219 Relation::KnownResult
1220 Relation::getImpliedResult(Instruction::BinaryOps Op) const {
1221   if (Rel == Op) return KnownTrue;
1222   if (Rel == SetCondInst::getInverseCondition(Op)) return KnownFalse;
1223
1224   switch (Rel) {
1225   default: assert(0 && "Unknown prior value!");
1226   case Instruction::SetEQ:
1227     if (Op == Instruction::SetLE || Op == Instruction::SetGE) return KnownTrue;
1228     if (Op == Instruction::SetLT || Op == Instruction::SetGT) return KnownFalse;
1229     break;
1230   case Instruction::SetLT:
1231     if (Op == Instruction::SetNE || Op == Instruction::SetLE) return KnownTrue;
1232     if (Op == Instruction::SetEQ) return KnownFalse;
1233     break;
1234   case Instruction::SetGT:
1235     if (Op == Instruction::SetNE || Op == Instruction::SetGE) return KnownTrue;
1236     if (Op == Instruction::SetEQ) return KnownFalse;
1237     break;
1238   case Instruction::SetNE:
1239   case Instruction::SetLE:
1240   case Instruction::SetGE:
1241   case Instruction::Add:
1242     break;
1243   }
1244   return Unknown;
1245 }
1246
1247
1248 //===----------------------------------------------------------------------===//
1249 // Printing Support...
1250 //===----------------------------------------------------------------------===//
1251
1252 // print - Implement the standard print form to print out analysis information.
1253 void CEE::print(std::ostream &O, const Module *M) const {
1254   O << "\nPrinting Correlated Expression Info:\n";
1255   for (std::map<BasicBlock*, RegionInfo>::const_iterator I = 
1256          RegionInfoMap.begin(), E = RegionInfoMap.end(); I != E; ++I)
1257     I->second.print(O);
1258 }
1259
1260 // print - Output information about this region...
1261 void RegionInfo::print(std::ostream &OS) const {
1262   if (ValueMap.empty()) return;
1263
1264   OS << " RegionInfo for basic block: " << BB->getName() << "\n";
1265   for (std::map<Value*, ValueInfo>::const_iterator
1266          I = ValueMap.begin(), E = ValueMap.end(); I != E; ++I)
1267     I->second.print(OS, I->first);
1268   OS << "\n";
1269 }
1270
1271 // print - Output information about this value relation...
1272 void ValueInfo::print(std::ostream &OS, Value *V) const {
1273   if (Relationships.empty()) return;
1274
1275   if (V) {
1276     OS << "  ValueInfo for: ";
1277     WriteAsOperand(OS, V);
1278   }
1279   OS << "\n    Bounds = " << Bounds << "\n";
1280   if (Replacement) {
1281     OS << "    Replacement = ";
1282     WriteAsOperand(OS, Replacement);
1283     OS << "\n";
1284   }
1285   for (unsigned i = 0, e = Relationships.size(); i != e; ++i)
1286     Relationships[i].print(OS);
1287 }
1288
1289 // print - Output this relation to the specified stream
1290 void Relation::print(std::ostream &OS) const {
1291   OS << "    is ";
1292   switch (Rel) {
1293   default:           OS << "*UNKNOWN*"; break;
1294   case Instruction::SetEQ: OS << "== "; break;
1295   case Instruction::SetNE: OS << "!= "; break;
1296   case Instruction::SetLT: OS << "< "; break;
1297   case Instruction::SetGT: OS << "> "; break;
1298   case Instruction::SetLE: OS << "<= "; break;
1299   case Instruction::SetGE: OS << ">= "; break;
1300   }
1301
1302   WriteAsOperand(OS, Val);
1303   OS << "\n";
1304 }
1305
1306 // Don't inline these methods or else we won't be able to call them from GDB!
1307 void Relation::dump() const { print(std::cerr); }
1308 void ValueInfo::dump() const { print(std::cerr, 0); }
1309 void RegionInfo::dump() const { print(std::cerr); }