bug 122:
[oota-llvm.git] / lib / Transforms / Utils / SimplifyCFG.cpp
1 //===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===//
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 // Peephole optimize the CFG.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "simplifycfg"
15 #include "llvm/Transforms/Utils/Local.h"
16 #include "llvm/Constants.h"
17 #include "llvm/Instructions.h"
18 #include "llvm/Type.h"
19 #include "llvm/Support/CFG.h"
20 #include "Support/Debug.h"
21 #include <algorithm>
22 #include <functional>
23 #include <set>
24 #include <iostream>
25
26 using namespace llvm;
27
28 // PropagatePredecessorsForPHIs - This gets "Succ" ready to have the
29 // predecessors from "BB".  This is a little tricky because "Succ" has PHI
30 // nodes, which need to have extra slots added to them to hold the merge edges
31 // from BB's predecessors, and BB itself might have had PHI nodes in it.  This
32 // function returns true (failure) if the Succ BB already has a predecessor that
33 // is a predecessor of BB and incoming PHI arguments would not be discernible.
34 //
35 // Assumption: Succ is the single successor for BB.
36 //
37 static bool PropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
38   assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
39
40   if (!isa<PHINode>(Succ->front()))
41     return false;  // We can make the transformation, no problem.
42
43   // If there is more than one predecessor, and there are PHI nodes in
44   // the successor, then we need to add incoming edges for the PHI nodes
45   //
46   const std::vector<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB));
47
48   // Check to see if one of the predecessors of BB is already a predecessor of
49   // Succ.  If so, we cannot do the transformation if there are any PHI nodes
50   // with incompatible values coming in from the two edges!
51   //
52   for (pred_iterator PI = pred_begin(Succ), PE = pred_end(Succ); PI != PE; ++PI)
53     if (find(BBPreds.begin(), BBPreds.end(), *PI) != BBPreds.end()) {
54       // Loop over all of the PHI nodes checking to see if there are
55       // incompatible values coming in.
56       for (BasicBlock::iterator I = Succ->begin();
57            PHINode *PN = dyn_cast<PHINode>(I); ++I) {
58         // Loop up the entries in the PHI node for BB and for *PI if the values
59         // coming in are non-equal, we cannot merge these two blocks (instead we
60         // should insert a conditional move or something, then merge the
61         // blocks).
62         int Idx1 = PN->getBasicBlockIndex(BB);
63         int Idx2 = PN->getBasicBlockIndex(*PI);
64         assert(Idx1 != -1 && Idx2 != -1 &&
65                "Didn't have entries for my predecessors??");
66         if (PN->getIncomingValue(Idx1) != PN->getIncomingValue(Idx2))
67           return true;  // Values are not equal...
68       }
69     }
70
71   // Loop over all of the PHI nodes in the successor BB.
72   for (BasicBlock::iterator I = Succ->begin();
73        PHINode *PN = dyn_cast<PHINode>(I); ++I) {
74     Value *OldVal = PN->removeIncomingValue(BB, false);
75     assert(OldVal && "No entry in PHI for Pred BB!");
76
77     // If this incoming value is one of the PHI nodes in BB, the new entries in
78     // the PHI node are the entries from the old PHI.
79     if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
80       PHINode *OldValPN = cast<PHINode>(OldVal);
81       for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i)
82         PN->addIncoming(OldValPN->getIncomingValue(i),
83                         OldValPN->getIncomingBlock(i));
84     } else {
85       for (std::vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(), 
86              End = BBPreds.end(); PredI != End; ++PredI) {
87         // Add an incoming value for each of the new incoming values...
88         PN->addIncoming(OldVal, *PredI);
89       }
90     }
91   }
92   return false;
93 }
94
95 /// GetIfCondition - Given a basic block (BB) with two predecessors (and
96 /// presumably PHI nodes in it), check to see if the merge at this block is due
97 /// to an "if condition".  If so, return the boolean condition that determines
98 /// which entry into BB will be taken.  Also, return by references the block
99 /// that will be entered from if the condition is true, and the block that will
100 /// be entered if the condition is false.
101 /// 
102 ///
103 static Value *GetIfCondition(BasicBlock *BB,
104                              BasicBlock *&IfTrue, BasicBlock *&IfFalse) {
105   assert(std::distance(pred_begin(BB), pred_end(BB)) == 2 &&
106          "Function can only handle blocks with 2 predecessors!");
107   BasicBlock *Pred1 = *pred_begin(BB);
108   BasicBlock *Pred2 = *++pred_begin(BB);
109
110   // We can only handle branches.  Other control flow will be lowered to
111   // branches if possible anyway.
112   if (!isa<BranchInst>(Pred1->getTerminator()) ||
113       !isa<BranchInst>(Pred2->getTerminator()))
114     return 0;
115   BranchInst *Pred1Br = cast<BranchInst>(Pred1->getTerminator());
116   BranchInst *Pred2Br = cast<BranchInst>(Pred2->getTerminator());
117
118   // Eliminate code duplication by ensuring that Pred1Br is conditional if
119   // either are.
120   if (Pred2Br->isConditional()) {
121     // If both branches are conditional, we don't have an "if statement".  In
122     // reality, we could transform this case, but since the condition will be
123     // required anyway, we stand no chance of eliminating it, so the xform is
124     // probably not profitable.
125     if (Pred1Br->isConditional())
126       return 0;
127
128     std::swap(Pred1, Pred2);
129     std::swap(Pred1Br, Pred2Br);
130   }
131
132   if (Pred1Br->isConditional()) {
133     // If we found a conditional branch predecessor, make sure that it branches
134     // to BB and Pred2Br.  If it doesn't, this isn't an "if statement".
135     if (Pred1Br->getSuccessor(0) == BB &&
136         Pred1Br->getSuccessor(1) == Pred2) {
137       IfTrue = Pred1;
138       IfFalse = Pred2;
139     } else if (Pred1Br->getSuccessor(0) == Pred2 &&
140                Pred1Br->getSuccessor(1) == BB) {
141       IfTrue = Pred2;
142       IfFalse = Pred1;
143     } else {
144       // We know that one arm of the conditional goes to BB, so the other must
145       // go somewhere unrelated, and this must not be an "if statement".
146       return 0;
147     }
148
149     // The only thing we have to watch out for here is to make sure that Pred2
150     // doesn't have incoming edges from other blocks.  If it does, the condition
151     // doesn't dominate BB.
152     if (++pred_begin(Pred2) != pred_end(Pred2))
153       return 0;
154
155     return Pred1Br->getCondition();
156   }
157
158   // Ok, if we got here, both predecessors end with an unconditional branch to
159   // BB.  Don't panic!  If both blocks only have a single (identical)
160   // predecessor, and THAT is a conditional branch, then we're all ok!
161   if (pred_begin(Pred1) == pred_end(Pred1) ||
162       ++pred_begin(Pred1) != pred_end(Pred1) ||
163       pred_begin(Pred2) == pred_end(Pred2) ||
164       ++pred_begin(Pred2) != pred_end(Pred2) ||
165       *pred_begin(Pred1) != *pred_begin(Pred2))
166     return 0;
167
168   // Otherwise, if this is a conditional branch, then we can use it!
169   BasicBlock *CommonPred = *pred_begin(Pred1);
170   if (BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator())) {
171     assert(BI->isConditional() && "Two successors but not conditional?");
172     if (BI->getSuccessor(0) == Pred1) {
173       IfTrue = Pred1;
174       IfFalse = Pred2;
175     } else {
176       IfTrue = Pred2;
177       IfFalse = Pred1;
178     }
179     return BI->getCondition();
180   }
181   return 0;
182 }
183
184
185 // If we have a merge point of an "if condition" as accepted above, return true
186 // if the specified value dominates the block.  We don't handle the true
187 // generality of domination here, just a special case which works well enough
188 // for us.
189 static bool DominatesMergePoint(Value *V, BasicBlock *BB, bool AllowAggressive){
190   Instruction *I = dyn_cast<Instruction>(V);
191   if (!I) return true;    // Non-instructions all dominate instructions.
192   BasicBlock *PBB = I->getParent();
193
194   // We don't want to allow wierd loops that might have the "if condition" in
195   // the bottom of this block.
196   if (PBB == BB) return false;
197
198   // If this instruction is defined in a block that contains an unconditional
199   // branch to BB, then it must be in the 'conditional' part of the "if
200   // statement".
201   if (BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator()))
202     if (BI->isUnconditional() && BI->getSuccessor(0) == BB) {
203       if (!AllowAggressive) return false;
204       // Okay, it looks like the instruction IS in the "condition".  Check to
205       // see if its a cheap instruction to unconditionally compute, and if it
206       // only uses stuff defined outside of the condition.  If so, hoist it out.
207       switch (I->getOpcode()) {
208       default: return false;  // Cannot hoist this out safely.
209       case Instruction::Load:
210         // We can hoist loads that are non-volatile and obviously cannot trap.
211         if (cast<LoadInst>(I)->isVolatile())
212           return false;
213         if (!isa<AllocaInst>(I->getOperand(0)) &&
214             !isa<Constant>(I->getOperand(0)))
215           return false;
216
217         // Finally, we have to check to make sure there are no instructions
218         // before the load in its basic block, as we are going to hoist the loop
219         // out to its predecessor.
220         if (PBB->begin() != BasicBlock::iterator(I))
221           return false;
222         break;
223       case Instruction::Add:
224       case Instruction::Sub:
225       case Instruction::And:
226       case Instruction::Or:
227       case Instruction::Xor:
228       case Instruction::Shl:
229       case Instruction::Shr:
230         break;   // These are all cheap and non-trapping instructions.
231       }
232       
233       // Okay, we can only really hoist these out if their operands are not
234       // defined in the conditional region.
235       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
236         if (!DominatesMergePoint(I->getOperand(i), BB, false))
237           return false;
238       // Okay, it's safe to do this!
239     }
240
241   return true;
242 }
243
244 // GatherConstantSetEQs - Given a potentially 'or'd together collection of seteq
245 // instructions that compare a value against a constant, return the value being
246 // compared, and stick the constant into the Values vector.
247 static Value *GatherConstantSetEQs(Value *V, std::vector<ConstantInt*> &Values){
248   if (Instruction *Inst = dyn_cast<Instruction>(V))
249     if (Inst->getOpcode() == Instruction::SetEQ) {
250       if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(1))) {
251         Values.push_back(C);
252         return Inst->getOperand(0);
253       } else if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
254         Values.push_back(C);
255         return Inst->getOperand(1);
256       }
257     } else if (Inst->getOpcode() == Instruction::Or) {
258       if (Value *LHS = GatherConstantSetEQs(Inst->getOperand(0), Values))
259         if (Value *RHS = GatherConstantSetEQs(Inst->getOperand(1), Values))
260           if (LHS == RHS)
261             return LHS;
262     }
263   return 0;
264 }
265
266 // GatherConstantSetNEs - Given a potentially 'and'd together collection of
267 // setne instructions that compare a value against a constant, return the value
268 // being compared, and stick the constant into the Values vector.
269 static Value *GatherConstantSetNEs(Value *V, std::vector<ConstantInt*> &Values){
270   if (Instruction *Inst = dyn_cast<Instruction>(V))
271     if (Inst->getOpcode() == Instruction::SetNE) {
272       if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(1))) {
273         Values.push_back(C);
274         return Inst->getOperand(0);
275       } else if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
276         Values.push_back(C);
277         return Inst->getOperand(1);
278       }
279     } else if (Inst->getOpcode() == Instruction::Cast) {
280       // Cast of X to bool is really a comparison against zero.
281       assert(Inst->getType() == Type::BoolTy && "Can only handle bool values!");
282       Values.push_back(ConstantInt::get(Inst->getOperand(0)->getType(), 0));
283       return Inst->getOperand(0);
284     } else if (Inst->getOpcode() == Instruction::And) {
285       if (Value *LHS = GatherConstantSetNEs(Inst->getOperand(0), Values))
286         if (Value *RHS = GatherConstantSetNEs(Inst->getOperand(1), Values))
287           if (LHS == RHS)
288             return LHS;
289     }
290   return 0;
291 }
292
293
294
295 /// GatherValueComparisons - If the specified Cond is an 'and' or 'or' of a
296 /// bunch of comparisons of one value against constants, return the value and
297 /// the constants being compared.
298 static bool GatherValueComparisons(Instruction *Cond, Value *&CompVal,
299                                    std::vector<ConstantInt*> &Values) {
300   if (Cond->getOpcode() == Instruction::Or) {
301     CompVal = GatherConstantSetEQs(Cond, Values);
302
303     // Return true to indicate that the condition is true if the CompVal is
304     // equal to one of the constants.
305     return true;
306   } else if (Cond->getOpcode() == Instruction::And) {
307     CompVal = GatherConstantSetNEs(Cond, Values);
308         
309     // Return false to indicate that the condition is false if the CompVal is
310     // equal to one of the constants.
311     return false;
312   }
313   return false;
314 }
315
316 /// ErasePossiblyDeadInstructionTree - If the specified instruction is dead and
317 /// has no side effects, nuke it.  If it uses any instructions that become dead
318 /// because the instruction is now gone, nuke them too.
319 static void ErasePossiblyDeadInstructionTree(Instruction *I) {
320   if (isInstructionTriviallyDead(I)) {
321     std::vector<Value*> Operands(I->op_begin(), I->op_end());
322     I->getParent()->getInstList().erase(I);
323     for (unsigned i = 0, e = Operands.size(); i != e; ++i)
324       if (Instruction *OpI = dyn_cast<Instruction>(Operands[i]))
325         ErasePossiblyDeadInstructionTree(OpI);
326   }
327 }
328
329 /// SafeToMergeTerminators - Return true if it is safe to merge these two
330 /// terminator instructions together.
331 ///
332 static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
333   if (SI1 == SI2) return false;  // Can't merge with self!
334
335   // It is not safe to merge these two switch instructions if they have a common
336   // successor, and if that successor has a PHI node, and if *that* PHI node has
337   // conflicting incoming values from the two switch blocks.
338   BasicBlock *SI1BB = SI1->getParent();
339   BasicBlock *SI2BB = SI2->getParent();
340   std::set<BasicBlock*> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
341
342   for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
343     if (SI1Succs.count(*I))
344       for (BasicBlock::iterator BBI = (*I)->begin();
345            PHINode *PN = dyn_cast<PHINode>(BBI); ++BBI)
346         if (PN->getIncomingValueForBlock(SI1BB) !=
347             PN->getIncomingValueForBlock(SI2BB))
348           return false;
349         
350   return true;
351 }
352
353 /// AddPredecessorToBlock - Update PHI nodes in Succ to indicate that there will
354 /// now be entries in it from the 'NewPred' block.  The values that will be
355 /// flowing into the PHI nodes will be the same as those coming in from
356 /// ExistPred, an existing predecessor of Succ.
357 static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
358                                   BasicBlock *ExistPred) {
359   assert(std::find(succ_begin(ExistPred), succ_end(ExistPred), Succ) !=
360          succ_end(ExistPred) && "ExistPred is not a predecessor of Succ!");
361   if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
362
363   for (BasicBlock::iterator I = Succ->begin();
364        PHINode *PN = dyn_cast<PHINode>(I); ++I) {
365     Value *V = PN->getIncomingValueForBlock(ExistPred);
366     PN->addIncoming(V, NewPred);
367   }
368 }
369
370 // isValueEqualityComparison - Return true if the specified terminator checks to
371 // see if a value is equal to constant integer value.
372 static Value *isValueEqualityComparison(TerminatorInst *TI) {
373   if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
374     // Do not permit merging of large switch instructions into their
375     // predecessors unless there is only one predecessor.
376     if (SI->getNumSuccessors() * std::distance(pred_begin(SI->getParent()),
377                                                pred_end(SI->getParent())) > 128)
378       return 0;
379
380     return SI->getCondition();
381   }
382   if (BranchInst *BI = dyn_cast<BranchInst>(TI))
383     if (BI->isConditional() && BI->getCondition()->hasOneUse())
384       if (SetCondInst *SCI = dyn_cast<SetCondInst>(BI->getCondition()))
385         if ((SCI->getOpcode() == Instruction::SetEQ ||
386              SCI->getOpcode() == Instruction::SetNE) && 
387             isa<ConstantInt>(SCI->getOperand(1)))
388           return SCI->getOperand(0);
389   return 0;
390 }
391
392 // Given a value comparison instruction, decode all of the 'cases' that it
393 // represents and return the 'default' block.
394 static BasicBlock *
395 GetValueEqualityComparisonCases(TerminatorInst *TI, 
396                                 std::vector<std::pair<ConstantInt*,
397                                                       BasicBlock*> > &Cases) {
398   if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
399     Cases.reserve(SI->getNumCases());
400     for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
401       Cases.push_back(std::make_pair(cast<ConstantInt>(SI->getCaseValue(i)),
402                                      SI->getSuccessor(i)));
403     return SI->getDefaultDest();
404   }
405
406   BranchInst *BI = cast<BranchInst>(TI);
407   SetCondInst *SCI = cast<SetCondInst>(BI->getCondition());
408   Cases.push_back(std::make_pair(cast<ConstantInt>(SCI->getOperand(1)),
409                                  BI->getSuccessor(SCI->getOpcode() ==
410                                                         Instruction::SetNE)));
411   return BI->getSuccessor(SCI->getOpcode() == Instruction::SetEQ);
412 }
413
414
415 // FoldValueComparisonIntoPredecessors - The specified terminator is a value
416 // equality comparison instruction (either a switch or a branch on "X == c").
417 // See if any of the predecessors of the terminator block are value comparisons
418 // on the same value.  If so, and if safe to do so, fold them together.
419 static bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI) {
420   BasicBlock *BB = TI->getParent();
421   Value *CV = isValueEqualityComparison(TI);  // CondVal
422   assert(CV && "Not a comparison?");
423   bool Changed = false;
424
425   std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
426   while (!Preds.empty()) {
427     BasicBlock *Pred = Preds.back();
428     Preds.pop_back();
429     
430     // See if the predecessor is a comparison with the same value.
431     TerminatorInst *PTI = Pred->getTerminator();
432     Value *PCV = isValueEqualityComparison(PTI);  // PredCondVal
433
434     if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
435       // Figure out which 'cases' to copy from SI to PSI.
436       std::vector<std::pair<ConstantInt*, BasicBlock*> > BBCases;
437       BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
438
439       std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases;
440       BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
441
442       // Based on whether the default edge from PTI goes to BB or not, fill in
443       // PredCases and PredDefault with the new switch cases we would like to
444       // build.
445       std::vector<BasicBlock*> NewSuccessors;
446
447       if (PredDefault == BB) {
448         // If this is the default destination from PTI, only the edges in TI
449         // that don't occur in PTI, or that branch to BB will be activated.
450         std::set<ConstantInt*> PTIHandled;
451         for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
452           if (PredCases[i].second != BB)
453             PTIHandled.insert(PredCases[i].first);
454           else {
455             // The default destination is BB, we don't need explicit targets.
456             std::swap(PredCases[i], PredCases.back());
457             PredCases.pop_back();
458             --i; --e;
459           }
460
461         // Reconstruct the new switch statement we will be building.
462         if (PredDefault != BBDefault) {
463           PredDefault->removePredecessor(Pred);
464           PredDefault = BBDefault;
465           NewSuccessors.push_back(BBDefault);
466         }
467         for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
468           if (!PTIHandled.count(BBCases[i].first) &&
469               BBCases[i].second != BBDefault) {
470             PredCases.push_back(BBCases[i]);
471             NewSuccessors.push_back(BBCases[i].second);
472           }
473
474       } else {
475         // If this is not the default destination from PSI, only the edges
476         // in SI that occur in PSI with a destination of BB will be
477         // activated.
478         std::set<ConstantInt*> PTIHandled;
479         for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
480           if (PredCases[i].second == BB) {
481             PTIHandled.insert(PredCases[i].first);
482             std::swap(PredCases[i], PredCases.back());
483             PredCases.pop_back();
484             --i; --e;
485           }
486
487         // Okay, now we know which constants were sent to BB from the
488         // predecessor.  Figure out where they will all go now.
489         for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
490           if (PTIHandled.count(BBCases[i].first)) {
491             // If this is one we are capable of getting...
492             PredCases.push_back(BBCases[i]);
493             NewSuccessors.push_back(BBCases[i].second);
494             PTIHandled.erase(BBCases[i].first);// This constant is taken care of
495           }
496
497         // If there are any constants vectored to BB that TI doesn't handle,
498         // they must go to the default destination of TI.
499         for (std::set<ConstantInt*>::iterator I = PTIHandled.begin(),
500                E = PTIHandled.end(); I != E; ++I) {
501           PredCases.push_back(std::make_pair(*I, BBDefault));
502           NewSuccessors.push_back(BBDefault);
503         }
504       }
505
506       // Okay, at this point, we know which new successor Pred will get.  Make
507       // sure we update the number of entries in the PHI nodes for these
508       // successors.
509       for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i)
510         AddPredecessorToBlock(NewSuccessors[i], Pred, BB);
511
512       // Now that the successors are updated, create the new Switch instruction.
513       SwitchInst *NewSI = new SwitchInst(CV, PredDefault, PTI);
514       for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
515         NewSI->addCase(PredCases[i].first, PredCases[i].second);
516       Pred->getInstList().erase(PTI);
517
518       // Okay, last check.  If BB is still a successor of PSI, then we must
519       // have an infinite loop case.  If so, add an infinitely looping block
520       // to handle the case to preserve the behavior of the code.
521       BasicBlock *InfLoopBlock = 0;
522       for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
523         if (NewSI->getSuccessor(i) == BB) {
524           if (InfLoopBlock == 0) {
525             // Insert it at the end of the loop, because it's either code,
526             // or it won't matter if it's hot. :)
527             InfLoopBlock = new BasicBlock("infloop", BB->getParent());
528             new BranchInst(InfLoopBlock, InfLoopBlock);
529           }
530           NewSI->setSuccessor(i, InfLoopBlock);
531         }
532           
533       Changed = true;
534     }
535   }
536   return Changed;
537 }
538
539 namespace {
540   /// ConstantIntOrdering - This class implements a stable ordering of constant
541   /// integers that does not depend on their address.  This is important for
542   /// applications that sort ConstantInt's to ensure uniqueness.
543   struct ConstantIntOrdering {
544     bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
545       return LHS->getRawValue() < RHS->getRawValue();
546     }
547   };
548 }
549
550
551 // SimplifyCFG - This function is used to do simplification of a CFG.  For
552 // example, it adjusts branches to branches to eliminate the extra hop, it
553 // eliminates unreachable basic blocks, and does other "peephole" optimization
554 // of the CFG.  It returns true if a modification was made.
555 //
556 // WARNING:  The entry node of a function may not be simplified.
557 //
558 bool llvm::SimplifyCFG(BasicBlock *BB) {
559   bool Changed = false;
560   Function *M = BB->getParent();
561
562   assert(BB && BB->getParent() && "Block not embedded in function!");
563   assert(BB->getTerminator() && "Degenerate basic block encountered!");
564   assert(&BB->getParent()->front() != BB && "Can't Simplify entry block!");
565
566   // Remove basic blocks that have no predecessors... which are unreachable.
567   if (pred_begin(BB) == pred_end(BB) ||
568       *pred_begin(BB) == BB && ++pred_begin(BB) == pred_end(BB)) {
569     DEBUG(std::cerr << "Removing BB: \n" << *BB);
570
571     // Loop through all of our successors and make sure they know that one
572     // of their predecessors is going away.
573     for_each(succ_begin(BB), succ_end(BB),
574              std::bind2nd(std::mem_fun(&BasicBlock::removePredecessor), BB));
575
576     while (!BB->empty()) {
577       Instruction &I = BB->back();
578       // If this instruction is used, replace uses with an arbitrary
579       // constant value.  Because control flow can't get here, we don't care
580       // what we replace the value with.  Note that since this block is 
581       // unreachable, and all values contained within it must dominate their
582       // uses, that all uses will eventually be removed.
583       if (!I.use_empty()) 
584         // Make all users of this instruction reference the constant instead
585         I.replaceAllUsesWith(Constant::getNullValue(I.getType()));
586       
587       // Remove the instruction from the basic block
588       BB->getInstList().pop_back();
589     }
590     M->getBasicBlockList().erase(BB);
591     return true;
592   }
593
594   // Check to see if we can constant propagate this terminator instruction
595   // away...
596   Changed |= ConstantFoldTerminator(BB);
597
598   // Check to see if this block has no non-phi instructions and only a single
599   // successor.  If so, replace references to this basic block with references
600   // to the successor.
601   succ_iterator SI(succ_begin(BB));
602   if (SI != succ_end(BB) && ++SI == succ_end(BB)) {  // One succ?
603
604     BasicBlock::iterator BBI = BB->begin();  // Skip over phi nodes...
605     while (isa<PHINode>(*BBI)) ++BBI;
606
607     if (BBI->isTerminator()) {   // Terminator is the only non-phi instruction!
608       BasicBlock *Succ = *succ_begin(BB); // There is exactly one successor
609      
610       if (Succ != BB) {   // Arg, don't hurt infinite loops!
611         // If our successor has PHI nodes, then we need to update them to
612         // include entries for BB's predecessors, not for BB itself.
613         // Be careful though, if this transformation fails (returns true) then
614         // we cannot do this transformation!
615         //
616         if (!PropagatePredecessorsForPHIs(BB, Succ)) {
617           DEBUG(std::cerr << "Killing Trivial BB: \n" << *BB);
618           std::string OldName = BB->getName();
619
620           std::vector<BasicBlock*>
621             OldSuccPreds(pred_begin(Succ), pred_end(Succ));
622
623           // Move all PHI nodes in BB to Succ if they are alive, otherwise
624           // delete them.
625           while (PHINode *PN = dyn_cast<PHINode>(&BB->front()))
626             if (PN->use_empty())
627               BB->getInstList().erase(BB->begin());  // Nuke instruction...
628             else {
629               // The instruction is alive, so this means that Succ must have
630               // *ONLY* had BB as a predecessor, and the PHI node is still valid
631               // now.  Simply move it into Succ, because we know that BB
632               // strictly dominated Succ.
633               BB->getInstList().remove(BB->begin());
634               Succ->getInstList().push_front(PN);
635
636               // We need to add new entries for the PHI node to account for
637               // predecessors of Succ that the PHI node does not take into
638               // account.  At this point, since we know that BB dominated succ,
639               // this means that we should any newly added incoming edges should
640               // use the PHI node as the value for these edges, because they are
641               // loop back edges.
642               for (unsigned i = 0, e = OldSuccPreds.size(); i != e; ++i)
643                 if (OldSuccPreds[i] != BB)
644                   PN->addIncoming(PN, OldSuccPreds[i]);
645             }
646
647           // Everything that jumped to BB now goes to Succ...
648           BB->replaceAllUsesWith(Succ);
649
650           // Delete the old basic block...
651           M->getBasicBlockList().erase(BB);
652         
653           if (!OldName.empty() && !Succ->hasName())  // Transfer name if we can
654             Succ->setName(OldName);
655           return true;
656         }
657       }
658     }
659   }
660
661   // If this is a returning block with only PHI nodes in it, fold the return
662   // instruction into any unconditional branch predecessors.
663   //
664   // If any predecessor is a conditional branch that just selects among
665   // different return values, fold the replace the branch/return with a select
666   // and return.
667   if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
668     BasicBlock::iterator BBI = BB->getTerminator();
669     if (BBI == BB->begin() || isa<PHINode>(--BBI)) {
670       // Find predecessors that end with branches.
671       std::vector<BasicBlock*> UncondBranchPreds;
672       std::vector<BranchInst*> CondBranchPreds;
673       for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
674         TerminatorInst *PTI = (*PI)->getTerminator();
675         if (BranchInst *BI = dyn_cast<BranchInst>(PTI))
676           if (BI->isUnconditional())
677             UncondBranchPreds.push_back(*PI);
678           else
679             CondBranchPreds.push_back(BI);
680       }
681       
682       // If we found some, do the transformation!
683       if (!UncondBranchPreds.empty()) {
684         while (!UncondBranchPreds.empty()) {
685           BasicBlock *Pred = UncondBranchPreds.back();
686           UncondBranchPreds.pop_back();
687           Instruction *UncondBranch = Pred->getTerminator();
688           // Clone the return and add it to the end of the predecessor.
689           Instruction *NewRet = RI->clone();
690           Pred->getInstList().push_back(NewRet);
691
692           // If the return instruction returns a value, and if the value was a
693           // PHI node in "BB", propagate the right value into the return.
694           if (NewRet->getNumOperands() == 1)
695             if (PHINode *PN = dyn_cast<PHINode>(NewRet->getOperand(0)))
696               if (PN->getParent() == BB)
697                 NewRet->setOperand(0, PN->getIncomingValueForBlock(Pred));
698           // Update any PHI nodes in the returning block to realize that we no
699           // longer branch to them.
700           BB->removePredecessor(Pred);
701           Pred->getInstList().erase(UncondBranch);
702         }
703
704         // If we eliminated all predecessors of the block, delete the block now.
705         if (pred_begin(BB) == pred_end(BB))
706           // We know there are no successors, so just nuke the block.
707           M->getBasicBlockList().erase(BB);
708
709         return true;
710       }
711
712       // Check out all of the conditional branches going to this return
713       // instruction.  If any of them just select between returns, change the
714       // branch itself into a select/return pair.
715       while (!CondBranchPreds.empty()) {
716         BranchInst *BI = CondBranchPreds.back();
717         CondBranchPreds.pop_back();
718         BasicBlock *TrueSucc = BI->getSuccessor(0);
719         BasicBlock *FalseSucc = BI->getSuccessor(1);
720         BasicBlock *OtherSucc = TrueSucc == BB ? FalseSucc : TrueSucc;
721
722         // Check to see if the non-BB successor is also a return block.
723         if (isa<ReturnInst>(OtherSucc->getTerminator())) {
724           // Check to see if there are only PHI instructions in this block.
725           BasicBlock::iterator OSI = OtherSucc->getTerminator();
726           if (OSI == OtherSucc->begin() || isa<PHINode>(--OSI)) {
727             // Okay, we found a branch that is going to two return nodes.  If
728             // there is no return value for this function, just change the
729             // branch into a return.
730             if (RI->getNumOperands() == 0) {
731               TrueSucc->removePredecessor(BI->getParent());
732               FalseSucc->removePredecessor(BI->getParent());
733               new ReturnInst(0, BI);
734               BI->getParent()->getInstList().erase(BI);
735               return true;
736             }
737
738             // Otherwise, figure out what the true and false return values are
739             // so we can insert a new select instruction.
740             Value *TrueValue = TrueSucc->getTerminator()->getOperand(0);
741             Value *FalseValue = FalseSucc->getTerminator()->getOperand(0);
742
743             // Unwrap any PHI nodes in the return blocks.
744             if (PHINode *TVPN = dyn_cast<PHINode>(TrueValue))
745               if (TVPN->getParent() == TrueSucc)
746                 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
747             if (PHINode *FVPN = dyn_cast<PHINode>(FalseValue))
748               if (FVPN->getParent() == FalseSucc)
749                 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
750
751             TrueSucc->removePredecessor(BI->getParent());
752             FalseSucc->removePredecessor(BI->getParent());
753
754             // Insert a new select instruction.
755             Value *NewRetVal = new SelectInst(BI->getCondition(), TrueValue,
756                                               FalseValue, "retval", BI);
757             new ReturnInst(NewRetVal, BI);
758             BI->getParent()->getInstList().erase(BI);
759             return true;
760           }
761         }
762       }
763     }
764   } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->begin())) {
765     // Check to see if the first instruction in this block is just an unwind.
766     // If so, replace any invoke instructions which use this as an exception
767     // destination with call instructions.
768     //
769     std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
770     while (!Preds.empty()) {
771       BasicBlock *Pred = Preds.back();
772       if (InvokeInst *II = dyn_cast<InvokeInst>(Pred->getTerminator()))
773         if (II->getUnwindDest() == BB) {
774           // Insert a new branch instruction before the invoke, because this
775           // is now a fall through...
776           BranchInst *BI = new BranchInst(II->getNormalDest(), II);
777           Pred->getInstList().remove(II);   // Take out of symbol table
778           
779           // Insert the call now...
780           std::vector<Value*> Args(II->op_begin()+3, II->op_end());
781           CallInst *CI = new CallInst(II->getCalledValue(), Args,
782                                       II->getName(), BI);
783           // If the invoke produced a value, the Call now does instead
784           II->replaceAllUsesWith(CI);
785           delete II;
786           Changed = true;
787         }
788       
789       Preds.pop_back();
790     }
791
792     // If this block is now dead, remove it.
793     if (pred_begin(BB) == pred_end(BB)) {
794       // We know there are no successors, so just nuke the block.
795       M->getBasicBlockList().erase(BB);
796       return true;
797     }
798
799   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->begin())) {
800     if (isValueEqualityComparison(SI))
801       if (FoldValueComparisonIntoPredecessors(SI))
802         return SimplifyCFG(BB) || 1;
803   } else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
804     if (BI->isConditional()) {
805       if (Value *CompVal = isValueEqualityComparison(BI)) {
806         // This block must be empty, except for the setcond inst, if it exists.
807         BasicBlock::iterator I = BB->begin();
808         if (&*I == BI ||
809             (&*I == cast<Instruction>(BI->getCondition()) &&
810              &*++I == BI))
811           if (FoldValueComparisonIntoPredecessors(BI))
812             return SimplifyCFG(BB) | true;
813       }
814
815       // If this basic block is ONLY a setcc and a branch, and if a predecessor
816       // branches to us and one of our successors, fold the setcc into the
817       // predecessor and use logical operations to pick the right destination.
818       BasicBlock *TrueDest  = BI->getSuccessor(0);
819       BasicBlock *FalseDest = BI->getSuccessor(1);
820       if (BinaryOperator *Cond = dyn_cast<BinaryOperator>(BI->getCondition()))
821         if (Cond->getParent() == BB && &BB->front() == Cond &&
822             Cond->getNext() == BI && Cond->hasOneUse() &&
823             TrueDest != BB && FalseDest != BB)
824           for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI!=E; ++PI)
825             if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
826               if (PBI->isConditional() && SafeToMergeTerminators(BI, PBI)) {
827                 BasicBlock *PredBlock = *PI;
828                 if (PBI->getSuccessor(0) == FalseDest ||
829                     PBI->getSuccessor(1) == TrueDest) {
830                   // Invert the predecessors condition test (xor it with true),
831                   // which allows us to write this code once.
832                   Value *NewCond =
833                     BinaryOperator::createNot(PBI->getCondition(),
834                                     PBI->getCondition()->getName()+".not", PBI);
835                   PBI->setCondition(NewCond);
836                   BasicBlock *OldTrue = PBI->getSuccessor(0);
837                   BasicBlock *OldFalse = PBI->getSuccessor(1);
838                   PBI->setSuccessor(0, OldFalse);
839                   PBI->setSuccessor(1, OldTrue);
840                 }
841
842                 if (PBI->getSuccessor(0) == TrueDest ||
843                     PBI->getSuccessor(1) == FalseDest) {
844                   // Clone Cond into the predecessor basic block, and or/and the
845                   // two conditions together.
846                   Instruction *New = Cond->clone();
847                   New->setName(Cond->getName());
848                   Cond->setName(Cond->getName()+".old");
849                   PredBlock->getInstList().insert(PBI, New);
850                   Instruction::BinaryOps Opcode =
851                     PBI->getSuccessor(0) == TrueDest ?
852                     Instruction::Or : Instruction::And;
853                   Value *NewCond = 
854                     BinaryOperator::create(Opcode, PBI->getCondition(),
855                                            New, "bothcond", PBI);
856                   PBI->setCondition(NewCond);
857                   if (PBI->getSuccessor(0) == BB) {
858                     AddPredecessorToBlock(TrueDest, PredBlock, BB);
859                     PBI->setSuccessor(0, TrueDest);
860                   }
861                   if (PBI->getSuccessor(1) == BB) {
862                     AddPredecessorToBlock(FalseDest, PredBlock, BB);
863                     PBI->setSuccessor(1, FalseDest);
864                   }
865                   return SimplifyCFG(BB) | 1;
866                 }
867               }
868
869       // If this block ends with a branch instruction, and if there is one
870       // predecessor, see if the previous block ended with a branch on the same
871       // condition, which makes this conditional branch redundant.
872       pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
873       BasicBlock *OnlyPred = *PI++;
874       for (; PI != PE; ++PI)// Search all predecessors, see if they are all same
875         if (*PI != OnlyPred) {
876           OnlyPred = 0;       // There are multiple different predecessors...
877           break;
878         }
879       
880       if (OnlyPred)
881         if (BranchInst *PBI = dyn_cast<BranchInst>(OnlyPred->getTerminator()))
882           if (PBI->isConditional() &&
883               PBI->getCondition() == BI->getCondition() &&
884               (PBI->getSuccessor(0) != BB || PBI->getSuccessor(1) != BB)) {
885             // Okay, the outcome of this conditional branch is statically
886             // knowable.  Delete the outgoing CFG edge that is impossible to
887             // execute.
888             bool CondIsTrue = PBI->getSuccessor(0) == BB;
889             BI->getSuccessor(CondIsTrue)->removePredecessor(BB);
890             new BranchInst(BI->getSuccessor(!CondIsTrue), BB);
891             BB->getInstList().erase(BI);
892             return SimplifyCFG(BB) | true;
893           }
894     }
895   }
896
897   // Merge basic blocks into their predecessor if there is only one distinct
898   // pred, and if there is only one distinct successor of the predecessor, and
899   // if there are no PHI nodes.
900   //
901   pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
902   BasicBlock *OnlyPred = *PI++;
903   for (; PI != PE; ++PI)  // Search all predecessors, see if they are all same
904     if (*PI != OnlyPred) {
905       OnlyPred = 0;       // There are multiple different predecessors...
906       break;
907     }
908
909   BasicBlock *OnlySucc = 0;
910   if (OnlyPred && OnlyPred != BB &&    // Don't break self loops
911       OnlyPred->getTerminator()->getOpcode() != Instruction::Invoke) {
912     // Check to see if there is only one distinct successor...
913     succ_iterator SI(succ_begin(OnlyPred)), SE(succ_end(OnlyPred));
914     OnlySucc = BB;
915     for (; SI != SE; ++SI)
916       if (*SI != OnlySucc) {
917         OnlySucc = 0;     // There are multiple distinct successors!
918         break;
919       }
920   }
921
922   if (OnlySucc) {
923     DEBUG(std::cerr << "Merging: " << *BB << "into: " << *OnlyPred);
924     TerminatorInst *Term = OnlyPred->getTerminator();
925
926     // Resolve any PHI nodes at the start of the block.  They are all
927     // guaranteed to have exactly one entry if they exist, unless there are
928     // multiple duplicate (but guaranteed to be equal) entries for the
929     // incoming edges.  This occurs when there are multiple edges from
930     // OnlyPred to OnlySucc.
931     //
932     while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
933       PN->replaceAllUsesWith(PN->getIncomingValue(0));
934       BB->getInstList().pop_front();  // Delete the phi node...
935     }
936
937     // Delete the unconditional branch from the predecessor...
938     OnlyPred->getInstList().pop_back();
939       
940     // Move all definitions in the successor to the predecessor...
941     OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
942                                      
943     // Make all PHI nodes that referred to BB now refer to Pred as their
944     // source...
945     BB->replaceAllUsesWith(OnlyPred);
946
947     std::string OldName = BB->getName();
948
949     // Erase basic block from the function... 
950     M->getBasicBlockList().erase(BB);
951
952     // Inherit predecessors name if it exists...
953     if (!OldName.empty() && !OnlyPred->hasName())
954       OnlyPred->setName(OldName);
955       
956     return true;
957   }
958
959   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
960     if (BranchInst *BI = dyn_cast<BranchInst>((*PI)->getTerminator()))
961       // Change br (X == 0 | X == 1), T, F into a switch instruction.
962       if (BI->isConditional() && isa<Instruction>(BI->getCondition())) {
963         Instruction *Cond = cast<Instruction>(BI->getCondition());
964         // If this is a bunch of seteq's or'd together, or if it's a bunch of
965         // 'setne's and'ed together, collect them.
966         Value *CompVal = 0;
967         std::vector<ConstantInt*> Values;
968         bool TrueWhenEqual = GatherValueComparisons(Cond, CompVal, Values);
969         if (CompVal && CompVal->getType()->isInteger()) {
970           // There might be duplicate constants in the list, which the switch
971           // instruction can't handle, remove them now.
972           std::sort(Values.begin(), Values.end(), ConstantIntOrdering());
973           Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
974           
975           // Figure out which block is which destination.
976           BasicBlock *DefaultBB = BI->getSuccessor(1);
977           BasicBlock *EdgeBB    = BI->getSuccessor(0);
978           if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
979           
980           // Create the new switch instruction now.
981           SwitchInst *New = new SwitchInst(CompVal, DefaultBB, BI);
982           
983           // Add all of the 'cases' to the switch instruction.
984           for (unsigned i = 0, e = Values.size(); i != e; ++i)
985             New->addCase(Values[i], EdgeBB);
986           
987           // We added edges from PI to the EdgeBB.  As such, if there were any
988           // PHI nodes in EdgeBB, they need entries to be added corresponding to
989           // the number of edges added.
990           for (BasicBlock::iterator BBI = EdgeBB->begin();
991                PHINode *PN = dyn_cast<PHINode>(BBI); ++BBI) {
992             Value *InVal = PN->getIncomingValueForBlock(*PI);
993             for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
994               PN->addIncoming(InVal, *PI);
995           }
996
997           // Erase the old branch instruction.
998           (*PI)->getInstList().erase(BI);
999
1000           // Erase the potentially condition tree that was used to computed the
1001           // branch condition.
1002           ErasePossiblyDeadInstructionTree(Cond);
1003           return true;
1004         }
1005       }
1006
1007   // If there is a trivial two-entry PHI node in this basic block, and we can
1008   // eliminate it, do so now.
1009   if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
1010     if (PN->getNumIncomingValues() == 2) {
1011       // Ok, this is a two entry PHI node.  Check to see if this is a simple "if
1012       // statement", which has a very simple dominance structure.  Basically, we
1013       // are trying to find the condition that is being branched on, which
1014       // subsequently causes this merge to happen.  We really want control
1015       // dependence information for this check, but simplifycfg can't keep it up
1016       // to date, and this catches most of the cases we care about anyway.
1017       //
1018       BasicBlock *IfTrue, *IfFalse;
1019       if (Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse)) {
1020         DEBUG(std::cerr << "FOUND IF CONDITION!  " << *IfCond << "  T: "
1021               << IfTrue->getName() << "  F: " << IfFalse->getName() << "\n");
1022
1023         // Figure out where to insert instructions as necessary.
1024         BasicBlock::iterator AfterPHIIt = BB->begin();
1025         while (isa<PHINode>(AfterPHIIt)) ++AfterPHIIt;
1026
1027         BasicBlock::iterator I = BB->begin();
1028         while (PHINode *PN = dyn_cast<PHINode>(I)) {
1029           ++I;
1030
1031           // If we can eliminate this PHI by directly computing it based on the
1032           // condition, do so now.  We can't eliminate PHI nodes where the
1033           // incoming values are defined in the conditional parts of the branch,
1034           // so check for this.
1035           //
1036           if (DominatesMergePoint(PN->getIncomingValue(0), BB, true) &&
1037               DominatesMergePoint(PN->getIncomingValue(1), BB, true)) {
1038             Value *TrueVal =
1039               PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
1040             Value *FalseVal =
1041               PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
1042
1043             // If one of the incoming values is defined in the conditional
1044             // region, move it into it's predecessor block, which we know is
1045             // safe.
1046             if (!DominatesMergePoint(TrueVal, BB, false)) {
1047               Instruction *TrueI = cast<Instruction>(TrueVal);
1048               BasicBlock *OldBB = TrueI->getParent();
1049               OldBB->getInstList().remove(TrueI);
1050               BasicBlock *NewBB = *pred_begin(OldBB);
1051               NewBB->getInstList().insert(NewBB->getTerminator(), TrueI);
1052             }
1053             if (!DominatesMergePoint(FalseVal, BB, false)) {
1054               Instruction *FalseI = cast<Instruction>(FalseVal);
1055               BasicBlock *OldBB = FalseI->getParent();
1056               OldBB->getInstList().remove(FalseI);
1057               BasicBlock *NewBB = *pred_begin(OldBB);
1058               NewBB->getInstList().insert(NewBB->getTerminator(), FalseI);
1059             }
1060
1061             // Change the PHI node into a select instruction.
1062             BasicBlock::iterator InsertPos = PN;
1063             while (isa<PHINode>(InsertPos)) ++InsertPos;
1064
1065             std::string Name = PN->getName(); PN->setName("");
1066             PN->replaceAllUsesWith(new SelectInst(IfCond, TrueVal, FalseVal,
1067                                                   Name, InsertPos));
1068             BB->getInstList().erase(PN);
1069             Changed = true;
1070           }
1071         }
1072       }
1073     }
1074   
1075   return Changed;
1076 }