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