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