Hrm, don't do debugging output when debugging is off. :(
[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.
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include "llvm/Transforms/LevelChange.h"
10 #include "TransformInternals.h"
11 #include "llvm/Method.h"
12 #include "llvm/iOther.h"
13 #include "llvm/iMemory.h"
14 #include "llvm/ConstantVals.h"
15 #include "llvm/Optimizations/ConstantHandling.h"
16 #include "llvm/Optimizations/DCE.h"
17 #include "llvm/Optimizations/ConstantProp.h"
18 #include "llvm/Analysis/Expressions.h"
19 #include "Support/STLExtras.h"
20 #include <algorithm>
21
22 #include "llvm/Assembly/Writer.h"
23
24 //#define DEBUG_PEEPHOLE_INSTS 1
25
26 #ifdef DEBUG_PEEPHOLE_INSTS
27 #define PRINT_PEEPHOLE(ID, NUM, I)            \
28   cerr << "Inst P/H " << ID << "[" << NUM << "] " << I;
29 #else
30 #define PRINT_PEEPHOLE(ID, NUM, I)
31 #endif
32
33 #define PRINT_PEEPHOLE1(ID, I1) do { PRINT_PEEPHOLE(ID, 0, I1); } while (0)
34 #define PRINT_PEEPHOLE2(ID, I1, I2) \
35   do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); } while (0)
36 #define PRINT_PEEPHOLE3(ID, I1, I2, I3) \
37   do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); \
38        PRINT_PEEPHOLE(ID, 2, I3); } while (0)
39 #define PRINT_PEEPHOLE4(ID, I1, I2, I3, I4) \
40   do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); \
41        PRINT_PEEPHOLE(ID, 2, I3); PRINT_PEEPHOLE(ID, 3, I4); } while (0)
42
43
44 // isReinterpretingCast - Return true if the cast instruction specified will
45 // cause the operand to be "reinterpreted".  A value is reinterpreted if the
46 // cast instruction would cause the underlying bits to change.
47 //
48 static inline bool isReinterpretingCast(const CastInst *CI) {
49   return!CI->getOperand(0)->getType()->isLosslesslyConvertableTo(CI->getType());
50 }
51
52
53
54 #if 0  // Unneccesary code, handled by convert exprs
55 // Peephole optimize the following instructions:
56 // %t1 = cast ? to x *
57 // %t2 = add x * %SP, %t1              ;; Constant must be 2nd operand
58 //
59 // Into: %t3 = getelementptr {<...>} * %SP, <element indices>
60 //       %t2 = cast <eltype> * %t3 to {<...>}*
61 //
62 static bool HandleCastToPointer(BasicBlock::iterator BI,
63                                 const PointerType *DestPTy) {
64   CastInst *CI = cast<CastInst>(*BI);
65
66   // Scan all of the uses, looking for any uses that are not add
67   // instructions.  If we have non-adds, do not make this transformation.
68   //
69   for (Value::use_iterator I = CI->use_begin(), E = CI->use_end();
70        I != E; ++I) {
71     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(*I)) {
72       if (BO->getOpcode() != Instruction::Add)
73         return false;
74     } else {
75       return false;
76     }
77   }
78
79   vector<Value*> Indices;
80   Value *Src = CI->getOperand(0);
81   const Type *Result = ConvertableToGEP(DestPTy, Src, Indices, &BI);
82   const PointerType *UsedType = DestPTy;
83
84   // If we fail, check to see if we have an pointer source type that, if
85   // converted to an unsized array type, would work.  In this case, we propogate
86   // the cast forward to the input of the add instruction.
87   //
88   if (Result == 0 && getPointedToComposite(DestPTy) == 0) {
89     // Make an unsized array and try again...
90     UsedType = PointerType::get(ArrayType::get(DestPTy->getElementType()));
91     Result = ConvertableToGEP(UsedType, Src, Indices, &BI);    
92   }
93
94   if (Result == 0) return false;  // Not convertable...
95
96   PRINT_PEEPHOLE2("cast-add-to-gep:in", Src, CI);
97
98   // If we have a getelementptr capability... transform all of the 
99   // add instruction uses into getelementptr's.
100   for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
101        UI != E; ++UI) {
102     Instruction *I = cast<Instruction>(*UI);
103     assert(I->getOpcode() == Instruction::Add && I->getNumOperands() == 2 &&
104            "Use is not a valid add instruction!");
105     
106     // Get the value added to the cast result pointer...
107     Value *OtherPtr = I->getOperand((I->getOperand(0) == CI) ? 1 : 0);
108
109     BasicBlock *BB = I->getParent();
110     BasicBlock::iterator AddIt = find(BB->getInstList().begin(),
111                                       BB->getInstList().end(), I);
112
113     if (UsedType != DestPTy) {
114       // Insert a cast of the incoming value to something addressable...
115       CastInst *C = new CastInst(OtherPtr, UsedType, OtherPtr->getName());
116       AddIt = BB->getInstList().insert(AddIt, C)+1;
117       OtherPtr = C;
118     }
119
120     GetElementPtrInst *GEP = new GetElementPtrInst(OtherPtr, Indices,
121                                                    I->getName());
122
123     PRINT_PEEPHOLE1("cast-add-to-gep:i", I);
124     
125     // Replace the old add instruction with the shiny new GEP inst
126     ReplaceInstWithInst(BB->getInstList(), AddIt, GEP);
127     PRINT_PEEPHOLE1("cast-add-to-gep:o", GEP);
128   }
129   return true;
130 }
131 #endif
132
133 // Peephole optimize the following instructions:
134 // %t1 = cast ulong <const int> to {<...>} *
135 // %t2 = add {<...>} * %SP, %t1              ;; Constant must be 2nd operand
136 //
137 //    or
138 // %t1 = cast {<...>}* %SP to int*
139 // %t5 = cast ulong <const int> to int*
140 // %t2 = add int* %t1, %t5                   ;; int is same size as field
141 //
142 // Into: %t3 = getelementptr {<...>} * %SP, <element indices>
143 //       %t2 = cast <eltype> * %t3 to {<...>}*
144 //
145 static bool PeepholeOptimizeAddCast(BasicBlock *BB, BasicBlock::iterator &BI,
146                                     Value *AddOp1, CastInst *AddOp2) {
147   const CompositeType *CompTy;
148   Value *OffsetVal = AddOp2->getOperand(0);
149   Value *SrcPtr;  // Of type pointer to struct...
150
151   if ((CompTy = getPointedToComposite(AddOp1->getType()))) {
152     SrcPtr = AddOp1;                      // Handle the first case...
153   } else if (CastInst *AddOp1c = dyn_cast<CastInst>(AddOp1)) {
154     SrcPtr = AddOp1c->getOperand(0);      // Handle the second case...
155     CompTy = getPointedToComposite(SrcPtr->getType());
156   }
157
158   // Only proceed if we have detected all of our conditions successfully...
159   if (!CompTy || !SrcPtr || !OffsetVal->getType()->isIntegral())
160     return false;
161
162   vector<Value*> Indices;
163   if (!ConvertableToGEP(SrcPtr->getType(), OffsetVal, Indices, &BI))
164     return false;  // Not convertable... perhaps next time
165
166   if (getPointedToComposite(AddOp1->getType())) {  // case 1
167     PRINT_PEEPHOLE2("add-to-gep1:in", AddOp2, *BI);
168   } else {
169     PRINT_PEEPHOLE3("add-to-gep2:in", AddOp1, AddOp2, *BI);
170   }
171
172   GetElementPtrInst *GEP = new GetElementPtrInst(SrcPtr, Indices,
173                                                  AddOp2->getName());
174   BI = BB->getInstList().insert(BI, GEP)+1;
175
176   Instruction *NCI = new CastInst(GEP, AddOp1->getType());
177   ReplaceInstWithInst(BB->getInstList(), BI, NCI);
178   PRINT_PEEPHOLE2("add-to-gep:out", GEP, NCI);
179   return true;
180 }
181
182 static bool PeepholeOptimize(BasicBlock *BB, BasicBlock::iterator &BI) {
183   Instruction *I = *BI;
184
185   if (CastInst *CI = dyn_cast<CastInst>(I)) {
186     Value       *Src    = CI->getOperand(0);
187     Instruction *SrcI   = dyn_cast<Instruction>(Src); // Nonnull if instr source
188     const Type  *DestTy = CI->getType();
189
190     // Peephole optimize the following instruction:
191     // %V2 = cast <ty> %V to <ty>
192     //
193     // Into: <nothing>
194     //
195     if (DestTy == Src->getType()) {   // Check for a cast to same type as src!!
196       PRINT_PEEPHOLE1("cast-of-self-ty", CI);
197       CI->replaceAllUsesWith(Src);
198       if (!Src->hasName() && CI->hasName()) {
199         string Name = CI->getName();
200         CI->setName("");
201         Src->setName(Name, BB->getParent()->getSymbolTable());
202       }
203       return true;
204     }
205
206     // Peephole optimize the following instructions:
207     // %tmp = cast <ty> %V to <ty2>
208     // %V   = cast <ty2> %tmp to <ty3>     ; Where ty & ty2 are same size
209     //
210     // Into: cast <ty> %V to <ty3>
211     //
212     if (SrcI)
213       if (CastInst *CSrc = dyn_cast<CastInst>(SrcI))
214         if (isReinterpretingCast(CI) + isReinterpretingCast(CSrc) < 2) {
215           // We can only do c-c elimination if, at most, one cast does a
216           // reinterpretation of the input data.
217           //
218           // If legal, make this cast refer the the original casts argument!
219           //
220           PRINT_PEEPHOLE2("cast-cast:in ", CI, CSrc);
221           CI->setOperand(0, CSrc->getOperand(0));
222           PRINT_PEEPHOLE1("cast-cast:out", CI);
223           return true;
224         }
225
226     // Check to see if it's a cast of an instruction that does not depend on the
227     // specific type of the operands to do it's job.
228     if (!isReinterpretingCast(CI)) {
229       // Check to see if we can convert the source of the cast to match the
230       // destination type of the cast...
231       //
232       ValueTypeCache ConvertedTypes;
233       if (ValueConvertableToType(CI, Src->getType(), ConvertedTypes)) {
234         PRINT_PEEPHOLE2("CAST-DEST-EXPR-CONV:in ", Src, CI);
235
236 #ifdef DEBUG_PEEPHOLE_INSTS
237         cerr << "\nCONVERTING EXPR TYPE:\n";
238 #endif
239         ValueMapCache ValueMap;
240         ConvertValueToNewType(CI, Src, ValueMap);  // This will delete CI!
241
242         BI = BB->begin();  // Rescan basic block.  BI might be invalidated.
243         PRINT_PEEPHOLE1("CAST-DEST-EXPR-CONV:out", Src);
244 #ifdef DEBUG_PEEPHOLE_INSTS
245         cerr << "DONE CONVERTING EXPR TYPE: \n\n";// << BB->getParent();
246 #endif
247         return true;
248       }
249
250       // Check to see if we can convert the users of the cast value to match the
251       // source type of the cast...
252       //
253       ConvertedTypes.clear();
254       if (ExpressionConvertableToType(Src, DestTy, ConvertedTypes)) {
255         PRINT_PEEPHOLE2("CAST-SRC-EXPR-CONV:in ", Src, CI);
256           
257 #ifdef DEBUG_PEEPHOLE_INSTS
258         cerr << "\nCONVERTING SRC EXPR TYPE:\n";
259 #endif
260         ValueMapCache ValueMap;
261         Value *E = ConvertExpressionToType(Src, DestTy, ValueMap);
262         if (Constant *CPV = dyn_cast<Constant>(E))
263           CI->replaceAllUsesWith(CPV);
264
265         BI = BB->begin();  // Rescan basic block.  BI might be invalidated.
266         PRINT_PEEPHOLE1("CAST-SRC-EXPR-CONV:out", E);
267 #ifdef DEBUG_PEEPHOLE_INSTS
268         cerr << "DONE CONVERTING SRC EXPR TYPE: \n\n";// << BB->getParent();
269 #endif
270         return true;
271       }
272 #if 0
273       // Otherwise find out it this cast is a cast to a pointer type, which is
274       // then added to some other pointer, then loaded or stored through.  If
275       // so, convert the add into a getelementptr instruction...
276       //
277       if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
278         if (HandleCastToPointer(BI, DestPTy))
279           return true;
280       }
281 #endif
282     }
283
284     // Check to see if we are casting from a structure pointer to a pointer to
285     // the first element of the structure... to avoid munching other peepholes,
286     // we only let this happen if there are no add uses of the cast.
287     //
288     // Peephole optimize the following instructions:
289     // %t1 = cast {<...>} * %StructPtr to <ty> *
290     //
291     // Into: %t2 = getelementptr {<...>} * %StructPtr, <0, 0, 0, ...>
292     //       %t1 = cast <eltype> * %t1 to <ty> *
293     //
294 #if 1
295     if (const CompositeType *CTy = getPointedToComposite(Src->getType()))
296       if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
297
298         // Loop over uses of the cast, checking for add instructions.  If an add
299         // exists, this is probably a part of a more complex GEP, so we don't
300         // want to mess around with the cast.
301         //
302         bool HasAddUse = false;
303         for (Value::use_iterator I = CI->use_begin(), E = CI->use_end();
304              I != E; ++I)
305           if (isa<Instruction>(*I) &&
306               cast<Instruction>(*I)->getOpcode() == Instruction::Add) {
307             HasAddUse = true; break;
308           }
309
310         // If it doesn't have an add use, check to see if the dest type is
311         // losslessly convertable to one of the types in the start of the struct
312         // type.
313         //
314         if (!HasAddUse) {
315           const Type *DestPointedTy = DestPTy->getElementType();
316           unsigned Depth = 1;
317           const CompositeType *CurCTy = CTy;
318           const Type *ElTy = 0;
319
320           // Build the index vector, full of all zeros
321           vector<Value*> Indices;
322
323           while (CurCTy) {
324             if (const StructType *CurSTy = dyn_cast<StructType>(CurCTy)) {
325               // Check for a zero element struct type... if we have one, bail.
326               if (CurSTy->getElementTypes().size() == 0) break;
327             
328               // Grab the first element of the struct type, which must lie at
329               // offset zero in the struct.
330               //
331               ElTy = CurSTy->getElementTypes()[0];
332             } else {
333               ElTy = cast<ArrayType>(CurCTy)->getElementType();
334             }
335
336             // Insert a zero to index through this type...
337             Indices.push_back(ConstantUInt::get(CurCTy->getIndexType(), 0));
338
339             // Did we find what we're looking for?
340             if (ElTy->isLosslesslyConvertableTo(DestPointedTy)) break;
341             
342             // Nope, go a level deeper.
343             ++Depth;
344             CurCTy = dyn_cast<CompositeType>(ElTy);
345             ElTy = 0;
346           }
347           
348           // Did we find what we were looking for? If so, do the transformation
349           if (ElTy) {
350             PRINT_PEEPHOLE1("cast-for-first:in", CI);
351
352             // Insert the new T cast instruction... stealing old T's name
353             GetElementPtrInst *GEP = new GetElementPtrInst(Src, Indices,
354                                                            CI->getName());
355             CI->setName("");
356             BI = BB->getInstList().insert(BI, GEP)+1;
357
358             // Make the old cast instruction reference the new GEP instead of
359             // the old src value.
360             //
361             CI->setOperand(0, GEP);
362             
363             PRINT_PEEPHOLE2("cast-for-first:out", GEP, CI);
364             return true;
365           }
366         }
367       }
368 #endif
369
370 #if 1
371   } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
372     Value *Val     = SI->getOperand(0);
373     Value *Pointer = SI->getPointerOperand();
374     
375     // Peephole optimize the following instructions:
376     // %t1 = getelementptr {<...>} * %StructPtr, <element indices>
377     // store <elementty> %v, <elementty> * %t1
378     //
379     // Into: store <elementty> %v, {<...>} * %StructPtr, <element indices>
380     //
381     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Pointer)) {
382       // Append any indices that the store instruction has onto the end of the
383       // ones that the GEP is carrying...
384       //
385       vector<Value*> Indices(GEP->copyIndices());
386       Indices.insert(Indices.end(), SI->idx_begin(), SI->idx_end());
387
388       PRINT_PEEPHOLE2("gep-store:in", GEP, SI);
389       ReplaceInstWithInst(BB->getInstList(), BI,
390                           SI = new StoreInst(Val, GEP->getPointerOperand(),
391                                              Indices));
392       PRINT_PEEPHOLE1("gep-store:out", SI);
393       return true;
394     }
395     
396     // Peephole optimize the following instructions:
397     // %t = cast <T1>* %P to <T2> * ;; If T1 is losslessly convertable to T2
398     // store <T2> %V, <T2>* %t
399     //
400     // Into: 
401     // %t = cast <T2> %V to <T1>
402     // store <T1> %t2, <T1>* %P
403     //
404     if (CastInst *CI = dyn_cast<CastInst>(Pointer))
405       if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
406         if (PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
407           // convertable types?
408           if (Val->getType()->isLosslesslyConvertableTo(CSPT->getElementType()) &&
409               !SI->hasIndices()) {      // No subscripts yet!
410             PRINT_PEEPHOLE3("st-src-cast:in ", Pointer, Val, SI);
411
412             // Insert the new T cast instruction... stealing old T's name
413             CastInst *NCI = new CastInst(Val, CSPT->getElementType(),
414                                          CI->getName());
415             CI->setName("");
416             BI = BB->getInstList().insert(BI, NCI)+1;
417
418             // Replace the old store with a new one!
419             ReplaceInstWithInst(BB->getInstList(), BI,
420                                 SI = new StoreInst(NCI, CastSrc));
421             PRINT_PEEPHOLE3("st-src-cast:out", NCI, CastSrc, SI);
422             return true;
423           }
424
425
426   } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
427     Value *Pointer = LI->getPointerOperand();
428     
429     // Peephole optimize the following instructions:
430     // %t1 = getelementptr {<...>} * %StructPtr, <element indices>
431     // %V  = load <elementty> * %t1
432     //
433     // Into: load {<...>} * %StructPtr, <element indices>
434     //
435     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Pointer)) {
436       // Append any indices that the load instruction has onto the end of the
437       // ones that the GEP is carrying...
438       //
439       vector<Value*> Indices(GEP->copyIndices());
440       Indices.insert(Indices.end(), LI->idx_begin(), LI->idx_end());
441
442       PRINT_PEEPHOLE2("gep-load:in", GEP, LI);
443       ReplaceInstWithInst(BB->getInstList(), BI,
444                           LI = new LoadInst(GEP->getPointerOperand(),
445                                             Indices));
446       PRINT_PEEPHOLE1("gep-load:out", LI);
447       return true;
448     }
449
450 #if 0
451     // Peephole optimize the following instructions:
452     // %t1 = cast <ty> * %t0 to <ty2> *
453     // %V  = load <ty2> * %t1
454     //
455     // Into: %t1 = load <ty> * %t0
456     //       %V  = cast <ty> %t1 to <ty2>
457     //
458     // The idea behind this transformation is that if the expression type
459     // conversion engine could not convert the cast into some other nice form,
460     // that there is something fundementally wrong with the current shape of
461     // the program.  Move the cast through the load and try again.  This will
462     // leave the original cast instruction, to presumably become dead.
463     //
464     if (CastInst *CI = dyn_cast<CastInst>(Pointer)) {
465       Value *SrcVal = CI->getOperand(0);
466       const PointerType *SrcTy = dyn_cast<PointerType>(SrcVal->getType());
467       const Type *ElTy = SrcTy ? SrcTy->getElementType() : 0;
468
469       // Make sure that nothing will be lost in the new cast...
470       if (!LI->hasIndices() && SrcTy &&
471           ElTy->isLosslesslyConvertableTo(LI->getType())) {
472         PRINT_PEEPHOLE2("CL-LoadCast:in ", CI, LI);
473
474         string CName = CI->getName(); CI->setName("");
475         LoadInst *NLI = new LoadInst(SrcVal, LI->getName());
476         LI->setName("");  // Take over the old load's name
477
478         // Insert the load before the old load
479         BI = BB->getInstList().insert(BI, NLI)+1;
480
481         // Replace the old load with a new cast...
482         ReplaceInstWithInst(BB->getInstList(), BI, 
483                             CI = new CastInst(NLI, LI->getType(), CName));
484         PRINT_PEEPHOLE2("CL-LoadCast:out", NLI, CI);
485
486         return true;
487       }
488     }
489 #endif
490   } else if (I->getOpcode() == Instruction::Add &&
491              isa<CastInst>(I->getOperand(1))) {
492
493     if (PeepholeOptimizeAddCast(BB, BI, I->getOperand(0),
494                                 cast<CastInst>(I->getOperand(1))))
495       return true;
496
497 #endif
498   }
499
500   return false;
501 }
502
503
504
505
506 static bool DoRaisePass(Method *M) {
507   bool Changed = false;
508   for (Method::iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI) {
509     BasicBlock *BB = *MI;
510     BasicBlock::InstListType &BIL = BB->getInstList();
511
512     for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
513       if (opt::DeadCodeElimination::dceInstruction(BIL, BI) ||
514           opt::ConstantPropogation::doConstantPropogation(BB, BI)) {
515         Changed = true; 
516 #ifdef DEBUG_PEEPHOLE_INSTS
517         cerr << "DeadCode Elinated!\n";
518 #endif
519       } else if (PeepholeOptimize(BB, BI))
520         Changed = true;
521       else
522         ++BI;
523     }
524   }
525   return Changed;
526 }
527
528
529
530
531 // DoInsertArrayCast - If the argument value has a pointer type, and if the
532 // argument value is used as an array, insert a cast before the specified 
533 // basic block iterator that casts the value to an array pointer.  Return the
534 // new cast instruction (in the CastResult var), or null if no cast is inserted.
535 //
536 static bool DoInsertArrayCast(Value *V, BasicBlock *BB,
537                               BasicBlock::iterator InsertBefore) {
538   const PointerType *ThePtrType = dyn_cast<PointerType>(V->getType());
539   if (!ThePtrType) return false;
540
541   const Type *ElTy = ThePtrType->getElementType();
542   if (isa<MethodType>(ElTy) || isa<ArrayType>(ElTy)) return false;
543
544   unsigned ElementSize = TD.getTypeSize(ElTy);
545   bool InsertCast = false;
546
547   for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I) {
548     Instruction *Inst = cast<Instruction>(*I);
549     switch (Inst->getOpcode()) {
550     case Instruction::Cast:          // There is already a cast instruction!
551       if (const PointerType *PT = dyn_cast<const PointerType>(Inst->getType()))
552         if (const ArrayType *AT = dyn_cast<const ArrayType>(PT->getElementType()))
553           if (AT->getElementType() == ThePtrType->getElementType()) {
554             // Cast already exists! Don't mess around with it.
555             return false;       // No changes made to program though...
556           }
557       break;
558     case Instruction::Add: {         // Analyze pointer arithmetic...
559       Value *OtherOp = Inst->getOperand(Inst->getOperand(0) == V);
560       analysis::ExprType Expr = analysis::ClassifyExpression(OtherOp);
561
562       // This looks like array addressing iff:
563       //   A. The constant of the index is larger than the size of the element
564       //      type.
565       //   B. The scale factor is >= the size of the type.
566       //
567       if (Expr.Offset && getConstantValue(Expr.Offset) >= (int)ElementSize) // A
568         InsertCast = true;
569
570       if (Expr.Scale && getConstantValue(Expr.Scale) >= (int)ElementSize) // B
571         InsertCast = true;
572
573       break;
574     }
575     default: break;                  // Not an interesting use...
576     }
577   }
578
579   if (!InsertCast) return false;  // There is no reason to insert a cast!
580
581   // Calculate the destination pointer type
582   const PointerType *DestTy = PointerType::get(ArrayType::get(ElTy));
583
584   // Check to make sure that all uses of the value can be converted over to use
585   // the newly typed value.
586   //
587   ValueTypeCache ConvertedTypes;
588   if (!ValueConvertableToType(V, DestTy, ConvertedTypes)) {
589     cerr << "FAILED to convert types of values for " << V << "\n";
590     ConvertedTypes.clear();
591     ValueConvertableToType(V, DestTy, ConvertedTypes);
592     return false;
593   }
594   ConvertedTypes.clear();
595
596   // Insert a cast!
597   CastInst *TheCast = 
598     new CastInst(Constant::getNullConstant(V->getType()), DestTy, V->getName());
599   BB->getInstList().insert(InsertBefore, TheCast);
600
601 #ifdef DEBUG_PEEPHOLE_INSTS
602   cerr << "Inserting cast for " << V << endl;
603 #endif
604
605   // Convert users of the old value over to use the cast result...
606   ValueMapCache VMC;
607   ConvertValueToNewType(V, TheCast, VMC);
608
609   // The cast is the only thing that is allowed to reference the value...
610   TheCast->setOperand(0, V);
611
612 #ifdef DEBUG_PEEPHOLE_INSTS
613   cerr << "Inserted ptr-array cast: " << TheCast;
614 #endif
615   return true;            // Made a change!
616 }
617
618
619 // DoInsertArrayCasts - Loop over all "incoming" values in the specified method,
620 // inserting a cast for pointer values that are used as arrays. For our
621 // purposes, an incoming value is considered to be either a value that is 
622 // either a method parameter, or a pointer returned from a function call.
623 //
624 static bool DoInsertArrayCasts(Method *M) {
625   assert(!M->isExternal() && "Can't handle external methods!");
626
627   // Insert casts for all arguments to the function...
628   bool Changed = false;
629   BasicBlock *CurBB = M->front();
630
631   for (Method::ArgumentListType::iterator AI = M->getArgumentList().begin(), 
632          AE = M->getArgumentList().end(); AI != AE; ++AI) {
633
634     Changed |= DoInsertArrayCast(*AI, CurBB, CurBB->begin());
635   }
636
637   // TODO: insert casts for alloca, malloc, and function call results.  Also, 
638   // look for pointers that already have casts, to add to the map.
639
640 #ifdef DEBUG_PEEPHOLE_INSTS
641   if (Changed) cerr << "Inserted casts:\n" << M;
642 #endif
643
644   return Changed;
645 }
646
647
648
649
650 // RaisePointerReferences::doit - Raise a method representation to a higher
651 // level.
652 //
653 bool RaisePointerReferences::doit(Method *M) {
654   if (M->isExternal()) return false;
655
656 #ifdef DEBUG_PEEPHOLE_INSTS
657   cerr << "\n\n\nStarting to work on Method '" << M->getName() << "'\n";
658 #endif
659
660   // Insert casts for all incoming pointer pointer values that are treated as
661   // arrays...
662   //
663   bool Changed = false, LocalChange;
664   
665   do {
666 #ifdef DEBUG_PEEPHOLE_INSTS
667     cerr << "Looping: \n" << M;
668 #endif
669     LocalChange = DoInsertArrayCasts(M);
670
671     // Iterate over the method, refining it, until it converges on a stable
672     // state
673     while (DoRaisePass(M)) LocalChange = true;
674     Changed |= LocalChange;
675
676   } while (LocalChange);
677
678   return Changed;
679 }