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