* Remove dead code from ExprTypeConvert.cpp
[oota-llvm.git] / lib / Transforms / ExprTypeConvert.cpp
1 //===- ExprTypeConvert.cpp - Code to change an LLVM Expr Type ---------------=//
2 //
3 // This file implements the part of level raising that checks to see if it is
4 // possible to coerce an entire expression tree into a different type.  If
5 // convertable, other routines from this file will do the conversion.
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include "TransformInternals.h"
10 #include "llvm/iOther.h"
11 #include "llvm/iPHINode.h"
12 #include "llvm/iMemory.h"
13 #include "llvm/ConstantHandling.h"
14 #include "llvm/Analysis/Expressions.h"
15 #include "Support/STLExtras.h"
16 #include "Support/StatisticReporter.h"
17 #include <algorithm>
18 #include <iostream>
19 using std::cerr;
20
21 static bool OperandConvertableToType(User *U, Value *V, const Type *Ty,
22                                      ValueTypeCache &ConvertedTypes);
23
24 static void ConvertOperandToType(User *U, Value *OldVal, Value *NewVal,
25                                  ValueMapCache &VMC);
26
27 // AllIndicesZero - Return true if all of the indices of the specified memory
28 // access instruction are zero, indicating an effectively nil offset to the 
29 // pointer value.
30 //
31 static bool AllIndicesZero(const MemAccessInst *MAI) {
32   for (User::const_op_iterator S = MAI->idx_begin(), E = MAI->idx_end();
33        S != E; ++S)
34     if (!isa<Constant>(S->get()) || !cast<Constant>(S->get())->isNullValue())
35       return false;
36   return true;
37 }
38
39
40 // Peephole Malloc instructions: we take a look at the use chain of the
41 // malloc instruction, and try to find out if the following conditions hold:
42 //   1. The malloc is of the form: 'malloc [sbyte], uint <constant>'
43 //   2. The only users of the malloc are cast & add instructions
44 //   3. Of the cast instructions, there is only one destination pointer type
45 //      [RTy] where the size of the pointed to object is equal to the number
46 //      of bytes allocated.
47 //
48 // If these conditions hold, we convert the malloc to allocate an [RTy]
49 // element.  TODO: This comment is out of date WRT arrays
50 //
51 static bool MallocConvertableToType(MallocInst *MI, const Type *Ty,
52                                     ValueTypeCache &CTMap) {
53   if (!isa<PointerType>(Ty)) return false;   // Malloc always returns pointers
54
55   // Deal with the type to allocate, not the pointer type...
56   Ty = cast<PointerType>(Ty)->getElementType();
57   if (!Ty->isSized()) return false;      // Can only alloc something with a size
58
59   // Analyze the number of bytes allocated...
60   analysis::ExprType Expr = analysis::ClassifyExpression(MI->getArraySize());
61
62   // Get information about the base datatype being allocated, before & after
63   int ReqTypeSize = TD.getTypeSize(Ty);
64   unsigned OldTypeSize = TD.getTypeSize(MI->getType()->getElementType());
65
66   // Must have a scale or offset to analyze it...
67   if (!Expr.Offset && !Expr.Scale && OldTypeSize == 1) return false;
68
69   // Get the offset and scale of the allocation...
70   int OffsetVal = Expr.Offset ? getConstantValue(Expr.Offset) : 0;
71   int ScaleVal = Expr.Scale ? getConstantValue(Expr.Scale) : (Expr.Var ? 1 : 0);
72
73   // The old type might not be of unit size, take old size into consideration
74   // here...
75   int Offset = OffsetVal * OldTypeSize;
76   int Scale  = ScaleVal  * OldTypeSize;
77   
78   // In order to be successful, both the scale and the offset must be a multiple
79   // of the requested data type's size.
80   //
81   if (Offset/ReqTypeSize*ReqTypeSize != Offset ||
82       Scale/ReqTypeSize*ReqTypeSize != Scale)
83     return false;   // Nope.
84
85   return true;
86 }
87
88 static Instruction *ConvertMallocToType(MallocInst *MI, const Type *Ty,
89                                         const std::string &Name,
90                                         ValueMapCache &VMC){
91   BasicBlock *BB = MI->getParent();
92   BasicBlock::iterator It = BB->end();
93
94   // Analyze the number of bytes allocated...
95   analysis::ExprType Expr = analysis::ClassifyExpression(MI->getArraySize());
96
97   const PointerType *AllocTy = cast<PointerType>(Ty);
98   const Type *ElType = AllocTy->getElementType();
99
100   unsigned DataSize = TD.getTypeSize(ElType);
101   unsigned OldTypeSize = TD.getTypeSize(MI->getType()->getElementType());
102
103   // Get the offset and scale coefficients that we are allocating...
104   int OffsetVal = (Expr.Offset ? getConstantValue(Expr.Offset) : 0);
105   int ScaleVal = Expr.Scale ? getConstantValue(Expr.Scale) : (Expr.Var ? 1 : 0);
106
107   // The old type might not be of unit size, take old size into consideration
108   // here...
109   unsigned Offset = (unsigned)OffsetVal * OldTypeSize / DataSize;
110   unsigned Scale  = (unsigned)ScaleVal  * OldTypeSize / DataSize;
111
112   // Locate the malloc instruction, because we may be inserting instructions
113   It = MI;
114
115   // If we have a scale, apply it first...
116   if (Expr.Var) {
117     // Expr.Var is not neccesarily unsigned right now, insert a cast now.
118     if (Expr.Var->getType() != Type::UIntTy) {
119       Instruction *CI = new CastInst(Expr.Var, Type::UIntTy);
120       if (Expr.Var->hasName()) CI->setName(Expr.Var->getName()+"-uint");
121       It = ++BB->getInstList().insert(It, CI);
122       Expr.Var = CI;
123     }
124
125     if (Scale != 1) {
126       Instruction *ScI =
127         BinaryOperator::create(Instruction::Mul, Expr.Var,
128                                ConstantUInt::get(Type::UIntTy, Scale));
129       if (Expr.Var->hasName()) ScI->setName(Expr.Var->getName()+"-scl");
130       It = ++BB->getInstList().insert(It, ScI);
131       Expr.Var = ScI;
132     }
133
134   } else {
135     // If we are not scaling anything, just make the offset be the "var"...
136     Expr.Var = ConstantUInt::get(Type::UIntTy, Offset);
137     Offset = 0; Scale = 1;
138   }
139
140   // If we have an offset now, add it in...
141   if (Offset != 0) {
142     assert(Expr.Var && "Var must be nonnull by now!");
143
144     Instruction *AddI =
145       BinaryOperator::create(Instruction::Add, Expr.Var,
146                              ConstantUInt::get(Type::UIntTy, Offset));
147     if (Expr.Var->hasName()) AddI->setName(Expr.Var->getName()+"-off");
148     It = ++BB->getInstList().insert(It, AddI);
149     Expr.Var = AddI;
150   }
151
152   Instruction *NewI = new MallocInst(AllocTy, Expr.Var, Name);
153
154   assert(AllocTy == Ty);
155   return NewI;
156 }
157
158
159 // ExpressionConvertableToType - Return true if it is possible
160 bool ExpressionConvertableToType(Value *V, const Type *Ty,
161                                  ValueTypeCache &CTMap) {
162   if (V->getType() == Ty) return true;  // Expression already correct type!
163
164   // Expression type must be holdable in a register.
165   if (!Ty->isFirstClassType())
166     return false;
167   
168   ValueTypeCache::iterator CTMI = CTMap.find(V);
169   if (CTMI != CTMap.end()) return CTMI->second == Ty;
170
171   CTMap[V] = Ty;
172
173   Instruction *I = dyn_cast<Instruction>(V);
174   if (I == 0) {
175     // It's not an instruction, check to see if it's a constant... all constants
176     // can be converted to an equivalent value (except pointers, they can't be
177     // const prop'd in general).  We just ask the constant propogator to see if
178     // it can convert the value...
179     //
180     if (Constant *CPV = dyn_cast<Constant>(V))
181       if (ConstantFoldCastInstruction(CPV, Ty))
182         return true;  // Don't worry about deallocating, it's a constant.
183
184     return false;              // Otherwise, we can't convert!
185   }
186
187   switch (I->getOpcode()) {
188   case Instruction::Cast:
189     // We can convert the expr if the cast destination type is losslessly
190     // convertable to the requested type.
191     if (!Ty->isLosslesslyConvertableTo(I->getType())) return false;
192
193     // We also do not allow conversion of a cast that casts from a ptr to array
194     // of X to a *X.  For example: cast [4 x %List *] * %val to %List * *
195     //
196     if (const PointerType *SPT = 
197         dyn_cast<PointerType>(I->getOperand(0)->getType()))
198       if (const PointerType *DPT = dyn_cast<PointerType>(I->getType()))
199         if (const ArrayType *AT = dyn_cast<ArrayType>(SPT->getElementType()))
200           if (AT->getElementType() == DPT->getElementType())
201             return false;
202     break;
203
204   case Instruction::Add:
205   case Instruction::Sub:
206     if (!ExpressionConvertableToType(I->getOperand(0), Ty, CTMap) ||
207         !ExpressionConvertableToType(I->getOperand(1), Ty, CTMap))
208       return false;
209     break;
210   case Instruction::Shr:
211     if (Ty->isSigned() != V->getType()->isSigned()) return false;
212     // FALL THROUGH
213   case Instruction::Shl:
214     if (!ExpressionConvertableToType(I->getOperand(0), Ty, CTMap))
215       return false;
216     break;
217
218   case Instruction::Load: {
219     LoadInst *LI = cast<LoadInst>(I);
220     if (LI->hasIndices() && !AllIndicesZero(LI)) {
221       // We can't convert a load expression if it has indices... unless they are
222       // all zero.
223       return false;
224     }
225
226     if (!ExpressionConvertableToType(LI->getPointerOperand(),
227                                      PointerType::get(Ty), CTMap))
228       return false;
229     break;                                     
230   }
231   case Instruction::PHINode: {
232     PHINode *PN = cast<PHINode>(I);
233     for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i)
234       if (!ExpressionConvertableToType(PN->getIncomingValue(i), Ty, CTMap))
235         return false;
236     break;
237   }
238
239   case Instruction::Malloc:
240     if (!MallocConvertableToType(cast<MallocInst>(I), Ty, CTMap))
241       return false;
242     break;
243
244   case Instruction::GetElementPtr: {
245     // GetElementPtr's are directly convertable to a pointer type if they have
246     // a number of zeros at the end.  Because removing these values does not
247     // change the logical offset of the GEP, it is okay and fair to remove them.
248     // This can change this:
249     //   %t1 = getelementptr %Hosp * %hosp, ubyte 4, ubyte 0  ; <%List **>
250     //   %t2 = cast %List * * %t1 to %List *
251     // into
252     //   %t2 = getelementptr %Hosp * %hosp, ubyte 4           ; <%List *>
253     // 
254     GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
255     const PointerType *PTy = dyn_cast<PointerType>(Ty);
256     if (!PTy) return false;  // GEP must always return a pointer...
257     const Type *PVTy = PTy->getElementType();
258
259     // Check to see if there are zero elements that we can remove from the
260     // index array.  If there are, check to see if removing them causes us to
261     // get to the right type...
262     //
263     std::vector<Value*> Indices = GEP->copyIndices();
264     const Type *BaseType = GEP->getPointerOperand()->getType();
265     const Type *ElTy = 0;
266
267     while (!Indices.empty() && isa<ConstantUInt>(Indices.back()) &&
268            cast<ConstantUInt>(Indices.back())->getValue() == 0) {
269       Indices.pop_back();
270       ElTy = GetElementPtrInst::getIndexedType(BaseType, Indices, true);
271       if (ElTy == PVTy)
272         break;  // Found a match!!
273       ElTy = 0;
274     }
275
276     if (ElTy) break;   // Found a number of zeros we can strip off!
277
278     // Otherwise, we can convert a GEP from one form to the other iff the
279     // current gep is of the form 'getelementptr sbyte*, unsigned N
280     // and we could convert this to an appropriate GEP for the new type.
281     //
282     if (GEP->getNumOperands() == 2 &&
283         GEP->getOperand(1)->getType() == Type::UIntTy &&
284         GEP->getType() == PointerType::get(Type::SByteTy)) {
285
286       // Do not Check to see if our incoming pointer can be converted
287       // to be a ptr to an array of the right type... because in more cases than
288       // not, it is simply not analyzable because of pointer/array
289       // discrepencies.  To fix this, we will insert a cast before the GEP.
290       //
291
292       // Check to see if 'N' is an expression that can be converted to
293       // the appropriate size... if so, allow it.
294       //
295       std::vector<Value*> Indices;
296       const Type *ElTy = ConvertableToGEP(PTy, I->getOperand(1), Indices);
297       if (ElTy == PVTy) {
298         if (!ExpressionConvertableToType(I->getOperand(0),
299                                          PointerType::get(ElTy), CTMap))
300           return false;  // Can't continue, ExConToTy might have polluted set!
301         break;
302       }
303     }
304
305     // Otherwise, it could be that we have something like this:
306     //     getelementptr [[sbyte] *] * %reg115, uint %reg138    ; [sbyte]**
307     // and want to convert it into something like this:
308     //     getelemenptr [[int] *] * %reg115, uint %reg138      ; [int]**
309     //
310     if (GEP->getNumOperands() == 2 && 
311         GEP->getOperand(1)->getType() == Type::UIntTy &&
312         TD.getTypeSize(PTy->getElementType()) == 
313         TD.getTypeSize(GEP->getType()->getElementType())) {
314       const PointerType *NewSrcTy = PointerType::get(PVTy);
315       if (!ExpressionConvertableToType(I->getOperand(0), NewSrcTy, CTMap))
316         return false;
317       break;
318     }
319
320     return false;   // No match, maybe next time.
321   }
322
323   default:
324     return false;
325   }
326
327   // Expressions are only convertable if all of the users of the expression can
328   // have this value converted.  This makes use of the map to avoid infinite
329   // recursion.
330   //
331   for (Value::use_iterator It = I->use_begin(), E = I->use_end(); It != E; ++It)
332     if (!OperandConvertableToType(*It, I, Ty, CTMap))
333       return false;
334
335   return true;
336 }
337
338
339 Value *ConvertExpressionToType(Value *V, const Type *Ty, ValueMapCache &VMC) {
340   if (V->getType() == Ty) return V;  // Already where we need to be?
341
342   ValueMapCache::ExprMapTy::iterator VMCI = VMC.ExprMap.find(V);
343   if (VMCI != VMC.ExprMap.end()) {
344     assert(VMCI->second->getType() == Ty);
345
346     if (Instruction *I = dyn_cast<Instruction>(V))
347       ValueHandle IHandle(VMC, I);  // Remove I if it is unused now!
348
349     return VMCI->second;
350   }
351
352   DEBUG(cerr << "CETT: " << (void*)V << " " << V);
353
354   Instruction *I = dyn_cast<Instruction>(V);
355   if (I == 0)
356     if (Constant *CPV = cast<Constant>(V)) {
357       // Constants are converted by constant folding the cast that is required.
358       // We assume here that all casts are implemented for constant prop.
359       Value *Result = ConstantFoldCastInstruction(CPV, Ty);
360       assert(Result && "ConstantFoldCastInstruction Failed!!!");
361       assert(Result->getType() == Ty && "Const prop of cast failed!");
362
363       // Add the instruction to the expression map
364       VMC.ExprMap[V] = Result;
365       return Result;
366     }
367
368
369   BasicBlock *BB = I->getParent();
370   BasicBlock::InstListType &BIL = BB->getInstList();
371   std::string Name = I->getName();  if (!Name.empty()) I->setName("");
372   Instruction *Res;     // Result of conversion
373
374   ValueHandle IHandle(VMC, I);  // Prevent I from being removed!
375   
376   Constant *Dummy = Constant::getNullValue(Ty);
377
378   switch (I->getOpcode()) {
379   case Instruction::Cast:
380     assert(VMC.NewCasts.count(ValueHandle(VMC, I)) == 0);
381     Res = new CastInst(I->getOperand(0), Ty, Name);
382     VMC.NewCasts.insert(ValueHandle(VMC, Res));
383     break;
384     
385   case Instruction::Add:
386   case Instruction::Sub:
387     Res = BinaryOperator::create(cast<BinaryOperator>(I)->getOpcode(),
388                                  Dummy, Dummy, Name);
389     VMC.ExprMap[I] = Res;   // Add node to expression eagerly
390
391     Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), Ty, VMC));
392     Res->setOperand(1, ConvertExpressionToType(I->getOperand(1), Ty, VMC));
393     break;
394
395   case Instruction::Shl:
396   case Instruction::Shr:
397     Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(), Dummy,
398                         I->getOperand(1), Name);
399     VMC.ExprMap[I] = Res;
400     Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), Ty, VMC));
401     break;
402
403   case Instruction::Load: {
404     LoadInst *LI = cast<LoadInst>(I);
405     assert(!LI->hasIndices() || AllIndicesZero(LI));
406
407     Res = new LoadInst(Constant::getNullValue(PointerType::get(Ty)), Name);
408     VMC.ExprMap[I] = Res;
409     Res->setOperand(0, ConvertExpressionToType(LI->getPointerOperand(),
410                                                PointerType::get(Ty), VMC));
411     assert(Res->getOperand(0)->getType() == PointerType::get(Ty));
412     assert(Ty == Res->getType());
413     assert(Res->getType()->isFirstClassType() && "Load of structure or array!");
414     break;
415   }
416
417   case Instruction::PHINode: {
418     PHINode *OldPN = cast<PHINode>(I);
419     PHINode *NewPN = new PHINode(Ty, Name);
420
421     VMC.ExprMap[I] = NewPN;   // Add node to expression eagerly
422     while (OldPN->getNumOperands()) {
423       BasicBlock *BB = OldPN->getIncomingBlock(0);
424       Value *OldVal = OldPN->getIncomingValue(0);
425       ValueHandle OldValHandle(VMC, OldVal);
426       OldPN->removeIncomingValue(BB);
427       Value *V = ConvertExpressionToType(OldVal, Ty, VMC);
428       NewPN->addIncoming(V, BB);
429     }
430     Res = NewPN;
431     break;
432   }
433
434   case Instruction::Malloc: {
435     Res = ConvertMallocToType(cast<MallocInst>(I), Ty, Name, VMC);
436     break;
437   }
438
439   case Instruction::GetElementPtr: {
440     // GetElementPtr's are directly convertable to a pointer type if they have
441     // a number of zeros at the end.  Because removing these values does not
442     // change the logical offset of the GEP, it is okay and fair to remove them.
443     // This can change this:
444     //   %t1 = getelementptr %Hosp * %hosp, ubyte 4, ubyte 0  ; <%List **>
445     //   %t2 = cast %List * * %t1 to %List *
446     // into
447     //   %t2 = getelementptr %Hosp * %hosp, ubyte 4           ; <%List *>
448     // 
449     GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
450
451     // Check to see if there are zero elements that we can remove from the
452     // index array.  If there are, check to see if removing them causes us to
453     // get to the right type...
454     //
455     std::vector<Value*> Indices = GEP->copyIndices();
456     const Type *BaseType = GEP->getPointerOperand()->getType();
457     const Type *PVTy = cast<PointerType>(Ty)->getElementType();
458     Res = 0;
459     while (!Indices.empty() && isa<ConstantUInt>(Indices.back()) &&
460            cast<ConstantUInt>(Indices.back())->getValue() == 0) {
461       Indices.pop_back();
462       if (GetElementPtrInst::getIndexedType(BaseType, Indices, true) == PVTy) {
463         if (Indices.size() == 0) {
464           Res = new CastInst(GEP->getPointerOperand(), BaseType); // NOOP
465         } else {
466           Res = new GetElementPtrInst(GEP->getPointerOperand(), Indices, Name);
467         }
468         break;
469       }
470     }
471
472     if (Res == 0 && GEP->getNumOperands() == 2 &&
473         GEP->getOperand(1)->getType() == Type::UIntTy &&
474         GEP->getType() == PointerType::get(Type::SByteTy)) {
475       
476       // Otherwise, we can convert a GEP from one form to the other iff the
477       // current gep is of the form 'getelementptr [sbyte]*, unsigned N
478       // and we could convert this to an appropriate GEP for the new type.
479       //
480       const PointerType *NewSrcTy = PointerType::get(PVTy);
481       BasicBlock::iterator It = I;
482
483       // Check to see if 'N' is an expression that can be converted to
484       // the appropriate size... if so, allow it.
485       //
486       std::vector<Value*> Indices;
487       const Type *ElTy = ConvertableToGEP(NewSrcTy, I->getOperand(1),
488                                           Indices, &It);
489       if (ElTy) {        
490         assert(ElTy == PVTy && "Internal error, setup wrong!");
491         Res = new GetElementPtrInst(Constant::getNullValue(NewSrcTy),
492                                     Indices, Name);
493         VMC.ExprMap[I] = Res;
494         Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
495                                                    NewSrcTy, VMC));
496       }
497     }
498
499     // Otherwise, it could be that we have something like this:
500     //     getelementptr [[sbyte] *] * %reg115, uint %reg138    ; [sbyte]**
501     // and want to convert it into something like this:
502     //     getelemenptr [[int] *] * %reg115, uint %reg138      ; [int]**
503     //
504     if (Res == 0) {
505       const PointerType *NewSrcTy = PointerType::get(PVTy);
506       Res = new GetElementPtrInst(Constant::getNullValue(NewSrcTy),
507                                   GEP->copyIndices(), Name);
508       VMC.ExprMap[I] = Res;
509       Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
510                                                  NewSrcTy, VMC));
511     }
512
513
514     assert(Res && "Didn't find match!");
515     break;   // No match, maybe next time.
516   }
517
518   default:
519     assert(0 && "Expression convertable, but don't know how to convert?");
520     return 0;
521   }
522
523   assert(Res->getType() == Ty && "Didn't convert expr to correct type!");
524
525   BIL.insert(I, Res);
526
527   // Add the instruction to the expression map
528   VMC.ExprMap[I] = Res;
529
530   // Expressions are only convertable if all of the users of the expression can
531   // have this value converted.  This makes use of the map to avoid infinite
532   // recursion.
533   //
534   unsigned NumUses = I->use_size();
535   for (unsigned It = 0; It < NumUses; ) {
536     unsigned OldSize = NumUses;
537     ConvertOperandToType(*(I->use_begin()+It), I, Res, VMC);
538     NumUses = I->use_size();
539     if (NumUses == OldSize) ++It;
540   }
541
542   DEBUG(cerr << "ExpIn: " << (void*)I << " " << I
543              << "ExpOut: " << (void*)Res << " " << Res);
544
545   return Res;
546 }
547
548
549
550 // ValueConvertableToType - Return true if it is possible
551 bool ValueConvertableToType(Value *V, const Type *Ty,
552                              ValueTypeCache &ConvertedTypes) {
553   ValueTypeCache::iterator I = ConvertedTypes.find(V);
554   if (I != ConvertedTypes.end()) return I->second == Ty;
555   ConvertedTypes[V] = Ty;
556
557   // It is safe to convert the specified value to the specified type IFF all of
558   // the uses of the value can be converted to accept the new typed value.
559   //
560   if (V->getType() != Ty) {
561     for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I)
562       if (!OperandConvertableToType(*I, V, Ty, ConvertedTypes))
563         return false;
564   }
565
566   return true;
567 }
568
569
570
571
572
573 // OperandConvertableToType - Return true if it is possible to convert operand
574 // V of User (instruction) U to the specified type.  This is true iff it is
575 // possible to change the specified instruction to accept this.  CTMap is a map
576 // of converted types, so that circular definitions will see the future type of
577 // the expression, not the static current type.
578 //
579 static bool OperandConvertableToType(User *U, Value *V, const Type *Ty,
580                                      ValueTypeCache &CTMap) {
581   //  if (V->getType() == Ty) return true;   // Operand already the right type?
582
583   // Expression type must be holdable in a register.
584   if (!Ty->isFirstClassType())
585     return false;
586
587   Instruction *I = dyn_cast<Instruction>(U);
588   if (I == 0) return false;              // We can't convert!
589
590   switch (I->getOpcode()) {
591   case Instruction::Cast:
592     assert(I->getOperand(0) == V);
593     // We can convert the expr if the cast destination type is losslessly
594     // convertable to the requested type.
595     // Also, do not change a cast that is a noop cast.  For all intents and
596     // purposes it should be eliminated.
597     if (!Ty->isLosslesslyConvertableTo(I->getOperand(0)->getType()) ||
598         I->getType() == I->getOperand(0)->getType())
599       return false;
600
601     // Do not allow a 'cast ushort %V to uint' to have it's first operand be
602     // converted to a 'short' type.  Doing so changes the way sign promotion
603     // happens, and breaks things.  Only allow the cast to take place if the
604     // signedness doesn't change... or if the current cast is not a lossy
605     // conversion.
606     //
607     if (!I->getType()->isLosslesslyConvertableTo(I->getOperand(0)->getType()) &&
608         I->getOperand(0)->getType()->isSigned() != Ty->isSigned())
609       return false;
610
611     // We also do not allow conversion of a cast that casts from a ptr to array
612     // of X to a *X.  For example: cast [4 x %List *] * %val to %List * *
613     //
614     if (const PointerType *SPT = 
615         dyn_cast<PointerType>(I->getOperand(0)->getType()))
616       if (const PointerType *DPT = dyn_cast<PointerType>(I->getType()))
617         if (const ArrayType *AT = dyn_cast<ArrayType>(SPT->getElementType()))
618           if (AT->getElementType() == DPT->getElementType())
619             return false;
620     return true;
621
622   case Instruction::Add:
623     if (isa<PointerType>(Ty)) {
624       Value *IndexVal = I->getOperand(V == I->getOperand(0) ? 1 : 0);
625       std::vector<Value*> Indices;
626       if (const Type *ETy = ConvertableToGEP(Ty, IndexVal, Indices)) {
627         const Type *RetTy = PointerType::get(ETy);
628
629         // Only successful if we can convert this type to the required type
630         if (ValueConvertableToType(I, RetTy, CTMap)) {
631           CTMap[I] = RetTy;
632           return true;
633         }
634         // We have to return failure here because ValueConvertableToType could 
635         // have polluted our map
636         return false;
637       }
638     }
639     // FALLTHROUGH
640   case Instruction::Sub: {
641     Value *OtherOp = I->getOperand((V == I->getOperand(0)) ? 1 : 0);
642     return ValueConvertableToType(I, Ty, CTMap) &&
643            ExpressionConvertableToType(OtherOp, Ty, CTMap);
644   }
645   case Instruction::SetEQ:
646   case Instruction::SetNE: {
647     Value *OtherOp = I->getOperand((V == I->getOperand(0)) ? 1 : 0);
648     return ExpressionConvertableToType(OtherOp, Ty, CTMap);
649   }
650   case Instruction::Shr:
651     if (Ty->isSigned() != V->getType()->isSigned()) return false;
652     // FALL THROUGH
653   case Instruction::Shl:
654     assert(I->getOperand(0) == V);
655     return ValueConvertableToType(I, Ty, CTMap);
656
657   case Instruction::Free:
658     assert(I->getOperand(0) == V);
659     return isa<PointerType>(Ty);    // Free can free any pointer type!
660
661   case Instruction::Load:
662     // Cannot convert the types of any subscripts...
663     if (I->getOperand(0) != V) return false;
664
665     if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
666       LoadInst *LI = cast<LoadInst>(I);
667       
668       if (LI->hasIndices() && !AllIndicesZero(LI))
669         return false;
670
671       const Type *LoadedTy = PT->getElementType();
672
673       // They could be loading the first element of a composite type...
674       if (const CompositeType *CT = dyn_cast<CompositeType>(LoadedTy)) {
675         unsigned Offset = 0;     // No offset, get first leaf.
676         std::vector<Value*> Indices;  // Discarded...
677         LoadedTy = getStructOffsetType(CT, Offset, Indices, false);
678         assert(Offset == 0 && "Offset changed from zero???");
679       }
680
681       if (!LoadedTy->isFirstClassType())
682         return false;
683
684       if (TD.getTypeSize(LoadedTy) != TD.getTypeSize(LI->getType()))
685         return false;
686
687       return ValueConvertableToType(LI, LoadedTy, CTMap);
688     }
689     return false;
690
691   case Instruction::Store: {
692     StoreInst *SI = cast<StoreInst>(I);
693     if (SI->hasIndices()) return false;
694
695     if (V == I->getOperand(0)) {
696       ValueTypeCache::iterator CTMI = CTMap.find(I->getOperand(1));
697       if (CTMI != CTMap.end()) {   // Operand #1 is in the table already?
698         // If so, check to see if it's Ty*, or, more importantly, if it is a
699         // pointer to a structure where the first element is a Ty... this code
700         // is neccesary because we might be trying to change the source and
701         // destination type of the store (they might be related) and the dest
702         // pointer type might be a pointer to structure.  Below we allow pointer
703         // to structures where the 0th element is compatible with the value,
704         // now we have to support the symmetrical part of this.
705         //
706         const Type *ElTy = cast<PointerType>(CTMI->second)->getElementType();
707
708         // Already a pointer to what we want?  Trivially accept...
709         if (ElTy == Ty) return true;
710
711         // Tricky case now, if the destination is a pointer to structure,
712         // obviously the source is not allowed to be a structure (cannot copy
713         // a whole structure at a time), so the level raiser must be trying to
714         // store into the first field.  Check for this and allow it now:
715         //
716         if (const StructType *SElTy = dyn_cast<StructType>(ElTy)) {
717           unsigned Offset = 0;
718           std::vector<Value*> Indices;
719           ElTy = getStructOffsetType(ElTy, Offset, Indices, false);
720           assert(Offset == 0 && "Offset changed!");
721           if (ElTy == 0)    // Element at offset zero in struct doesn't exist!
722             return false;   // Can only happen for {}*
723           
724           if (ElTy == Ty)   // Looks like the 0th element of structure is
725             return true;    // compatible!  Accept now!
726
727           // Otherwise we know that we can't work, so just stop trying now.
728           return false;
729         }
730       }
731
732       // Can convert the store if we can convert the pointer operand to match
733       // the new  value type...
734       return ExpressionConvertableToType(I->getOperand(1), PointerType::get(Ty),
735                                          CTMap);
736     } else if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
737       const Type *ElTy = PT->getElementType();
738       assert(V == I->getOperand(1));
739
740       if (isa<StructType>(ElTy)) {
741         // We can change the destination pointer if we can store our first
742         // argument into the first element of the structure...
743         //
744         unsigned Offset = 0;
745         std::vector<Value*> Indices;
746         ElTy = getStructOffsetType(ElTy, Offset, Indices, false);
747         assert(Offset == 0 && "Offset changed!");
748         if (ElTy == 0)    // Element at offset zero in struct doesn't exist!
749           return false;   // Can only happen for {}*
750       }
751
752       // Must move the same amount of data...
753       if (!ElTy->isSized() || 
754           TD.getTypeSize(ElTy) != TD.getTypeSize(I->getOperand(0)->getType()))
755         return false;
756
757       // Can convert store if the incoming value is convertable...
758       return ExpressionConvertableToType(I->getOperand(0), ElTy, CTMap);
759     }
760     return false;
761   }
762
763   case Instruction::GetElementPtr:
764     if (V != I->getOperand(0) || !isa<PointerType>(Ty)) return false;
765
766     // If we have a two operand form of getelementptr, this is really little
767     // more than a simple addition.  As with addition, check to see if the
768     // getelementptr instruction can be changed to index into the new type.
769     //
770     if (I->getNumOperands() == 2) {
771       const Type *OldElTy = cast<PointerType>(I->getType())->getElementType();
772       unsigned DataSize = TD.getTypeSize(OldElTy);
773       Value *Index = I->getOperand(1);
774       Instruction *TempScale = 0;
775
776       // If the old data element is not unit sized, we have to create a scale
777       // instruction so that ConvertableToGEP will know the REAL amount we are
778       // indexing by.  Note that this is never inserted into the instruction
779       // stream, so we have to delete it when we're done.
780       //
781       if (DataSize != 1) {
782         TempScale = BinaryOperator::create(Instruction::Mul, Index,
783                                            ConstantUInt::get(Type::UIntTy,
784                                                              DataSize));
785         Index = TempScale;
786       }
787
788       // Check to see if the second argument is an expression that can
789       // be converted to the appropriate size... if so, allow it.
790       //
791       std::vector<Value*> Indices;
792       const Type *ElTy = ConvertableToGEP(Ty, Index, Indices);
793       delete TempScale;   // Free our temporary multiply if we made it
794
795       if (ElTy == 0) return false;  // Cannot make conversion...
796       return ValueConvertableToType(I, PointerType::get(ElTy), CTMap);
797     }
798     return false;
799
800   case Instruction::PHINode: {
801     PHINode *PN = cast<PHINode>(I);
802     for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i)
803       if (!ExpressionConvertableToType(PN->getIncomingValue(i), Ty, CTMap))
804         return false;
805     return ValueConvertableToType(PN, Ty, CTMap);
806   }
807
808   case Instruction::Call: {
809     User::op_iterator OI = find(I->op_begin(), I->op_end(), V);
810     assert (OI != I->op_end() && "Not using value!");
811     unsigned OpNum = OI - I->op_begin();
812
813     // Are we trying to change the function pointer value to a new type?
814     if (OpNum == 0) {
815       const PointerType *PTy = dyn_cast<PointerType>(Ty);
816       if (PTy == 0) return false;  // Can't convert to a non-pointer type...
817       const FunctionType *MTy = dyn_cast<FunctionType>(PTy->getElementType());
818       if (MTy == 0) return false;  // Can't convert to a non ptr to function...
819
820       // Perform sanity checks to make sure that new function type has the
821       // correct number of arguments...
822       //
823       unsigned NumArgs = I->getNumOperands()-1;  // Don't include function ptr
824
825       // Cannot convert to a type that requires more fixed arguments than
826       // the call provides...
827       //
828       if (NumArgs < MTy->getParamTypes().size()) return false;
829       
830       // Unless this is a vararg function type, we cannot provide more arguments
831       // than are desired...
832       //
833       if (!MTy->isVarArg() && NumArgs > MTy->getParamTypes().size())
834         return false;
835
836       // Okay, at this point, we know that the call and the function type match
837       // number of arguments.  Now we see if we can convert the arguments
838       // themselves.  Note that we do not require operands to be convertable,
839       // we can insert casts if they are convertible but not compatible.  The
840       // reason for this is that we prefer to have resolved functions but casted
841       // arguments if possible.
842       //
843       const FunctionType::ParamTypes &PTs = MTy->getParamTypes();
844       for (unsigned i = 0, NA = PTs.size(); i < NA; ++i)
845         if (!PTs[i]->isLosslesslyConvertableTo(I->getOperand(i+1)->getType()))
846           return false;   // Operands must have compatible types!
847
848       // Okay, at this point, we know that all of the arguments can be
849       // converted.  We succeed if we can change the return type if
850       // neccesary...
851       //
852       return ValueConvertableToType(I, MTy->getReturnType(), CTMap);
853     }
854     
855     const PointerType *MPtr = cast<PointerType>(I->getOperand(0)->getType());
856     const FunctionType *MTy = cast<FunctionType>(MPtr->getElementType());
857     if (!MTy->isVarArg()) return false;
858
859     if ((OpNum-1) < MTy->getParamTypes().size())
860       return false;  // It's not in the varargs section...
861
862     // If we get this far, we know the value is in the varargs section of the
863     // function!  We can convert if we don't reinterpret the value...
864     //
865     return Ty->isLosslesslyConvertableTo(V->getType());
866   }
867   }
868   return false;
869 }
870
871
872 void ConvertValueToNewType(Value *V, Value *NewVal, ValueMapCache &VMC) {
873   ValueHandle VH(VMC, V);
874
875   unsigned NumUses = V->use_size();
876   for (unsigned It = 0; It < NumUses; ) {
877     unsigned OldSize = NumUses;
878     ConvertOperandToType(*(V->use_begin()+It), V, NewVal, VMC);
879     NumUses = V->use_size();
880     if (NumUses == OldSize) ++It;
881   }
882 }
883
884
885
886 static void ConvertOperandToType(User *U, Value *OldVal, Value *NewVal,
887                                  ValueMapCache &VMC) {
888   if (isa<ValueHandle>(U)) return;  // Valuehandles don't let go of operands...
889
890   if (VMC.OperandsMapped.count(U)) return;
891   VMC.OperandsMapped.insert(U);
892
893   ValueMapCache::ExprMapTy::iterator VMCI = VMC.ExprMap.find(U);
894   if (VMCI != VMC.ExprMap.end())
895     return;
896
897
898   Instruction *I = cast<Instruction>(U);  // Only Instructions convertable
899
900   BasicBlock *BB = I->getParent();
901   assert(BB != 0 && "Instruction not embedded in basic block!");
902   BasicBlock::InstListType &BIL = BB->getInstList();
903   std::string Name = I->getName();
904   I->setName("");
905   Instruction *Res;     // Result of conversion
906
907   //cerr << endl << endl << "Type:\t" << Ty << "\nInst: " << I << "BB Before: " << BB << endl;
908
909   // Prevent I from being removed...
910   ValueHandle IHandle(VMC, I);
911
912   const Type *NewTy = NewVal->getType();
913   Constant *Dummy = (NewTy != Type::VoidTy) ? 
914                   Constant::getNullValue(NewTy) : 0;
915
916   switch (I->getOpcode()) {
917   case Instruction::Cast:
918     if (VMC.NewCasts.count(ValueHandle(VMC, I))) {
919       // This cast has already had it's value converted, causing a new cast to
920       // be created.  We don't want to create YET ANOTHER cast instruction
921       // representing the original one, so just modify the operand of this cast
922       // instruction, which we know is newly created.
923       I->setOperand(0, NewVal);
924       I->setName(Name);  // give I its name back
925       return;
926
927     } else {
928       Res = new CastInst(NewVal, I->getType(), Name);
929     }
930     break;
931
932   case Instruction::Add:
933     if (isa<PointerType>(NewTy)) {
934       Value *IndexVal = I->getOperand(OldVal == I->getOperand(0) ? 1 : 0);
935       std::vector<Value*> Indices;
936       BasicBlock::iterator It = I;
937
938       if (const Type *ETy = ConvertableToGEP(NewTy, IndexVal, Indices, &It)) {
939         // If successful, convert the add to a GEP
940         //const Type *RetTy = PointerType::get(ETy);
941         // First operand is actually the given pointer...
942         Res = new GetElementPtrInst(NewVal, Indices, Name);
943         assert(cast<PointerType>(Res->getType())->getElementType() == ETy &&
944                "ConvertableToGEP broken!");
945         break;
946       }
947     }
948     // FALLTHROUGH
949
950   case Instruction::Sub:
951   case Instruction::SetEQ:
952   case Instruction::SetNE: {
953     Res = BinaryOperator::create(cast<BinaryOperator>(I)->getOpcode(),
954                                  Dummy, Dummy, Name);
955     VMC.ExprMap[I] = Res;   // Add node to expression eagerly
956
957     unsigned OtherIdx = (OldVal == I->getOperand(0)) ? 1 : 0;
958     Value *OtherOp    = I->getOperand(OtherIdx);
959     Value *NewOther   = ConvertExpressionToType(OtherOp, NewTy, VMC);
960
961     Res->setOperand(OtherIdx, NewOther);
962     Res->setOperand(!OtherIdx, NewVal);
963     break;
964   }
965   case Instruction::Shl:
966   case Instruction::Shr:
967     assert(I->getOperand(0) == OldVal);
968     Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(), NewVal,
969                         I->getOperand(1), Name);
970     break;
971
972   case Instruction::Free:            // Free can free any pointer type!
973     assert(I->getOperand(0) == OldVal);
974     Res = new FreeInst(NewVal);
975     break;
976
977
978   case Instruction::Load: {
979     assert(I->getOperand(0) == OldVal && isa<PointerType>(NewVal->getType()));
980     const Type *LoadedTy =
981       cast<PointerType>(NewVal->getType())->getElementType();
982
983     std::vector<Value*> Indices;
984     Indices.push_back(ConstantUInt::get(Type::UIntTy, 0));
985
986     if (const CompositeType *CT = dyn_cast<CompositeType>(LoadedTy)) {
987       unsigned Offset = 0;   // No offset, get first leaf.
988       LoadedTy = getStructOffsetType(CT, Offset, Indices, false);
989     }
990     assert(LoadedTy->isFirstClassType());
991
992     Res = new LoadInst(NewVal, Indices, Name);
993     assert(Res->getType()->isFirstClassType() && "Load of structure or array!");
994     break;
995   }
996
997   case Instruction::Store: {
998     if (I->getOperand(0) == OldVal) {  // Replace the source value
999       const PointerType *NewPT = PointerType::get(NewTy);
1000       Res = new StoreInst(NewVal, Constant::getNullValue(NewPT));
1001       VMC.ExprMap[I] = Res;
1002       Res->setOperand(1, ConvertExpressionToType(I->getOperand(1), NewPT, VMC));
1003     } else {                           // Replace the source pointer
1004       const Type *ValTy = cast<PointerType>(NewTy)->getElementType();
1005       std::vector<Value*> Indices;
1006
1007       if (isa<StructType>(ValTy)) {
1008         unsigned Offset = 0;
1009         Indices.push_back(ConstantUInt::get(Type::UIntTy, 0));
1010         ValTy = getStructOffsetType(ValTy, Offset, Indices, false);
1011         assert(Offset == 0 && ValTy);
1012       }
1013
1014       Res = new StoreInst(Constant::getNullValue(ValTy), NewVal, Indices);
1015       VMC.ExprMap[I] = Res;
1016       Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), ValTy, VMC));
1017     }
1018     break;
1019   }
1020
1021
1022   case Instruction::GetElementPtr: {
1023     // Convert a one index getelementptr into just about anything that is
1024     // desired.
1025     //
1026     BasicBlock::iterator It = I;
1027     const Type *OldElTy = cast<PointerType>(I->getType())->getElementType();
1028     unsigned DataSize = TD.getTypeSize(OldElTy);
1029     Value *Index = I->getOperand(1);
1030
1031     if (DataSize != 1) {
1032       // Insert a multiply of the old element type is not a unit size...
1033       Index = BinaryOperator::create(Instruction::Mul, Index,
1034                                      ConstantUInt::get(Type::UIntTy, DataSize));
1035       It = ++BIL.insert(It, cast<Instruction>(Index));
1036     }
1037
1038     // Perform the conversion now...
1039     //
1040     std::vector<Value*> Indices;
1041     const Type *ElTy = ConvertableToGEP(NewVal->getType(), Index, Indices, &It);
1042     assert(ElTy != 0 && "GEP Conversion Failure!");
1043     Res = new GetElementPtrInst(NewVal, Indices, Name);
1044     assert(Res->getType() == PointerType::get(ElTy) &&
1045            "ConvertableToGet failed!");
1046   }
1047 #if 0
1048     if (I->getType() == PointerType::get(Type::SByteTy)) {
1049       // Convert a getelementptr sbyte * %reg111, uint 16 freely back to
1050       // anything that is a pointer type...
1051       //
1052       BasicBlock::iterator It = I;
1053     
1054       // Check to see if the second argument is an expression that can
1055       // be converted to the appropriate size... if so, allow it.
1056       //
1057       std::vector<Value*> Indices;
1058       const Type *ElTy = ConvertableToGEP(NewVal->getType(), I->getOperand(1),
1059                                           Indices, &It);
1060       assert(ElTy != 0 && "GEP Conversion Failure!");
1061       
1062       Res = new GetElementPtrInst(NewVal, Indices, Name);
1063     } else {
1064       // Convert a getelementptr ulong * %reg123, uint %N
1065       // to        getelementptr  long * %reg123, uint %N
1066       // ... where the type must simply stay the same size...
1067       //
1068       Res = new GetElementPtrInst(NewVal,
1069                                   cast<GetElementPtrInst>(I)->copyIndices(),
1070                                   Name);
1071     }
1072 #endif
1073     break;
1074
1075   case Instruction::PHINode: {
1076     PHINode *OldPN = cast<PHINode>(I);
1077     PHINode *NewPN = new PHINode(NewTy, Name);
1078     VMC.ExprMap[I] = NewPN;
1079
1080     while (OldPN->getNumOperands()) {
1081       BasicBlock *BB = OldPN->getIncomingBlock(0);
1082       Value *OldVal = OldPN->getIncomingValue(0);
1083       OldPN->removeIncomingValue(BB);
1084       Value *V = ConvertExpressionToType(OldVal, NewTy, VMC);
1085       NewPN->addIncoming(V, BB);
1086     }
1087     Res = NewPN;
1088     break;
1089   }
1090
1091   case Instruction::Call: {
1092     Value *Meth = I->getOperand(0);
1093     std::vector<Value*> Params(I->op_begin()+1, I->op_end());
1094
1095     if (Meth == OldVal) {   // Changing the function pointer?
1096       const PointerType *NewPTy = cast<PointerType>(NewVal->getType());
1097       const FunctionType *NewTy = cast<FunctionType>(NewPTy->getElementType());
1098       const FunctionType::ParamTypes &PTs = NewTy->getParamTypes();
1099
1100       // Get an iterator to the call instruction so that we can insert casts for
1101       // operands if needbe.  Note that we do not require operands to be
1102       // convertable, we can insert casts if they are convertible but not
1103       // compatible.  The reason for this is that we prefer to have resolved
1104       // functions but casted arguments if possible.
1105       //
1106       BasicBlock::iterator It = I;
1107
1108       // Convert over all of the call operands to their new types... but only
1109       // convert over the part that is not in the vararg section of the call.
1110       //
1111       for (unsigned i = 0; i < PTs.size(); ++i)
1112         if (Params[i]->getType() != PTs[i]) {
1113           // Create a cast to convert it to the right type, we know that this
1114           // is a lossless cast...
1115           //
1116           Params[i] = new CastInst(Params[i], PTs[i], "call.resolve.cast");
1117           It = ++BIL.insert(It, cast<Instruction>(Params[i]));
1118         }
1119       Meth = NewVal;  // Update call destination to new value
1120
1121     } else {                   // Changing an argument, must be in vararg area
1122       std::vector<Value*>::iterator OI =
1123         find(Params.begin(), Params.end(), OldVal);
1124       assert (OI != Params.end() && "Not using value!");
1125
1126       *OI = NewVal;
1127     }
1128
1129     Res = new CallInst(Meth, Params, Name);
1130     break;
1131   }
1132   default:
1133     assert(0 && "Expression convertable, but don't know how to convert?");
1134     return;
1135   }
1136
1137   // If the instruction was newly created, insert it into the instruction
1138   // stream.
1139   //
1140   BasicBlock::iterator It = I;
1141   assert(It != BIL.end() && "Instruction not in own basic block??");
1142   BIL.insert(It, Res);   // Keep It pointing to old instruction
1143
1144   DEBUG(cerr << "COT CREATED: "  << (void*)Res << " " << Res
1145              << "In: " << (void*)I << " " << I << "Out: " << (void*)Res
1146              << " " << Res);
1147
1148   // Add the instruction to the expression map
1149   VMC.ExprMap[I] = Res;
1150
1151   if (I->getType() != Res->getType())
1152     ConvertValueToNewType(I, Res, VMC);
1153   else {
1154     for (unsigned It = 0; It < I->use_size(); ) {
1155       User *Use = *(I->use_begin()+It);
1156       if (isa<ValueHandle>(Use))            // Don't remove ValueHandles!
1157         ++It;
1158       else
1159         Use->replaceUsesOfWith(I, Res);
1160     }
1161
1162     for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
1163          UI != UE; ++UI)
1164       assert(isa<ValueHandle>((Value*)*UI) &&"Uses of Instruction remain!!!");
1165   }
1166 }
1167
1168
1169 ValueHandle::ValueHandle(ValueMapCache &VMC, Value *V)
1170   : Instruction(Type::VoidTy, UserOp1, ""), Cache(VMC) {
1171   //DEBUG(cerr << "VH AQUIRING: " << (void*)V << " " << V);
1172   Operands.push_back(Use(V, this));
1173 }
1174
1175 ValueHandle::ValueHandle(const ValueHandle &VH)
1176   : Instruction(Type::VoidTy, UserOp1, ""), Cache(VH.Cache) {
1177   //DEBUG(cerr << "VH AQUIRING: " << (void*)V << " " << V);
1178   Operands.push_back(Use((Value*)VH.getOperand(0), this));
1179 }
1180
1181 static void RecursiveDelete(ValueMapCache &Cache, Instruction *I) {
1182   if (!I || !I->use_empty()) return;
1183
1184   assert(I->getParent() && "Inst not in basic block!");
1185
1186   //DEBUG(cerr << "VH DELETING: " << (void*)I << " " << I);
1187
1188   for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); 
1189        OI != OE; ++OI)
1190     if (Instruction *U = dyn_cast<Instruction>(OI->get())) {
1191       *OI = 0;
1192       RecursiveDelete(Cache, U);
1193     }
1194
1195   I->getParent()->getInstList().remove(I);
1196
1197   Cache.OperandsMapped.erase(I);
1198   Cache.ExprMap.erase(I);
1199   delete I;
1200 }
1201
1202 ValueHandle::~ValueHandle() {
1203   if (Operands[0]->use_size() == 1) {
1204     Value *V = Operands[0];
1205     Operands[0] = 0;   // Drop use!
1206
1207     // Now we just need to remove the old instruction so we don't get infinite
1208     // loops.  Note that we cannot use DCE because DCE won't remove a store
1209     // instruction, for example.
1210     //
1211     RecursiveDelete(Cache, dyn_cast<Instruction>(V));
1212   } else {
1213     //DEBUG(cerr << "VH RELEASING: " << (void*)Operands[0].get() << " "
1214     //           << Operands[0]->use_size() << " " << Operands[0]);
1215   }
1216 }