9be508d3a857c82aad602c038cf1a0d6b1b0df5e
[oota-llvm.git] / lib / Transforms / Scalar / CorrelatedExprs.cpp
1 //===- CorrelatedExprs.cpp - Pass to detect and eliminated c.e.'s ---------===//
2 //
3 // Correlated Expression Elimination propogates information from conditional
4 // branches to blocks dominated by destinations of the branch.  It propogates
5 // information from the condition check itself into the body of the branch,
6 // allowing transformations like these for example:
7 //
8 //  if (i == 7)
9 //    ... 4*i;  // constant propogation
10 //
11 //  M = i+1; N = j+1;
12 //  if (i == j)
13 //    X = M-N;  // = M-M == 0;
14 //
15 // This is called Correlated Expression Elimination because we eliminate or
16 // simplify expressions that are correlated with the direction of a branch.  In
17 // this way we use static information to give us some information about the
18 // dynamic value of a variable.
19 //
20 //===----------------------------------------------------------------------===//
21
22 #include "llvm/Transforms/Scalar.h"
23 #include "llvm/Pass.h"
24 #include "llvm/Function.h"
25 #include "llvm/iTerminators.h"
26 #include "llvm/iPHINode.h"
27 #include "llvm/iOperators.h"
28 #include "llvm/ConstantHandling.h"
29 #include "llvm/Assembly/Writer.h"
30 #include "llvm/Analysis/Dominators.h"
31 #include "llvm/Transforms/Utils/Local.h"
32 #include "llvm/Support/ConstantRange.h"
33 #include "llvm/Support/CFG.h"
34 #include "Support/PostOrderIterator.h"
35 #include "Support/StatisticReporter.h"
36 #include <algorithm>
37
38 namespace {
39   Statistic<>NumSetCCRemoved("cee\t\t- Number of setcc instruction eliminated");
40   Statistic<>NumOperandsCann("cee\t\t- Number of operands cannonicalized");
41   Statistic<>BranchRevectors("cee\t\t- Number of branches revectored");
42
43   class ValueInfo;
44   class Relation {
45     Value *Val;                 // Relation to what value?
46     Instruction::BinaryOps Rel; // SetCC relation, or Add if no information
47   public:
48     Relation(Value *V) : Val(V), Rel(Instruction::Add) {}
49     bool operator<(const Relation &R) const { return Val < R.Val; }
50     Value *getValue() const { return Val; }
51     Instruction::BinaryOps getRelation() const { return Rel; }
52
53     // contradicts - Return true if the relationship specified by the operand
54     // contradicts already known information.
55     //
56     bool contradicts(Instruction::BinaryOps Rel, const ValueInfo &VI) const;
57
58     // incorporate - Incorporate information in the argument into this relation
59     // entry.  This assumes that the information doesn't contradict itself.  If
60     // any new information is gained, true is returned, otherwise false is
61     // returned to indicate that nothing was updated.
62     //
63     bool incorporate(Instruction::BinaryOps Rel, ValueInfo &VI);
64
65     // KnownResult - Whether or not this condition determines the result of a
66     // setcc in the program.  False & True are intentionally 0 & 1 so we can
67     // convert to bool by casting after checking for unknown.
68     //
69     enum KnownResult { KnownFalse = 0, KnownTrue = 1, Unknown = 2 };
70
71     // getImpliedResult - If this relationship between two values implies that
72     // the specified relationship is true or false, return that.  If we cannot
73     // determine the result required, return Unknown.
74     //
75     KnownResult getImpliedResult(Instruction::BinaryOps Rel) const;
76
77     // print - Output this relation to the specified stream
78     void print(std::ostream &OS) const;
79     void dump() const;
80   };
81
82
83   // ValueInfo - One instance of this record exists for every value with
84   // relationships between other values.  It keeps track of all of the
85   // relationships to other values in the program (specified with Relation) that
86   // are known to be valid in a region.
87   //
88   class ValueInfo {
89     // RelationShips - this value is know to have the specified relationships to
90     // other values.  There can only be one entry per value, and this list is
91     // kept sorted by the Val field.
92     std::vector<Relation> Relationships;
93
94     // If information about this value is known or propogated from constant
95     // expressions, this range contains the possible values this value may hold.
96     ConstantRange Bounds;
97
98     // If we find that this value is equal to another value that has a lower
99     // rank, this value is used as it's replacement.
100     //
101     Value *Replacement;
102   public:
103     ValueInfo(const Type *Ty)
104       : Bounds(Ty->isIntegral() ? Ty : Type::IntTy), Replacement(0) {}
105
106     // getBounds() - Return the constant bounds of the value...
107     const ConstantRange &getBounds() const { return Bounds; }
108     ConstantRange &getBounds() { return Bounds; }
109
110     const std::vector<Relation> &getRelationships() { return Relationships; }
111
112     // getReplacement - Return the value this value is to be replaced with if it
113     // exists, otherwise return null.
114     //
115     Value *getReplacement() const { return Replacement; }
116
117     // setReplacement - Used by the replacement calculation pass to figure out
118     // what to replace this value with, if anything.
119     //
120     void setReplacement(Value *Repl) { Replacement = Repl; }
121
122     // getRelation - return the relationship entry for the specified value.
123     // This can invalidate references to other Relation's, so use it carefully.
124     //
125     Relation &getRelation(Value *V) {
126       // Binary search for V's entry...
127       std::vector<Relation>::iterator I =
128         std::lower_bound(Relationships.begin(), Relationships.end(), V);
129
130       // If we found the entry, return it...
131       if (I != Relationships.end() && I->getValue() == V)
132         return *I;
133
134       // Insert and return the new relationship...
135       return *Relationships.insert(I, V);
136     }
137
138     const Relation *requestRelation(Value *V) const {
139       // Binary search for V's entry...
140       std::vector<Relation>::const_iterator I =
141         std::lower_bound(Relationships.begin(), Relationships.end(), V);
142       if (I != Relationships.end() && I->getValue() == V)
143         return &*I;
144       return 0;
145     }
146
147     // print - Output information about this value relation...
148     void print(std::ostream &OS, Value *V) const;
149     void dump() const;
150   };
151
152   // RegionInfo - Keeps track of all of the value relationships for a region.  A
153   // region is the are dominated by a basic block.  RegionInfo's keep track of
154   // the RegionInfo for their dominator, because anything known in a dominator
155   // is known to be true in a dominated block as well.
156   //
157   class RegionInfo {
158     BasicBlock *BB;
159
160     // ValueMap - Tracks the ValueInformation known for this region
161     typedef std::map<Value*, ValueInfo> ValueMapTy;
162     ValueMapTy ValueMap;
163   public:
164     RegionInfo(BasicBlock *bb) : BB(bb) {}
165
166     // getEntryBlock - Return the block that dominates all of the members of
167     // this region.
168     BasicBlock *getEntryBlock() const { return BB; }
169
170     const RegionInfo &operator=(const RegionInfo &RI) {
171       ValueMap = RI.ValueMap;
172       return *this;
173     }
174
175     // print - Output information about this region...
176     void print(std::ostream &OS) const;
177
178     // Allow external access.
179     typedef ValueMapTy::iterator iterator;
180     iterator begin() { return ValueMap.begin(); }
181     iterator end() { return ValueMap.end(); }
182
183     ValueInfo &getValueInfo(Value *V) {
184       ValueMapTy::iterator I = ValueMap.lower_bound(V);
185       if (I != ValueMap.end() && I->first == V) return I->second;
186       return ValueMap.insert(I, std::make_pair(V, V->getType()))->second;
187     }
188
189     const ValueInfo *requestValueInfo(Value *V) const {
190       ValueMapTy::const_iterator I = ValueMap.find(V);
191       if (I != ValueMap.end()) return &I->second;
192       return 0;
193     }
194   };
195
196   /// CEE - Correlated Expression Elimination
197   class CEE : public FunctionPass {
198     std::map<Value*, unsigned> RankMap;
199     std::map<BasicBlock*, RegionInfo> RegionInfoMap;
200     DominatorSet *DS;
201     DominatorTree *DT;
202   public:
203     virtual bool runOnFunction(Function &F);
204
205     // We don't modify the program, so we preserve all analyses
206     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
207       //AU.preservesCFG();
208       AU.addRequired<DominatorSet>();
209       AU.addRequired<DominatorTree>();
210     };
211
212     // print - Implement the standard print form to print out analysis
213     // information.
214     virtual void print(std::ostream &O, const Module *M) const;
215
216   private:
217     RegionInfo &getRegionInfo(BasicBlock *BB) {
218       std::map<BasicBlock*, RegionInfo>::iterator I
219         = RegionInfoMap.lower_bound(BB);
220       if (I != RegionInfoMap.end() && I->first == BB) return I->second;
221       return RegionInfoMap.insert(I, std::make_pair(BB, BB))->second;
222     }
223
224     void BuildRankMap(Function &F);
225     unsigned getRank(Value *V) const {
226       if (isa<Constant>(V) || isa<GlobalValue>(V)) return 0;
227       std::map<Value*, unsigned>::const_iterator I = RankMap.find(V);
228       if (I != RankMap.end()) return I->second;
229       return 0; // Must be some other global thing
230     }
231
232     bool TransformRegion(BasicBlock *BB, std::set<BasicBlock*> &VisitedBlocks);
233
234     BasicBlock *isCorrelatedBranchBlock(BasicBlock *BB, RegionInfo &RI);
235     void PropogateBranchInfo(BranchInst *BI);
236     void PropogateEquality(Value *Op0, Value *Op1, RegionInfo &RI);
237     void PropogateRelation(Instruction::BinaryOps Opcode, Value *Op0,
238                            Value *Op1, RegionInfo &RI);
239     void UpdateUsersOfValue(Value *V, RegionInfo &RI);
240     void IncorporateInstruction(Instruction *Inst, RegionInfo &RI);
241     void ComputeReplacements(RegionInfo &RI);
242
243
244     // getSetCCResult - Given a setcc instruction, determine if the result is
245     // determined by facts we already know about the region under analysis.
246     // Return KnownTrue, KnownFalse, or Unknown based on what we can determine.
247     //
248     Relation::KnownResult getSetCCResult(SetCondInst *SC, const RegionInfo &RI);
249
250
251     bool SimplifyBasicBlock(BasicBlock &BB, const RegionInfo &RI);
252     bool SimplifyInstruction(Instruction *Inst, const RegionInfo &RI);
253   }; 
254   RegisterOpt<CEE> X("cee", "Correlated Expression Elimination");
255 }
256
257 Pass *createCorrelatedExpressionEliminationPass() { return new CEE(); }
258
259
260 bool CEE::runOnFunction(Function &F) {
261   // Build a rank map for the function...
262   BuildRankMap(F);
263
264   // Traverse the dominator tree, computing information for each node in the
265   // tree.  Note that our traversal will not even touch unreachable basic
266   // blocks.
267   DS = &getAnalysis<DominatorSet>();
268   DT = &getAnalysis<DominatorTree>();
269   
270   std::set<BasicBlock*> VisitedBlocks;
271   bool Changed = TransformRegion(&F.getEntryNode(), VisitedBlocks);
272
273   RegionInfoMap.clear();
274   RankMap.clear();
275   return Changed;
276 }
277
278 // TransformRegion - Transform the region starting with BB according to the
279 // calculated region information for the block.  Transforming the region
280 // involves analyzing any information this block provides to successors,
281 // propogating the information to successors, and finally transforming
282 // successors.
283 //
284 // This method processes the function in depth first order, which guarantees
285 // that we process the immediate dominator of a block before the block itself.
286 // Because we are passing information from immediate dominators down to
287 // dominatees, we obviously have to process the information source before the
288 // information consumer.
289 //
290 bool CEE::TransformRegion(BasicBlock *BB, std::set<BasicBlock*> &VisitedBlocks){
291   // Prevent infinite recursion...
292   if (VisitedBlocks.count(BB)) return false;
293   VisitedBlocks.insert(BB);
294
295   // Get the computed region information for this block...
296   RegionInfo &RI = getRegionInfo(BB);
297
298   // Compute the replacement information for this block...
299   ComputeReplacements(RI);
300
301   // If debugging, print computed region information...
302   DEBUG(RI.print(std::cerr));
303
304   // Simplify the contents of this block...
305   bool Changed = SimplifyBasicBlock(*BB, RI);
306
307   // Get the terminator of this basic block...
308   TerminatorInst *TI = BB->getTerminator();
309
310   // If this is a conditional branch, make sure that there is a branch target
311   // for each successor that can hold any information gleaned from the branch,
312   // by breaking any critical edges that may be laying about.
313   //
314   if (TI->getNumSuccessors() > 1) {
315     // If any of the successors has multiple incoming branches, add a new dummy
316     // destination branch that only contains an unconditional branch to the real
317     // target.
318     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
319       BasicBlock *Succ = TI->getSuccessor(i);
320       // If there is more than one predecessor of the destination block, break
321       // this critical edge by inserting a new block.  This updates dominatorset
322       // and dominatortree information.
323       //
324       if (isCriticalEdge(TI, i))
325         SplitCriticalEdge(TI, i, this);
326     }
327   }
328
329   // Loop over all of the blocks that this block is the immediate dominator for.
330   // Because all information known in this region is also known in all of the
331   // blocks that are dominated by this one, we can safely propogate the
332   // information down now.
333   //
334   DominatorTree::Node *BBN = (*DT)[BB];
335   for (unsigned i = 0, e = BBN->getChildren().size(); i != e; ++i) {
336     BasicBlock *Dominated = BBN->getChildren()[i]->getNode();
337     assert(RegionInfoMap.find(Dominated) == RegionInfoMap.end() &&
338            "RegionInfo should be calculated in dominanace order!");
339     getRegionInfo(Dominated) = RI;
340   }
341
342   // Now that all of our successors have information if they deserve it,
343   // propogate any information our terminator instruction finds to our
344   // successors.
345   if (BranchInst *BI = dyn_cast<BranchInst>(TI))
346     if (BI->isConditional())
347       PropogateBranchInfo(BI);
348
349   // If this is a branch to a block outside our region that simply performs
350   // another conditional branch, one whose outcome is known inside of this
351   // region, then vector this outgoing edge directly to the known destination.
352   //
353   for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
354     while (BasicBlock *Dest = isCorrelatedBranchBlock(TI->getSuccessor(i), RI)){
355       // If there are any PHI nodes in the Dest BB, we must duplicate the entry
356       // in the PHI node for the old successor to now include an entry from the
357       // current basic block.
358       //
359       BasicBlock *OldSucc = TI->getSuccessor(i);
360
361       // Loop over all of the PHI nodes...
362       for (BasicBlock::iterator I = Dest->begin();
363            PHINode *PN = dyn_cast<PHINode>(&*I); ++I) {
364         // Find the entry in the PHI node for OldSucc, create a duplicate entry
365         // for BB now.
366         int BlockIndex = PN->getBasicBlockIndex(OldSucc);
367         assert(BlockIndex != -1 && "Block should have entry in PHI!");
368         PN->addIncoming(PN->getIncomingValue(BlockIndex), BB);
369       }
370
371       // Actually revector the branch now...
372       TI->setSuccessor(i, Dest);
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]->getNode(), VisitedBlocks);
380
381   return Changed;
382 }
383
384 // If this block is a simple block not in the current region, which contains
385 // only a conditional branch, we determine if the outcome of the branch can be
386 // determined from information inside of the region.  Instead of going to this
387 // block, we can instead go to the destination we know is the right target.
388 //
389 BasicBlock *CEE::isCorrelatedBranchBlock(BasicBlock *BB, RegionInfo &RI) {
390   // Check to see if we dominate the block. If so, this block will get the
391   // condition turned to a constant anyway.
392   //
393   //if (DS->dominates(RI.getEntryBlock(), BB))
394   // return 0;
395
396   // Check to see if this is a conditional branch...
397   if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
398     if (BI->isConditional()) {
399       // Make sure that the block is either empty, or only contains a setcc.
400       if (BB->size() == 1 || 
401           (BB->size() == 2 && &BB->front() == BI->getCondition() &&
402            BI->getCondition()->use_size() == 1))
403         if (SetCondInst *SCI = dyn_cast<SetCondInst>(BI->getCondition())) {
404           Relation::KnownResult Result = getSetCCResult(SCI, RI);
405         
406           if (Result == Relation::KnownTrue)
407             return BI->getSuccessor(0);
408           else if (Result == Relation::KnownFalse)
409             return BI->getSuccessor(1);
410         }
411     }
412   return 0;
413 }
414
415 // BuildRankMap - This method builds the rank map data structure which gives
416 // each instruction/value in the function a value based on how early it appears
417 // in the function.  We give constants and globals rank 0, arguments are
418 // numbered starting at one, and instructions are numbered in reverse post-order
419 // from where the arguments leave off.  This gives instructions in loops higher
420 // values than instructions not in loops.
421 //
422 void CEE::BuildRankMap(Function &F) {
423   unsigned Rank = 1;  // Skip rank zero.
424
425   // Number the arguments...
426   for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
427     RankMap[I] = Rank++;
428
429   // Number the instructions in reverse post order...
430   ReversePostOrderTraversal<Function*> RPOT(&F);
431   for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
432          E = RPOT.end(); I != E; ++I)
433     for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
434          BBI != E; ++BBI)
435       if (BBI->getType() != Type::VoidTy)
436         RankMap[BBI] = Rank++;
437 }
438
439
440 // PropogateBranchInfo - When this method is invoked, we need to propogate
441 // information derived from the branch condition into the true and false
442 // branches of BI.  Since we know that there aren't any critical edges in the
443 // flow graph, this can proceed unconditionally.
444 //
445 void CEE::PropogateBranchInfo(BranchInst *BI) {
446   assert(BI->isConditional() && "Must be a conditional branch!");
447   BasicBlock *BB = BI->getParent();
448   BasicBlock *TrueBB  = BI->getSuccessor(0);
449   BasicBlock *FalseBB = BI->getSuccessor(1);
450
451   // Propogate information into the true block...
452   //
453   PropogateEquality(BI->getCondition(), ConstantBool::True,
454                     getRegionInfo(TrueBB));
455   
456   // Propogate information into the false block...
457   //
458   PropogateEquality(BI->getCondition(), ConstantBool::False,
459                     getRegionInfo(FalseBB));
460 }
461
462
463 // PropogateEquality - If we discover that two values are equal to each other in
464 // a specified region, propogate this knowledge recursively.
465 //
466 void CEE::PropogateEquality(Value *Op0, Value *Op1, RegionInfo &RI) {
467   if (Op0 == Op1) return;  // Gee whiz. Are these really equal each other?
468
469   if (isa<Constant>(Op0))  // Make sure the constant is always Op1
470     std::swap(Op0, Op1);
471
472   // Make sure we don't already know these are equal, to avoid infinite loops...
473   ValueInfo &VI = RI.getValueInfo(Op0);
474
475   // Get information about the known relationship between Op0 & Op1
476   Relation &KnownRelation = VI.getRelation(Op1);
477
478   // If we already know they're equal, don't reprocess...
479   if (KnownRelation.getRelation() == Instruction::SetEQ)
480     return;
481
482   // If this is boolean, check to see if one of the operands is a constant.  If
483   // it's a constant, then see if the other one is one of a setcc instruction,
484   // an AND, OR, or XOR instruction.
485   //
486   if (ConstantBool *CB = dyn_cast<ConstantBool>(Op1)) {
487
488     if (Instruction *Inst = dyn_cast<Instruction>(Op0)) {
489       // If we know that this instruction is an AND instruction, and the result
490       // is true, this means that both operands to the OR are known to be true
491       // as well.
492       //
493       if (CB->getValue() && Inst->getOpcode() == Instruction::And) {
494         PropogateEquality(Inst->getOperand(0), CB, RI);
495         PropogateEquality(Inst->getOperand(1), CB, RI);
496       }
497       
498       // If we know that this instruction is an OR instruction, and the result
499       // is false, this means that both operands to the OR are know to be false
500       // as well.
501       //
502       if (!CB->getValue() && Inst->getOpcode() == Instruction::Or) {
503         PropogateEquality(Inst->getOperand(0), CB, RI);
504         PropogateEquality(Inst->getOperand(1), CB, RI);
505       }
506       
507       // If we know that this instruction is a NOT instruction, we know that the
508       // operand is known to be the inverse of whatever the current value is.
509       //
510       if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(Inst))
511         if (BinaryOperator::isNot(BOp))
512           PropogateEquality(BinaryOperator::getNotArgument(BOp),
513                             ConstantBool::get(!CB->getValue()), RI);
514
515       // If we know the value of a SetCC instruction, propogate the information
516       // about the relation into this region as well.
517       //
518       if (SetCondInst *SCI = dyn_cast<SetCondInst>(Inst)) {
519         if (CB->getValue()) {  // If we know the condition is true...
520           // Propogate info about the LHS to the RHS & RHS to LHS
521           PropogateRelation(SCI->getOpcode(), SCI->getOperand(0),
522                             SCI->getOperand(1), RI);
523           PropogateRelation(SCI->getSwappedCondition(),
524                             SCI->getOperand(1), SCI->getOperand(0), RI);
525
526         } else {               // If we know the condition is false...
527           // We know the opposite of the condition is true...
528           Instruction::BinaryOps C = SCI->getInverseCondition();
529           
530           PropogateRelation(C, SCI->getOperand(0), SCI->getOperand(1), RI);
531           PropogateRelation(SetCondInst::getSwappedCondition(C),
532                             SCI->getOperand(1), SCI->getOperand(0), RI);
533         }
534       }
535     }
536   }
537
538   // Propogate information about Op0 to Op1 & visa versa
539   PropogateRelation(Instruction::SetEQ, Op0, Op1, RI);
540   PropogateRelation(Instruction::SetEQ, Op1, Op0, RI);
541 }
542
543
544 // PropogateRelation - We know that the specified relation is true in all of the
545 // blocks in the specified region.  Propogate the information about Op0 and
546 // anything derived from it into this region.
547 //
548 void CEE::PropogateRelation(Instruction::BinaryOps Opcode, Value *Op0,
549                             Value *Op1, RegionInfo &RI) {
550   assert(Op0->getType() == Op1->getType() && "Equal types expected!");
551
552   // Constants are already pretty well understood.  We will apply information
553   // about the constant to Op1 in another call to PropogateRelation.
554   //
555   if (isa<Constant>(Op0)) return;
556
557   // Get the region information for this block to update...
558   ValueInfo &VI = RI.getValueInfo(Op0);
559
560   // Get information about the known relationship between Op0 & Op1
561   Relation &Op1R = VI.getRelation(Op1);
562
563   // Quick bailout for common case if we are reprocessing an instruction...
564   if (Op1R.getRelation() == Opcode)
565     return;
566
567   // If we already have information that contradicts the current information we
568   // are propogating, ignore this info.  Something bad must have happened!
569   //
570   if (Op1R.contradicts(Opcode, VI)) {
571     Op1R.contradicts(Opcode, VI);
572     std::cerr << "Contradiction found for opcode: "
573               << Instruction::getOpcodeName(Opcode) << "\n";
574     Op1R.print(std::cerr);
575     return;
576   }
577
578   // If the information propogted is new, then we want process the uses of this
579   // instruction to propogate the information down to them.
580   //
581   if (Op1R.incorporate(Opcode, VI))
582     UpdateUsersOfValue(Op0, RI);
583 }
584
585
586 // UpdateUsersOfValue - The information about V in this region has been updated.
587 // Propogate this to all consumers of the value.
588 //
589 void CEE::UpdateUsersOfValue(Value *V, RegionInfo &RI) {
590   for (Value::use_iterator I = V->use_begin(), E = V->use_end();
591        I != E; ++I)
592     if (Instruction *Inst = dyn_cast<Instruction>(*I)) {
593       // If this is an instruction using a value that we know something about,
594       // try to propogate information to the value produced by the
595       // instruction.  We can only do this if it is an instruction we can
596       // propogate information for (a setcc for example), and we only WANT to
597       // do this if the instruction dominates this region.
598       //
599       // If the instruction doesn't dominate this region, then it cannot be
600       // used in this region and we don't care about it.  If the instruction
601       // is IN this region, then we will simplify the instruction before we
602       // get to uses of it anyway, so there is no reason to bother with it
603       // here.  This check is also effectively checking to make sure that Inst
604       // is in the same function as our region (in case V is a global f.e.).
605       //
606       if (DS->properlyDominates(Inst->getParent(), RI.getEntryBlock()))
607         IncorporateInstruction(Inst, RI);
608     }
609 }
610
611 // IncorporateInstruction - We just updated the information about one of the
612 // operands to the specified instruction.  Update the information about the
613 // value produced by this instruction
614 //
615 void CEE::IncorporateInstruction(Instruction *Inst, RegionInfo &RI) {
616   if (SetCondInst *SCI = dyn_cast<SetCondInst>(Inst)) {
617     // See if we can figure out a result for this instruction...
618     Relation::KnownResult Result = getSetCCResult(SCI, RI);
619     if (Result != Relation::Unknown) {
620       PropogateEquality(SCI, Result ? ConstantBool::True : ConstantBool::False,
621                         RI);
622     }
623   }
624 }
625
626
627 // ComputeReplacements - Some values are known to be equal to other values in a
628 // region.  For example if there is a comparison of equality between a variable
629 // X and a constant C, we can replace all uses of X with C in the region we are
630 // interested in.  We generalize this replacement to replace variables with
631 // other variables if they are equal and there is a variable with lower rank
632 // than the current one.  This offers a cannonicalizing property that exposes
633 // more redundancies for later transformations to take advantage of.
634 //
635 void CEE::ComputeReplacements(RegionInfo &RI) {
636   // Loop over all of the values in the region info map...
637   for (RegionInfo::iterator I = RI.begin(), E = RI.end(); I != E; ++I) {
638     ValueInfo &VI = I->second;
639
640     // If we know that this value is a particular constant, set Replacement to
641     // the constant...
642     Value *Replacement = VI.getBounds().getSingleElement();
643
644     // If this value is not known to be some constant, figure out the lowest
645     // rank value that it is known to be equal to (if anything).
646     //
647     if (Replacement == 0) {
648       // Find out if there are any equality relationships with values of lower
649       // rank than VI itself...
650       unsigned MinRank = getRank(I->first);
651
652       // Loop over the relationships known about Op0.
653       const std::vector<Relation> &Relationships = VI.getRelationships();
654       for (unsigned i = 0, e = Relationships.size(); i != e; ++i)
655         if (Relationships[i].getRelation() == Instruction::SetEQ) {
656           unsigned R = getRank(Relationships[i].getValue());
657           if (R < MinRank) {
658             MinRank = R;
659             Replacement = Relationships[i].getValue();
660           }
661         }
662     }
663
664     // If we found something to replace this value with, keep track of it.
665     if (Replacement)
666       VI.setReplacement(Replacement);
667   }
668 }
669
670 // SimplifyBasicBlock - Given information about values in region RI, simplify
671 // the instructions in the specified basic block.
672 //
673 bool CEE::SimplifyBasicBlock(BasicBlock &BB, const RegionInfo &RI) {
674   bool Changed = false;
675   for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ) {
676     Instruction *Inst = &*I++;
677
678     // Convert instruction arguments to canonical forms...
679     Changed |= SimplifyInstruction(Inst, RI);
680
681     if (SetCondInst *SCI = dyn_cast<SetCondInst>(Inst)) {
682       // Try to simplify a setcc instruction based on inherited information
683       Relation::KnownResult Result = getSetCCResult(SCI, RI);
684       if (Result != Relation::Unknown) {
685         DEBUG(std::cerr << "Replacing setcc with " << Result
686                         << " constant: " << SCI);
687
688         SCI->replaceAllUsesWith(ConstantBool::get((bool)Result));
689         // The instruction is now dead, remove it from the program.
690         SCI->getParent()->getInstList().erase(SCI);
691         ++NumSetCCRemoved;
692         Changed = true;
693       }
694     }
695   }
696
697   return Changed;
698 }
699
700 // SimplifyInstruction - Inspect the operands of the instruction, converting
701 // them to their cannonical form if possible.  This takes care of, for example,
702 // replacing a value 'X' with a constant 'C' if the instruction in question is
703 // dominated by a true seteq 'X', 'C'.
704 //
705 bool CEE::SimplifyInstruction(Instruction *I, const RegionInfo &RI) {
706   bool Changed = false;
707
708   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
709     if (const ValueInfo *VI = RI.requestValueInfo(I->getOperand(i)))
710       if (Value *Repl = VI->getReplacement()) {
711         // If we know if a replacement with lower rank than Op0, make the
712         // replacement now.
713         DEBUG(std::cerr << "In Inst: " << I << "  Replacing operand #" << i
714                         << " with " << Repl << "\n");
715         I->setOperand(i, Repl);
716         Changed = true;
717         ++NumOperandsCann;
718       }
719
720   return Changed;
721 }
722
723
724 // SimplifySetCC - Try to simplify a setcc instruction based on information
725 // inherited from a dominating setcc instruction.  V is one of the operands to
726 // the setcc instruction, and VI is the set of information known about it.  We
727 // take two cases into consideration here.  If the comparison is against a
728 // constant value, we can use the constant range to see if the comparison is
729 // possible to succeed.  If it is not a comparison against a constant, we check
730 // to see if there is a known relationship between the two values.  If so, we
731 // may be able to eliminate the check.
732 //
733 Relation::KnownResult CEE::getSetCCResult(SetCondInst *SCI,
734                                           const RegionInfo &RI) {
735   Value *Op0 = SCI->getOperand(0), *Op1 = SCI->getOperand(1);
736   Instruction::BinaryOps Opcode = SCI->getOpcode();
737   
738   if (isa<Constant>(Op0)) {
739     if (isa<Constant>(Op1)) {
740       if (Constant *Result = ConstantFoldInstruction(SCI)) {
741         // Wow, this is easy, directly eliminate the SetCondInst.
742         DEBUG(std::cerr << "Replacing setcc with constant fold: " << SCI);
743         return cast<ConstantBool>(Result)->getValue()
744           ? Relation::KnownTrue : Relation::KnownFalse;
745       }
746     } else {
747       // We want to swap this instruction so that operand #0 is the constant.
748       std::swap(Op0, Op1);
749       Opcode = SCI->getSwappedCondition();
750     }
751   }
752
753   // Try to figure out what the result of this comparison will be...
754   Relation::KnownResult Result = Relation::Unknown;
755
756   // We have to know something about the relationship to prove anything...
757   if (const ValueInfo *Op0VI = RI.requestValueInfo(Op0)) {
758
759     // At this point, we know that if we have a constant argument that it is in
760     // Op1.  Check to see if we know anything about comparing value with a
761     // constant, and if we can use this info to fold the setcc.
762     //
763     if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(Op1)) {
764       // Check to see if we already know the result of this comparison...
765       ConstantRange R = ConstantRange(Opcode, C);
766       ConstantRange Int = R.intersectWith(Op0VI->getBounds());
767
768       // If the intersection of the two ranges is empty, then the condition
769       // could never be true!
770       // 
771       if (Int.isEmptySet()) {
772         Result = Relation::KnownFalse;
773
774       // Otherwise, if VI.getBounds() (the possible values) is a subset of R
775       // (the allowed values) then we know that the condition must always be
776       // true!
777       //
778       } else if (Int == Op0VI->getBounds()) {
779         Result = Relation::KnownTrue;
780       }
781     } else {
782       // If we are here, we know that the second argument is not a constant
783       // integral.  See if we know anything about Op0 & Op1 that allows us to
784       // fold this anyway.
785       //
786       // Do we have value information about Op0 and a relation to Op1?
787       if (const Relation *Op2R = Op0VI->requestRelation(Op1))
788         Result = Op2R->getImpliedResult(Opcode);
789     }
790   }
791   return Result;
792 }
793
794 //===----------------------------------------------------------------------===//
795 //  Relation Implementation
796 //===----------------------------------------------------------------------===//
797
798 // CheckCondition - Return true if the specified condition is false.  Bound may
799 // be null.
800 static bool CheckCondition(Constant *Bound, Constant *C,
801                            Instruction::BinaryOps BO) {
802   assert(C != 0 && "C is not specified!");
803   if (Bound == 0) return false;
804
805   ConstantBool *Val;
806   switch (BO) {
807   default: assert(0 && "Unknown Condition code!");
808   case Instruction::SetEQ: Val = *Bound == *C; break;
809   case Instruction::SetNE: Val = *Bound != *C; break;
810   case Instruction::SetLT: Val = *Bound <  *C; break;
811   case Instruction::SetGT: Val = *Bound >  *C; break;
812   case Instruction::SetLE: Val = *Bound <= *C; break;
813   case Instruction::SetGE: Val = *Bound >= *C; break;
814   }
815
816   // ConstantHandling code may not succeed in the comparison...
817   if (Val == 0) return false;
818   return !Val->getValue();  // Return true if the condition is false...
819 }
820
821 // contradicts - Return true if the relationship specified by the operand
822 // contradicts already known information.
823 //
824 bool Relation::contradicts(Instruction::BinaryOps Op,
825                            const ValueInfo &VI) const {
826   assert (Op != Instruction::Add && "Invalid relation argument!");
827
828   // If this is a relationship with a constant, make sure that this relationship
829   // does not contradict properties known about the bounds of the constant.
830   //
831   if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(Val))
832     if (ConstantRange(Op, C).intersectWith(VI.getBounds()).isEmptySet())
833       return true;
834
835   switch (Rel) {
836   default: assert(0 && "Unknown Relationship code!");
837   case Instruction::Add: return false;  // Nothing known, nothing contradicts
838   case Instruction::SetEQ:
839     return Op == Instruction::SetLT || Op == Instruction::SetGT ||
840            Op == Instruction::SetNE;
841   case Instruction::SetNE: return Op == Instruction::SetEQ;
842   case Instruction::SetLE: return Op == Instruction::SetGT;
843   case Instruction::SetGE: return Op == Instruction::SetLT;
844   case Instruction::SetLT:
845     return Op == Instruction::SetEQ || Op == Instruction::SetGT ||
846            Op == Instruction::SetGE;
847   case Instruction::SetGT:
848     return Op == Instruction::SetEQ || Op == Instruction::SetLT ||
849            Op == Instruction::SetLE;
850   }
851 }
852
853 // incorporate - Incorporate information in the argument into this relation
854 // entry.  This assumes that the information doesn't contradict itself.  If any
855 // new information is gained, true is returned, otherwise false is returned to
856 // indicate that nothing was updated.
857 //
858 bool Relation::incorporate(Instruction::BinaryOps Op, ValueInfo &VI) {
859   assert(!contradicts(Op, VI) &&
860          "Cannot incorporate contradictory information!");
861
862   // If this is a relationship with a constant, make sure that we update the
863   // range that is possible for the value to have...
864   //
865   if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(Val))
866     VI.getBounds() = ConstantRange(Op, C).intersectWith(VI.getBounds());
867
868   switch (Rel) {
869   default: assert(0 && "Unknown prior value!");
870   case Instruction::Add:   Rel = Op; return true;
871   case Instruction::SetEQ: return false;  // Nothing is more precise
872   case Instruction::SetNE: return false;  // Nothing is more precise
873   case Instruction::SetLT: return false;  // Nothing is more precise
874   case Instruction::SetGT: return false;  // Nothing is more precise
875   case Instruction::SetLE:
876     if (Op == Instruction::SetEQ || Op == Instruction::SetLT) {
877       Rel = Op;
878       return true;
879     } else if (Op == Instruction::SetNE) {
880       Rel = Instruction::SetLT;
881       return true;
882     }
883     return false;
884   case Instruction::SetGE: return Op == Instruction::SetLT;
885     if (Op == Instruction::SetEQ || Op == Instruction::SetGT) {
886       Rel = Op;
887       return true;
888     } else if (Op == Instruction::SetNE) {
889       Rel = Instruction::SetGT;
890       return true;
891     }
892     return false;
893   }
894 }
895
896 // getImpliedResult - If this relationship between two values implies that
897 // the specified relationship is true or false, return that.  If we cannot
898 // determine the result required, return Unknown.
899 //
900 Relation::KnownResult
901 Relation::getImpliedResult(Instruction::BinaryOps Op) const {
902   if (Rel == Op) return KnownTrue;
903   if (Rel == SetCondInst::getInverseCondition(Op)) return KnownFalse;
904
905   switch (Rel) {
906   default: assert(0 && "Unknown prior value!");
907   case Instruction::SetEQ:
908     if (Op == Instruction::SetLE || Op == Instruction::SetGE) return KnownTrue;
909     if (Op == Instruction::SetLT || Op == Instruction::SetGT) return KnownFalse;
910     break;
911   case Instruction::SetLT:
912     if (Op == Instruction::SetNE || Op == Instruction::SetLE) return KnownTrue;
913     if (Op == Instruction::SetEQ) return KnownFalse;
914     break;
915   case Instruction::SetGT:
916     if (Op == Instruction::SetNE || Op == Instruction::SetGE) return KnownTrue;
917     if (Op == Instruction::SetEQ) return KnownFalse;
918     break;
919   case Instruction::SetNE:
920   case Instruction::SetLE:
921   case Instruction::SetGE:
922   case Instruction::Add:
923     break;
924   }
925   return Unknown;
926 }
927
928
929 //===----------------------------------------------------------------------===//
930 // Printing Support...
931 //===----------------------------------------------------------------------===//
932
933 // print - Implement the standard print form to print out analysis information.
934 void CEE::print(std::ostream &O, const Module *M) const {
935   O << "\nPrinting Correlated Expression Info:\n";
936   for (std::map<BasicBlock*, RegionInfo>::const_iterator I = 
937          RegionInfoMap.begin(), E = RegionInfoMap.end(); I != E; ++I)
938     I->second.print(O);
939 }
940
941 // print - Output information about this region...
942 void RegionInfo::print(std::ostream &OS) const {
943   if (ValueMap.empty()) return;
944
945   OS << " RegionInfo for basic block: " << BB->getName() << "\n";
946   for (std::map<Value*, ValueInfo>::const_iterator
947          I = ValueMap.begin(), E = ValueMap.end(); I != E; ++I)
948     I->second.print(OS, I->first);
949   OS << "\n";
950 }
951
952 // print - Output information about this value relation...
953 void ValueInfo::print(std::ostream &OS, Value *V) const {
954   if (Relationships.empty()) return;
955
956   if (V) {
957     OS << "  ValueInfo for: ";
958     WriteAsOperand(OS, V);
959   }
960   OS << "\n    Bounds = " << Bounds << "\n";
961   if (Replacement) {
962     OS << "    Replacement = ";
963     WriteAsOperand(OS, Replacement);
964     OS << "\n";
965   }
966   for (unsigned i = 0, e = Relationships.size(); i != e; ++i)
967     Relationships[i].print(OS);
968 }
969
970 // print - Output this relation to the specified stream
971 void Relation::print(std::ostream &OS) const {
972   OS << "    is ";
973   switch (Rel) {
974   default:           OS << "*UNKNOWN*"; break;
975   case Instruction::SetEQ: OS << "== "; break;
976   case Instruction::SetNE: OS << "!= "; break;
977   case Instruction::SetLT: OS << "< "; break;
978   case Instruction::SetGT: OS << "> "; break;
979   case Instruction::SetLE: OS << "<= "; break;
980   case Instruction::SetGE: OS << ">= "; break;
981   }
982
983   WriteAsOperand(OS, Val);
984   OS << "\n";
985 }
986
987 void Relation::dump() const { print(std::cerr); }
988 void ValueInfo::dump() const { print(std::cerr, 0); }