Fix levelraise/2003-01-30-ShiftCrash.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/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         PTy->getElementType()->isSized() &&
278         TD.getTypeSize(PTy->getElementType()) == 
279         TD.getTypeSize(GEP->getType()->getElementType())) {
280       const PointerType *NewSrcTy = PointerType::get(PVTy);
281       if (!ExpressionConvertableToType(I->getOperand(0), NewSrcTy, CTMap))
282         return false;
283       break;
284     }
285
286     return false;   // No match, maybe next time.
287   }
288
289   case Instruction::Call: {
290     if (isa<Function>(I->getOperand(0)))
291       return false;  // Don't even try to change direct calls.
292
293     // If this is a function pointer, we can convert the return type if we can
294     // convert the source function pointer.
295     //
296     const PointerType *PT = cast<PointerType>(I->getOperand(0)->getType());
297     const FunctionType *FT = cast<FunctionType>(PT->getElementType());
298     std::vector<const Type *> ArgTys(FT->getParamTypes().begin(),
299                                      FT->getParamTypes().end());
300     const FunctionType *NewTy =
301       FunctionType::get(Ty, ArgTys, FT->isVarArg());
302     if (!ExpressionConvertableToType(I->getOperand(0),
303                                      PointerType::get(NewTy), CTMap))
304       return false;
305     break;
306   }
307   default:
308     return false;
309   }
310
311   // Expressions are only convertable if all of the users of the expression can
312   // have this value converted.  This makes use of the map to avoid infinite
313   // recursion.
314   //
315   for (Value::use_iterator It = I->use_begin(), E = I->use_end(); It != E; ++It)
316     if (!OperandConvertableToType(*It, I, Ty, CTMap))
317       return false;
318
319   return true;
320 }
321
322
323 Value *ConvertExpressionToType(Value *V, const Type *Ty, ValueMapCache &VMC) {
324   if (V->getType() == Ty) return V;  // Already where we need to be?
325
326   ValueMapCache::ExprMapTy::iterator VMCI = VMC.ExprMap.find(V);
327   if (VMCI != VMC.ExprMap.end()) {
328     const Value *GV = VMCI->second;
329     const Type *GTy = VMCI->second->getType();
330     assert(VMCI->second->getType() == Ty);
331
332     if (Instruction *I = dyn_cast<Instruction>(V))
333       ValueHandle IHandle(VMC, I);  // Remove I if it is unused now!
334
335     return VMCI->second;
336   }
337
338   DEBUG(cerr << "CETT: " << (void*)V << " " << V);
339
340   Instruction *I = dyn_cast<Instruction>(V);
341   if (I == 0) {
342     Constant *CPV = cast<Constant>(V);
343     // Constants are converted by constant folding the cast that is required.
344     // We assume here that all casts are implemented for constant prop.
345     Value *Result = ConstantFoldCastInstruction(CPV, Ty);
346     assert(Result && "ConstantFoldCastInstruction Failed!!!");
347     assert(Result->getType() == Ty && "Const prop of cast failed!");
348
349     // Add the instruction to the expression map
350     //VMC.ExprMap[V] = Result;
351     return Result;
352   }
353
354
355   BasicBlock *BB = I->getParent();
356   std::string Name = I->getName();  if (!Name.empty()) I->setName("");
357   Instruction *Res;     // Result of conversion
358
359   ValueHandle IHandle(VMC, I);  // Prevent I from being removed!
360   
361   Constant *Dummy = Constant::getNullValue(Ty);
362
363   switch (I->getOpcode()) {
364   case Instruction::Cast:
365     assert(VMC.NewCasts.count(ValueHandle(VMC, I)) == 0);
366     Res = new CastInst(I->getOperand(0), Ty, Name);
367     VMC.NewCasts.insert(ValueHandle(VMC, Res));
368     break;
369     
370   case Instruction::Add:
371   case Instruction::Sub:
372     Res = BinaryOperator::create(cast<BinaryOperator>(I)->getOpcode(),
373                                  Dummy, Dummy, Name);
374     VMC.ExprMap[I] = Res;   // Add node to expression eagerly
375
376     Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), Ty, VMC));
377     Res->setOperand(1, ConvertExpressionToType(I->getOperand(1), Ty, VMC));
378     break;
379
380   case Instruction::Shl:
381   case Instruction::Shr:
382     Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(), Dummy,
383                         I->getOperand(1), Name);
384     VMC.ExprMap[I] = Res;
385     Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), Ty, VMC));
386     break;
387
388   case Instruction::Load: {
389     LoadInst *LI = cast<LoadInst>(I);
390
391     Res = new LoadInst(Constant::getNullValue(PointerType::get(Ty)), Name);
392     VMC.ExprMap[I] = Res;
393     Res->setOperand(0, ConvertExpressionToType(LI->getPointerOperand(),
394                                                PointerType::get(Ty), VMC));
395     assert(Res->getOperand(0)->getType() == PointerType::get(Ty));
396     assert(Ty == Res->getType());
397     assert(Res->getType()->isFirstClassType() && "Load of structure or array!");
398     break;
399   }
400
401   case Instruction::PHINode: {
402     PHINode *OldPN = cast<PHINode>(I);
403     PHINode *NewPN = new PHINode(Ty, Name);
404
405     VMC.ExprMap[I] = NewPN;   // Add node to expression eagerly
406     while (OldPN->getNumOperands()) {
407       BasicBlock *BB = OldPN->getIncomingBlock(0);
408       Value *OldVal = OldPN->getIncomingValue(0);
409       ValueHandle OldValHandle(VMC, OldVal);
410       OldPN->removeIncomingValue(BB, false);
411       Value *V = ConvertExpressionToType(OldVal, Ty, VMC);
412       NewPN->addIncoming(V, BB);
413     }
414     Res = NewPN;
415     break;
416   }
417
418   case Instruction::Malloc: {
419     Res = ConvertMallocToType(cast<MallocInst>(I), Ty, Name, VMC);
420     break;
421   }
422
423   case Instruction::GetElementPtr: {
424     // GetElementPtr's are directly convertable to a pointer type if they have
425     // a number of zeros at the end.  Because removing these values does not
426     // change the logical offset of the GEP, it is okay and fair to remove them.
427     // This can change this:
428     //   %t1 = getelementptr %Hosp * %hosp, ubyte 4, ubyte 0  ; <%List **>
429     //   %t2 = cast %List * * %t1 to %List *
430     // into
431     //   %t2 = getelementptr %Hosp * %hosp, ubyte 4           ; <%List *>
432     // 
433     GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
434
435     // Check to see if there are zero elements that we can remove from the
436     // index array.  If there are, check to see if removing them causes us to
437     // get to the right type...
438     //
439     std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
440     const Type *BaseType = GEP->getPointerOperand()->getType();
441     const Type *PVTy = cast<PointerType>(Ty)->getElementType();
442     Res = 0;
443     while (!Indices.empty() &&
444            Indices.back() == Constant::getNullValue(Indices.back()->getType())){
445       Indices.pop_back();
446       if (GetElementPtrInst::getIndexedType(BaseType, Indices, true) == PVTy) {
447         if (Indices.size() == 0)
448           Res = new CastInst(GEP->getPointerOperand(), BaseType); // NOOP CAST
449         else
450           Res = new GetElementPtrInst(GEP->getPointerOperand(), Indices, Name);
451         break;
452       }
453     }
454
455     if (Res == 0 && GEP->getNumOperands() == 2 &&
456         GEP->getOperand(1)->getType() == Type::LongTy &&
457         GEP->getType() == PointerType::get(Type::SByteTy)) {
458       
459       // Otherwise, we can convert a GEP from one form to the other iff the
460       // current gep is of the form 'getelementptr [sbyte]*, unsigned N
461       // and we could convert this to an appropriate GEP for the new type.
462       //
463       const PointerType *NewSrcTy = PointerType::get(PVTy);
464       BasicBlock::iterator It = I;
465
466       // Check to see if 'N' is an expression that can be converted to
467       // the appropriate size... if so, allow it.
468       //
469       std::vector<Value*> Indices;
470       const Type *ElTy = ConvertableToGEP(NewSrcTy, I->getOperand(1),
471                                           Indices, &It);
472       if (ElTy) {        
473         assert(ElTy == PVTy && "Internal error, setup wrong!");
474         Res = new GetElementPtrInst(Constant::getNullValue(NewSrcTy),
475                                     Indices, Name);
476         VMC.ExprMap[I] = Res;
477         Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
478                                                    NewSrcTy, VMC));
479       }
480     }
481
482     // Otherwise, it could be that we have something like this:
483     //     getelementptr [[sbyte] *] * %reg115, uint %reg138    ; [sbyte]**
484     // and want to convert it into something like this:
485     //     getelemenptr [[int] *] * %reg115, uint %reg138      ; [int]**
486     //
487     if (Res == 0) {
488       const PointerType *NewSrcTy = PointerType::get(PVTy);
489       std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
490       Res = new GetElementPtrInst(Constant::getNullValue(NewSrcTy),
491                                   Indices, Name);
492       VMC.ExprMap[I] = Res;
493       Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
494                                                  NewSrcTy, VMC));
495     }
496
497
498     assert(Res && "Didn't find match!");
499     break;
500   }
501
502   case Instruction::Call: {
503     assert(!isa<Function>(I->getOperand(0)));
504
505     // If this is a function pointer, we can convert the return type if we can
506     // convert the source function pointer.
507     //
508     const PointerType *PT = cast<PointerType>(I->getOperand(0)->getType());
509     const FunctionType *FT = cast<FunctionType>(PT->getElementType());
510     std::vector<const Type *> ArgTys(FT->getParamTypes().begin(),
511                                      FT->getParamTypes().end());
512     const FunctionType *NewTy =
513       FunctionType::get(Ty, ArgTys, FT->isVarArg());
514     const PointerType *NewPTy = PointerType::get(NewTy);
515
516     Res = new CallInst(Constant::getNullValue(NewPTy),
517                        std::vector<Value*>(I->op_begin()+1, I->op_end()),
518                        Name);
519     VMC.ExprMap[I] = Res;
520     Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), NewPTy, VMC));
521     break;
522   }
523   default:
524     assert(0 && "Expression convertable, but don't know how to convert?");
525     return 0;
526   }
527
528   assert(Res->getType() == Ty && "Didn't convert expr to correct type!");
529
530   BB->getInstList().insert(I, Res);
531
532   // Add the instruction to the expression map
533   VMC.ExprMap[I] = Res;
534
535   // Expressions are only convertable if all of the users of the expression can
536   // have this value converted.  This makes use of the map to avoid infinite
537   // recursion.
538   //
539   unsigned NumUses = I->use_size();
540   for (unsigned It = 0; It < NumUses; ) {
541     unsigned OldSize = NumUses;
542     ConvertOperandToType(*(I->use_begin()+It), I, Res, VMC);
543     NumUses = I->use_size();
544     if (NumUses == OldSize) ++It;
545   }
546
547   DEBUG(cerr << "ExpIn: " << (void*)I << " " << I
548              << "ExpOut: " << (void*)Res << " " << Res);
549
550   return Res;
551 }
552
553
554
555 // ValueConvertableToType - Return true if it is possible
556 bool ValueConvertableToType(Value *V, const Type *Ty,
557                              ValueTypeCache &ConvertedTypes) {
558   ValueTypeCache::iterator I = ConvertedTypes.find(V);
559   if (I != ConvertedTypes.end()) return I->second == Ty;
560   ConvertedTypes[V] = Ty;
561
562   // It is safe to convert the specified value to the specified type IFF all of
563   // the uses of the value can be converted to accept the new typed value.
564   //
565   if (V->getType() != Ty) {
566     for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I)
567       if (!OperandConvertableToType(*I, V, Ty, ConvertedTypes))
568         return false;
569   }
570
571   return true;
572 }
573
574
575
576
577
578 // OperandConvertableToType - Return true if it is possible to convert operand
579 // V of User (instruction) U to the specified type.  This is true iff it is
580 // possible to change the specified instruction to accept this.  CTMap is a map
581 // of converted types, so that circular definitions will see the future type of
582 // the expression, not the static current type.
583 //
584 static bool OperandConvertableToType(User *U, Value *V, const Type *Ty,
585                                      ValueTypeCache &CTMap) {
586   //  if (V->getType() == Ty) return true;   // Operand already the right type?
587
588   // Expression type must be holdable in a register.
589   if (!Ty->isFirstClassType())
590     return false;
591
592   Instruction *I = dyn_cast<Instruction>(U);
593   if (I == 0) return false;              // We can't convert!
594
595   switch (I->getOpcode()) {
596   case Instruction::Cast:
597     assert(I->getOperand(0) == V);
598     // We can convert the expr if the cast destination type is losslessly
599     // convertable to the requested type.
600     // Also, do not change a cast that is a noop cast.  For all intents and
601     // purposes it should be eliminated.
602     if (!Ty->isLosslesslyConvertableTo(I->getOperand(0)->getType()) ||
603         I->getType() == I->getOperand(0)->getType())
604       return false;
605
606     // Do not allow a 'cast ushort %V to uint' to have it's first operand be
607     // converted to a 'short' type.  Doing so changes the way sign promotion
608     // happens, and breaks things.  Only allow the cast to take place if the
609     // signedness doesn't change... or if the current cast is not a lossy
610     // conversion.
611     //
612     if (!I->getType()->isLosslesslyConvertableTo(I->getOperand(0)->getType()) &&
613         I->getOperand(0)->getType()->isSigned() != Ty->isSigned())
614       return false;
615
616     // We also do not allow conversion of a cast that casts from a ptr to array
617     // of X to a *X.  For example: cast [4 x %List *] * %val to %List * *
618     //
619     if (const PointerType *SPT = 
620         dyn_cast<PointerType>(I->getOperand(0)->getType()))
621       if (const PointerType *DPT = dyn_cast<PointerType>(I->getType()))
622         if (const ArrayType *AT = dyn_cast<ArrayType>(SPT->getElementType()))
623           if (AT->getElementType() == DPT->getElementType())
624             return false;
625     return true;
626
627   case Instruction::Add:
628     if (isa<PointerType>(Ty)) {
629       Value *IndexVal = I->getOperand(V == I->getOperand(0) ? 1 : 0);
630       std::vector<Value*> Indices;
631       if (const Type *ETy = ConvertableToGEP(Ty, IndexVal, Indices)) {
632         const Type *RetTy = PointerType::get(ETy);
633
634         // Only successful if we can convert this type to the required type
635         if (ValueConvertableToType(I, RetTy, CTMap)) {
636           CTMap[I] = RetTy;
637           return true;
638         }
639         // We have to return failure here because ValueConvertableToType could 
640         // have polluted our map
641         return false;
642       }
643     }
644     // FALLTHROUGH
645   case Instruction::Sub: {
646     if (!Ty->isInteger() && !Ty->isFloatingPoint()) return false;
647
648     Value *OtherOp = I->getOperand((V == I->getOperand(0)) ? 1 : 0);
649     return ValueConvertableToType(I, Ty, CTMap) &&
650            ExpressionConvertableToType(OtherOp, Ty, CTMap);
651   }
652   case Instruction::SetEQ:
653   case Instruction::SetNE: {
654     Value *OtherOp = I->getOperand((V == I->getOperand(0)) ? 1 : 0);
655     return ExpressionConvertableToType(OtherOp, Ty, CTMap);
656   }
657   case Instruction::Shr:
658     if (Ty->isSigned() != V->getType()->isSigned()) return false;
659     // FALL THROUGH
660   case Instruction::Shl:
661     if (I->getOperand(1) == V) return false;  // Cannot change shift amount type
662     if (!Ty->isInteger()) return false;
663     return ValueConvertableToType(I, Ty, CTMap);
664
665   case Instruction::Free:
666     assert(I->getOperand(0) == V);
667     return isa<PointerType>(Ty);    // Free can free any pointer type!
668
669   case Instruction::Load:
670     // Cannot convert the types of any subscripts...
671     if (I->getOperand(0) != V) return false;
672
673     if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
674       LoadInst *LI = cast<LoadInst>(I);
675       
676       const Type *LoadedTy = PT->getElementType();
677
678       // They could be loading the first element of a composite type...
679       if (const CompositeType *CT = dyn_cast<CompositeType>(LoadedTy)) {
680         unsigned Offset = 0;     // No offset, get first leaf.
681         std::vector<Value*> Indices;  // Discarded...
682         LoadedTy = getStructOffsetType(CT, Offset, Indices, false);
683         assert(Offset == 0 && "Offset changed from zero???");
684       }
685
686       if (!LoadedTy->isFirstClassType())
687         return false;
688
689       if (TD.getTypeSize(LoadedTy) != TD.getTypeSize(LI->getType()))
690         return false;
691
692       return ValueConvertableToType(LI, LoadedTy, CTMap);
693     }
694     return false;
695
696   case Instruction::Store: {
697     StoreInst *SI = cast<StoreInst>(I);
698
699     if (V == I->getOperand(0)) {
700       ValueTypeCache::iterator CTMI = CTMap.find(I->getOperand(1));
701       if (CTMI != CTMap.end()) {   // Operand #1 is in the table already?
702         // If so, check to see if it's Ty*, or, more importantly, if it is a
703         // pointer to a structure where the first element is a Ty... this code
704         // is neccesary because we might be trying to change the source and
705         // destination type of the store (they might be related) and the dest
706         // pointer type might be a pointer to structure.  Below we allow pointer
707         // to structures where the 0th element is compatible with the value,
708         // now we have to support the symmetrical part of this.
709         //
710         const Type *ElTy = cast<PointerType>(CTMI->second)->getElementType();
711
712         // Already a pointer to what we want?  Trivially accept...
713         if (ElTy == Ty) return true;
714
715         // Tricky case now, if the destination is a pointer to structure,
716         // obviously the source is not allowed to be a structure (cannot copy
717         // a whole structure at a time), so the level raiser must be trying to
718         // store into the first field.  Check for this and allow it now:
719         //
720         if (const StructType *SElTy = dyn_cast<StructType>(ElTy)) {
721           unsigned Offset = 0;
722           std::vector<Value*> Indices;
723           ElTy = getStructOffsetType(ElTy, Offset, Indices, false);
724           assert(Offset == 0 && "Offset changed!");
725           if (ElTy == 0)    // Element at offset zero in struct doesn't exist!
726             return false;   // Can only happen for {}*
727           
728           if (ElTy == Ty)   // Looks like the 0th element of structure is
729             return true;    // compatible!  Accept now!
730
731           // Otherwise we know that we can't work, so just stop trying now.
732           return false;
733         }
734       }
735
736       // Can convert the store if we can convert the pointer operand to match
737       // the new  value type...
738       return ExpressionConvertableToType(I->getOperand(1), PointerType::get(Ty),
739                                          CTMap);
740     } else if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
741       const Type *ElTy = PT->getElementType();
742       assert(V == I->getOperand(1));
743
744       if (isa<StructType>(ElTy)) {
745         // We can change the destination pointer if we can store our first
746         // argument into the first element of the structure...
747         //
748         unsigned Offset = 0;
749         std::vector<Value*> Indices;
750         ElTy = getStructOffsetType(ElTy, Offset, Indices, false);
751         assert(Offset == 0 && "Offset changed!");
752         if (ElTy == 0)    // Element at offset zero in struct doesn't exist!
753           return false;   // Can only happen for {}*
754       }
755
756       // Must move the same amount of data...
757       if (!ElTy->isSized() || 
758           TD.getTypeSize(ElTy) != TD.getTypeSize(I->getOperand(0)->getType()))
759         return false;
760
761       // Can convert store if the incoming value is convertable...
762       return ExpressionConvertableToType(I->getOperand(0), ElTy, CTMap);
763     }
764     return false;
765   }
766
767   case Instruction::GetElementPtr:
768     if (V != I->getOperand(0) || !isa<PointerType>(Ty)) return false;
769
770     // If we have a two operand form of getelementptr, this is really little
771     // more than a simple addition.  As with addition, check to see if the
772     // getelementptr instruction can be changed to index into the new type.
773     //
774     if (I->getNumOperands() == 2) {
775       const Type *OldElTy = cast<PointerType>(I->getType())->getElementType();
776       unsigned DataSize = TD.getTypeSize(OldElTy);
777       Value *Index = I->getOperand(1);
778       Instruction *TempScale = 0;
779
780       // If the old data element is not unit sized, we have to create a scale
781       // instruction so that ConvertableToGEP will know the REAL amount we are
782       // indexing by.  Note that this is never inserted into the instruction
783       // stream, so we have to delete it when we're done.
784       //
785       if (DataSize != 1) {
786         TempScale = BinaryOperator::create(Instruction::Mul, Index,
787                                            ConstantSInt::get(Type::LongTy,
788                                                              DataSize));
789         Index = TempScale;
790       }
791
792       // Check to see if the second argument is an expression that can
793       // be converted to the appropriate size... if so, allow it.
794       //
795       std::vector<Value*> Indices;
796       const Type *ElTy = ConvertableToGEP(Ty, Index, Indices);
797       delete TempScale;   // Free our temporary multiply if we made it
798
799       if (ElTy == 0) return false;  // Cannot make conversion...
800       return ValueConvertableToType(I, PointerType::get(ElTy), CTMap);
801     }
802     return false;
803
804   case Instruction::PHINode: {
805     PHINode *PN = cast<PHINode>(I);
806     for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i)
807       if (!ExpressionConvertableToType(PN->getIncomingValue(i), Ty, CTMap))
808         return false;
809     return ValueConvertableToType(PN, Ty, CTMap);
810   }
811
812   case Instruction::Call: {
813     User::op_iterator OI = find(I->op_begin(), I->op_end(), V);
814     assert (OI != I->op_end() && "Not using value!");
815     unsigned OpNum = OI - I->op_begin();
816
817     // Are we trying to change the function pointer value to a new type?
818     if (OpNum == 0) {
819       const PointerType *PTy = dyn_cast<PointerType>(Ty);
820       if (PTy == 0) return false;  // Can't convert to a non-pointer type...
821       const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
822       if (FTy == 0) return false;  // Can't convert to a non ptr to function...
823
824       // Do not allow converting to a call where all of the operands are ...'s
825       if (FTy->getNumParams() == 0 && FTy->isVarArg())
826         return false;              // Do not permit this conversion!
827
828       // Perform sanity checks to make sure that new function type has the
829       // correct number of arguments...
830       //
831       unsigned NumArgs = I->getNumOperands()-1;  // Don't include function ptr
832
833       // Cannot convert to a type that requires more fixed arguments than
834       // the call provides...
835       //
836       if (NumArgs < FTy->getNumParams()) return false;
837       
838       // Unless this is a vararg function type, we cannot provide more arguments
839       // than are desired...
840       //
841       if (!FTy->isVarArg() && NumArgs > FTy->getNumParams())
842         return false;
843
844       // Okay, at this point, we know that the call and the function type match
845       // number of arguments.  Now we see if we can convert the arguments
846       // themselves.  Note that we do not require operands to be convertable,
847       // we can insert casts if they are convertible but not compatible.  The
848       // reason for this is that we prefer to have resolved functions but casted
849       // arguments if possible.
850       //
851       const FunctionType::ParamTypes &PTs = FTy->getParamTypes();
852       for (unsigned i = 0, NA = PTs.size(); i < NA; ++i)
853         if (!PTs[i]->isLosslesslyConvertableTo(I->getOperand(i+1)->getType()))
854           return false;   // Operands must have compatible types!
855
856       // Okay, at this point, we know that all of the arguments can be
857       // converted.  We succeed if we can change the return type if
858       // neccesary...
859       //
860       return ValueConvertableToType(I, FTy->getReturnType(), CTMap);
861     }
862     
863     const PointerType *MPtr = cast<PointerType>(I->getOperand(0)->getType());
864     const FunctionType *FTy = cast<FunctionType>(MPtr->getElementType());
865     if (!FTy->isVarArg()) return false;
866
867     if ((OpNum-1) < FTy->getParamTypes().size())
868       return false;  // It's not in the varargs section...
869
870     // If we get this far, we know the value is in the varargs section of the
871     // function!  We can convert if we don't reinterpret the value...
872     //
873     return Ty->isLosslesslyConvertableTo(V->getType());
874   }
875   }
876   return false;
877 }
878
879
880 void ConvertValueToNewType(Value *V, Value *NewVal, ValueMapCache &VMC) {
881   ValueHandle VH(VMC, V);
882
883   unsigned NumUses = V->use_size();
884   for (unsigned It = 0; It < NumUses; ) {
885     unsigned OldSize = NumUses;
886     ConvertOperandToType(*(V->use_begin()+It), V, NewVal, VMC);
887     NumUses = V->use_size();
888     if (NumUses == OldSize) ++It;
889   }
890 }
891
892
893
894 static void ConvertOperandToType(User *U, Value *OldVal, Value *NewVal,
895                                  ValueMapCache &VMC) {
896   if (isa<ValueHandle>(U)) return;  // Valuehandles don't let go of operands...
897
898   if (VMC.OperandsMapped.count(U)) return;
899   VMC.OperandsMapped.insert(U);
900
901   ValueMapCache::ExprMapTy::iterator VMCI = VMC.ExprMap.find(U);
902   if (VMCI != VMC.ExprMap.end())
903     return;
904
905
906   Instruction *I = cast<Instruction>(U);  // Only Instructions convertable
907
908   BasicBlock *BB = I->getParent();
909   assert(BB != 0 && "Instruction not embedded in basic block!");
910   std::string Name = I->getName();
911   I->setName("");
912   Instruction *Res;     // Result of conversion
913
914   //cerr << endl << endl << "Type:\t" << Ty << "\nInst: " << I << "BB Before: " << BB << endl;
915
916   // Prevent I from being removed...
917   ValueHandle IHandle(VMC, I);
918
919   const Type *NewTy = NewVal->getType();
920   Constant *Dummy = (NewTy != Type::VoidTy) ? 
921                   Constant::getNullValue(NewTy) : 0;
922
923   switch (I->getOpcode()) {
924   case Instruction::Cast:
925     if (VMC.NewCasts.count(ValueHandle(VMC, I))) {
926       // This cast has already had it's value converted, causing a new cast to
927       // be created.  We don't want to create YET ANOTHER cast instruction
928       // representing the original one, so just modify the operand of this cast
929       // instruction, which we know is newly created.
930       I->setOperand(0, NewVal);
931       I->setName(Name);  // give I its name back
932       return;
933
934     } else {
935       Res = new CastInst(NewVal, I->getType(), Name);
936     }
937     break;
938
939   case Instruction::Add:
940     if (isa<PointerType>(NewTy)) {
941       Value *IndexVal = I->getOperand(OldVal == I->getOperand(0) ? 1 : 0);
942       std::vector<Value*> Indices;
943       BasicBlock::iterator It = I;
944
945       if (const Type *ETy = ConvertableToGEP(NewTy, IndexVal, Indices, &It)) {
946         // If successful, convert the add to a GEP
947         //const Type *RetTy = PointerType::get(ETy);
948         // First operand is actually the given pointer...
949         Res = new GetElementPtrInst(NewVal, Indices, Name);
950         assert(cast<PointerType>(Res->getType())->getElementType() == ETy &&
951                "ConvertableToGEP broken!");
952         break;
953       }
954     }
955     // FALLTHROUGH
956
957   case Instruction::Sub:
958   case Instruction::SetEQ:
959   case Instruction::SetNE: {
960     Res = BinaryOperator::create(cast<BinaryOperator>(I)->getOpcode(),
961                                  Dummy, Dummy, Name);
962     VMC.ExprMap[I] = Res;   // Add node to expression eagerly
963
964     unsigned OtherIdx = (OldVal == I->getOperand(0)) ? 1 : 0;
965     Value *OtherOp    = I->getOperand(OtherIdx);
966     Value *NewOther   = ConvertExpressionToType(OtherOp, NewTy, VMC);
967
968     Res->setOperand(OtherIdx, NewOther);
969     Res->setOperand(!OtherIdx, NewVal);
970     break;
971   }
972   case Instruction::Shl:
973   case Instruction::Shr:
974     assert(I->getOperand(0) == OldVal);
975     Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(), NewVal,
976                         I->getOperand(1), Name);
977     break;
978
979   case Instruction::Free:            // Free can free any pointer type!
980     assert(I->getOperand(0) == OldVal);
981     Res = new FreeInst(NewVal);
982     break;
983
984
985   case Instruction::Load: {
986     assert(I->getOperand(0) == OldVal && isa<PointerType>(NewVal->getType()));
987     const Type *LoadedTy =
988       cast<PointerType>(NewVal->getType())->getElementType();
989
990     Value *Src = NewVal;
991
992     if (const CompositeType *CT = dyn_cast<CompositeType>(LoadedTy)) {
993       std::vector<Value*> Indices;
994       Indices.push_back(ConstantSInt::get(Type::LongTy, 0));
995
996       unsigned Offset = 0;   // No offset, get first leaf.
997       LoadedTy = getStructOffsetType(CT, Offset, Indices, false);
998       assert(LoadedTy->isFirstClassType());
999
1000       if (Indices.size() != 1) {     // Do not generate load X, 0
1001         // Insert the GEP instruction before this load.
1002         Src = new GetElementPtrInst(Src, Indices, Name+".idx", I);
1003       }
1004     }
1005     
1006     Res = new LoadInst(Src, Name);
1007     assert(Res->getType()->isFirstClassType() && "Load of structure or array!");
1008     break;
1009   }
1010
1011   case Instruction::Store: {
1012     if (I->getOperand(0) == OldVal) {  // Replace the source value
1013       // Check to see if operand #1 has already been converted...
1014       ValueMapCache::ExprMapTy::iterator VMCI =
1015         VMC.ExprMap.find(I->getOperand(1));
1016       if (VMCI != VMC.ExprMap.end()) {
1017         // Comments describing this stuff are in the OperandConvertableToType
1018         // switch statement for Store...
1019         //
1020         const Type *ElTy =
1021           cast<PointerType>(VMCI->second->getType())->getElementType();
1022         
1023         Value *SrcPtr = VMCI->second;
1024
1025         if (ElTy != NewTy) {
1026           // We check that this is a struct in the initial scan...
1027           const StructType *SElTy = cast<StructType>(ElTy);
1028           
1029           std::vector<Value*> Indices;
1030           Indices.push_back(Constant::getNullValue(Type::LongTy));
1031
1032           unsigned Offset = 0;
1033           const Type *Ty = getStructOffsetType(ElTy, Offset, Indices, false);
1034           assert(Offset == 0 && "Offset changed!");
1035           assert(NewTy == Ty && "Did not convert to correct type!");
1036
1037           // Insert the GEP instruction before this store.
1038           SrcPtr = new GetElementPtrInst(SrcPtr, Indices,
1039                                          SrcPtr->getName()+".idx", I);
1040         }
1041         Res = new StoreInst(NewVal, SrcPtr);
1042
1043         VMC.ExprMap[I] = Res;
1044       } else {
1045         // Otherwise, we haven't converted Operand #1 over yet...
1046         const PointerType *NewPT = PointerType::get(NewTy);
1047         Res = new StoreInst(NewVal, Constant::getNullValue(NewPT));
1048         VMC.ExprMap[I] = Res;
1049         Res->setOperand(1, ConvertExpressionToType(I->getOperand(1),
1050                                                    NewPT, VMC));
1051       }
1052     } else {                           // Replace the source pointer
1053       const Type *ValTy = cast<PointerType>(NewTy)->getElementType();
1054
1055       Value *SrcPtr = NewVal;
1056
1057       if (isa<StructType>(ValTy)) {
1058         std::vector<Value*> Indices;
1059         Indices.push_back(Constant::getNullValue(Type::LongTy));
1060
1061         unsigned Offset = 0;
1062         ValTy = getStructOffsetType(ValTy, Offset, Indices, false);
1063
1064         assert(Offset == 0 && ValTy);
1065
1066         // Insert the GEP instruction before this store.
1067         SrcPtr = new GetElementPtrInst(SrcPtr, Indices,
1068                                        SrcPtr->getName()+".idx", I);
1069       }
1070
1071       Res = new StoreInst(Constant::getNullValue(ValTy), SrcPtr);
1072       VMC.ExprMap[I] = Res;
1073       Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), ValTy, VMC));
1074     }
1075     break;
1076   }
1077
1078
1079   case Instruction::GetElementPtr: {
1080     // Convert a one index getelementptr into just about anything that is
1081     // desired.
1082     //
1083     BasicBlock::iterator It = I;
1084     const Type *OldElTy = cast<PointerType>(I->getType())->getElementType();
1085     unsigned DataSize = TD.getTypeSize(OldElTy);
1086     Value *Index = I->getOperand(1);
1087
1088     if (DataSize != 1) {
1089       // Insert a multiply of the old element type is not a unit size...
1090       Index = BinaryOperator::create(Instruction::Mul, Index,
1091                                      ConstantSInt::get(Type::LongTy, DataSize),
1092                                      "scale", It);
1093     }
1094
1095     // Perform the conversion now...
1096     //
1097     std::vector<Value*> Indices;
1098     const Type *ElTy = ConvertableToGEP(NewVal->getType(), Index, Indices, &It);
1099     assert(ElTy != 0 && "GEP Conversion Failure!");
1100     Res = new GetElementPtrInst(NewVal, Indices, Name);
1101     assert(Res->getType() == PointerType::get(ElTy) &&
1102            "ConvertableToGet failed!");
1103   }
1104 #if 0
1105     if (I->getType() == PointerType::get(Type::SByteTy)) {
1106       // Convert a getelementptr sbyte * %reg111, uint 16 freely back to
1107       // anything that is a pointer type...
1108       //
1109       BasicBlock::iterator It = I;
1110     
1111       // Check to see if the second argument is an expression that can
1112       // be converted to the appropriate size... if so, allow it.
1113       //
1114       std::vector<Value*> Indices;
1115       const Type *ElTy = ConvertableToGEP(NewVal->getType(), I->getOperand(1),
1116                                           Indices, &It);
1117       assert(ElTy != 0 && "GEP Conversion Failure!");
1118       
1119       Res = new GetElementPtrInst(NewVal, Indices, Name);
1120     } else {
1121       // Convert a getelementptr ulong * %reg123, uint %N
1122       // to        getelementptr  long * %reg123, uint %N
1123       // ... where the type must simply stay the same size...
1124       //
1125       GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
1126       std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
1127       Res = new GetElementPtrInst(NewVal, Indices, Name);
1128     }
1129 #endif
1130     break;
1131
1132   case Instruction::PHINode: {
1133     PHINode *OldPN = cast<PHINode>(I);
1134     PHINode *NewPN = new PHINode(NewTy, Name);
1135     VMC.ExprMap[I] = NewPN;
1136
1137     while (OldPN->getNumOperands()) {
1138       BasicBlock *BB = OldPN->getIncomingBlock(0);
1139       Value *OldVal = OldPN->getIncomingValue(0);
1140       OldPN->removeIncomingValue(BB, false);
1141       Value *V = ConvertExpressionToType(OldVal, NewTy, VMC);
1142       NewPN->addIncoming(V, BB);
1143     }
1144     Res = NewPN;
1145     break;
1146   }
1147
1148   case Instruction::Call: {
1149     Value *Meth = I->getOperand(0);
1150     std::vector<Value*> Params(I->op_begin()+1, I->op_end());
1151
1152     if (Meth == OldVal) {   // Changing the function pointer?
1153       const PointerType *NewPTy = cast<PointerType>(NewVal->getType());
1154       const FunctionType *NewTy = cast<FunctionType>(NewPTy->getElementType());
1155       const FunctionType::ParamTypes &PTs = NewTy->getParamTypes();
1156
1157       // Get an iterator to the call instruction so that we can insert casts for
1158       // operands if needbe.  Note that we do not require operands to be
1159       // convertable, we can insert casts if they are convertible but not
1160       // compatible.  The reason for this is that we prefer to have resolved
1161       // functions but casted arguments if possible.
1162       //
1163       BasicBlock::iterator It = I;
1164
1165       // Convert over all of the call operands to their new types... but only
1166       // convert over the part that is not in the vararg section of the call.
1167       //
1168       for (unsigned i = 0; i < PTs.size(); ++i)
1169         if (Params[i]->getType() != PTs[i]) {
1170           // Create a cast to convert it to the right type, we know that this
1171           // is a lossless cast...
1172           //
1173           Params[i] = new CastInst(Params[i], PTs[i],  "callarg.cast." +
1174                                    Params[i]->getName(), It);
1175         }
1176       Meth = NewVal;  // Update call destination to new value
1177
1178     } else {                   // Changing an argument, must be in vararg area
1179       std::vector<Value*>::iterator OI =
1180         find(Params.begin(), Params.end(), OldVal);
1181       assert (OI != Params.end() && "Not using value!");
1182
1183       *OI = NewVal;
1184     }
1185
1186     Res = new CallInst(Meth, Params, Name);
1187     break;
1188   }
1189   default:
1190     assert(0 && "Expression convertable, but don't know how to convert?");
1191     return;
1192   }
1193
1194   // If the instruction was newly created, insert it into the instruction
1195   // stream.
1196   //
1197   BasicBlock::iterator It = I;
1198   assert(It != BB->end() && "Instruction not in own basic block??");
1199   BB->getInstList().insert(It, Res);   // Keep It pointing to old instruction
1200
1201   DEBUG(cerr << "COT CREATED: "  << (void*)Res << " " << Res
1202              << "In: " << (void*)I << " " << I << "Out: " << (void*)Res
1203              << " " << Res);
1204
1205   // Add the instruction to the expression map
1206   VMC.ExprMap[I] = Res;
1207
1208   if (I->getType() != Res->getType())
1209     ConvertValueToNewType(I, Res, VMC);
1210   else {
1211     for (unsigned It = 0; It < I->use_size(); ) {
1212       User *Use = *(I->use_begin()+It);
1213       if (isa<ValueHandle>(Use))            // Don't remove ValueHandles!
1214         ++It;
1215       else
1216         Use->replaceUsesOfWith(I, Res);
1217     }
1218
1219     for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
1220          UI != UE; ++UI)
1221       assert(isa<ValueHandle>((Value*)*UI) &&"Uses of Instruction remain!!!");
1222   }
1223 }
1224
1225
1226 ValueHandle::ValueHandle(ValueMapCache &VMC, Value *V)
1227   : Instruction(Type::VoidTy, UserOp1, ""), Cache(VMC) {
1228   //DEBUG(cerr << "VH AQUIRING: " << (void*)V << " " << V);
1229   Operands.push_back(Use(V, this));
1230 }
1231
1232 ValueHandle::ValueHandle(const ValueHandle &VH)
1233   : Instruction(Type::VoidTy, UserOp1, ""), Cache(VH.Cache) {
1234   //DEBUG(cerr << "VH AQUIRING: " << (void*)V << " " << V);
1235   Operands.push_back(Use((Value*)VH.getOperand(0), this));
1236 }
1237
1238 static void RecursiveDelete(ValueMapCache &Cache, Instruction *I) {
1239   if (!I || !I->use_empty()) return;
1240
1241   assert(I->getParent() && "Inst not in basic block!");
1242
1243   //DEBUG(cerr << "VH DELETING: " << (void*)I << " " << I);
1244
1245   for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); 
1246        OI != OE; ++OI)
1247     if (Instruction *U = dyn_cast<Instruction>(OI->get())) {
1248       *OI = 0;
1249       RecursiveDelete(Cache, U);
1250     }
1251
1252   I->getParent()->getInstList().remove(I);
1253
1254   Cache.OperandsMapped.erase(I);
1255   Cache.ExprMap.erase(I);
1256   delete I;
1257 }
1258
1259 ValueHandle::~ValueHandle() {
1260   if (Operands[0]->use_size() == 1) {
1261     Value *V = Operands[0];
1262     Operands[0] = 0;   // Drop use!
1263
1264     // Now we just need to remove the old instruction so we don't get infinite
1265     // loops.  Note that we cannot use DCE because DCE won't remove a store
1266     // instruction, for example.
1267     //
1268     RecursiveDelete(Cache, dyn_cast<Instruction>(V));
1269   } else {
1270     //DEBUG(cerr << "VH RELEASING: " << (void*)Operands[0].get() << " "
1271     //           << Operands[0]->use_size() << " " << Operands[0]);
1272   }
1273 }