Cleanup and restructure the code to make it easier to read and maintain.
[oota-llvm.git] / lib / Transforms / LevelRaise.cpp
1 //===- LevelRaise.cpp - Code to change LLVM to higher level ---------------===//
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 // This file implements the 'raising' part of the LevelChange API.  This is
11 // useful because, in general, it makes the LLVM code terser and easier to
12 // analyze.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "llvm/Transforms/Scalar.h"
17 #include "llvm/Transforms/Utils/Local.h"
18 #include "TransformInternals.h"
19 #include "llvm/iOther.h"
20 #include "llvm/iMemory.h"
21 #include "llvm/Pass.h"
22 #include "llvm/ConstantHandling.h"
23 #include "llvm/Analysis/Expressions.h"
24 #include "llvm/Analysis/Verifier.h"
25 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
26 #include "Support/CommandLine.h"
27 #include "Support/Debug.h"
28 #include "Support/Statistic.h"
29 #include "Support/STLExtras.h"
30 #include <algorithm>
31
32 namespace llvm {
33
34 // StartInst - This enables the -raise-start-inst=foo option to cause the level
35 // raising pass to start at instruction "foo", which is immensely useful for
36 // debugging!
37 //
38 static cl::opt<std::string>
39 StartInst("raise-start-inst", cl::Hidden, cl::value_desc("inst name"),
40        cl::desc("Start raise pass at the instruction with the specified name"));
41
42 static Statistic<>
43 NumLoadStorePeepholes("raise", "Number of load/store peepholes");
44
45 static Statistic<> 
46 NumGEPInstFormed("raise", "Number of other getelementptr's formed");
47
48 static Statistic<>
49 NumExprTreesConv("raise", "Number of expression trees converted");
50
51 static Statistic<>
52 NumCastOfCast("raise", "Number of cast-of-self removed");
53
54 static Statistic<>
55 NumDCEorCP("raise", "Number of insts DCEd or constprop'd");
56
57 static Statistic<>
58 NumVarargCallChanges("raise", "Number of vararg call peepholes");
59
60 #define PRINT_PEEPHOLE(ID, NUM, I)            \
61   DEBUG(std::cerr << "Inst P/H " << ID << "[" << NUM << "] " << I)
62
63 #define PRINT_PEEPHOLE1(ID, I1) do { PRINT_PEEPHOLE(ID, 0, I1); } while (0)
64 #define PRINT_PEEPHOLE2(ID, I1, I2) \
65   do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); } while (0)
66 #define PRINT_PEEPHOLE3(ID, I1, I2, I3) \
67   do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); \
68        PRINT_PEEPHOLE(ID, 2, I3); } while (0)
69 #define PRINT_PEEPHOLE4(ID, I1, I2, I3, I4) \
70   do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); \
71        PRINT_PEEPHOLE(ID, 2, I3); PRINT_PEEPHOLE(ID, 3, I4); } while (0)
72
73 namespace {
74   struct RPR : public FunctionPass {
75     virtual bool runOnFunction(Function &F);
76
77     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
78       AU.setPreservesCFG();
79       AU.addRequired<TargetData>();
80     }
81
82   private:
83     bool DoRaisePass(Function &F);
84     bool PeepholeOptimize(BasicBlock *BB, BasicBlock::iterator &BI);
85   };
86
87   RegisterOpt<RPR> X("raise", "Raise Pointer References");
88 }
89
90
91 Pass *createRaisePointerReferencesPass() {
92   return new RPR();
93 }
94
95
96 // isReinterpretingCast - Return true if the cast instruction specified will
97 // cause the operand to be "reinterpreted".  A value is reinterpreted if the
98 // cast instruction would cause the underlying bits to change.
99 //
100 static inline bool isReinterpretingCast(const CastInst *CI) {
101   return!CI->getOperand(0)->getType()->isLosslesslyConvertibleTo(CI->getType());
102 }
103
104
105 // Peephole optimize the following instructions:
106 // %t1 = cast ? to x *
107 // %t2 = add x * %SP, %t1              ;; Constant must be 2nd operand
108 //
109 // Into: %t3 = getelementptr {<...>} * %SP, <element indices>
110 //       %t2 = cast <eltype> * %t3 to {<...>}*
111 //
112 static bool HandleCastToPointer(BasicBlock::iterator BI,
113                                 const PointerType *DestPTy,
114                                 const TargetData &TD) {
115   CastInst &CI = cast<CastInst>(*BI);
116   if (CI.use_empty()) return false;
117
118   // Scan all of the uses, looking for any uses that are not add or sub
119   // instructions.  If we have non-adds, do not make this transformation.
120   //
121   bool HasSubUse = false;  // Keep track of any subtracts...
122   for (Value::use_iterator I = CI.use_begin(), E = CI.use_end();
123        I != E; ++I)
124     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(*I)) {
125       if ((BO->getOpcode() != Instruction::Add &&
126            BO->getOpcode() != Instruction::Sub) ||
127           // Avoid add sbyte* %X, %X cases...
128           BO->getOperand(0) == BO->getOperand(1))
129         return false;
130       else
131         HasSubUse |= BO->getOpcode() == Instruction::Sub;
132     } else {
133       return false;
134     }
135
136   std::vector<Value*> Indices;
137   Value *Src = CI.getOperand(0);
138   const Type *Result = ConvertibleToGEP(DestPTy, Src, Indices, TD, &BI);
139   if (Result == 0) return false;  // Not convertible...
140
141   // Cannot handle subtracts if there is more than one index required...
142   if (HasSubUse && Indices.size() != 1) return false;
143
144   PRINT_PEEPHOLE2("cast-add-to-gep:in", Src, CI);
145
146   // If we have a getelementptr capability... transform all of the 
147   // add instruction uses into getelementptr's.
148   while (!CI.use_empty()) {
149     BinaryOperator *I = cast<BinaryOperator>(*CI.use_begin());
150     assert((I->getOpcode() == Instruction::Add ||
151             I->getOpcode() == Instruction::Sub) && 
152            "Use is not a valid add instruction!");
153     
154     // Get the value added to the cast result pointer...
155     Value *OtherPtr = I->getOperand((I->getOperand(0) == &CI) ? 1 : 0);
156
157     Instruction *GEP = new GetElementPtrInst(OtherPtr, Indices, I->getName());
158     PRINT_PEEPHOLE1("cast-add-to-gep:i", I);
159
160     // If the instruction is actually a subtract, we are guaranteed to only have
161     // one index (from code above), so we just need to negate the pointer index
162     // long value.
163     if (I->getOpcode() == Instruction::Sub) {
164       Instruction *Neg = BinaryOperator::createNeg(GEP->getOperand(1), 
165                                        GEP->getOperand(1)->getName()+".neg", I);
166       GEP->setOperand(1, Neg);
167     }
168
169     if (GEP->getType() == I->getType()) {
170       // Replace the old add instruction with the shiny new GEP inst
171       ReplaceInstWithInst(I, GEP);
172     } else {
173       // If the type produced by the gep instruction differs from the original
174       // add instruction type, insert a cast now.
175       //
176
177       // Insert the GEP instruction before the old add instruction...
178       I->getParent()->getInstList().insert(I, GEP);
179
180       PRINT_PEEPHOLE1("cast-add-to-gep:o", GEP);
181       GEP = new CastInst(GEP, I->getType());
182
183       // Replace the old add instruction with the shiny new GEP inst
184       ReplaceInstWithInst(I, GEP);
185     }
186
187     PRINT_PEEPHOLE1("cast-add-to-gep:o", GEP);
188   }
189   return true;
190 }
191
192 // Peephole optimize the following instructions:
193 // %t1 = cast ulong <const int> to {<...>} *
194 // %t2 = add {<...>} * %SP, %t1              ;; Constant must be 2nd operand
195 //
196 //    or
197 // %t1 = cast {<...>}* %SP to int*
198 // %t5 = cast ulong <const int> to int*
199 // %t2 = add int* %t1, %t5                   ;; int is same size as field
200 //
201 // Into: %t3 = getelementptr {<...>} * %SP, <element indices>
202 //       %t2 = cast <eltype> * %t3 to {<...>}*
203 //
204 static bool PeepholeOptimizeAddCast(BasicBlock *BB, BasicBlock::iterator &BI,
205                                     Value *AddOp1, CastInst *AddOp2,
206                                     const TargetData &TD) {
207   const CompositeType *CompTy;
208   Value *OffsetVal = AddOp2->getOperand(0);
209   Value *SrcPtr = 0;  // Of type pointer to struct...
210
211   if ((CompTy = getPointedToComposite(AddOp1->getType()))) {
212     SrcPtr = AddOp1;                      // Handle the first case...
213   } else if (CastInst *AddOp1c = dyn_cast<CastInst>(AddOp1)) {
214     SrcPtr = AddOp1c->getOperand(0);      // Handle the second case...
215     CompTy = getPointedToComposite(SrcPtr->getType());
216   }
217
218   // Only proceed if we have detected all of our conditions successfully...
219   if (!CompTy || !SrcPtr || !OffsetVal->getType()->isInteger())
220     return false;
221
222   std::vector<Value*> Indices;
223   if (!ConvertibleToGEP(SrcPtr->getType(), OffsetVal, Indices, TD, &BI))
224     return false;  // Not convertible... perhaps next time
225
226   if (getPointedToComposite(AddOp1->getType())) {  // case 1
227     PRINT_PEEPHOLE2("add-to-gep1:in", AddOp2, *BI);
228   } else {
229     PRINT_PEEPHOLE3("add-to-gep2:in", AddOp1, AddOp2, *BI);
230   }
231
232   GetElementPtrInst *GEP = new GetElementPtrInst(SrcPtr, Indices,
233                                                  AddOp2->getName(), BI);
234
235   Instruction *NCI = new CastInst(GEP, AddOp1->getType());
236   ReplaceInstWithInst(BB->getInstList(), BI, NCI);
237   PRINT_PEEPHOLE2("add-to-gep:out", GEP, NCI);
238   return true;
239 }
240
241 bool RPR::PeepholeOptimize(BasicBlock *BB, BasicBlock::iterator &BI) {
242   Instruction *I = BI;
243   const TargetData &TD = getAnalysis<TargetData>();
244
245   if (CastInst *CI = dyn_cast<CastInst>(I)) {
246     Value       *Src    = CI->getOperand(0);
247     Instruction *SrcI   = dyn_cast<Instruction>(Src); // Nonnull if instr source
248     const Type  *DestTy = CI->getType();
249
250     // Peephole optimize the following instruction:
251     // %V2 = cast <ty> %V to <ty>
252     //
253     // Into: <nothing>
254     //
255     if (DestTy == Src->getType()) {   // Check for a cast to same type as src!!
256       PRINT_PEEPHOLE1("cast-of-self-ty", CI);
257       CI->replaceAllUsesWith(Src);
258       if (!Src->hasName() && CI->hasName()) {
259         std::string Name = CI->getName();
260         CI->setName("");
261         Src->setName(Name, &BB->getParent()->getSymbolTable());
262       }
263
264       // DCE the instruction now, to avoid having the iterative version of DCE
265       // have to worry about it.
266       //
267       BI = BB->getInstList().erase(BI);
268
269       ++NumCastOfCast;
270       return true;
271     }
272
273     // Check to see if it's a cast of an instruction that does not depend on the
274     // specific type of the operands to do it's job.
275     if (!isReinterpretingCast(CI)) {
276       ValueTypeCache ConvertedTypes;
277
278       // Check to see if we can convert the source of the cast to match the
279       // destination type of the cast...
280       //
281       ConvertedTypes[CI] = CI->getType();  // Make sure the cast doesn't change
282       if (ExpressionConvertibleToType(Src, DestTy, ConvertedTypes, TD)) {
283         PRINT_PEEPHOLE3("CAST-SRC-EXPR-CONV:in ", Src, CI, BB->getParent());
284           
285         DEBUG(std::cerr << "\nCONVERTING SRC EXPR TYPE:\n");
286         { // ValueMap must be destroyed before function verified!
287           ValueMapCache ValueMap;
288           Value *E = ConvertExpressionToType(Src, DestTy, ValueMap, TD);
289
290           if (Constant *CPV = dyn_cast<Constant>(E))
291             CI->replaceAllUsesWith(CPV);
292           
293           PRINT_PEEPHOLE1("CAST-SRC-EXPR-CONV:out", E);
294           DEBUG(std::cerr << "DONE CONVERTING SRC EXPR TYPE: \n"
295                           << BB->getParent());
296         }
297
298         DEBUG(assert(verifyFunction(*BB->getParent()) == false &&
299                      "Function broken!"));
300         BI = BB->begin();  // Rescan basic block.  BI might be invalidated.
301         ++NumExprTreesConv;
302         return true;
303       }
304
305       // Check to see if we can convert the users of the cast value to match the
306       // source type of the cast...
307       //
308       ConvertedTypes.clear();
309       // Make sure the source doesn't change type
310       ConvertedTypes[Src] = Src->getType();
311       if (ValueConvertibleToType(CI, Src->getType(), ConvertedTypes, TD)) {
312         PRINT_PEEPHOLE3("CAST-DEST-EXPR-CONV:in ", Src, CI, BB->getParent());
313
314         DEBUG(std::cerr << "\nCONVERTING EXPR TYPE:\n");
315         { // ValueMap must be destroyed before function verified!
316           ValueMapCache ValueMap;
317           ConvertValueToNewType(CI, Src, ValueMap, TD);  // This will delete CI!
318         }
319
320         PRINT_PEEPHOLE1("CAST-DEST-EXPR-CONV:out", Src);
321         DEBUG(std::cerr << "DONE CONVERTING EXPR TYPE: \n\n" << BB->getParent());
322
323         DEBUG(assert(verifyFunction(*BB->getParent()) == false &&
324                      "Function broken!"));
325         BI = BB->begin();  // Rescan basic block.  BI might be invalidated.
326         ++NumExprTreesConv;
327         return true;
328       }
329     }
330
331     // Otherwise find out it this cast is a cast to a pointer type, which is
332     // then added to some other pointer, then loaded or stored through.  If
333     // so, convert the add into a getelementptr instruction...
334     //
335     if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
336       if (HandleCastToPointer(BI, DestPTy, TD)) {
337         BI = BB->begin();  // Rescan basic block.  BI might be invalidated.
338         ++NumGEPInstFormed;
339         return true;
340       }
341     }
342
343     // Check to see if we are casting from a structure pointer to a pointer to
344     // the first element of the structure... to avoid munching other peepholes,
345     // we only let this happen if there are no add uses of the cast.
346     //
347     // Peephole optimize the following instructions:
348     // %t1 = cast {<...>} * %StructPtr to <ty> *
349     //
350     // Into: %t2 = getelementptr {<...>} * %StructPtr, <0, 0, 0, ...>
351     //       %t1 = cast <eltype> * %t1 to <ty> *
352     //
353     if (const CompositeType *CTy = getPointedToComposite(Src->getType()))
354       if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
355
356         // Loop over uses of the cast, checking for add instructions.  If an add
357         // exists, this is probably a part of a more complex GEP, so we don't
358         // want to mess around with the cast.
359         //
360         bool HasAddUse = false;
361         for (Value::use_iterator I = CI->use_begin(), E = CI->use_end();
362              I != E; ++I)
363           if (isa<Instruction>(*I) &&
364               cast<Instruction>(*I)->getOpcode() == Instruction::Add) {
365             HasAddUse = true; break;
366           }
367
368         // If it doesn't have an add use, check to see if the dest type is
369         // losslessly convertible to one of the types in the start of the struct
370         // type.
371         //
372         if (!HasAddUse) {
373           const Type *DestPointedTy = DestPTy->getElementType();
374           unsigned Depth = 1;
375           const CompositeType *CurCTy = CTy;
376           const Type *ElTy = 0;
377
378           // Build the index vector, full of all zeros
379           std::vector<Value*> Indices;
380           Indices.push_back(ConstantSInt::get(Type::LongTy, 0));
381           while (CurCTy && !isa<PointerType>(CurCTy)) {
382             if (const StructType *CurSTy = dyn_cast<StructType>(CurCTy)) {
383               // Check for a zero element struct type... if we have one, bail.
384               if (CurSTy->getElementTypes().size() == 0) break;
385             
386               // Grab the first element of the struct type, which must lie at
387               // offset zero in the struct.
388               //
389               ElTy = CurSTy->getElementTypes()[0];
390             } else {
391               ElTy = cast<ArrayType>(CurCTy)->getElementType();
392             }
393
394             // Insert a zero to index through this type...
395             Indices.push_back(Constant::getNullValue(CurCTy->getIndexType()));
396
397             // Did we find what we're looking for?
398             if (ElTy->isLosslesslyConvertibleTo(DestPointedTy)) break;
399             
400             // Nope, go a level deeper.
401             ++Depth;
402             CurCTy = dyn_cast<CompositeType>(ElTy);
403             ElTy = 0;
404           }
405           
406           // Did we find what we were looking for? If so, do the transformation
407           if (ElTy) {
408             PRINT_PEEPHOLE1("cast-for-first:in", CI);
409
410             std::string Name = CI->getName(); CI->setName("");
411
412             // Insert the new T cast instruction... stealing old T's name
413             GetElementPtrInst *GEP = new GetElementPtrInst(Src, Indices,
414                                                            Name, BI);
415
416             // Make the old cast instruction reference the new GEP instead of
417             // the old src value.
418             //
419             CI->setOperand(0, GEP);
420             
421             PRINT_PEEPHOLE2("cast-for-first:out", GEP, CI);
422             ++NumGEPInstFormed;
423             return true;
424           }
425         }
426       }
427
428   } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
429     Value *Val     = SI->getOperand(0);
430     Value *Pointer = SI->getPointerOperand();
431     
432     // Peephole optimize the following instructions:
433     // %t = cast <T1>* %P to <T2> * ;; If T1 is losslessly convertible to T2
434     // store <T2> %V, <T2>* %t
435     //
436     // Into: 
437     // %t = cast <T2> %V to <T1>
438     // store <T1> %t2, <T1>* %P
439     //
440     // Note: This is not taken care of by expr conversion because there might
441     // not be a cast available for the store to convert the incoming value of.
442     // This code is basically here to make sure that pointers don't have casts
443     // if possible.
444     //
445     if (CastInst *CI = dyn_cast<CastInst>(Pointer))
446       if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
447         if (const PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
448           // convertible types?
449           if (Val->getType()->isLosslesslyConvertibleTo(CSPT->getElementType())) {
450             PRINT_PEEPHOLE3("st-src-cast:in ", Pointer, Val, SI);
451
452             // Insert the new T cast instruction... stealing old T's name
453             std::string Name(CI->getName()); CI->setName("");
454             CastInst *NCI = new CastInst(Val, CSPT->getElementType(),
455                                          Name, BI);
456
457             // Replace the old store with a new one!
458             ReplaceInstWithInst(BB->getInstList(), BI,
459                                 SI = new StoreInst(NCI, CastSrc));
460             PRINT_PEEPHOLE3("st-src-cast:out", NCI, CastSrc, SI);
461             ++NumLoadStorePeepholes;
462             return true;
463           }
464
465   } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
466     Value *Pointer = LI->getOperand(0);
467     const Type *PtrElType =
468       cast<PointerType>(Pointer->getType())->getElementType();
469     
470     // Peephole optimize the following instructions:
471     // %Val = cast <T1>* to <T2>*    ;; If T1 is losslessly convertible to T2
472     // %t = load <T2>* %P
473     //
474     // Into: 
475     // %t = load <T1>* %P
476     // %Val = cast <T1> to <T2>
477     //
478     // Note: This is not taken care of by expr conversion because there might
479     // not be a cast available for the store to convert the incoming value of.
480     // This code is basically here to make sure that pointers don't have casts
481     // if possible.
482     //
483     if (CastInst *CI = dyn_cast<CastInst>(Pointer))
484       if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
485         if (const PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
486           // convertible types?
487           if (PtrElType->isLosslesslyConvertibleTo(CSPT->getElementType())) {
488             PRINT_PEEPHOLE2("load-src-cast:in ", Pointer, LI);
489
490             // Create the new load instruction... loading the pre-casted value
491             LoadInst *NewLI = new LoadInst(CastSrc, LI->getName(), BI);
492             
493             // Insert the new T cast instruction... stealing old T's name
494             CastInst *NCI = new CastInst(NewLI, LI->getType(), CI->getName());
495
496             // Replace the old store with a new one!
497             ReplaceInstWithInst(BB->getInstList(), BI, NCI);
498             PRINT_PEEPHOLE3("load-src-cast:out", NCI, CastSrc, NewLI);
499             ++NumLoadStorePeepholes;
500             return true;
501           }
502
503   } else if (I->getOpcode() == Instruction::Add &&
504              isa<CastInst>(I->getOperand(1))) {
505
506     if (PeepholeOptimizeAddCast(BB, BI, I->getOperand(0),
507                                 cast<CastInst>(I->getOperand(1)), TD)) {
508       ++NumGEPInstFormed;
509       return true;
510     }
511   } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
512     // If we have a call with all varargs arguments, convert the call to use the
513     // actual argument types present...
514     //
515     const PointerType *PTy = cast<PointerType>(CI->getCalledValue()->getType());
516     const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
517
518     // Is the call to a vararg variable with no real parameters?
519     if (FTy->isVarArg() && FTy->getNumParams() == 0 &&
520         !CI->getCalledFunction()) {
521       // If so, insert a new cast instruction, casting it to a function type
522       // that matches the current arguments...
523       //
524       std::vector<const Type *> Params;  // Parameter types...
525       for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
526         Params.push_back(CI->getOperand(i)->getType());
527
528       FunctionType *NewFT = FunctionType::get(FTy->getReturnType(),
529                                               Params, false);
530       PointerType *NewPFunTy = PointerType::get(NewFT);
531
532       // Create a new cast, inserting it right before the function call...
533       Value *NewCast;
534       Constant *ConstantCallSrc = 0;
535       if (Constant *CS = dyn_cast<Constant>(CI->getCalledValue()))
536         ConstantCallSrc = CS;
537       else if (GlobalValue *GV = dyn_cast<GlobalValue>(CI->getCalledValue()))
538         ConstantCallSrc = ConstantPointerRef::get(GV);
539
540       if (ConstantCallSrc)
541         NewCast = ConstantExpr::getCast(ConstantCallSrc, NewPFunTy);
542       else
543         NewCast = new CastInst(CI->getCalledValue(), NewPFunTy,
544                                CI->getCalledValue()->getName()+"_c",CI);
545
546       // Create a new call instruction...
547       CallInst *NewCall = new CallInst(NewCast,
548                            std::vector<Value*>(CI->op_begin()+1, CI->op_end()));
549       ++BI;
550       ReplaceInstWithInst(CI, NewCall);
551       
552       ++NumVarargCallChanges;
553       return true;
554     }
555
556   }
557
558   return false;
559 }
560
561
562
563
564 bool RPR::DoRaisePass(Function &F) {
565   bool Changed = false;
566   for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
567     for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
568       DEBUG(std::cerr << "Processing: " << *BI);
569       if (dceInstruction(BI) || doConstantPropagation(BI)) {
570         Changed = true; 
571         ++NumDCEorCP;
572         DEBUG(std::cerr << "***\t\t^^-- Dead code eliminated!\n");
573       } else if (PeepholeOptimize(BB, BI)) {
574         Changed = true;
575       } else {
576         ++BI;
577       }
578     }
579
580   return Changed;
581 }
582
583
584 // runOnFunction - Raise a function representation to a higher level.
585 bool RPR::runOnFunction(Function &F) {
586   DEBUG(std::cerr << "\n\n\nStarting to work on Function '" << F.getName()
587                   << "'\n");
588
589   // Insert casts for all incoming pointer pointer values that are treated as
590   // arrays...
591   //
592   bool Changed = false, LocalChange;
593
594   // If the StartInst option was specified, then Peephole optimize that
595   // instruction first if it occurs in this function.
596   //
597   if (!StartInst.empty()) {
598     for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
599       for (BasicBlock::iterator BI = BB->begin(); BI != BB->end(); ++BI)
600         if (BI->getName() == StartInst) {
601           bool SavedDebug = DebugFlag;  // Save the DEBUG() controlling flag.
602           DebugFlag = true;             // Turn on DEBUG's
603           Changed |= PeepholeOptimize(BB, BI);
604           DebugFlag = SavedDebug;       // Restore DebugFlag to previous state
605         }
606   }
607
608   do {
609     DEBUG(std::cerr << "Looping: \n" << F);
610
611     // Iterate over the function, refining it, until it converges on a stable
612     // state
613     LocalChange = false;
614     while (DoRaisePass(F)) LocalChange = true;
615     Changed |= LocalChange;
616
617   } while (LocalChange);
618
619   return Changed;
620 }
621
622 } // End llvm namespace