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