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