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