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