Implement review feedback for the ConstantBool->ConstantInt merge. Chris
[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 #define DEBUG_TYPE "cee"
30 #include "llvm/Transforms/Scalar.h"
31 #include "llvm/Constants.h"
32 #include "llvm/Pass.h"
33 #include "llvm/Function.h"
34 #include "llvm/Instructions.h"
35 #include "llvm/Type.h"
36 #include "llvm/Analysis/Dominators.h"
37 #include "llvm/Assembly/Writer.h"
38 #include "llvm/Transforms/Utils/Local.h"
39 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
40 #include "llvm/Support/ConstantRange.h"
41 #include "llvm/Support/CFG.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/ADT/PostOrderIterator.h"
44 #include "llvm/ADT/Statistic.h"
45 #include <algorithm>
46 using namespace llvm;
47
48 STATISTIC(NumCmpRemoved, "Number of cmp instruction eliminated");
49 STATISTIC(NumOperandsCann, "Number of operands canonicalized");
50 STATISTIC(BranchRevectors, "Number of branches revectored");
51
52 namespace {
53   class ValueInfo;
54   class Relation {
55     Value *Val;          // Relation to what value?
56     unsigned Rel;        // SetCC or ICmp 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     unsigned 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(unsigned 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(unsigned Rel, ValueInfo &VI);
74
75     // KnownResult - Whether or not this condition determines the result of a
76     // setcc or icmp in the program.  False & True are intentionally 0 & 1 
77     // so we can 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(unsigned 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::Int32Ty), 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 PropagateSwitchInfo(SwitchInst *SI);
271     void PropagateEquality(Value *Op0, Value *Op1, RegionInfo &RI);
272     void PropagateRelation(unsigned Opcode, Value *Op0,
273                            Value *Op1, RegionInfo &RI);
274     void UpdateUsersOfValue(Value *V, RegionInfo &RI);
275     void IncorporateInstruction(Instruction *Inst, RegionInfo &RI);
276     void ComputeReplacements(RegionInfo &RI);
277
278     // getCmpResult - Given a icmp 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     Relation::KnownResult getCmpResult(CmpInst *ICI, const RegionInfo &RI);
282
283     bool SimplifyBasicBlock(BasicBlock &BB, const RegionInfo &RI);
284     bool SimplifyInstruction(Instruction *Inst, const RegionInfo &RI);
285   };
286   RegisterPass<CEE> X("cee", "Correlated Expression Elimination");
287 }
288
289 FunctionPass *llvm::createCorrelatedExpressionEliminationPass() {
290   return new CEE();
291 }
292
293
294 bool CEE::runOnFunction(Function &F) {
295   // Build a rank map for the function...
296   BuildRankMap(F);
297
298   // Traverse the dominator tree, computing information for each node in the
299   // tree.  Note that our traversal will not even touch unreachable basic
300   // blocks.
301   EF = &getAnalysis<ETForest>();
302   DT = &getAnalysis<DominatorTree>();
303
304   std::set<BasicBlock*> VisitedBlocks;
305   bool Changed = TransformRegion(&F.getEntryBlock(), VisitedBlocks);
306
307   RegionInfoMap.clear();
308   RankMap.clear();
309   return Changed;
310 }
311
312 // TransformRegion - Transform the region starting with BB according to the
313 // calculated region information for the block.  Transforming the region
314 // involves analyzing any information this block provides to successors,
315 // propagating the information to successors, and finally transforming
316 // successors.
317 //
318 // This method processes the function in depth first order, which guarantees
319 // that we process the immediate dominator of a block before the block itself.
320 // Because we are passing information from immediate dominators down to
321 // dominatees, we obviously have to process the information source before the
322 // information consumer.
323 //
324 bool CEE::TransformRegion(BasicBlock *BB, std::set<BasicBlock*> &VisitedBlocks){
325   // Prevent infinite recursion...
326   if (VisitedBlocks.count(BB)) return false;
327   VisitedBlocks.insert(BB);
328
329   // Get the computed region information for this block...
330   RegionInfo &RI = getRegionInfo(BB);
331
332   // Compute the replacement information for this block...
333   ComputeReplacements(RI);
334
335   // If debugging, print computed region information...
336   DEBUG(RI.print(*cerr.stream()));
337
338   // Simplify the contents of this block...
339   bool Changed = SimplifyBasicBlock(*BB, RI);
340
341   // Get the terminator of this basic block...
342   TerminatorInst *TI = BB->getTerminator();
343
344   // Loop over all of the blocks that this block is the immediate dominator for.
345   // Because all information known in this region is also known in all of the
346   // blocks that are dominated by this one, we can safely propagate the
347   // information down now.
348   //
349   DominatorTree::Node *BBN = (*DT)[BB];
350   if (!RI.empty())        // Time opt: only propagate if we can change something
351     for (unsigned i = 0, e = BBN->getChildren().size(); i != e; ++i) {
352       BasicBlock *Dominated = BBN->getChildren()[i]->getBlock();
353       assert(RegionInfoMap.find(Dominated) == RegionInfoMap.end() &&
354              "RegionInfo should be calculated in dominanace order!");
355       getRegionInfo(Dominated) = RI;
356     }
357
358   // Now that all of our successors have information if they deserve it,
359   // propagate any information our terminator instruction finds to our
360   // successors.
361   if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
362     if (BI->isConditional())
363       PropagateBranchInfo(BI);
364   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
365     PropagateSwitchInfo(SI);
366   }
367
368   // If this is a branch to a block outside our region that simply performs
369   // another conditional branch, one whose outcome is known inside of this
370   // region, then vector this outgoing edge directly to the known destination.
371   //
372   for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
373     while (ForwardCorrelatedEdgeDestination(TI, i, RI)) {
374       ++BranchRevectors;
375       Changed = true;
376     }
377
378   // Now that all of our successors have information, recursively process them.
379   for (unsigned i = 0, e = BBN->getChildren().size(); i != e; ++i)
380     Changed |= TransformRegion(BBN->getChildren()[i]->getBlock(),VisitedBlocks);
381
382   return Changed;
383 }
384
385 // isBlockSimpleEnoughForCheck to see if the block is simple enough for us to
386 // revector the conditional branch in the bottom of the block, do so now.
387 //
388 static bool isBlockSimpleEnough(BasicBlock *BB) {
389   assert(isa<BranchInst>(BB->getTerminator()));
390   BranchInst *BI = cast<BranchInst>(BB->getTerminator());
391   assert(BI->isConditional());
392
393   // Check the common case first: empty block, or block with just a setcc.
394   if (BB->size() == 1 ||
395       (BB->size() == 2 && &BB->front() == BI->getCondition() &&
396        BI->getCondition()->hasOneUse()))
397     return true;
398
399   // Check the more complex case now...
400   BasicBlock::iterator I = BB->begin();
401
402   // FIXME: This should be reenabled once the regression with SIM is fixed!
403 #if 0
404   // PHI Nodes are ok, just skip over them...
405   while (isa<PHINode>(*I)) ++I;
406 #endif
407
408   // Accept the setcc instruction...
409   if (&*I == BI->getCondition())
410     ++I;
411
412   // Nothing else is acceptable here yet.  We must not revector... unless we are
413   // at the terminator instruction.
414   if (&*I == BI)
415     return true;
416
417   return false;
418 }
419
420
421 bool CEE::ForwardCorrelatedEdgeDestination(TerminatorInst *TI, unsigned SuccNo,
422                                            RegionInfo &RI) {
423   // If this successor is a simple block not in the current region, which
424   // contains only a conditional branch, we decide if the outcome of the branch
425   // can be determined from information inside of the region.  Instead of going
426   // to this block, we can instead go to the destination we know is the right
427   // target.
428   //
429
430   // Check to see if we dominate the block. If so, this block will get the
431   // condition turned to a constant anyway.
432   //
433   //if (EF->dominates(RI.getEntryBlock(), BB))
434   // return 0;
435
436   BasicBlock *BB = TI->getParent();
437
438   // Get the destination block of this edge...
439   BasicBlock *OldSucc = TI->getSuccessor(SuccNo);
440
441   // Make sure that the block ends with a conditional branch and is simple
442   // enough for use to be able to revector over.
443   BranchInst *BI = dyn_cast<BranchInst>(OldSucc->getTerminator());
444   if (BI == 0 || !BI->isConditional() || !isBlockSimpleEnough(OldSucc))
445     return false;
446
447   // We can only forward the branch over the block if the block ends with a
448   // cmp we can determine the outcome for.
449   //
450   // FIXME: we can make this more generic.  Code below already handles more
451   // generic case.
452   if (!isa<CmpInst>(BI->getCondition()))
453     return false;
454
455   // Make a new RegionInfo structure so that we can simulate the effect of the
456   // PHI nodes in the block we are skipping over...
457   //
458   RegionInfo NewRI(RI);
459
460   // Remove value information for all of the values we are simulating... to make
461   // sure we don't have any stale information.
462   for (BasicBlock::iterator I = OldSucc->begin(), E = OldSucc->end(); I!=E; ++I)
463     if (I->getType() != Type::VoidTy)
464       NewRI.removeValueInfo(I);
465
466   // Put the newly discovered information into the RegionInfo...
467   for (BasicBlock::iterator I = OldSucc->begin(), E = OldSucc->end(); I!=E; ++I)
468     if (PHINode *PN = dyn_cast<PHINode>(I)) {
469       int OpNum = PN->getBasicBlockIndex(BB);
470       assert(OpNum != -1 && "PHI doesn't have incoming edge for predecessor!?");
471       PropagateEquality(PN, PN->getIncomingValue(OpNum), NewRI);
472     } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
473       Relation::KnownResult Res = getCmpResult(CI, NewRI);
474       if (Res == Relation::Unknown) return false;
475       PropagateEquality(CI, ConstantInt::get(Type::Int1Ty, Res), NewRI);
476     } else {
477       assert(isa<BranchInst>(*I) && "Unexpected instruction type!");
478     }
479
480   // Compute the facts implied by what we have discovered...
481   ComputeReplacements(NewRI);
482
483   ValueInfo &PredicateVI = NewRI.getValueInfo(BI->getCondition());
484   if (PredicateVI.getReplacement() &&
485       isa<Constant>(PredicateVI.getReplacement()) &&
486       !isa<GlobalValue>(PredicateVI.getReplacement())) {
487     ConstantInt *CB = cast<ConstantInt>(PredicateVI.getReplacement());
488
489     // Forward to the successor that corresponds to the branch we will take.
490     ForwardSuccessorTo(TI, SuccNo, 
491                        BI->getSuccessor(!CB->getZExtValue()), NewRI);
492     return true;
493   }
494
495   return false;
496 }
497
498 static Value *getReplacementOrValue(Value *V, RegionInfo &RI) {
499   if (const ValueInfo *VI = RI.requestValueInfo(V))
500     if (Value *Repl = VI->getReplacement())
501       return Repl;
502   return V;
503 }
504
505 /// ForwardSuccessorTo - We have found that we can forward successor # 'SuccNo'
506 /// of Terminator 'TI' to the 'Dest' BasicBlock.  This method performs the
507 /// mechanics of updating SSA information and revectoring the branch.
508 ///
509 void CEE::ForwardSuccessorTo(TerminatorInst *TI, unsigned SuccNo,
510                              BasicBlock *Dest, RegionInfo &RI) {
511   // If there are any PHI nodes in the Dest BB, we must duplicate the entry
512   // in the PHI node for the old successor to now include an entry from the
513   // current basic block.
514   //
515   BasicBlock *OldSucc = TI->getSuccessor(SuccNo);
516   BasicBlock *BB = TI->getParent();
517
518   DOUT << "Forwarding branch in basic block %" << BB->getName()
519        << " from block %" << OldSucc->getName() << " to block %"
520        << Dest->getName() << "\n"
521        << "Before forwarding: " << *BB->getParent();
522
523   // Because we know that there cannot be critical edges in the flow graph, and
524   // that OldSucc has multiple outgoing edges, this means that Dest cannot have
525   // multiple incoming edges.
526   //
527 #ifndef NDEBUG
528   pred_iterator DPI = pred_begin(Dest); ++DPI;
529   assert(DPI == pred_end(Dest) && "Critical edge found!!");
530 #endif
531
532   // Loop over any PHI nodes in the destination, eliminating them, because they
533   // may only have one input.
534   //
535   while (PHINode *PN = dyn_cast<PHINode>(&Dest->front())) {
536     assert(PN->getNumIncomingValues() == 1 && "Crit edge found!");
537     // Eliminate the PHI node
538     PN->replaceAllUsesWith(PN->getIncomingValue(0));
539     Dest->getInstList().erase(PN);
540   }
541
542   // If there are values defined in the "OldSucc" basic block, we need to insert
543   // PHI nodes in the regions we are dealing with to emulate them.  This can
544   // insert dead phi nodes, but it is more trouble to see if they are used than
545   // to just blindly insert them.
546   //
547   if (EF->dominates(OldSucc, Dest)) {
548     // RegionExitBlocks - Find all of the blocks that are not dominated by Dest,
549     // but have predecessors that are.  Additionally, prune down the set to only
550     // include blocks that are dominated by OldSucc as well.
551     //
552     std::vector<BasicBlock*> RegionExitBlocks;
553     CalculateRegionExitBlocks(Dest, OldSucc, RegionExitBlocks);
554
555     for (BasicBlock::iterator I = OldSucc->begin(), E = OldSucc->end();
556          I != E; ++I)
557       if (I->getType() != Type::VoidTy) {
558         // Create and insert the PHI node into the top of Dest.
559         PHINode *NewPN = new PHINode(I->getType(), I->getName()+".fw_merge",
560                                      Dest->begin());
561         // There is definitely an edge from OldSucc... add the edge now
562         NewPN->addIncoming(I, OldSucc);
563
564         // There is also an edge from BB now, add the edge with the calculated
565         // value from the RI.
566         NewPN->addIncoming(getReplacementOrValue(I, RI), BB);
567
568         // Make everything in the Dest region use the new PHI node now...
569         ReplaceUsesOfValueInRegion(I, NewPN, Dest);
570
571         // Make sure that exits out of the region dominated by NewPN get PHI
572         // nodes that merge the values as appropriate.
573         InsertRegionExitMerges(NewPN, I, RegionExitBlocks);
574       }
575   }
576
577   // If there were PHI nodes in OldSucc, we need to remove the entry for this
578   // edge from the PHI node, and we need to replace any references to the PHI
579   // node with a new value.
580   //
581   for (BasicBlock::iterator I = OldSucc->begin(); isa<PHINode>(I); ) {
582     PHINode *PN = cast<PHINode>(I);
583
584     // Get the value flowing across the old edge and remove the PHI node entry
585     // for this edge: we are about to remove the edge!  Don't remove the PHI
586     // node yet though if this is the last edge into it.
587     Value *EdgeValue = PN->removeIncomingValue(BB, false);
588
589     // Make sure that anything that used to use PN now refers to EdgeValue
590     ReplaceUsesOfValueInRegion(PN, EdgeValue, Dest);
591
592     // If there is only one value left coming into the PHI node, replace the PHI
593     // node itself with the one incoming value left.
594     //
595     if (PN->getNumIncomingValues() == 1) {
596       assert(PN->getNumIncomingValues() == 1);
597       PN->replaceAllUsesWith(PN->getIncomingValue(0));
598       PN->getParent()->getInstList().erase(PN);
599       I = OldSucc->begin();
600     } else if (PN->getNumIncomingValues() == 0) {  // Nuke the PHI
601       // If we removed the last incoming value to this PHI, nuke the PHI node
602       // now.
603       PN->replaceAllUsesWith(Constant::getNullValue(PN->getType()));
604       PN->getParent()->getInstList().erase(PN);
605       I = OldSucc->begin();
606     } else {
607       ++I;  // Otherwise, move on to the next PHI node
608     }
609   }
610
611   // Actually revector the branch now...
612   TI->setSuccessor(SuccNo, Dest);
613
614   // If we just introduced a critical edge in the flow graph, make sure to break
615   // it right away...
616   SplitCriticalEdge(TI, SuccNo, this);
617
618   // Make sure that we don't introduce critical edges from oldsucc now!
619   for (unsigned i = 0, e = OldSucc->getTerminator()->getNumSuccessors();
620        i != e; ++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   DOUT << "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
727   // Loop over all of the blocks we have to place PHIs in, doing it.
728   for (unsigned i = 0, e = RegionExitBlocks.size(); i != e; ++i) {
729     BasicBlock *FBlock = RegionExitBlocks[i];  // Block on the frontier
730
731     // Create the new PHI node
732     PHINode *NewPN = new PHINode(BBVal->getType(),
733                                  OldVal->getName()+".fw_frontier",
734                                  FBlock->begin());
735
736     // Add an incoming value for every predecessor of the block...
737     for (pred_iterator PI = pred_begin(FBlock), PE = pred_end(FBlock);
738          PI != PE; ++PI) {
739       // If the incoming edge is from the region dominated by BB, use BBVal,
740       // otherwise use OldVal.
741       NewPN->addIncoming(EF->dominates(BB, *PI) ? BBVal : OldVal, *PI);
742     }
743
744     // Now make everyone dominated by this block use this new value!
745     ReplaceUsesOfValueInRegion(OldVal, NewPN, FBlock);
746   }
747 }
748
749
750
751 // BuildRankMap - This method builds the rank map data structure which gives
752 // each instruction/value in the function a value based on how early it appears
753 // in the function.  We give constants and globals rank 0, arguments are
754 // numbered starting at one, and instructions are numbered in reverse post-order
755 // from where the arguments leave off.  This gives instructions in loops higher
756 // values than instructions not in loops.
757 //
758 void CEE::BuildRankMap(Function &F) {
759   unsigned Rank = 1;  // Skip rank zero.
760
761   // Number the arguments...
762   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I)
763     RankMap[I] = Rank++;
764
765   // Number the instructions in reverse post order...
766   ReversePostOrderTraversal<Function*> RPOT(&F);
767   for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
768          E = RPOT.end(); I != E; ++I)
769     for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
770          BBI != E; ++BBI)
771       if (BBI->getType() != Type::VoidTy)
772         RankMap[BBI] = Rank++;
773 }
774
775
776 // PropagateBranchInfo - When this method is invoked, we need to propagate
777 // information derived from the branch condition into the true and false
778 // branches of BI.  Since we know that there aren't any critical edges in the
779 // flow graph, this can proceed unconditionally.
780 //
781 void CEE::PropagateBranchInfo(BranchInst *BI) {
782   assert(BI->isConditional() && "Must be a conditional branch!");
783
784   // Propagate information into the true block...
785   //
786   PropagateEquality(BI->getCondition(), ConstantInt::getTrue(),
787                     getRegionInfo(BI->getSuccessor(0)));
788
789   // Propagate information into the false block...
790   //
791   PropagateEquality(BI->getCondition(), ConstantInt::getFalse(),
792                     getRegionInfo(BI->getSuccessor(1)));
793 }
794
795
796 // PropagateSwitchInfo - We need to propagate the value tested by the
797 // switch statement through each case block.
798 //
799 void CEE::PropagateSwitchInfo(SwitchInst *SI) {
800   // Propagate information down each of our non-default case labels.  We
801   // don't yet propagate information down the default label, because a
802   // potentially large number of inequality constraints provide less
803   // benefit per unit work than a single equality constraint.
804   //
805   Value *cond = SI->getCondition();
806   for (unsigned i = 1; i < SI->getNumSuccessors(); ++i)
807     PropagateEquality(cond, SI->getSuccessorValue(i),
808                       getRegionInfo(SI->getSuccessor(i)));
809 }
810
811
812 // PropagateEquality - If we discover that two values are equal to each other in
813 // a specified region, propagate this knowledge recursively.
814 //
815 void CEE::PropagateEquality(Value *Op0, Value *Op1, RegionInfo &RI) {
816   if (Op0 == Op1) return;  // Gee whiz. Are these really equal each other?
817
818   if (isa<Constant>(Op0))  // Make sure the constant is always Op1
819     std::swap(Op0, Op1);
820
821   // Make sure we don't already know these are equal, to avoid infinite loops...
822   ValueInfo &VI = RI.getValueInfo(Op0);
823
824   // Get information about the known relationship between Op0 & Op1
825   Relation &KnownRelation = VI.getRelation(Op1);
826
827   // If we already know they're equal, don't reprocess...
828   if (KnownRelation.getRelation() == FCmpInst::FCMP_OEQ ||
829       KnownRelation.getRelation() == ICmpInst::ICMP_EQ)
830     return;
831
832   // If this is boolean, check to see if one of the operands is a constant.  If
833   // it's a constant, then see if the other one is one of a setcc instruction,
834   // an AND, OR, or XOR instruction.
835   //
836   if (Op1->getType() == Type::Int1Ty)
837     if (ConstantInt *CB = dyn_cast<ConstantInt>(Op1)) {
838   
839       if (Instruction *Inst = dyn_cast<Instruction>(Op0)) {
840         // If we know that this instruction is an AND instruction, and the result
841         // is true, this means that both operands to the OR are known to be true
842         // as well.
843         //
844         if (CB->getZExtValue() && Inst->getOpcode() == Instruction::And) {
845           PropagateEquality(Inst->getOperand(0), CB, RI);
846           PropagateEquality(Inst->getOperand(1), CB, RI);
847         }
848   
849         // If we know that this instruction is an OR instruction, and the result
850         // is false, this means that both operands to the OR are know to be false
851         // as well.
852         //
853         if (!CB->getZExtValue() && Inst->getOpcode() == Instruction::Or) {
854           PropagateEquality(Inst->getOperand(0), CB, RI);
855           PropagateEquality(Inst->getOperand(1), CB, RI);
856         }
857
858         // If we know that this instruction is a NOT instruction, we know that 
859         // the operand is known to be the inverse of whatever the current 
860         // value is.
861         //
862         if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(Inst))
863           if (BinaryOperator::isNot(BOp))
864             PropagateEquality(BinaryOperator::getNotArgument(BOp),
865                               ConstantInt::get(Type::Int1Ty, 
866                                                !CB->getZExtValue()), RI);
867
868         // If we know the value of a FCmp instruction, propagate the information
869         // about the relation into this region as well.
870         //
871         if (FCmpInst *FCI = dyn_cast<FCmpInst>(Inst)) {
872           if (CB->getZExtValue()) {  // If we know the condition is true...
873             // Propagate info about the LHS to the RHS & RHS to LHS
874             PropagateRelation(FCI->getPredicate(), FCI->getOperand(0),
875                               FCI->getOperand(1), RI);
876             PropagateRelation(FCI->getSwappedPredicate(),
877                               FCI->getOperand(1), FCI->getOperand(0), RI);
878
879           } else {               // If we know the condition is false...
880             // We know the opposite of the condition is true...
881             FCmpInst::Predicate C = FCI->getInversePredicate();
882
883             PropagateRelation(C, FCI->getOperand(0), FCI->getOperand(1), RI);
884             PropagateRelation(FCmpInst::getSwappedPredicate(C),
885                               FCI->getOperand(1), FCI->getOperand(0), RI);
886           }
887         }
888       
889         // If we know the value of a ICmp instruction, propagate the information
890         // about the relation into this region as well.
891         //
892         if (ICmpInst *ICI = dyn_cast<ICmpInst>(Inst)) {
893           if (CB->getZExtValue()) { // If we know the condition is true...
894             // Propagate info about the LHS to the RHS & RHS to LHS
895             PropagateRelation(ICI->getPredicate(), ICI->getOperand(0),
896                               ICI->getOperand(1), RI);
897             PropagateRelation(ICI->getSwappedPredicate(), ICI->getOperand(1),
898                               ICI->getOperand(1), RI);
899
900           } else {               // If we know the condition is false ...
901             // We know the opposite of the condition is true...
902             ICmpInst::Predicate C = ICI->getInversePredicate();
903
904             PropagateRelation(C, ICI->getOperand(0), ICI->getOperand(1), RI);
905             PropagateRelation(ICmpInst::getSwappedPredicate(C),
906                               ICI->getOperand(1), ICI->getOperand(0), RI);
907           }
908         }
909       }
910     }
911
912   // Propagate information about Op0 to Op1 & visa versa
913   PropagateRelation(ICmpInst::ICMP_EQ, Op0, Op1, RI);
914   PropagateRelation(ICmpInst::ICMP_EQ, Op1, Op0, RI);
915   PropagateRelation(FCmpInst::FCMP_OEQ, Op0, Op1, RI);
916   PropagateRelation(FCmpInst::FCMP_OEQ, Op1, Op0, RI);
917 }
918
919
920 // PropagateRelation - We know that the specified relation is true in all of the
921 // blocks in the specified region.  Propagate the information about Op0 and
922 // anything derived from it into this region.
923 //
924 void CEE::PropagateRelation(unsigned Opcode, Value *Op0,
925                             Value *Op1, RegionInfo &RI) {
926   assert(Op0->getType() == Op1->getType() && "Equal types expected!");
927
928   // Constants are already pretty well understood.  We will apply information
929   // about the constant to Op1 in another call to PropagateRelation.
930   //
931   if (isa<Constant>(Op0)) return;
932
933   // Get the region information for this block to update...
934   ValueInfo &VI = RI.getValueInfo(Op0);
935
936   // Get information about the known relationship between Op0 & Op1
937   Relation &Op1R = VI.getRelation(Op1);
938
939   // Quick bailout for common case if we are reprocessing an instruction...
940   if (Op1R.getRelation() == Opcode)
941     return;
942
943   // If we already have information that contradicts the current information we
944   // are propagating, ignore this info.  Something bad must have happened!
945   //
946   if (Op1R.contradicts(Opcode, VI)) {
947     Op1R.contradicts(Opcode, VI);
948     cerr << "Contradiction found for opcode: "
949          << ((isa<ICmpInst>(Op0)||isa<ICmpInst>(Op1)) ? 
950                   Instruction::getOpcodeName(Instruction::ICmp) :
951                   Instruction::getOpcodeName(Opcode))
952          << "\n";
953     Op1R.print(*cerr.stream());
954     return;
955   }
956
957   // If the information propagated is new, then we want process the uses of this
958   // instruction to propagate the information down to them.
959   //
960   if (Op1R.incorporate(Opcode, VI))
961     UpdateUsersOfValue(Op0, RI);
962 }
963
964
965 // UpdateUsersOfValue - The information about V in this region has been updated.
966 // Propagate this to all consumers of the value.
967 //
968 void CEE::UpdateUsersOfValue(Value *V, RegionInfo &RI) {
969   for (Value::use_iterator I = V->use_begin(), E = V->use_end();
970        I != E; ++I)
971     if (Instruction *Inst = dyn_cast<Instruction>(*I)) {
972       // If this is an instruction using a value that we know something about,
973       // try to propagate information to the value produced by the
974       // instruction.  We can only do this if it is an instruction we can
975       // propagate information for (a setcc for example), and we only WANT to
976       // do this if the instruction dominates this region.
977       //
978       // If the instruction doesn't dominate this region, then it cannot be
979       // used in this region and we don't care about it.  If the instruction
980       // is IN this region, then we will simplify the instruction before we
981       // get to uses of it anyway, so there is no reason to bother with it
982       // here.  This check is also effectively checking to make sure that Inst
983       // is in the same function as our region (in case V is a global f.e.).
984       //
985       if (EF->properlyDominates(Inst->getParent(), RI.getEntryBlock()))
986         IncorporateInstruction(Inst, RI);
987     }
988 }
989
990 // IncorporateInstruction - We just updated the information about one of the
991 // operands to the specified instruction.  Update the information about the
992 // value produced by this instruction
993 //
994 void CEE::IncorporateInstruction(Instruction *Inst, RegionInfo &RI) {
995   if (CmpInst *CI = dyn_cast<CmpInst>(Inst)) {
996     // See if we can figure out a result for this instruction...
997     Relation::KnownResult Result = getCmpResult(CI, RI);
998     if (Result != Relation::Unknown) {
999       PropagateEquality(CI, ConstantInt::get(Type::Int1Ty, Result != 0), RI);
1000     }
1001   }
1002 }
1003
1004
1005 // ComputeReplacements - Some values are known to be equal to other values in a
1006 // region.  For example if there is a comparison of equality between a variable
1007 // X and a constant C, we can replace all uses of X with C in the region we are
1008 // interested in.  We generalize this replacement to replace variables with
1009 // other variables if they are equal and there is a variable with lower rank
1010 // than the current one.  This offers a canonicalizing property that exposes
1011 // more redundancies for later transformations to take advantage of.
1012 //
1013 void CEE::ComputeReplacements(RegionInfo &RI) {
1014   // Loop over all of the values in the region info map...
1015   for (RegionInfo::iterator I = RI.begin(), E = RI.end(); I != E; ++I) {
1016     ValueInfo &VI = I->second;
1017
1018     // If we know that this value is a particular constant, set Replacement to
1019     // the constant...
1020     Value *Replacement = VI.getBounds().getSingleElement();
1021
1022     // If this value is not known to be some constant, figure out the lowest
1023     // rank value that it is known to be equal to (if anything).
1024     //
1025     if (Replacement == 0) {
1026       // Find out if there are any equality relationships with values of lower
1027       // rank than VI itself...
1028       unsigned MinRank = getRank(I->first);
1029
1030       // Loop over the relationships known about Op0.
1031       const std::vector<Relation> &Relationships = VI.getRelationships();
1032       for (unsigned i = 0, e = Relationships.size(); i != e; ++i)
1033         if (Relationships[i].getRelation() == FCmpInst::FCMP_OEQ) {
1034           unsigned R = getRank(Relationships[i].getValue());
1035           if (R < MinRank) {
1036             MinRank = R;
1037             Replacement = Relationships[i].getValue();
1038           }
1039         }
1040         else if (Relationships[i].getRelation() == ICmpInst::ICMP_EQ) {
1041           unsigned R = getRank(Relationships[i].getValue());
1042           if (R < MinRank) {
1043             MinRank = R;
1044             Replacement = Relationships[i].getValue();
1045           }
1046         }
1047     }
1048
1049     // If we found something to replace this value with, keep track of it.
1050     if (Replacement)
1051       VI.setReplacement(Replacement);
1052   }
1053 }
1054
1055 // SimplifyBasicBlock - Given information about values in region RI, simplify
1056 // the instructions in the specified basic block.
1057 //
1058 bool CEE::SimplifyBasicBlock(BasicBlock &BB, const RegionInfo &RI) {
1059   bool Changed = false;
1060   for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ) {
1061     Instruction *Inst = I++;
1062
1063     // Convert instruction arguments to canonical forms...
1064     Changed |= SimplifyInstruction(Inst, RI);
1065
1066     if (CmpInst *CI = dyn_cast<CmpInst>(Inst)) {
1067       // Try to simplify a setcc instruction based on inherited information
1068       Relation::KnownResult Result = getCmpResult(CI, RI);
1069       if (Result != Relation::Unknown) {
1070         DEBUG(cerr << "Replacing icmp with " << Result
1071                    << " constant: " << *CI);
1072
1073         CI->replaceAllUsesWith(ConstantInt::get(Type::Int1Ty, (bool)Result));
1074         // The instruction is now dead, remove it from the program.
1075         CI->getParent()->getInstList().erase(CI);
1076         ++NumCmpRemoved;
1077         Changed = true;
1078       }
1079     }
1080   }
1081
1082   return Changed;
1083 }
1084
1085 // SimplifyInstruction - Inspect the operands of the instruction, converting
1086 // them to their canonical form if possible.  This takes care of, for example,
1087 // replacing a value 'X' with a constant 'C' if the instruction in question is
1088 // dominated by a true seteq 'X', 'C'.
1089 //
1090 bool CEE::SimplifyInstruction(Instruction *I, const RegionInfo &RI) {
1091   bool Changed = false;
1092
1093   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1094     if (const ValueInfo *VI = RI.requestValueInfo(I->getOperand(i)))
1095       if (Value *Repl = VI->getReplacement()) {
1096         // If we know if a replacement with lower rank than Op0, make the
1097         // replacement now.
1098         DOUT << "In Inst: " << *I << "  Replacing operand #" << i
1099              << " with " << *Repl << "\n";
1100         I->setOperand(i, Repl);
1101         Changed = true;
1102         ++NumOperandsCann;
1103       }
1104
1105   return Changed;
1106 }
1107
1108 // getCmpResult - Try to simplify a cmp instruction based on information
1109 // inherited from a dominating icmp instruction.  V is one of the operands to
1110 // the icmp instruction, and VI is the set of information known about it.  We
1111 // take two cases into consideration here.  If the comparison is against a
1112 // constant value, we can use the constant range to see if the comparison is
1113 // possible to succeed.  If it is not a comparison against a constant, we check
1114 // to see if there is a known relationship between the two values.  If so, we
1115 // may be able to eliminate the check.
1116 //
1117 Relation::KnownResult CEE::getCmpResult(CmpInst *CI,
1118                                         const RegionInfo &RI) {
1119   Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
1120   unsigned short predicate = CI->getPredicate();
1121
1122   if (isa<Constant>(Op0)) {
1123     if (isa<Constant>(Op1)) {
1124       if (Constant *Result = ConstantFoldInstruction(CI)) {
1125         // Wow, this is easy, directly eliminate the ICmpInst.
1126         DEBUG(cerr << "Replacing cmp with constant fold: " << *CI);
1127         return cast<ConstantInt>(Result)->getZExtValue()
1128           ? Relation::KnownTrue : Relation::KnownFalse;
1129       }
1130     } else {
1131       // We want to swap this instruction so that operand #0 is the constant.
1132       std::swap(Op0, Op1);
1133       if (isa<ICmpInst>(CI))
1134         predicate = cast<ICmpInst>(CI)->getSwappedPredicate();
1135       else
1136         predicate = cast<FCmpInst>(CI)->getSwappedPredicate();
1137     }
1138   }
1139
1140   // Try to figure out what the result of this comparison will be...
1141   Relation::KnownResult Result = Relation::Unknown;
1142
1143   // We have to know something about the relationship to prove anything...
1144   if (const ValueInfo *Op0VI = RI.requestValueInfo(Op0)) {
1145
1146     // At this point, we know that if we have a constant argument that it is in
1147     // Op1.  Check to see if we know anything about comparing value with a
1148     // constant, and if we can use this info to fold the icmp.
1149     //
1150     if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
1151       // Check to see if we already know the result of this comparison...
1152       ConstantRange R = ConstantRange(predicate, C);
1153       ConstantRange Int = R.intersectWith(Op0VI->getBounds(),
1154           ICmpInst::isSignedPredicate(ICmpInst::Predicate(predicate)));
1155
1156       // If the intersection of the two ranges is empty, then the condition
1157       // could never be true!
1158       //
1159       if (Int.isEmptySet()) {
1160         Result = Relation::KnownFalse;
1161
1162       // Otherwise, if VI.getBounds() (the possible values) is a subset of R
1163       // (the allowed values) then we know that the condition must always be
1164       // true!
1165       //
1166       } else if (Int == Op0VI->getBounds()) {
1167         Result = Relation::KnownTrue;
1168       }
1169     } else {
1170       // If we are here, we know that the second argument is not a constant
1171       // integral.  See if we know anything about Op0 & Op1 that allows us to
1172       // fold this anyway.
1173       //
1174       // Do we have value information about Op0 and a relation to Op1?
1175       if (const Relation *Op2R = Op0VI->requestRelation(Op1))
1176         Result = Op2R->getImpliedResult(predicate);
1177     }
1178   }
1179   return Result;
1180 }
1181
1182 //===----------------------------------------------------------------------===//
1183 //  Relation Implementation
1184 //===----------------------------------------------------------------------===//
1185
1186 // contradicts - Return true if the relationship specified by the operand
1187 // contradicts already known information.
1188 //
1189 bool Relation::contradicts(unsigned Op,
1190                            const ValueInfo &VI) const {
1191   assert (Op != Instruction::Add && "Invalid relation argument!");
1192
1193   // If this is a relationship with a constant, make sure that this relationship
1194   // does not contradict properties known about the bounds of the constant.
1195   //
1196   if (ConstantInt *C = dyn_cast<ConstantInt>(Val))
1197     if (Op >= ICmpInst::FIRST_ICMP_PREDICATE && 
1198         Op <= ICmpInst::LAST_ICMP_PREDICATE)
1199       if (ConstantRange(Op, C).intersectWith(VI.getBounds(),
1200           ICmpInst::isSignedPredicate(ICmpInst::Predicate(Op))).isEmptySet())
1201         return true;
1202
1203   switch (Rel) {
1204   default: assert(0 && "Unknown Relationship code!");
1205   case Instruction::Add: return false;  // Nothing known, nothing contradicts
1206   case ICmpInst::ICMP_EQ:
1207     return Op == ICmpInst::ICMP_ULT || Op == ICmpInst::ICMP_SLT ||
1208            Op == ICmpInst::ICMP_UGT || Op == ICmpInst::ICMP_SGT ||
1209            Op == ICmpInst::ICMP_NE;
1210   case ICmpInst::ICMP_NE:  return Op == ICmpInst::ICMP_EQ;
1211   case ICmpInst::ICMP_ULE:
1212   case ICmpInst::ICMP_SLE: return Op == ICmpInst::ICMP_UGT ||
1213                                   Op == ICmpInst::ICMP_SGT;
1214   case ICmpInst::ICMP_UGE:
1215   case ICmpInst::ICMP_SGE: return Op == ICmpInst::ICMP_ULT ||
1216                                   Op == ICmpInst::ICMP_SLT;
1217   case ICmpInst::ICMP_ULT:
1218   case ICmpInst::ICMP_SLT:
1219     return Op == ICmpInst::ICMP_EQ  || Op == ICmpInst::ICMP_UGT ||
1220            Op == ICmpInst::ICMP_SGT || Op == ICmpInst::ICMP_UGE ||
1221            Op == ICmpInst::ICMP_SGE;
1222   case ICmpInst::ICMP_UGT:
1223   case ICmpInst::ICMP_SGT:
1224     return Op == ICmpInst::ICMP_EQ  || Op == ICmpInst::ICMP_ULT ||
1225            Op == ICmpInst::ICMP_SLT || Op == ICmpInst::ICMP_ULE ||
1226            Op == ICmpInst::ICMP_SLE;
1227   case FCmpInst::FCMP_OEQ:
1228     return Op == FCmpInst::FCMP_OLT || Op == FCmpInst::FCMP_OGT ||
1229            Op == FCmpInst::FCMP_ONE;
1230   case FCmpInst::FCMP_ONE: return Op == FCmpInst::FCMP_OEQ;
1231   case FCmpInst::FCMP_OLE: return Op == FCmpInst::FCMP_OGT;
1232   case FCmpInst::FCMP_OGE: return Op == FCmpInst::FCMP_OLT;
1233   case FCmpInst::FCMP_OLT:
1234     return Op == FCmpInst::FCMP_OEQ || Op == FCmpInst::FCMP_OGT ||
1235            Op == FCmpInst::FCMP_OGE;
1236   case FCmpInst::FCMP_OGT:
1237     return Op == FCmpInst::FCMP_OEQ || Op == FCmpInst::FCMP_OLT ||
1238            Op == FCmpInst::FCMP_OLE;
1239   }
1240 }
1241
1242 // incorporate - Incorporate information in the argument into this relation
1243 // entry.  This assumes that the information doesn't contradict itself.  If any
1244 // new information is gained, true is returned, otherwise false is returned to
1245 // indicate that nothing was updated.
1246 //
1247 bool Relation::incorporate(unsigned Op, ValueInfo &VI) {
1248   assert(!contradicts(Op, VI) &&
1249          "Cannot incorporate contradictory information!");
1250
1251   // If this is a relationship with a constant, make sure that we update the
1252   // range that is possible for the value to have...
1253   //
1254   if (ConstantInt *C = dyn_cast<ConstantInt>(Val))
1255     if (Op >= ICmpInst::FIRST_ICMP_PREDICATE && 
1256         Op <= ICmpInst::LAST_ICMP_PREDICATE)
1257       VI.getBounds() = ConstantRange(Op, C).intersectWith(VI.getBounds(),
1258           ICmpInst::isSignedPredicate(ICmpInst::Predicate(Op)));
1259
1260   switch (Rel) {
1261   default: assert(0 && "Unknown prior value!");
1262   case Instruction::Add:   Rel = Op; return true;
1263   case ICmpInst::ICMP_EQ:
1264   case ICmpInst::ICMP_NE:
1265   case ICmpInst::ICMP_ULT:
1266   case ICmpInst::ICMP_SLT:
1267   case ICmpInst::ICMP_UGT:
1268   case ICmpInst::ICMP_SGT: return false;  // Nothing is more precise
1269   case ICmpInst::ICMP_ULE:
1270   case ICmpInst::ICMP_SLE:
1271     if (Op == ICmpInst::ICMP_EQ  || Op == ICmpInst::ICMP_ULT ||
1272         Op == ICmpInst::ICMP_SLT) {
1273       Rel = Op;
1274       return true;
1275     } else if (Op == ICmpInst::ICMP_NE) {
1276       Rel = Rel == ICmpInst::ICMP_ULE ? ICmpInst::ICMP_ULT :
1277             ICmpInst::ICMP_SLT;
1278       return true;
1279     }
1280     return false;
1281   case ICmpInst::ICMP_UGE:
1282   case ICmpInst::ICMP_SGE:
1283     if (Op == ICmpInst::ICMP_EQ  || ICmpInst::ICMP_UGT ||
1284         Op == ICmpInst::ICMP_SGT) {
1285       Rel = Op;
1286       return true;
1287     } else if (Op == ICmpInst::ICMP_NE) {
1288       Rel = Rel == ICmpInst::ICMP_UGE ? ICmpInst::ICMP_UGT :
1289             ICmpInst::ICMP_SGT;
1290       return true;
1291     }
1292     return false;
1293   case FCmpInst::FCMP_OEQ: return false;  // Nothing is more precise
1294   case FCmpInst::FCMP_ONE: return false;  // Nothing is more precise
1295   case FCmpInst::FCMP_OLT: return false;  // Nothing is more precise
1296   case FCmpInst::FCMP_OGT: return false;  // Nothing is more precise
1297   case FCmpInst::FCMP_OLE:
1298     if (Op == FCmpInst::FCMP_OEQ || Op == FCmpInst::FCMP_OLT) {
1299       Rel = Op;
1300       return true;
1301     } else if (Op == FCmpInst::FCMP_ONE) {
1302       Rel = FCmpInst::FCMP_OLT;
1303       return true;
1304     }
1305     return false;
1306   case FCmpInst::FCMP_OGE: 
1307     return Op == FCmpInst::FCMP_OLT;
1308     if (Op == FCmpInst::FCMP_OEQ || Op == FCmpInst::FCMP_OGT) {
1309       Rel = Op;
1310       return true;
1311     } else if (Op == FCmpInst::FCMP_ONE) {
1312       Rel = FCmpInst::FCMP_OGT;
1313       return true;
1314     }
1315     return false;
1316   }
1317 }
1318
1319 // getImpliedResult - If this relationship between two values implies that
1320 // the specified relationship is true or false, return that.  If we cannot
1321 // determine the result required, return Unknown.
1322 //
1323 Relation::KnownResult
1324 Relation::getImpliedResult(unsigned Op) const {
1325   if (Rel == Op) return KnownTrue;
1326   if (Op >= ICmpInst::FIRST_ICMP_PREDICATE && 
1327       Op <= ICmpInst::LAST_ICMP_PREDICATE) {
1328     if (Rel == unsigned(ICmpInst::getInversePredicate(ICmpInst::Predicate(Op))))
1329       return KnownFalse;
1330   } else if (Op <= FCmpInst::LAST_FCMP_PREDICATE) {
1331     if (Rel == unsigned(FCmpInst::getInversePredicate(FCmpInst::Predicate(Op))))
1332     return KnownFalse;
1333   }
1334
1335   switch (Rel) {
1336   default: assert(0 && "Unknown prior value!");
1337   case ICmpInst::ICMP_EQ:
1338     if (Op == ICmpInst::ICMP_ULE || Op == ICmpInst::ICMP_SLE || 
1339         Op == ICmpInst::ICMP_UGE || Op == ICmpInst::ICMP_SGE) return KnownTrue;
1340     if (Op == ICmpInst::ICMP_ULT || Op == ICmpInst::ICMP_SLT || 
1341         Op == ICmpInst::ICMP_UGT || Op == ICmpInst::ICMP_SGT) return KnownFalse;
1342     break;
1343   case ICmpInst::ICMP_ULT:
1344   case ICmpInst::ICMP_SLT:
1345     if (Op == ICmpInst::ICMP_ULE || Op == ICmpInst::ICMP_SLE ||
1346         Op == ICmpInst::ICMP_NE) return KnownTrue;
1347     if (Op == ICmpInst::ICMP_EQ) return KnownFalse;
1348     break;
1349   case ICmpInst::ICMP_UGT:
1350   case ICmpInst::ICMP_SGT:
1351     if (Op == ICmpInst::ICMP_UGE || Op == ICmpInst::ICMP_SGE ||
1352         Op == ICmpInst::ICMP_NE) return KnownTrue;
1353     if (Op == ICmpInst::ICMP_EQ) return KnownFalse;
1354     break;
1355   case FCmpInst::FCMP_OEQ:
1356     if (Op == FCmpInst::FCMP_OLE || Op == FCmpInst::FCMP_OGE) return KnownTrue;
1357     if (Op == FCmpInst::FCMP_OLT || Op == FCmpInst::FCMP_OGT) return KnownFalse;
1358     break;
1359   case FCmpInst::FCMP_OLT:
1360     if (Op == FCmpInst::FCMP_ONE || Op == FCmpInst::FCMP_OLE) return KnownTrue;
1361     if (Op == FCmpInst::FCMP_OEQ) return KnownFalse;
1362     break;
1363   case FCmpInst::FCMP_OGT:
1364     if (Op == FCmpInst::FCMP_ONE || Op == FCmpInst::FCMP_OGE) return KnownTrue;
1365     if (Op == FCmpInst::FCMP_OEQ) return KnownFalse;
1366     break;
1367   case ICmpInst::ICMP_NE:
1368   case ICmpInst::ICMP_SLE:
1369   case ICmpInst::ICMP_ULE:
1370   case ICmpInst::ICMP_UGE:
1371   case ICmpInst::ICMP_SGE:
1372   case FCmpInst::FCMP_ONE:
1373   case FCmpInst::FCMP_OLE:
1374   case FCmpInst::FCMP_OGE:
1375   case FCmpInst::FCMP_FALSE:
1376   case FCmpInst::FCMP_ORD:
1377   case FCmpInst::FCMP_UNO:
1378   case FCmpInst::FCMP_UEQ:
1379   case FCmpInst::FCMP_UGT:
1380   case FCmpInst::FCMP_UGE:
1381   case FCmpInst::FCMP_ULT:
1382   case FCmpInst::FCMP_ULE:
1383   case FCmpInst::FCMP_UNE:
1384   case FCmpInst::FCMP_TRUE:
1385     break;
1386   }
1387   return Unknown;
1388 }
1389
1390
1391 //===----------------------------------------------------------------------===//
1392 // Printing Support...
1393 //===----------------------------------------------------------------------===//
1394
1395 // print - Implement the standard print form to print out analysis information.
1396 void CEE::print(std::ostream &O, const Module *M) const {
1397   O << "\nPrinting Correlated Expression Info:\n";
1398   for (std::map<BasicBlock*, RegionInfo>::const_iterator I =
1399          RegionInfoMap.begin(), E = RegionInfoMap.end(); I != E; ++I)
1400     I->second.print(O);
1401 }
1402
1403 // print - Output information about this region...
1404 void RegionInfo::print(std::ostream &OS) const {
1405   if (ValueMap.empty()) return;
1406
1407   OS << " RegionInfo for basic block: " << BB->getName() << "\n";
1408   for (std::map<Value*, ValueInfo>::const_iterator
1409          I = ValueMap.begin(), E = ValueMap.end(); I != E; ++I)
1410     I->second.print(OS, I->first);
1411   OS << "\n";
1412 }
1413
1414 // print - Output information about this value relation...
1415 void ValueInfo::print(std::ostream &OS, Value *V) const {
1416   if (Relationships.empty()) return;
1417
1418   if (V) {
1419     OS << "  ValueInfo for: ";
1420     WriteAsOperand(OS, V);
1421   }
1422   OS << "\n    Bounds = " << Bounds << "\n";
1423   if (Replacement) {
1424     OS << "    Replacement = ";
1425     WriteAsOperand(OS, Replacement);
1426     OS << "\n";
1427   }
1428   for (unsigned i = 0, e = Relationships.size(); i != e; ++i)
1429     Relationships[i].print(OS);
1430 }
1431
1432 // print - Output this relation to the specified stream
1433 void Relation::print(std::ostream &OS) const {
1434   OS << "    is ";
1435   switch (Rel) {
1436   default:           OS << "*UNKNOWN*"; break;
1437   case ICmpInst::ICMP_EQ:
1438   case FCmpInst::FCMP_ORD:
1439   case FCmpInst::FCMP_UEQ:
1440   case FCmpInst::FCMP_OEQ: OS << "== "; break;
1441   case ICmpInst::ICMP_NE:
1442   case FCmpInst::FCMP_UNO:
1443   case FCmpInst::FCMP_UNE:
1444   case FCmpInst::FCMP_ONE: OS << "!= "; break;
1445   case ICmpInst::ICMP_ULT:
1446   case ICmpInst::ICMP_SLT:
1447   case FCmpInst::FCMP_ULT:
1448   case FCmpInst::FCMP_OLT: OS << "< "; break;
1449   case ICmpInst::ICMP_UGT:
1450   case ICmpInst::ICMP_SGT:
1451   case FCmpInst::FCMP_UGT:
1452   case FCmpInst::FCMP_OGT: OS << "> "; break;
1453   case ICmpInst::ICMP_ULE:
1454   case ICmpInst::ICMP_SLE:
1455   case FCmpInst::FCMP_ULE:
1456   case FCmpInst::FCMP_OLE: OS << "<= "; break;
1457   case ICmpInst::ICMP_UGE:
1458   case ICmpInst::ICMP_SGE:
1459   case FCmpInst::FCMP_UGE:
1460   case FCmpInst::FCMP_OGE: OS << ">= "; break;
1461   }
1462
1463   WriteAsOperand(OS, Val);
1464   OS << "\n";
1465 }
1466
1467 // Don't inline these methods or else we won't be able to call them from GDB!
1468 void Relation::dump() const { print(*cerr.stream()); }
1469 void ValueInfo::dump() const { print(*cerr.stream(), 0); }
1470 void RegionInfo::dump() const { print(*cerr.stream()); }