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