d46878d26b6b0894ff6968c2f0099cb685e734cd
[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     for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i)
210       if (!ExpressionConvertibleToType(PN->getIncomingValue(i), Ty, CTMap, TD))
211         return false;
212     break;
213   }
214
215   case Instruction::Malloc:
216     if (!MallocConvertibleToType(cast<MallocInst>(I), Ty, CTMap, TD))
217       return false;
218     break;
219
220   case Instruction::GetElementPtr: {
221     // GetElementPtr's are directly convertible to a pointer type if they have
222     // a number of zeros at the end.  Because removing these values does not
223     // change the logical offset of the GEP, it is okay and fair to remove them.
224     // This can change this:
225     //   %t1 = getelementptr %Hosp * %hosp, ubyte 4, ubyte 0  ; <%List **>
226     //   %t2 = cast %List * * %t1 to %List *
227     // into
228     //   %t2 = getelementptr %Hosp * %hosp, ubyte 4           ; <%List *>
229     // 
230     GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
231     const PointerType *PTy = dyn_cast<PointerType>(Ty);
232     if (!PTy) return false;  // GEP must always return a pointer...
233     const Type *PVTy = PTy->getElementType();
234
235     // Check to see if there are zero elements that we can remove from the
236     // index array.  If there are, check to see if removing them causes us to
237     // get to the right type...
238     //
239     std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
240     const Type *BaseType = GEP->getPointerOperand()->getType();
241     const Type *ElTy = 0;
242
243     while (!Indices.empty() &&
244            Indices.back() == Constant::getNullValue(Indices.back()->getType())){
245       Indices.pop_back();
246       ElTy = GetElementPtrInst::getIndexedType(BaseType, Indices, true);
247       if (ElTy == PVTy)
248         break;  // Found a match!!
249       ElTy = 0;
250     }
251
252     if (ElTy) break;   // Found a number of zeros we can strip off!
253
254     // Otherwise, we can convert a GEP from one form to the other iff the
255     // current gep is of the form 'getelementptr sbyte*, long N
256     // and we could convert this to an appropriate GEP for the new type.
257     //
258     if (GEP->getNumOperands() == 2 &&
259         GEP->getType() == PointerType::get(Type::SByteTy)) {
260
261       // Do not Check to see if our incoming pointer can be converted
262       // to be a ptr to an array of the right type... because in more cases than
263       // not, it is simply not analyzable because of pointer/array
264       // discrepancies.  To fix this, we will insert a cast before the GEP.
265       //
266
267       // Check to see if 'N' is an expression that can be converted to
268       // the appropriate size... if so, allow it.
269       //
270       std::vector<Value*> Indices;
271       const Type *ElTy = ConvertibleToGEP(PTy, I->getOperand(1), Indices, TD);
272       if (ElTy == PVTy) {
273         if (!ExpressionConvertibleToType(I->getOperand(0),
274                                          PointerType::get(ElTy), CTMap, TD))
275           return false;  // Can't continue, ExConToTy might have polluted set!
276         break;
277       }
278     }
279
280     // Otherwise, it could be that we have something like this:
281     //     getelementptr [[sbyte] *] * %reg115, long %reg138    ; [sbyte]**
282     // and want to convert it into something like this:
283     //     getelemenptr [[int] *] * %reg115, long %reg138      ; [int]**
284     //
285     if (GEP->getNumOperands() == 2 && 
286         PTy->getElementType()->isSized() &&
287         TD.getTypeSize(PTy->getElementType()) == 
288         TD.getTypeSize(GEP->getType()->getElementType())) {
289       const PointerType *NewSrcTy = PointerType::get(PVTy);
290       if (!ExpressionConvertibleToType(I->getOperand(0), NewSrcTy, CTMap, TD))
291         return false;
292       break;
293     }
294
295     return false;   // No match, maybe next time.
296   }
297
298   case Instruction::Call: {
299     if (isa<Function>(I->getOperand(0)))
300       return false;  // Don't even try to change direct calls.
301
302     // If this is a function pointer, we can convert the return type if we can
303     // convert the source function pointer.
304     //
305     const PointerType *PT = cast<PointerType>(I->getOperand(0)->getType());
306     const FunctionType *FT = cast<FunctionType>(PT->getElementType());
307     std::vector<const Type *> ArgTys(FT->getParamTypes().begin(),
308                                      FT->getParamTypes().end());
309     const FunctionType *NewTy =
310       FunctionType::get(Ty, ArgTys, FT->isVarArg());
311     if (!ExpressionConvertibleToType(I->getOperand(0),
312                                      PointerType::get(NewTy), CTMap, TD))
313       return false;
314     break;
315   }
316   default:
317     return false;
318   }
319
320   // Expressions are only convertible if all of the users of the expression can
321   // have this value converted.  This makes use of the map to avoid infinite
322   // recursion.
323   //
324   for (Value::use_iterator It = I->use_begin(), E = I->use_end(); It != E; ++It)
325     if (!OperandConvertibleToType(*It, I, Ty, CTMap, TD))
326       return false;
327
328   return true;
329 }
330
331
332 Value *llvm::ConvertExpressionToType(Value *V, const Type *Ty, 
333                                      ValueMapCache &VMC, const TargetData &TD) {
334   if (V->getType() == Ty) return V;  // Already where we need to be?
335
336   ValueMapCache::ExprMapTy::iterator VMCI = VMC.ExprMap.find(V);
337   if (VMCI != VMC.ExprMap.end()) {
338     const Value *GV = VMCI->second;
339     const Type *GTy = VMCI->second->getType();
340     assert(VMCI->second->getType() == Ty);
341
342     if (Instruction *I = dyn_cast<Instruction>(V))
343       ValueHandle IHandle(VMC, I);  // Remove I if it is unused now!
344
345     return VMCI->second;
346   }
347
348   DEBUG(std::cerr << "CETT: " << (void*)V << " " << V);
349
350   Instruction *I = dyn_cast<Instruction>(V);
351   if (I == 0) {
352     Constant *CPV = cast<Constant>(V);
353     // Constants are converted by constant folding the cast that is required.
354     // We assume here that all casts are implemented for constant prop.
355     Value *Result = ConstantExpr::getCast(CPV, Ty);
356     // Add the instruction to the expression map
357     //VMC.ExprMap[V] = Result;
358     return Result;
359   }
360
361
362   BasicBlock *BB = I->getParent();
363   std::string Name = I->getName();  if (!Name.empty()) I->setName("");
364   Instruction *Res;     // Result of conversion
365
366   ValueHandle IHandle(VMC, I);  // Prevent I from being removed!
367   
368   Constant *Dummy = Constant::getNullValue(Ty);
369
370   switch (I->getOpcode()) {
371   case Instruction::Cast:
372     assert(VMC.NewCasts.count(ValueHandle(VMC, I)) == 0);
373     Res = new CastInst(I->getOperand(0), Ty, Name);
374     VMC.NewCasts.insert(ValueHandle(VMC, Res));
375     break;
376     
377   case Instruction::Add:
378   case Instruction::Sub:
379     Res = BinaryOperator::create(cast<BinaryOperator>(I)->getOpcode(),
380                                  Dummy, Dummy, Name);
381     VMC.ExprMap[I] = Res;   // Add node to expression eagerly
382
383     Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), Ty, VMC, TD));
384     Res->setOperand(1, ConvertExpressionToType(I->getOperand(1), Ty, VMC, TD));
385     break;
386
387   case Instruction::Shl:
388   case Instruction::Shr:
389     Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(), Dummy,
390                         I->getOperand(1), Name);
391     VMC.ExprMap[I] = Res;
392     Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), Ty, VMC, TD));
393     break;
394
395   case Instruction::Load: {
396     LoadInst *LI = cast<LoadInst>(I);
397
398     Res = new LoadInst(Constant::getNullValue(PointerType::get(Ty)), Name);
399     VMC.ExprMap[I] = Res;
400     Res->setOperand(0, ConvertExpressionToType(LI->getPointerOperand(),
401                                                PointerType::get(Ty), VMC, TD));
402     assert(Res->getOperand(0)->getType() == PointerType::get(Ty));
403     assert(Ty == Res->getType());
404     assert(Res->getType()->isFirstClassType() && "Load of structure or array!");
405     break;
406   }
407
408   case Instruction::PHI: {
409     PHINode *OldPN = cast<PHINode>(I);
410     PHINode *NewPN = new PHINode(Ty, Name);
411
412     VMC.ExprMap[I] = NewPN;   // Add node to expression eagerly
413     while (OldPN->getNumOperands()) {
414       BasicBlock *BB = OldPN->getIncomingBlock(0);
415       Value *OldVal = OldPN->getIncomingValue(0);
416       ValueHandle OldValHandle(VMC, OldVal);
417       OldPN->removeIncomingValue(BB, false);
418       Value *V = ConvertExpressionToType(OldVal, Ty, VMC, TD);
419       NewPN->addIncoming(V, BB);
420     }
421     Res = NewPN;
422     break;
423   }
424
425   case Instruction::Malloc: {
426     Res = ConvertMallocToType(cast<MallocInst>(I), Ty, Name, VMC, TD);
427     break;
428   }
429
430   case Instruction::GetElementPtr: {
431     // GetElementPtr's are directly convertible to a pointer type if they have
432     // a number of zeros at the end.  Because removing these values does not
433     // change the logical offset of the GEP, it is okay and fair to remove them.
434     // This can change this:
435     //   %t1 = getelementptr %Hosp * %hosp, ubyte 4, ubyte 0  ; <%List **>
436     //   %t2 = cast %List * * %t1 to %List *
437     // into
438     //   %t2 = getelementptr %Hosp * %hosp, ubyte 4           ; <%List *>
439     // 
440     GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
441
442     // Check to see if there are zero elements that we can remove from the
443     // index array.  If there are, check to see if removing them causes us to
444     // get to the right type...
445     //
446     std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
447     const Type *BaseType = GEP->getPointerOperand()->getType();
448     const Type *PVTy = cast<PointerType>(Ty)->getElementType();
449     Res = 0;
450     while (!Indices.empty() &&
451            Indices.back() == Constant::getNullValue(Indices.back()->getType())){
452       Indices.pop_back();
453       if (GetElementPtrInst::getIndexedType(BaseType, Indices, true) == PVTy) {
454         if (Indices.size() == 0)
455           Res = new CastInst(GEP->getPointerOperand(), BaseType); // NOOP CAST
456         else
457           Res = new GetElementPtrInst(GEP->getPointerOperand(), Indices, Name);
458         break;
459       }
460     }
461
462     if (Res == 0 && GEP->getNumOperands() == 2 &&
463         GEP->getType() == PointerType::get(Type::SByteTy)) {
464       
465       // Otherwise, we can convert a GEP from one form to the other iff the
466       // current gep is of the form 'getelementptr sbyte*, unsigned N
467       // and we could convert this to an appropriate GEP for the new type.
468       //
469       const PointerType *NewSrcTy = PointerType::get(PVTy);
470       BasicBlock::iterator It = I;
471
472       // Check to see if 'N' is an expression that can be converted to
473       // the appropriate size... if so, allow it.
474       //
475       std::vector<Value*> Indices;
476       const Type *ElTy = ConvertibleToGEP(NewSrcTy, I->getOperand(1),
477                                           Indices, TD, &It);
478       if (ElTy) {        
479         assert(ElTy == PVTy && "Internal error, setup wrong!");
480         Res = new GetElementPtrInst(Constant::getNullValue(NewSrcTy),
481                                     Indices, Name);
482         VMC.ExprMap[I] = Res;
483         Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
484                                                    NewSrcTy, VMC, TD));
485       }
486     }
487
488     // Otherwise, it could be that we have something like this:
489     //     getelementptr [[sbyte] *] * %reg115, uint %reg138    ; [sbyte]**
490     // and want to convert it into something like this:
491     //     getelemenptr [[int] *] * %reg115, uint %reg138      ; [int]**
492     //
493     if (Res == 0) {
494       const PointerType *NewSrcTy = PointerType::get(PVTy);
495       std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
496       Res = new GetElementPtrInst(Constant::getNullValue(NewSrcTy),
497                                   Indices, Name);
498       VMC.ExprMap[I] = Res;
499       Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
500                                                  NewSrcTy, VMC, TD));
501     }
502
503
504     assert(Res && "Didn't find match!");
505     break;
506   }
507
508   case Instruction::Call: {
509     assert(!isa<Function>(I->getOperand(0)));
510
511     // If this is a function pointer, we can convert the return type if we can
512     // convert the source function pointer.
513     //
514     const PointerType *PT = cast<PointerType>(I->getOperand(0)->getType());
515     const FunctionType *FT = cast<FunctionType>(PT->getElementType());
516     std::vector<const Type *> ArgTys(FT->getParamTypes().begin(),
517                                      FT->getParamTypes().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         // FIXME, PR82
800         TempScale = BinaryOperator::create(Instruction::Mul, Index,
801                                            ConstantSInt::get(Type::LongTy,
802                                                              DataSize));
803         Index = TempScale;
804       }
805
806       // Check to see if the second argument is an expression that can
807       // be converted to the appropriate size... if so, allow it.
808       //
809       std::vector<Value*> Indices;
810       const Type *ElTy = ConvertibleToGEP(Ty, Index, Indices, TD);
811       delete TempScale;   // Free our temporary multiply if we made it
812
813       if (ElTy == 0) return false;  // Cannot make conversion...
814       return ValueConvertibleToType(I, PointerType::get(ElTy), CTMap, TD);
815     }
816     return false;
817
818   case Instruction::PHI: {
819     PHINode *PN = cast<PHINode>(I);
820     for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i)
821       if (!ExpressionConvertibleToType(PN->getIncomingValue(i), Ty, CTMap, TD))
822         return false;
823     return ValueConvertibleToType(PN, Ty, CTMap, TD);
824   }
825
826   case Instruction::Call: {
827     User::op_iterator OI = find(I->op_begin(), I->op_end(), V);
828     assert (OI != I->op_end() && "Not using value!");
829     unsigned OpNum = OI - I->op_begin();
830
831     // Are we trying to change the function pointer value to a new type?
832     if (OpNum == 0) {
833       const PointerType *PTy = dyn_cast<PointerType>(Ty);
834       if (PTy == 0) return false;  // Can't convert to a non-pointer type...
835       const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
836       if (FTy == 0) return false;  // Can't convert to a non ptr to function...
837
838       // Do not allow converting to a call where all of the operands are ...'s
839       if (FTy->getNumParams() == 0 && FTy->isVarArg())
840         return false;              // Do not permit this conversion!
841
842       // Perform sanity checks to make sure that new function type has the
843       // correct number of arguments...
844       //
845       unsigned NumArgs = I->getNumOperands()-1;  // Don't include function ptr
846
847       // Cannot convert to a type that requires more fixed arguments than
848       // the call provides...
849       //
850       if (NumArgs < FTy->getNumParams()) return false;
851       
852       // Unless this is a vararg function type, we cannot provide more arguments
853       // than are desired...
854       //
855       if (!FTy->isVarArg() && NumArgs > FTy->getNumParams())
856         return false;
857
858       // Okay, at this point, we know that the call and the function type match
859       // number of arguments.  Now we see if we can convert the arguments
860       // themselves.  Note that we do not require operands to be convertible,
861       // we can insert casts if they are convertible but not compatible.  The
862       // reason for this is that we prefer to have resolved functions but casted
863       // arguments if possible.
864       //
865       const FunctionType::ParamTypes &PTs = FTy->getParamTypes();
866       for (unsigned i = 0, NA = PTs.size(); i < NA; ++i)
867         if (!PTs[i]->isLosslesslyConvertibleTo(I->getOperand(i+1)->getType()))
868           return false;   // Operands must have compatible types!
869
870       // Okay, at this point, we know that all of the arguments can be
871       // converted.  We succeed if we can change the return type if
872       // necessary...
873       //
874       return ValueConvertibleToType(I, FTy->getReturnType(), CTMap, TD);
875     }
876     
877     const PointerType *MPtr = cast<PointerType>(I->getOperand(0)->getType());
878     const FunctionType *FTy = cast<FunctionType>(MPtr->getElementType());
879     if (!FTy->isVarArg()) return false;
880
881     if ((OpNum-1) < FTy->getParamTypes().size())
882       return false;  // It's not in the varargs section...
883
884     // If we get this far, we know the value is in the varargs section of the
885     // function!  We can convert if we don't reinterpret the value...
886     //
887     return Ty->isLosslesslyConvertibleTo(V->getType());
888   }
889   }
890   return false;
891 }
892
893
894 void llvm::ConvertValueToNewType(Value *V, Value *NewVal, ValueMapCache &VMC,
895                                  const TargetData &TD) {
896   ValueHandle VH(VMC, V);
897
898   unsigned NumUses = V->use_size();
899   for (unsigned It = 0; It < NumUses; ) {
900     unsigned OldSize = NumUses;
901     Value::use_iterator UI = V->use_begin();
902     std::advance(UI, It);
903     ConvertOperandToType(*UI, V, NewVal, VMC, TD);
904     NumUses = V->use_size();
905     if (NumUses == OldSize) ++It;
906   }
907 }
908
909
910
911 static void ConvertOperandToType(User *U, Value *OldVal, Value *NewVal,
912                                  ValueMapCache &VMC, const TargetData &TD) {
913   if (isa<ValueHandle>(U)) return;  // Valuehandles don't let go of operands...
914
915   if (VMC.OperandsMapped.count(U)) return;
916   VMC.OperandsMapped.insert(U);
917
918   ValueMapCache::ExprMapTy::iterator VMCI = VMC.ExprMap.find(U);
919   if (VMCI != VMC.ExprMap.end())
920     return;
921
922
923   Instruction *I = cast<Instruction>(U);  // Only Instructions convertible
924
925   BasicBlock *BB = I->getParent();
926   assert(BB != 0 && "Instruction not embedded in basic block!");
927   std::string Name = I->getName();
928   I->setName("");
929   Instruction *Res;     // Result of conversion
930
931   //std::cerr << endl << endl << "Type:\t" << Ty << "\nInst: " << I
932   //          << "BB Before: " << BB << endl;
933
934   // Prevent I from being removed...
935   ValueHandle IHandle(VMC, I);
936
937   const Type *NewTy = NewVal->getType();
938   Constant *Dummy = (NewTy != Type::VoidTy) ? 
939                   Constant::getNullValue(NewTy) : 0;
940
941   switch (I->getOpcode()) {
942   case Instruction::Cast:
943     if (VMC.NewCasts.count(ValueHandle(VMC, I))) {
944       // This cast has already had it's value converted, causing a new cast to
945       // be created.  We don't want to create YET ANOTHER cast instruction
946       // representing the original one, so just modify the operand of this cast
947       // instruction, which we know is newly created.
948       I->setOperand(0, NewVal);
949       I->setName(Name);  // give I its name back
950       return;
951
952     } else {
953       Res = new CastInst(NewVal, I->getType(), Name);
954     }
955     break;
956
957   case Instruction::Add:
958     if (isa<PointerType>(NewTy)) {
959       Value *IndexVal = I->getOperand(OldVal == I->getOperand(0) ? 1 : 0);
960       std::vector<Value*> Indices;
961       BasicBlock::iterator It = I;
962
963       if (const Type *ETy = ConvertibleToGEP(NewTy, IndexVal, Indices, TD,&It)){
964         // If successful, convert the add to a GEP
965         //const Type *RetTy = PointerType::get(ETy);
966         // First operand is actually the given pointer...
967         Res = new GetElementPtrInst(NewVal, Indices, Name);
968         assert(cast<PointerType>(Res->getType())->getElementType() == ETy &&
969                "ConvertibleToGEP broken!");
970         break;
971       }
972     }
973     // FALLTHROUGH
974
975   case Instruction::Sub:
976   case Instruction::SetEQ:
977   case Instruction::SetNE: {
978     Res = BinaryOperator::create(cast<BinaryOperator>(I)->getOpcode(),
979                                  Dummy, Dummy, Name);
980     VMC.ExprMap[I] = Res;   // Add node to expression eagerly
981
982     unsigned OtherIdx = (OldVal == I->getOperand(0)) ? 1 : 0;
983     Value *OtherOp    = I->getOperand(OtherIdx);
984     Value *NewOther   = ConvertExpressionToType(OtherOp, NewTy, VMC, TD);
985
986     Res->setOperand(OtherIdx, NewOther);
987     Res->setOperand(!OtherIdx, NewVal);
988     break;
989   }
990   case Instruction::Shl:
991   case Instruction::Shr:
992     assert(I->getOperand(0) == OldVal);
993     Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(), NewVal,
994                         I->getOperand(1), Name);
995     break;
996
997   case Instruction::Free:            // Free can free any pointer type!
998     assert(I->getOperand(0) == OldVal);
999     Res = new FreeInst(NewVal);
1000     break;
1001
1002
1003   case Instruction::Load: {
1004     assert(I->getOperand(0) == OldVal && isa<PointerType>(NewVal->getType()));
1005     const Type *LoadedTy =
1006       cast<PointerType>(NewVal->getType())->getElementType();
1007
1008     Value *Src = NewVal;
1009
1010     if (const CompositeType *CT = dyn_cast<CompositeType>(LoadedTy)) {
1011       std::vector<Value*> Indices;
1012       // FIXME, PR82
1013       Indices.push_back(ConstantSInt::get(Type::LongTy, 0));
1014
1015       unsigned Offset = 0;   // No offset, get first leaf.
1016       LoadedTy = getStructOffsetType(CT, Offset, Indices, TD, false);
1017       assert(LoadedTy->isFirstClassType());
1018
1019       if (Indices.size() != 1) {     // Do not generate load X, 0
1020         // Insert the GEP instruction before this load.
1021         Src = new GetElementPtrInst(Src, Indices, Name+".idx", I);
1022       }
1023     }
1024     
1025     Res = new LoadInst(Src, Name);
1026     assert(Res->getType()->isFirstClassType() && "Load of structure or array!");
1027     break;
1028   }
1029
1030   case Instruction::Store: {
1031     if (I->getOperand(0) == OldVal) {  // Replace the source value
1032       // Check to see if operand #1 has already been converted...
1033       ValueMapCache::ExprMapTy::iterator VMCI =
1034         VMC.ExprMap.find(I->getOperand(1));
1035       if (VMCI != VMC.ExprMap.end()) {
1036         // Comments describing this stuff are in the OperandConvertibleToType
1037         // switch statement for Store...
1038         //
1039         const Type *ElTy =
1040           cast<PointerType>(VMCI->second->getType())->getElementType();
1041         
1042         Value *SrcPtr = VMCI->second;
1043
1044         if (ElTy != NewTy) {
1045           // We check that this is a struct in the initial scan...
1046           const StructType *SElTy = cast<StructType>(ElTy);
1047           
1048           std::vector<Value*> Indices;
1049           // FIXME, PR82
1050           Indices.push_back(Constant::getNullValue(Type::LongTy));
1051
1052           unsigned Offset = 0;
1053           const Type *Ty = getStructOffsetType(ElTy, Offset, Indices, TD,false);
1054           assert(Offset == 0 && "Offset changed!");
1055           assert(NewTy == Ty && "Did not convert to correct type!");
1056
1057           // Insert the GEP instruction before this store.
1058           SrcPtr = new GetElementPtrInst(SrcPtr, Indices,
1059                                          SrcPtr->getName()+".idx", I);
1060         }
1061         Res = new StoreInst(NewVal, SrcPtr);
1062
1063         VMC.ExprMap[I] = Res;
1064       } else {
1065         // Otherwise, we haven't converted Operand #1 over yet...
1066         const PointerType *NewPT = PointerType::get(NewTy);
1067         Res = new StoreInst(NewVal, Constant::getNullValue(NewPT));
1068         VMC.ExprMap[I] = Res;
1069         Res->setOperand(1, ConvertExpressionToType(I->getOperand(1),
1070                                                    NewPT, VMC, TD));
1071       }
1072     } else {                           // Replace the source pointer
1073       const Type *ValTy = cast<PointerType>(NewTy)->getElementType();
1074
1075       Value *SrcPtr = NewVal;
1076
1077       if (isa<StructType>(ValTy)) {
1078         std::vector<Value*> Indices;
1079         // FIXME: PR82
1080         Indices.push_back(Constant::getNullValue(Type::LongTy));
1081
1082         unsigned Offset = 0;
1083         ValTy = getStructOffsetType(ValTy, Offset, Indices, TD, false);
1084
1085         assert(Offset == 0 && ValTy);
1086
1087         // Insert the GEP instruction before this store.
1088         SrcPtr = new GetElementPtrInst(SrcPtr, Indices,
1089                                        SrcPtr->getName()+".idx", I);
1090       }
1091
1092       Res = new StoreInst(Constant::getNullValue(ValTy), SrcPtr);
1093       VMC.ExprMap[I] = Res;
1094       Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
1095                                                  ValTy, VMC, TD));
1096     }
1097     break;
1098   }
1099
1100
1101   case Instruction::GetElementPtr: {
1102     // Convert a one index getelementptr into just about anything that is
1103     // desired.
1104     //
1105     BasicBlock::iterator It = I;
1106     const Type *OldElTy = cast<PointerType>(I->getType())->getElementType();
1107     unsigned DataSize = TD.getTypeSize(OldElTy);
1108     Value *Index = I->getOperand(1);
1109
1110     if (DataSize != 1) {
1111       // Insert a multiply of the old element type is not a unit size...
1112       Index = BinaryOperator::create(Instruction::Mul, Index,
1113                                      // FIXME: PR82
1114                                      ConstantSInt::get(Type::LongTy, DataSize),
1115                                      "scale", It);
1116     }
1117
1118     // Perform the conversion now...
1119     //
1120     std::vector<Value*> Indices;
1121     const Type *ElTy = ConvertibleToGEP(NewVal->getType(),Index,Indices,TD,&It);
1122     assert(ElTy != 0 && "GEP Conversion Failure!");
1123     Res = new GetElementPtrInst(NewVal, Indices, Name);
1124     assert(Res->getType() == PointerType::get(ElTy) &&
1125            "ConvertibleToGet failed!");
1126   }
1127 #if 0
1128     if (I->getType() == PointerType::get(Type::SByteTy)) {
1129       // Convert a getelementptr sbyte * %reg111, uint 16 freely back to
1130       // anything that is a pointer type...
1131       //
1132       BasicBlock::iterator It = I;
1133     
1134       // Check to see if the second argument is an expression that can
1135       // be converted to the appropriate size... if so, allow it.
1136       //
1137       std::vector<Value*> Indices;
1138       const Type *ElTy = ConvertibleToGEP(NewVal->getType(), I->getOperand(1),
1139                                           Indices, TD, &It);
1140       assert(ElTy != 0 && "GEP Conversion Failure!");
1141       
1142       Res = new GetElementPtrInst(NewVal, Indices, Name);
1143     } else {
1144       // Convert a getelementptr ulong * %reg123, uint %N
1145       // to        getelementptr  long * %reg123, uint %N
1146       // ... where the type must simply stay the same size...
1147       //
1148       GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
1149       std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
1150       Res = new GetElementPtrInst(NewVal, Indices, Name);
1151     }
1152 #endif
1153     break;
1154
1155   case Instruction::PHI: {
1156     PHINode *OldPN = cast<PHINode>(I);
1157     PHINode *NewPN = new PHINode(NewTy, Name);
1158     VMC.ExprMap[I] = NewPN;
1159
1160     while (OldPN->getNumOperands()) {
1161       BasicBlock *BB = OldPN->getIncomingBlock(0);
1162       Value *OldVal = OldPN->getIncomingValue(0);
1163       OldPN->removeIncomingValue(BB, false);
1164       Value *V = ConvertExpressionToType(OldVal, NewTy, VMC, TD);
1165       NewPN->addIncoming(V, BB);
1166     }
1167     Res = NewPN;
1168     break;
1169   }
1170
1171   case Instruction::Call: {
1172     Value *Meth = I->getOperand(0);
1173     std::vector<Value*> Params(I->op_begin()+1, I->op_end());
1174
1175     if (Meth == OldVal) {   // Changing the function pointer?
1176       const PointerType *NewPTy = cast<PointerType>(NewVal->getType());
1177       const FunctionType *NewTy = cast<FunctionType>(NewPTy->getElementType());
1178       const FunctionType::ParamTypes &PTs = NewTy->getParamTypes();
1179
1180       if (NewTy->getReturnType() == Type::VoidTy)
1181         Name = "";  // Make sure not to name a void call!
1182
1183       // Get an iterator to the call instruction so that we can insert casts for
1184       // operands if need be.  Note that we do not require operands to be
1185       // convertible, we can insert casts if they are convertible but not
1186       // compatible.  The reason for this is that we prefer to have resolved
1187       // functions but casted arguments if possible.
1188       //
1189       BasicBlock::iterator It = I;
1190
1191       // Convert over all of the call operands to their new types... but only
1192       // convert over the part that is not in the vararg section of the call.
1193       //
1194       for (unsigned i = 0; i < PTs.size(); ++i)
1195         if (Params[i]->getType() != PTs[i]) {
1196           // Create a cast to convert it to the right type, we know that this
1197           // is a lossless cast...
1198           //
1199           Params[i] = new CastInst(Params[i], PTs[i],  "callarg.cast." +
1200                                    Params[i]->getName(), It);
1201         }
1202       Meth = NewVal;  // Update call destination to new value
1203
1204     } else {                   // Changing an argument, must be in vararg area
1205       std::vector<Value*>::iterator OI =
1206         find(Params.begin(), Params.end(), OldVal);
1207       assert (OI != Params.end() && "Not using value!");
1208
1209       *OI = NewVal;
1210     }
1211
1212     Res = new CallInst(Meth, Params, Name);
1213     break;
1214   }
1215   default:
1216     assert(0 && "Expression convertible, but don't know how to convert?");
1217     return;
1218   }
1219
1220   // If the instruction was newly created, insert it into the instruction
1221   // stream.
1222   //
1223   BasicBlock::iterator It = I;
1224   assert(It != BB->end() && "Instruction not in own basic block??");
1225   BB->getInstList().insert(It, Res);   // Keep It pointing to old instruction
1226
1227   DEBUG(std::cerr << "COT CREATED: "  << (void*)Res << " " << Res
1228                   << "In: " << (void*)I << " " << I << "Out: " << (void*)Res
1229                   << " " << Res);
1230
1231   // Add the instruction to the expression map
1232   VMC.ExprMap[I] = Res;
1233
1234   if (I->getType() != Res->getType())
1235     ConvertValueToNewType(I, Res, VMC, TD);
1236   else {
1237     bool FromStart = true;
1238     Value::use_iterator UI;
1239     while (1) {
1240       if (FromStart) UI = I->use_begin();
1241       if (UI == I->use_end()) break;
1242       
1243       if (isa<ValueHandle>(*UI)) {
1244         ++UI;
1245         FromStart = false;
1246       } else {
1247         User *U = *UI;
1248         if (!FromStart) --UI;
1249         U->replaceUsesOfWith(I, Res);
1250         if (!FromStart) ++UI;
1251       }
1252     }
1253   }
1254 }
1255
1256
1257 ValueHandle::ValueHandle(ValueMapCache &VMC, Value *V)
1258   : Instruction(Type::VoidTy, UserOp1, ""), Cache(VMC) {
1259   //DEBUG(std::cerr << "VH AQUIRING: " << (void*)V << " " << V);
1260   Operands.push_back(Use(V, this));
1261 }
1262
1263 ValueHandle::ValueHandle(const ValueHandle &VH)
1264   : Instruction(Type::VoidTy, UserOp1, ""), Cache(VH.Cache) {
1265   //DEBUG(std::cerr << "VH AQUIRING: " << (void*)V << " " << V);
1266   Operands.push_back(Use((Value*)VH.getOperand(0), this));
1267 }
1268
1269 static void RecursiveDelete(ValueMapCache &Cache, Instruction *I) {
1270   if (!I || !I->use_empty()) return;
1271
1272   assert(I->getParent() && "Inst not in basic block!");
1273
1274   //DEBUG(std::cerr << "VH DELETING: " << (void*)I << " " << I);
1275
1276   for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); 
1277        OI != OE; ++OI)
1278     if (Instruction *U = dyn_cast<Instruction>(OI)) {
1279       *OI = 0;
1280       RecursiveDelete(Cache, U);
1281     }
1282
1283   I->getParent()->getInstList().remove(I);
1284
1285   Cache.OperandsMapped.erase(I);
1286   Cache.ExprMap.erase(I);
1287   delete I;
1288 }
1289
1290 ValueHandle::~ValueHandle() {
1291   if (Operands[0]->hasOneUse()) {
1292     Value *V = Operands[0];
1293     Operands[0] = 0;   // Drop use!
1294
1295     // Now we just need to remove the old instruction so we don't get infinite
1296     // loops.  Note that we cannot use DCE because DCE won't remove a store
1297     // instruction, for example.
1298     //
1299     RecursiveDelete(Cache, dyn_cast<Instruction>(V));
1300   } else {
1301     //DEBUG(std::cerr << "VH RELEASING: " << (void*)Operands[0].get() << " "
1302     //                << Operands[0]->use_size() << " " << Operands[0]);
1303   }
1304 }
1305