d716bca76deaafe41497c44c8f2dddd6ef6d1ad3
[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       // Must move the same amount of data...
725       if (TD.getTypeSize(ElTy) != TD.getTypeSize(I->getOperand(0)->getType()))
726         return false;
727
728       // Can convert store if the incoming value is convertable...
729       return ExpressionConvertableToType(I->getOperand(0), ElTy, CTMap);
730     }
731     return false;
732   }
733
734   case Instruction::GetElementPtr:
735     if (V != I->getOperand(0) || !isa<PointerType>(Ty)) return false;
736
737     // If we have a two operand form of getelementptr, this is really little
738     // more than a simple addition.  As with addition, check to see if the
739     // getelementptr instruction can be changed to index into the new type.
740     //
741     if (I->getNumOperands() == 2) {
742       const Type *OldElTy = cast<PointerType>(I->getType())->getElementType();
743       unsigned DataSize = TD.getTypeSize(OldElTy);
744       Value *Index = I->getOperand(1);
745       Instruction *TempScale = 0;
746
747       // If the old data element is not unit sized, we have to create a scale
748       // instruction so that ConvertableToGEP will know the REAL amount we are
749       // indexing by.  Note that this is never inserted into the instruction
750       // stream, so we have to delete it when we're done.
751       //
752       if (DataSize != 1) {
753         TempScale = BinaryOperator::create(Instruction::Mul, Index,
754                                            ConstantUInt::get(Type::UIntTy,
755                                                              DataSize));
756         Index = TempScale;
757       }
758
759       // Check to see if the second argument is an expression that can
760       // be converted to the appropriate size... if so, allow it.
761       //
762       std::vector<Value*> Indices;
763       const Type *ElTy = ConvertableToGEP(Ty, Index, Indices);
764       delete TempScale;   // Free our temporary multiply if we made it
765
766       if (ElTy == 0) return false;  // Cannot make conversion...
767       return ValueConvertableToType(I, PointerType::get(ElTy), CTMap);
768     }
769     return false;
770
771   case Instruction::PHINode: {
772     PHINode *PN = cast<PHINode>(I);
773     for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i)
774       if (!ExpressionConvertableToType(PN->getIncomingValue(i), Ty, CTMap))
775         return false;
776     return ValueConvertableToType(PN, Ty, CTMap);
777   }
778
779   case Instruction::Call: {
780     User::op_iterator OI = find(I->op_begin(), I->op_end(), V);
781     assert (OI != I->op_end() && "Not using value!");
782     unsigned OpNum = OI - I->op_begin();
783
784     // Are we trying to change the method pointer value to a new type?
785     if (OpNum == 0) {
786       PointerType *PTy = dyn_cast<PointerType>(Ty);
787       if (PTy == 0) return false;  // Can't convert to a non-pointer type...
788       MethodType *MTy = dyn_cast_or_null<MethodType>(PTy->getElementType());
789       if (MTy == 0) return false;  // Can't convert to a non ptr to method...
790
791       // Perform sanity checks to make sure that new method type has the
792       // correct number of arguments...
793       //
794       unsigned NumArgs = I->getNumOperands()-1;  // Don't include method ptr
795
796       // Cannot convert to a type that requires more fixed arguments than
797       // the call provides...
798       //
799       if (NumArgs < MTy->getParamTypes().size()) return false;
800       
801       // Unless this is a vararg method type, we cannot provide more arguments
802       // than are desired...
803       //
804       if (!MTy->isVarArg() && NumArgs > MTy->getParamTypes().size())
805         return false;
806
807       // Okay, at this point, we know that the call and the method type match
808       // number of arguments.  Now we see if we can convert the arguments
809       // themselves.
810       //
811       const MethodType::ParamTypes &PTs = MTy->getParamTypes();
812       for (unsigned i = 0, NA = PTs.size(); i < NA; ++i)
813         if (!PTs[i]->isLosslesslyConvertableTo(I->getOperand(i+1)->getType()))
814           return false;   // Operands must have compatible types!
815
816       // Okay, at this point, we know that all of the arguments can be
817       // converted.  We succeed if we can change the return type if
818       // neccesary...
819       //
820       return ValueConvertableToType(I, MTy->getReturnType(), CTMap);
821     }
822     
823     const PointerType *MPtr = cast<PointerType>(I->getOperand(0)->getType());
824     const MethodType *MTy = cast<MethodType>(MPtr->getElementType());
825     if (!MTy->isVarArg()) return false;
826
827     if ((OpNum-1) < MTy->getParamTypes().size())
828       return false;  // It's not in the varargs section...
829
830     // If we get this far, we know the value is in the varargs section of the
831     // method!  We can convert if we don't reinterpret the value...
832     //
833     return Ty->isLosslesslyConvertableTo(V->getType());
834   }
835   }
836   return false;
837 }
838
839
840 void ConvertValueToNewType(Value *V, Value *NewVal, ValueMapCache &VMC) {
841   ValueHandle VH(VMC, V);
842
843   unsigned NumUses = V->use_size();
844   for (unsigned It = 0; It < NumUses; ) {
845     unsigned OldSize = NumUses;
846     ConvertOperandToType(*(V->use_begin()+It), V, NewVal, VMC);
847     NumUses = V->use_size();
848     if (NumUses == OldSize) ++It;
849   }
850 }
851
852
853
854 static void ConvertOperandToType(User *U, Value *OldVal, Value *NewVal,
855                                  ValueMapCache &VMC) {
856   if (isa<ValueHandle>(U)) return;  // Valuehandles don't let go of operands...
857
858   if (VMC.OperandsMapped.count(U)) return;
859   VMC.OperandsMapped.insert(U);
860
861   ValueMapCache::ExprMapTy::iterator VMCI = VMC.ExprMap.find(U);
862   if (VMCI != VMC.ExprMap.end())
863     return;
864
865
866   Instruction *I = cast<Instruction>(U);  // Only Instructions convertable
867
868   BasicBlock *BB = I->getParent();
869   BasicBlock::InstListType &BIL = BB->getInstList();
870   std::string Name = I->getName();  if (!Name.empty()) I->setName("");
871   Instruction *Res;     // Result of conversion
872
873   //cerr << endl << endl << "Type:\t" << Ty << "\nInst: " << I << "BB Before: " << BB << endl;
874
875   // Prevent I from being removed...
876   ValueHandle IHandle(VMC, I);
877
878   const Type *NewTy = NewVal->getType();
879   Constant *Dummy = (NewTy != Type::VoidTy) ? 
880                   Constant::getNullConstant(NewTy) : 0;
881
882   switch (I->getOpcode()) {
883   case Instruction::Cast:
884     assert(I->getOperand(0) == OldVal);
885     Res = new CastInst(NewVal, I->getType(), Name);
886     break;
887
888   case Instruction::Add:
889     if (isa<PointerType>(NewTy)) {
890       Value *IndexVal = I->getOperand(OldVal == I->getOperand(0) ? 1 : 0);
891       std::vector<Value*> Indices;
892       BasicBlock::iterator It = find(BIL.begin(), BIL.end(), I);
893
894       if (const Type *ETy = ConvertableToGEP(NewTy, IndexVal, Indices, &It)) {
895         // If successful, convert the add to a GEP
896         //const Type *RetTy = PointerType::get(ETy);
897         // First operand is actually the given pointer...
898         Res = new GetElementPtrInst(NewVal, Indices, Name);
899         assert(cast<PointerType>(Res->getType())->getElementType() == ETy &&
900                "ConvertableToGEP broken!");
901         break;
902       }
903     }
904     // FALLTHROUGH
905
906   case Instruction::Sub:
907   case Instruction::SetEQ:
908   case Instruction::SetNE: {
909     Res = BinaryOperator::create(cast<BinaryOperator>(I)->getOpcode(),
910                                  Dummy, Dummy, Name);
911     VMC.ExprMap[I] = Res;   // Add node to expression eagerly
912
913     unsigned OtherIdx = (OldVal == I->getOperand(0)) ? 1 : 0;
914     Value *OtherOp    = I->getOperand(OtherIdx);
915     Value *NewOther   = ConvertExpressionToType(OtherOp, NewTy, VMC);
916
917     Res->setOperand(OtherIdx, NewOther);
918     Res->setOperand(!OtherIdx, NewVal);
919     break;
920   }
921   case Instruction::Shl:
922   case Instruction::Shr:
923     assert(I->getOperand(0) == OldVal);
924     Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(), NewVal,
925                         I->getOperand(1), Name);
926     break;
927
928   case Instruction::Free:            // Free can free any pointer type!
929     assert(I->getOperand(0) == OldVal);
930     Res = new FreeInst(NewVal);
931     break;
932
933
934   case Instruction::Load: {
935     assert(I->getOperand(0) == OldVal && isa<PointerType>(NewVal->getType()));
936     const Type *LoadedTy =
937       cast<PointerType>(NewVal->getType())->getElementType();
938
939     std::vector<Value*> Indices;
940     Indices.push_back(ConstantUInt::get(Type::UIntTy, 0));
941
942     if (const CompositeType *CT = dyn_cast<CompositeType>(LoadedTy)) {
943       unsigned Offset = 0;   // No offset, get first leaf.
944       LoadedTy = getStructOffsetType(CT, Offset, Indices, false);
945     }
946     assert(LoadedTy->isFirstClassType());
947
948     Res = new LoadInst(NewVal, Indices, Name);
949     assert(Res->getType()->isFirstClassType() && "Load of structure or array!");
950     break;
951   }
952
953   case Instruction::Store: {
954     if (I->getOperand(0) == OldVal) {  // Replace the source value
955       const PointerType *NewPT = PointerType::get(NewTy);
956       Res = new StoreInst(NewVal, Constant::getNullConstant(NewPT));
957       VMC.ExprMap[I] = Res;
958       Res->setOperand(1, ConvertExpressionToType(I->getOperand(1), NewPT, VMC));
959     } else {                           // Replace the source pointer
960       const Type *ValTy = cast<PointerType>(NewTy)->getElementType();
961       std::vector<Value*> Indices;
962 #if 0
963       Indices.push_back(ConstantUInt::get(Type::UIntTy, 0));
964       while (ArrayType *AT = dyn_cast<ArrayType>(ValTy)) {
965         Indices.push_back(ConstantUInt::get(Type::UIntTy, 0));
966         ValTy = AT->getElementType();
967       }
968 #endif
969       Res = new StoreInst(Constant::getNullConstant(ValTy), NewVal, Indices);
970       VMC.ExprMap[I] = Res;
971       Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), ValTy, VMC));
972     }
973     break;
974   }
975
976
977   case Instruction::GetElementPtr: {
978     // Convert a one index getelementptr into just about anything that is
979     // desired.
980     //
981     BasicBlock::iterator It = find(BIL.begin(), BIL.end(), I);
982     const Type *OldElTy = cast<PointerType>(I->getType())->getElementType();
983     unsigned DataSize = TD.getTypeSize(OldElTy);
984     Value *Index = I->getOperand(1);
985
986     if (DataSize != 1) {
987       // Insert a multiply of the old element type is not a unit size...
988       Index = BinaryOperator::create(Instruction::Mul, Index,
989                                      ConstantUInt::get(Type::UIntTy, DataSize));
990       It = BIL.insert(It, cast<Instruction>(Index))+1;
991     }
992
993     // Perform the conversion now...
994     //
995     std::vector<Value*> Indices;
996     const Type *ElTy = ConvertableToGEP(NewVal->getType(), Index, Indices, &It);
997     assert(ElTy != 0 && "GEP Conversion Failure!");
998     Res = new GetElementPtrInst(NewVal, Indices, Name);
999     assert(Res->getType() == PointerType::get(ElTy) &&
1000            "ConvertableToGet failed!");
1001   }
1002 #if 0
1003     if (I->getType() == PointerType::get(Type::SByteTy)) {
1004       // Convert a getelementptr sbyte * %reg111, uint 16 freely back to
1005       // anything that is a pointer type...
1006       //
1007       BasicBlock::iterator It = find(BIL.begin(), BIL.end(), I);
1008     
1009       // Check to see if the second argument is an expression that can
1010       // be converted to the appropriate size... if so, allow it.
1011       //
1012       std::vector<Value*> Indices;
1013       const Type *ElTy = ConvertableToGEP(NewVal->getType(), I->getOperand(1),
1014                                           Indices, &It);
1015       assert(ElTy != 0 && "GEP Conversion Failure!");
1016       
1017       Res = new GetElementPtrInst(NewVal, Indices, Name);
1018     } else {
1019       // Convert a getelementptr ulong * %reg123, uint %N
1020       // to        getelementptr  long * %reg123, uint %N
1021       // ... where the type must simply stay the same size...
1022       //
1023       Res = new GetElementPtrInst(NewVal,
1024                                   cast<GetElementPtrInst>(I)->copyIndices(),
1025                                   Name);
1026     }
1027 #endif
1028     break;
1029
1030   case Instruction::PHINode: {
1031     PHINode *OldPN = cast<PHINode>(I);
1032     PHINode *NewPN = new PHINode(NewTy, Name);
1033     VMC.ExprMap[I] = NewPN;
1034
1035     while (OldPN->getNumOperands()) {
1036       BasicBlock *BB = OldPN->getIncomingBlock(0);
1037       Value *OldVal = OldPN->getIncomingValue(0);
1038       OldPN->removeIncomingValue(BB);
1039       Value *V = ConvertExpressionToType(OldVal, NewTy, VMC);
1040       NewPN->addIncoming(V, BB);
1041     }
1042     Res = NewPN;
1043     break;
1044   }
1045
1046   case Instruction::Call: {
1047     Value *Meth = I->getOperand(0);
1048     std::vector<Value*> Params(I->op_begin()+1, I->op_end());
1049
1050     if (Meth == OldVal) {   // Changing the method pointer?
1051       PointerType *NewPTy = cast<PointerType>(NewVal->getType());
1052       MethodType *NewTy = cast<MethodType>(NewPTy->getElementType());
1053       const MethodType::ParamTypes &PTs = NewTy->getParamTypes();
1054
1055       // Convert over all of the call operands to their new types... but only
1056       // convert over the part that is not in the vararg section of the call.
1057       //
1058       for (unsigned i = 0; i < PTs.size(); ++i)
1059         Params[i] = ConvertExpressionToType(Params[i], PTs[i], VMC);
1060       Meth = NewVal;  // Update call destination to new value
1061
1062     } else {                   // Changing an argument, must be in vararg area
1063       std::vector<Value*>::iterator OI =
1064         find(Params.begin(), Params.end(), OldVal);
1065       assert (OI != Params.end() && "Not using value!");
1066
1067       *OI = NewVal;
1068     }
1069
1070     Res = new CallInst(Meth, Params, Name);
1071     break;
1072   }
1073   default:
1074     assert(0 && "Expression convertable, but don't know how to convert?");
1075     return;
1076   }
1077
1078   // If the instruction was newly created, insert it into the instruction
1079   // stream.
1080   //
1081   BasicBlock::iterator It = find(BIL.begin(), BIL.end(), I);
1082   assert(It != BIL.end() && "Instruction not in own basic block??");
1083   BIL.insert(It, Res);   // Keep It pointing to old instruction
1084
1085 #ifdef DEBUG_EXPR_CONVERT
1086   cerr << "COT CREATED: "  << (void*)Res << " " << Res;
1087   cerr << "In: " << (void*)I << " " << I << "Out: " << (void*)Res << " " << Res;
1088 #endif
1089
1090   // Add the instruction to the expression map
1091   VMC.ExprMap[I] = Res;
1092
1093   if (I->getType() != Res->getType())
1094     ConvertValueToNewType(I, Res, VMC);
1095   else {
1096     for (unsigned It = 0; It < I->use_size(); ) {
1097       User *Use = *(I->use_begin()+It);
1098       if (isa<ValueHandle>(Use))            // Don't remove ValueHandles!
1099         ++It;
1100       else
1101         Use->replaceUsesOfWith(I, Res);
1102     }
1103
1104     if (I->use_empty()) {
1105       // Now we just need to remove the old instruction so we don't get infinite
1106       // loops.  Note that we cannot use DCE because DCE won't remove a store
1107       // instruction, for example.
1108       //
1109 #ifdef DEBUG_EXPR_CONVERT
1110       cerr << "DELETING: " << (void*)I << " " << I;
1111 #endif
1112       BIL.remove(I);
1113       VMC.OperandsMapped.erase(I);
1114       VMC.ExprMap.erase(I);
1115       delete I;
1116     } else {
1117       for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
1118            UI != UE; ++UI)
1119         assert(isa<ValueHandle>((Value*)*UI) &&"Uses of Instruction remain!!!");
1120     }
1121   }
1122 }
1123
1124
1125 ValueHandle::ValueHandle(ValueMapCache &VMC, Value *V)
1126   : Instruction(Type::VoidTy, UserOp1, ""), Cache(VMC) {
1127 #ifdef DEBUG_EXPR_CONVERT
1128   //cerr << "VH AQUIRING: " << (void*)V << " " << V;
1129 #endif
1130   Operands.push_back(Use(V, this));
1131 }
1132
1133 static void RecursiveDelete(ValueMapCache &Cache, Instruction *I) {
1134   if (!I || !I->use_empty()) return;
1135
1136   assert(I->getParent() && "Inst not in basic block!");
1137
1138 #ifdef DEBUG_EXPR_CONVERT
1139   //cerr << "VH DELETING: " << (void*)I << " " << I;
1140 #endif
1141
1142   for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); 
1143        OI != OE; ++OI)
1144     if (Instruction *U = dyn_cast<Instruction>(*OI)) {
1145       *OI = 0;
1146       RecursiveDelete(Cache, U);
1147     }
1148
1149   I->getParent()->getInstList().remove(I);
1150
1151   Cache.OperandsMapped.erase(I);
1152   Cache.ExprMap.erase(I);
1153   delete I;
1154 }
1155
1156 ValueHandle::~ValueHandle() {
1157   if (Operands[0]->use_size() == 1) {
1158     Value *V = Operands[0];
1159     Operands[0] = 0;   // Drop use!
1160
1161     // Now we just need to remove the old instruction so we don't get infinite
1162     // loops.  Note that we cannot use DCE because DCE won't remove a store
1163     // instruction, for example.
1164     //
1165     RecursiveDelete(Cache, dyn_cast<Instruction>(V));
1166   } else {
1167 #ifdef DEBUG_EXPR_CONVERT
1168     //cerr << "VH RELEASING: " << (void*)Operands[0].get() << " " << Operands[0]->use_size() << " " << Operands[0];
1169 #endif
1170   }
1171 }