13140b4ea8b487d7d3557bc18c27f31da626dbe5
[oota-llvm.git] / lib / Transforms / LevelRaise.cpp
1 //===- LevelRaise.cpp - Code to change LLVM to higher level -----------------=//
2 //
3 // This file implements the 'raising' part of the LevelChange API.  This is
4 // useful because, in general, it makes the LLVM code terser and easier to
5 // analyze.  Note that it is good to run DCE after doing this transformation.
6 //
7 //  Eliminate silly things in the source that do not effect the level, but do
8 //  clean up the code:
9 //    * Casts of casts
10 //    - getelementptr/load & getelementptr/store are folded into a direct
11 //      load or store
12 //    - Convert this code (for both alloca and malloc):
13 //          %reg110 = shl uint %n, ubyte 2          ;;<uint>
14 //          %reg108 = alloca ubyte, uint %reg110            ;;<ubyte*>
15 //          %cast76 = cast ubyte* %reg108 to uint*          ;;<uint*>
16 //      To: %cast76 = alloca uint, uint %n
17 //   Convert explicit addressing to use getelementptr instruction where possible
18 //      - ...
19 //
20 //   Convert explicit addressing on pointers to use getelementptr instruction.
21 //    - If a pointer is used by arithmetic operation, insert an array casted
22 //      version into the source program, only for the following pointer types:
23 //        * Method argument pointers
24 //        - Pointers returned by alloca or malloc
25 //        - Pointers returned by function calls
26 //    - If a pointer is indexed with a value scaled by a constant size equal
27 //      to the element size of the array, the expression is replaced with a
28 //      getelementptr instruction.
29 //
30 //===----------------------------------------------------------------------===//
31
32 #include "llvm/Transforms/LevelChange.h"
33 #include "TransformInternals.h"
34 #include "llvm/Method.h"
35 #include "llvm/Support/STLExtras.h"
36 #include "llvm/iOther.h"
37 #include "llvm/iMemory.h"
38 #include "llvm/ConstPoolVals.h"
39 #include "llvm/Optimizations/ConstantHandling.h"
40 #include "llvm/Optimizations/DCE.h"
41 #include <algorithm>
42
43 #include "llvm/Assembly/Writer.h"
44
45 //#define DEBUG_PEEPHOLE_INSTS 1
46
47 #ifdef DEBUG_PEEPHOLE_INSTS
48 #define PRINT_PEEPHOLE(ID, NUM, I)            \
49   cerr << "Inst P/H " << ID << "[" << NUM << "] " << I;
50 #else
51 #define PRINT_PEEPHOLE(ID, NUM, I)
52 #endif
53
54 #define PRINT_PEEPHOLE1(ID, I1) do { PRINT_PEEPHOLE(ID, 0, I1); } while (0)
55 #define PRINT_PEEPHOLE2(ID, I1, I2) \
56   do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); } while (0)
57 #define PRINT_PEEPHOLE3(ID, I1, I2, I3) \
58   do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); \
59        PRINT_PEEPHOLE(ID, 2, I3); } while (0)
60
61
62 // isReinterpretingCast - Return true if the cast instruction specified will
63 // cause the operand to be "reinterpreted".  A value is reinterpreted if the
64 // cast instruction would cause the underlying bits to change.
65 //
66 static inline bool isReinterpretingCast(const CastInst *CI) {
67   return !losslessCastableTypes(CI->getOperand(0)->getType(), CI->getType());
68 }
69
70
71 // getPointedToStruct - If the argument is a pointer type, and the pointed to
72 // value is a struct type, return the struct type, else return null.
73 //
74 static const StructType *getPointedToStruct(const Type *Ty) {
75   const PointerType *PT = dyn_cast<PointerType>(Ty);
76   return PT ? dyn_cast<StructType>(PT->getValueType()) : 0;
77 }
78
79
80 // getStructOffsetType - Return a vector of offsets that are to be used to index
81 // into the specified struct type to get as close as possible to index as we
82 // can.  Note that it is possible that we cannot get exactly to Offset, in which
83 // case we update offset to be the offset we actually obtained.  The resultant
84 // leaf type is returned.
85 //
86 static const Type *getStructOffsetType(const Type *Ty, unsigned &Offset,
87                                        vector<ConstPoolVal*> &Offsets) {
88   if (!isa<StructType>(Ty)) {
89     Offset = 0;   // Return the offset that we were able to acheive
90     return Ty;    // Return the leaf type
91   }
92
93   assert(Offset < TD.getTypeSize(Ty) && "Offset not in struct!");
94   const StructType *STy = cast<StructType>(Ty);
95   const StructLayout *SL = TD.getStructLayout(STy);
96
97   // This loop terminates always on a 0 <= i < MemberOffsets.size()
98   unsigned i;
99   for (i = 0; i < SL->MemberOffsets.size()-1; ++i)
100     if (Offset >= SL->MemberOffsets[i] && Offset <  SL->MemberOffsets[i+1])
101       break;
102   
103   assert(Offset >= SL->MemberOffsets[i] &&
104          (i == SL->MemberOffsets.size()-1 || Offset <  SL->MemberOffsets[i+1]));
105
106   // Make sure to save the current index...
107   Offsets.push_back(ConstPoolUInt::get(Type::UByteTy, i));
108
109   unsigned SubOffs = Offset - SL->MemberOffsets[i];
110   const Type *LeafTy = getStructOffsetType(STy->getElementTypes()[i], SubOffs,
111                                            Offsets);
112   Offset = SL->MemberOffsets[i] + SubOffs;
113   return LeafTy;
114 }
115
116
117
118
119
120 // DoInsertArrayCast - If the argument value has a pointer type, and if the
121 // argument value is used as an array, insert a cast before the specified 
122 // basic block iterator that casts the value to an array pointer.  Return the
123 // new cast instruction (in the CastResult var), or null if no cast is inserted.
124 //
125 static bool DoInsertArrayCast(Method *CurMeth, Value *V, BasicBlock *BB,
126                               BasicBlock::iterator &InsertBefore,
127                               CastInst *&CastResult) {
128   const PointerType *ThePtrType = dyn_cast<PointerType>(V->getType());
129   if (!ThePtrType) return false;
130   bool InsertCast = false;
131
132   for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I) {
133     Instruction *Inst = cast<Instruction>(*I);
134     switch (Inst->getOpcode()) {
135     default: break;                  // Not an interesting use...
136     case Instruction::Add:           // It's being used as an array index!
137   //case Instruction::Sub:
138       InsertCast = true;
139       break;
140     case Instruction::Cast:          // There is already a cast instruction!
141       if (const PointerType *PT = dyn_cast<const PointerType>(Inst->getType()))
142         if (const ArrayType *AT = dyn_cast<const ArrayType>(PT->getValueType()))
143           if (AT->getElementType() == ThePtrType->getValueType()) {
144             // Cast already exists! Return the existing one!
145             CastResult = cast<CastInst>(Inst);
146             return false;       // No changes made to program though...
147           }
148       break;
149     }
150   }
151
152   if (!InsertCast) return false;  // There is no reason to insert a cast!
153
154   // Insert a cast!
155   const Type *ElTy = ThePtrType->getValueType();
156   const PointerType *DestTy = PointerType::get(ArrayType::get(ElTy));
157
158   CastResult = new CastInst(V, DestTy);
159   BB->getInstList().insert(InsertBefore, CastResult);
160   //cerr << "Inserted cast: " << CastResult;
161   return true;            // Made a change!
162 }
163
164
165 // DoInsertArrayCasts - Loop over all "incoming" values in the specified method,
166 // inserting a cast for pointer values that are used as arrays. For our
167 // purposes, an incoming value is considered to be either a value that is 
168 // either a method parameter, a value created by alloca or malloc, or a value
169 // returned from a function call.  All casts are kept attached to their original
170 // values through the PtrCasts map.
171 //
172 static bool DoInsertArrayCasts(Method *M, map<Value*, CastInst*> &PtrCasts) {
173   assert(!M->isExternal() && "Can't handle external methods!");
174
175   // Insert casts for all arguments to the function...
176   bool Changed = false;
177   BasicBlock *CurBB = M->front();
178   BasicBlock::iterator It = CurBB->begin();
179   for (Method::ArgumentListType::iterator AI = M->getArgumentList().begin(), 
180          AE = M->getArgumentList().end(); AI != AE; ++AI) {
181     CastInst *TheCast = 0;
182     if (DoInsertArrayCast(M, *AI, CurBB, It, TheCast)) {
183       It = CurBB->begin();      // We might have just invalidated the iterator!
184       Changed = true;           // Yes we made a change
185       ++It;                     // Insert next cast AFTER this one...
186     }
187
188     if (TheCast)                // Is there a cast associated with this value?
189       PtrCasts[*AI] = TheCast;  // Yes, add it to the map...
190   }
191
192   // TODO: insert casts for alloca, malloc, and function call results.  Also, 
193   // look for pointers that already have casts, to add to the map.
194
195   return Changed;
196 }
197
198
199
200
201 // DoElminatePointerArithmetic - Loop over each incoming pointer variable,
202 // replacing indexing arithmetic with getelementptr calls.
203 //
204 static bool DoEliminatePointerArithmetic(const pair<Value*, CastInst*> &Val) {
205   Value    *V  = Val.first;   // The original pointer
206   CastInst *CV = Val.second;  // The array casted version of the pointer...
207
208   for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I) {
209     Instruction *Inst = cast<Instruction>(*I);
210     if (Inst->getOpcode() != Instruction::Add) 
211       continue;   // We only care about add instructions
212
213     BinaryOperator *Add = cast<BinaryOperator>(Inst);
214
215     // Make sure the array is the first operand of the add expression...
216     if (Add->getOperand(0) != V)
217       Add->swapOperands();
218
219     // Get the amount added to the pointer value...
220     Value *AddAmount = Add->getOperand(1);
221
222     
223   }
224   return false;
225 }
226
227
228 // Peephole Malloc instructions: we take a look at the use chain of the
229 // malloc instruction, and try to find out if the following conditions hold:
230 //   1. The malloc is of the form: 'malloc [sbyte], uint <constant>'
231 //   2. The only users of the malloc are cast & add instructions
232 //   3. Of the cast instructions, there is only one destination pointer type
233 //      [RTy] where the size of the pointed to object is equal to the number
234 //      of bytes allocated.
235 //
236 // If these conditions hold, we convert the malloc to allocate an [RTy]
237 // element.  This should be extended in the future to handle arrays. TODO
238 //
239 static bool PeepholeMallocInst(BasicBlock *BB, BasicBlock::iterator &BI) {
240   MallocInst *MI = cast<MallocInst>(*BI);
241   if (!MI->isArrayAllocation()) return false;    // No array allocation?
242
243   ConstPoolUInt *Amt = dyn_cast<ConstPoolUInt>(MI->getArraySize());
244   if (Amt == 0 || MI->getAllocatedType() != ArrayType::get(Type::SByteTy))
245     return false;
246
247   // Get the number of bytes allocated...
248   unsigned Size = Amt->getValue();
249   const Type *ResultTy = 0;
250
251   // Loop over all of the uses of the malloc instruction, inspecting casts.
252   for (Value::use_iterator I = MI->use_begin(), E = MI->use_end();
253        I != E; ++I) {
254     if (CastInst *CI = dyn_cast<CastInst>(*I)) {
255         //cerr << "\t" << CI;
256     
257       // We only work on casts to pointer types for sure, be conservative
258       if (!isa<PointerType>(CI->getType())) {
259         cerr << "Found cast of malloc value to non pointer type:\n" << CI;
260         return false;
261       }
262
263       const Type *DestTy = cast<PointerType>(CI->getType())->getValueType();
264       if (TD.getTypeSize(DestTy) == Size && DestTy != ResultTy) {
265         // Does the size of the allocated type match the number of bytes
266         // allocated?
267         //
268         if (ResultTy == 0) {
269           ResultTy = DestTy;   // Keep note of this for future uses...
270         } else {
271           // It's overdefined!  We don't know which type to convert to!
272           return false;
273         }
274       }
275     }
276   }
277
278   // If we get this far, we have either found, or not, a type that is cast to
279   // that is of the same size as the malloc instruction.
280   if (!ResultTy) return false;
281
282   // Now we check to see if we can convert the return value of malloc to the
283   // specified pointer type.  All this is moot if we can't.
284   //
285   ValueTypeCache ConvertedTypes;
286   if (RetValConvertableToType(MI, PointerType::get(ResultTy), ConvertedTypes)) {
287     // Yup, it's convertable, do the transformation now!
288     PRINT_PEEPHOLE1("mall-refine:in ", MI);
289
290     // Create a new malloc instruction, and insert it into the method...
291     MallocInst *NewMI = new MallocInst(PointerType::get(ResultTy));
292     NewMI->setName(MI->getName());
293     MI->setName("");
294     BI = BB->getInstList().insert(BI, NewMI)+1;
295
296     // Create a new cast instruction to cast it to the old type...
297     CastInst *NewCI = new CastInst(NewMI, MI->getType());
298     BB->getInstList().insert(BI, NewCI);
299
300     // Move all users of the old malloc instruction over to use the new cast...
301     MI->replaceAllUsesWith(NewCI);
302
303     ValueMapCache ValueMap;
304     ConvertUsersType(NewCI, NewMI, ValueMap);  // This will delete MI!
305         
306     BI = BB->begin();  // Rescan basic block.  BI might be invalidated.
307     PRINT_PEEPHOLE1("mall-refine:out", NewMI);
308     return true;
309   }
310   return false;
311 }
312
313
314 // Peephole optimize the following instructions:
315 //   %t1 = cast int (uint) * %reg111 to uint (...) *
316 //   %t2 = call uint (...) * %cast111( uint %key )
317 //
318 // Into: %t3 = call int (uint) * %reg111( uint %key )
319 //       %t2 = cast int %t3 to uint
320 //
321 static bool PeepholeCallInst(BasicBlock *BB, BasicBlock::iterator &BI) {
322   CallInst *CI = cast<CallInst>(*BI);
323   return false;
324 }
325
326
327 static bool PeepholeOptimize(BasicBlock *BB, BasicBlock::iterator &BI) {
328   Instruction *I = *BI;
329
330   if (CastInst *CI = dyn_cast<CastInst>(I)) {
331     Value       *Src    = CI->getOperand(0);
332     Instruction *SrcI   = dyn_cast<Instruction>(Src); // Nonnull if instr source
333     const Type  *DestTy = CI->getType();
334
335     // Peephole optimize the following instruction:
336     // %V2 = cast <ty> %V to <ty>
337     //
338     // Into: <nothing>
339     //
340     if (DestTy == Src->getType()) {   // Check for a cast to same type as src!!
341       PRINT_PEEPHOLE1("cast-of-self-ty", CI);
342       CI->replaceAllUsesWith(Src);
343       if (!Src->hasName() && CI->hasName()) {
344         string Name = CI->getName();
345         CI->setName("");
346         Src->setName(Name, BB->getParent()->getSymbolTable());
347       }
348       return true;
349     }
350
351     // Peephole optimize the following instructions:
352     // %tmp = cast <ty> %V to <ty2>
353     // %V  = cast <ty2> %tmp to <ty3>     ; Where ty & ty2 are same size
354     //
355     // Into: cast <ty> %V to <ty3>
356     //
357     if (SrcI)
358       if (CastInst *CSrc = dyn_cast<CastInst>(SrcI))
359         if (isReinterpretingCast(CI) + isReinterpretingCast(CSrc) < 2) {
360           // We can only do c-c elimination if, at most, one cast does a
361           // reinterpretation of the input data.
362           //
363           // If legal, make this cast refer the the original casts argument!
364           //
365           PRINT_PEEPHOLE2("cast-cast:in ", CI, CSrc);
366           CI->setOperand(0, CSrc->getOperand(0));
367           PRINT_PEEPHOLE1("cast-cast:out", CI);
368           return true;
369         }
370
371     // Check to see if it's a cast of an instruction that does not depend on the
372     // specific type of the operands to do it's job.
373     if (!isReinterpretingCast(CI)) {
374       ValueTypeCache ConvertedTypes;
375       if (RetValConvertableToType(CI, Src->getType(), ConvertedTypes)) {
376         PRINT_PEEPHOLE2("CAST-DEST-EXPR-CONV:in ", CI, Src);
377
378         //cerr << "\nCONVERTING EXPR TYPE:\n";
379         ValueMapCache ValueMap;
380         ConvertUsersType(CI, Src, ValueMap);  // This will delete CI!
381
382         BI = BB->begin();  // Rescan basic block.  BI might be invalidated.
383         PRINT_PEEPHOLE1("CAST-DEST-EXPR-CONV:out", Src);
384         //cerr << "DONE CONVERTING EXPR TYPE: ";// << BB->getParent();
385         return true;
386       }
387     }
388
389     // Check to see if we are casting from a structure pointer to a pointer to
390     // the first element of the structure... to avoid munching other peepholes,
391     // we only let this happen if there are no add uses of the cast.
392     //
393     // Peephole optimize the following instructions:
394     // %t1 = cast {<...>} * %StructPtr to <ty> *
395     //
396     // Into: %t2 = getelementptr {<...>} * %StructPtr, <0, 0, 0, ...>
397     //       %t1 = cast <eltype> * %t1 to <ty> *
398     //
399     if (const StructType *STy = getPointedToStruct(Src->getType()))
400       if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
401
402         // Loop over uses of the cast, checking for add instructions.  If an add
403         // exists, this is probably a part of a more complex GEP, so we don't
404         // want to mess around with the cast.
405         //
406         bool HasAddUse = false;
407         for (Value::use_iterator I = CI->use_begin(), E = CI->use_end();
408              I != E; ++I)
409           if (isa<Instruction>(*I) &&
410               cast<Instruction>(*I)->getOpcode() == Instruction::Add) {
411             HasAddUse = true; break;
412           }
413
414         // If it doesn't have an add use, check to see if the dest type is
415         // losslessly convertable to one of the types in the start of the struct
416         // type.
417         //
418         if (!HasAddUse) {
419           const Type *DestPointedTy = DestPTy->getValueType();
420           unsigned Depth = 1;
421           const StructType *CurSTy = STy;
422           const Type *ElTy = 0;
423           while (CurSTy) {
424             
425             // Check for a zero element struct type... if we have one, bail.
426             if (CurSTy->getElementTypes().size() == 0) break;
427             
428             // Grab the first element of the struct type, which must lie at
429             // offset zero in the struct.
430             //
431             ElTy = CurSTy->getElementTypes()[0];
432
433             // Did we find what we're looking for?
434             if (losslessCastableTypes(ElTy, DestPointedTy)) break;
435             
436             // Nope, go a level deeper.
437             ++Depth;
438             CurSTy = dyn_cast<StructType>(ElTy);
439             ElTy = 0;
440           }
441           
442           // Did we find what we were looking for? If so, do the transformation
443           if (ElTy) {
444             PRINT_PEEPHOLE1("cast-for-first:in", CI);
445
446             // Build the index vector, full of all zeros
447             vector<ConstPoolVal *> Indices(Depth,
448                                            ConstPoolUInt::get(Type::UByteTy,0));
449
450             // Insert the new T cast instruction... stealing old T's name
451             GetElementPtrInst *GEP = new GetElementPtrInst(Src, Indices,
452                                                            CI->getName());
453             CI->setName("");
454             BI = BB->getInstList().insert(BI, GEP)+1;
455
456             // Make the old cast instruction reference the new GEP instead of
457             // the old src value.
458             //
459             CI->setOperand(0, GEP);
460             
461             PRINT_PEEPHOLE2("cast-for-first:out", GEP, CI);
462             return true;
463           }
464         }
465       }
466
467
468   } else if (MallocInst *MI = dyn_cast<MallocInst>(I)) {
469     if (PeepholeMallocInst(BB, BI)) return true;
470
471   } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
472     if (PeepholeCallInst(BB, BI)) return true;
473
474   } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
475     Value *Val     = SI->getOperand(0);
476     Value *Pointer = SI->getPtrOperand();
477     
478     // Peephole optimize the following instructions:
479     // %t1 = getelementptr {<...>} * %StructPtr, <element indices>
480     // store <elementty> %v, <elementty> * %t1
481     //
482     // Into: store <elementty> %v, {<...>} * %StructPtr, <element indices>
483     //
484     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Pointer)) {
485       PRINT_PEEPHOLE2("gep-store:in", GEP, SI);
486       ReplaceInstWithInst(BB->getInstList(), BI,
487                           SI = new StoreInst(Val, GEP->getPtrOperand(),
488                                              GEP->getIndices()));
489       PRINT_PEEPHOLE1("gep-store:out", SI);
490       return true;
491     }
492     
493     // Peephole optimize the following instructions:
494     // %t = cast <T1>* %P to <T2> * ;; If T1 is losslessly convertable to T2
495     // store <T2> %V, <T2>* %t
496     //
497     // Into: 
498     // %t = cast <T2> %V to <T1>
499     // store <T1> %t2, <T1>* %P
500     //
501     if (CastInst *CI = dyn_cast<CastInst>(Pointer))
502       if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
503         if (PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
504           if (losslessCastableTypes(Val->getType(), // convertable types!
505                                     CSPT->getValueType()) &&
506               !SI->hasIndices()) {      // No subscripts yet!
507             PRINT_PEEPHOLE3("st-src-cast:in ", Pointer, Val, SI);
508
509             // Insert the new T cast instruction... stealing old T's name
510             CastInst *NCI = new CastInst(Val, CSPT->getValueType(),
511                                          CI->getName());
512             CI->setName("");
513             BI = BB->getInstList().insert(BI, NCI)+1;
514
515             // Replace the old store with a new one!
516             ReplaceInstWithInst(BB->getInstList(), BI,
517                                 SI = new StoreInst(NCI, CastSrc));
518             PRINT_PEEPHOLE3("st-src-cast:out", NCI, CastSrc, SI);
519             return true;
520           }
521
522
523   } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
524     Value *Pointer = LI->getPtrOperand();
525     
526     // Peephole optimize the following instructions:
527     // %t1 = getelementptr {<...>} * %StructPtr, <element indices>
528     // %V  = load <elementty> * %t1
529     //
530     // Into: load {<...>} * %StructPtr, <element indices>
531     //
532     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Pointer)) {
533       PRINT_PEEPHOLE2("gep-load:in", GEP, LI);
534       ReplaceInstWithInst(BB->getInstList(), BI,
535                           LI = new LoadInst(GEP->getPtrOperand(),
536                                             GEP->getIndices()));
537       PRINT_PEEPHOLE1("gep-load:out", LI);
538       return true;
539     }
540   } else if (I->getOpcode() == Instruction::Add &&
541              isa<CastInst>(I->getOperand(1))) {
542
543     // Peephole optimize the following instructions:
544     // %t1 = cast ulong <const int> to {<...>} *
545     // %t2 = add {<...>} * %SP, %t1              ;; Constant must be 2nd operand
546     //
547     //    or
548     // %t1 = cast {<...>}* %SP to int*
549     // %t5 = cast ulong <const int> to int*
550     // %t2 = add int* %t1, %t5                   ;; int is same size as field
551     //
552     // Into: %t3 = getelementptr {<...>} * %SP, <element indices>
553     //       %t2 = cast <eltype> * %t3 to {<...>}*
554     //
555     Value            *AddOp1  = I->getOperand(0);
556     CastInst         *AddOp2  = cast<CastInst>(I->getOperand(1));
557     ConstPoolUInt    *OffsetV = dyn_cast<ConstPoolUInt>(AddOp2->getOperand(0));
558     unsigned          Offset  = OffsetV ? OffsetV->getValue() : 0;
559     Value            *SrcPtr;  // Of type pointer to struct...
560     const StructType *StructTy;
561
562     if ((StructTy = getPointedToStruct(AddOp1->getType()))) {
563       SrcPtr = AddOp1;                      // Handle the first case...
564     } else if (CastInst *AddOp1c = dyn_cast<CastInst>(AddOp1)) {
565       SrcPtr = AddOp1c->getOperand(0);      // Handle the second case...
566       StructTy = getPointedToStruct(SrcPtr->getType());
567     }
568     
569     // Only proceed if we have detected all of our conditions successfully...
570     if (Offset && StructTy && SrcPtr && Offset < TD.getTypeSize(StructTy)) {
571       const StructLayout *SL = TD.getStructLayout(StructTy);
572       vector<ConstPoolVal*> Offsets;
573       unsigned ActualOffset = Offset;
574       const Type *ElTy = getStructOffsetType(StructTy, ActualOffset, Offsets);
575
576       if (getPointedToStruct(AddOp1->getType())) {  // case 1
577         PRINT_PEEPHOLE2("add-to-gep1:in", AddOp2, I);
578       } else {
579         PRINT_PEEPHOLE3("add-to-gep2:in", AddOp1, AddOp2, I);
580       }
581
582       GetElementPtrInst *GEP = new GetElementPtrInst(SrcPtr, Offsets);
583       BI = BB->getInstList().insert(BI, GEP)+1;
584
585       assert(Offset-ActualOffset == 0  &&
586              "GEP to middle of element not implemented yet!");
587
588       ReplaceInstWithInst(BB->getInstList(), BI, 
589                           I = new CastInst(GEP, I->getType()));
590       PRINT_PEEPHOLE2("add-to-gep:out", GEP, I);
591       return true;
592     }
593   }
594
595   return false;
596 }
597
598
599
600
601 static bool DoRaisePass(Method *M) {
602   bool Changed = false;
603   for (Method::iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI) {
604     BasicBlock *BB = *MI;
605     BasicBlock::InstListType &BIL = BB->getInstList();
606
607     for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
608       if (opt::DeadCodeElimination::dceInstruction(BIL, BI) ||
609           PeepholeOptimize(BB, BI))
610         Changed = true;
611       else
612         ++BI;
613     }
614   }
615   return Changed;
616 }
617
618
619 // RaisePointerReferences::doit - Raise a method representation to a higher
620 // level.
621 //
622 bool RaisePointerReferences::doit(Method *M) {
623   if (M->isExternal()) return false;
624   bool Changed = false;
625
626 #ifdef DEBUG_PEEPHOLE_INSTS
627   cerr << "\n\n\nStarting to work on Method '" << M->getName() << "'\n";
628 #endif
629
630   while (DoRaisePass(M)) Changed = true;
631
632   // PtrCasts - Keep a mapping between the pointer values (the key of the 
633   // map), and the cast to array pointer (the value) in this map.  This is
634   // used when converting pointer math into array addressing.
635   // 
636   map<Value*, CastInst*> PtrCasts;
637
638   // Insert casts for all incoming pointer values.  Keep track of those casts
639   // and the identified incoming values in the PtrCasts map.
640   //
641   Changed |= DoInsertArrayCasts(M, PtrCasts);
642
643   // Loop over each incoming pointer variable, replacing indexing arithmetic
644   // with getelementptr calls.
645   //
646   Changed |= reduce_apply_bool(PtrCasts.begin(), PtrCasts.end(), 
647                                ptr_fun(DoEliminatePointerArithmetic));
648
649   return Changed;
650 }