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