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