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