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