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