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