Add new constructor to accept vector of exported names while creating
[oota-llvm.git] / lib / Transforms / ExprTypeConvert.cpp
1 //===- ExprTypeConvert.cpp - Code to change an LLVM Expr Type -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the part of level raising that checks to see if it is
11 // possible to coerce an entire expression tree into a different type.  If
12 // convertible, other routines from this file will do the conversion.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "TransformInternals.h"
17 #include "llvm/Constants.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/Support/Debug.h"
21 #include <algorithm>
22 #include <iostream>
23 using namespace llvm;
24
25 static bool OperandConvertibleToType(User *U, Value *V, const Type *Ty,
26                                      ValueTypeCache &ConvertedTypes,
27                                      const TargetData &TD);
28
29 static void ConvertOperandToType(User *U, Value *OldVal, Value *NewVal,
30                                  ValueMapCache &VMC, const TargetData &TD);
31
32
33 // ExpressionConvertibleToType - Return true if it is possible
34 bool llvm::ExpressionConvertibleToType(Value *V, const Type *Ty,
35                                  ValueTypeCache &CTMap, const TargetData &TD) {
36   // Expression type must be holdable in a register.
37   if (!Ty->isFirstClassType())
38     return false;
39
40   ValueTypeCache::iterator CTMI = CTMap.find(V);
41   if (CTMI != CTMap.end()) return CTMI->second == Ty;
42
43   // If it's a constant... all constants can be converted to a different
44   // type.
45   //
46   if (isa<Constant>(V) && !isa<GlobalValue>(V))
47     return true;
48
49   CTMap[V] = Ty;
50   if (V->getType() == Ty) return true;  // Expression already correct type!
51
52   Instruction *I = dyn_cast<Instruction>(V);
53   if (I == 0) return false;              // Otherwise, we can't convert!
54
55   switch (I->getOpcode()) {
56   case Instruction::Cast:
57     // We can convert the expr if the cast destination type is losslessly
58     // convertible to the requested type.
59     if (!Ty->isLosslesslyConvertibleTo(I->getType())) return false;
60
61     // We also do not allow conversion of a cast that casts from a ptr to array
62     // of X to a *X.  For example: cast [4 x %List *] * %val to %List * *
63     //
64     if (const PointerType *SPT =
65         dyn_cast<PointerType>(I->getOperand(0)->getType()))
66       if (const PointerType *DPT = dyn_cast<PointerType>(I->getType()))
67         if (const ArrayType *AT = dyn_cast<ArrayType>(SPT->getElementType()))
68           if (AT->getElementType() == DPT->getElementType())
69             return false;
70     break;
71
72   case Instruction::Add:
73   case Instruction::Sub:
74     if (!Ty->isInteger() && !Ty->isFloatingPoint()) return false;
75     if (!ExpressionConvertibleToType(I->getOperand(0), Ty, CTMap, TD) ||
76         !ExpressionConvertibleToType(I->getOperand(1), Ty, CTMap, TD))
77       return false;
78     break;
79   case Instruction::Shr:
80     if (!Ty->isInteger()) return false;
81     if (Ty->isSigned() != V->getType()->isSigned()) return false;
82     // FALL THROUGH
83   case Instruction::Shl:
84     if (!Ty->isInteger()) return false;
85     if (!ExpressionConvertibleToType(I->getOperand(0), Ty, CTMap, TD))
86       return false;
87     break;
88
89   case Instruction::Load: {
90     LoadInst *LI = cast<LoadInst>(I);
91     if (!ExpressionConvertibleToType(LI->getPointerOperand(),
92                                      PointerType::get(Ty), CTMap, TD))
93       return false;
94     break;
95   }
96   case Instruction::PHI: {
97     PHINode *PN = cast<PHINode>(I);
98     // Be conservative if we find a giant PHI node.
99     if (PN->getNumIncomingValues() > 32) return false;
100
101     for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i)
102       if (!ExpressionConvertibleToType(PN->getIncomingValue(i), Ty, CTMap, TD))
103         return false;
104     break;
105   }
106
107   case Instruction::GetElementPtr: {
108     // GetElementPtr's are directly convertible to a pointer type if they have
109     // a number of zeros at the end.  Because removing these values does not
110     // change the logical offset of the GEP, it is okay and fair to remove them.
111     // This can change this:
112     //   %t1 = getelementptr %Hosp * %hosp, ubyte 4, ubyte 0  ; <%List **>
113     //   %t2 = cast %List * * %t1 to %List *
114     // into
115     //   %t2 = getelementptr %Hosp * %hosp, ubyte 4           ; <%List *>
116     //
117     GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
118     const PointerType *PTy = dyn_cast<PointerType>(Ty);
119     if (!PTy) return false;  // GEP must always return a pointer...
120     const Type *PVTy = PTy->getElementType();
121
122     // Check to see if there are zero elements that we can remove from the
123     // index array.  If there are, check to see if removing them causes us to
124     // get to the right type...
125     //
126     std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
127     const Type *BaseType = GEP->getPointerOperand()->getType();
128     const Type *ElTy = 0;
129
130     while (!Indices.empty() &&
131            Indices.back() == Constant::getNullValue(Indices.back()->getType())){
132       Indices.pop_back();
133       ElTy = GetElementPtrInst::getIndexedType(BaseType, Indices, true);
134       if (ElTy == PVTy)
135         break;  // Found a match!!
136       ElTy = 0;
137     }
138
139     if (ElTy) break;   // Found a number of zeros we can strip off!
140
141     // Otherwise, it could be that we have something like this:
142     //     getelementptr [[sbyte] *] * %reg115, long %reg138    ; [sbyte]**
143     // and want to convert it into something like this:
144     //     getelemenptr [[int] *] * %reg115, long %reg138      ; [int]**
145     //
146     if (GEP->getNumOperands() == 2 &&
147         PTy->getElementType()->isSized() &&
148         TD.getTypeSize(PTy->getElementType()) ==
149         TD.getTypeSize(GEP->getType()->getElementType())) {
150       const PointerType *NewSrcTy = PointerType::get(PVTy);
151       if (!ExpressionConvertibleToType(I->getOperand(0), NewSrcTy, CTMap, TD))
152         return false;
153       break;
154     }
155
156     return false;   // No match, maybe next time.
157   }
158
159   case Instruction::Call: {
160     if (isa<Function>(I->getOperand(0)))
161       return false;  // Don't even try to change direct calls.
162
163     // If this is a function pointer, we can convert the return type if we can
164     // convert the source function pointer.
165     //
166     const PointerType *PT = cast<PointerType>(I->getOperand(0)->getType());
167     const FunctionType *FT = cast<FunctionType>(PT->getElementType());
168     std::vector<const Type *> ArgTys(FT->param_begin(), FT->param_end());
169     const FunctionType *NewTy =
170       FunctionType::get(Ty, ArgTys, FT->isVarArg());
171     if (!ExpressionConvertibleToType(I->getOperand(0),
172                                      PointerType::get(NewTy), CTMap, TD))
173       return false;
174     break;
175   }
176   default:
177     return false;
178   }
179
180   // Expressions are only convertible if all of the users of the expression can
181   // have this value converted.  This makes use of the map to avoid infinite
182   // recursion.
183   //
184   for (Value::use_iterator It = I->use_begin(), E = I->use_end(); It != E; ++It)
185     if (!OperandConvertibleToType(*It, I, Ty, CTMap, TD))
186       return false;
187
188   return true;
189 }
190
191
192 Value *llvm::ConvertExpressionToType(Value *V, const Type *Ty,
193                                      ValueMapCache &VMC, const TargetData &TD) {
194   if (V->getType() == Ty) return V;  // Already where we need to be?
195
196   ValueMapCache::ExprMapTy::iterator VMCI = VMC.ExprMap.find(V);
197   if (VMCI != VMC.ExprMap.end()) {
198     assert(VMCI->second->getType() == Ty);
199
200     if (Instruction *I = dyn_cast<Instruction>(V))
201       ValueHandle IHandle(VMC, I);  // Remove I if it is unused now!
202
203     return VMCI->second;
204   }
205
206   DEBUG(std::cerr << "CETT: " << (void*)V << " " << *V);
207
208   Instruction *I = dyn_cast<Instruction>(V);
209   if (I == 0) {
210     Constant *CPV = cast<Constant>(V);
211     // Constants are converted by constant folding the cast that is required.
212     // We assume here that all casts are implemented for constant prop.
213     Value *Result = ConstantExpr::getCast(CPV, Ty);
214     // Add the instruction to the expression map
215     //VMC.ExprMap[V] = Result;
216     return Result;
217   }
218
219
220   BasicBlock *BB = I->getParent();
221   std::string Name = I->getName();  if (!Name.empty()) I->setName("");
222   Instruction *Res;     // Result of conversion
223
224   ValueHandle IHandle(VMC, I);  // Prevent I from being removed!
225
226   Constant *Dummy = Constant::getNullValue(Ty);
227
228   switch (I->getOpcode()) {
229   case Instruction::Cast:
230     assert(VMC.NewCasts.count(ValueHandle(VMC, I)) == 0);
231     Res = new CastInst(I->getOperand(0), Ty, Name);
232     VMC.NewCasts.insert(ValueHandle(VMC, Res));
233     break;
234
235   case Instruction::Add:
236   case Instruction::Sub:
237     Res = BinaryOperator::create(cast<BinaryOperator>(I)->getOpcode(),
238                                  Dummy, Dummy, Name);
239     VMC.ExprMap[I] = Res;   // Add node to expression eagerly
240
241     Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), Ty, VMC, TD));
242     Res->setOperand(1, ConvertExpressionToType(I->getOperand(1), Ty, VMC, TD));
243     break;
244
245   case Instruction::Shl:
246   case Instruction::Shr:
247     Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(), Dummy,
248                         I->getOperand(1), Name);
249     VMC.ExprMap[I] = Res;
250     Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), Ty, VMC, TD));
251     break;
252
253   case Instruction::Load: {
254     LoadInst *LI = cast<LoadInst>(I);
255
256     Res = new LoadInst(Constant::getNullValue(PointerType::get(Ty)), Name);
257     VMC.ExprMap[I] = Res;
258     Res->setOperand(0, ConvertExpressionToType(LI->getPointerOperand(),
259                                                PointerType::get(Ty), VMC, TD));
260     assert(Res->getOperand(0)->getType() == PointerType::get(Ty));
261     assert(Ty == Res->getType());
262     assert(Res->getType()->isFirstClassType() && "Load of structure or array!");
263     break;
264   }
265
266   case Instruction::PHI: {
267     PHINode *OldPN = cast<PHINode>(I);
268     PHINode *NewPN = new PHINode(Ty, Name);
269
270     VMC.ExprMap[I] = NewPN;   // Add node to expression eagerly
271     while (OldPN->getNumOperands()) {
272       BasicBlock *BB = OldPN->getIncomingBlock(0);
273       Value *OldVal = OldPN->getIncomingValue(0);
274       ValueHandle OldValHandle(VMC, OldVal);
275       OldPN->removeIncomingValue(BB, false);
276       Value *V = ConvertExpressionToType(OldVal, Ty, VMC, TD);
277       NewPN->addIncoming(V, BB);
278     }
279     Res = NewPN;
280     break;
281   }
282
283   case Instruction::GetElementPtr: {
284     // GetElementPtr's are directly convertible to a pointer type if they have
285     // a number of zeros at the end.  Because removing these values does not
286     // change the logical offset of the GEP, it is okay and fair to remove them.
287     // This can change this:
288     //   %t1 = getelementptr %Hosp * %hosp, ubyte 4, ubyte 0  ; <%List **>
289     //   %t2 = cast %List * * %t1 to %List *
290     // into
291     //   %t2 = getelementptr %Hosp * %hosp, ubyte 4           ; <%List *>
292     //
293     GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
294
295     // Check to see if there are zero elements that we can remove from the
296     // index array.  If there are, check to see if removing them causes us to
297     // get to the right type...
298     //
299     std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
300     const Type *BaseType = GEP->getPointerOperand()->getType();
301     const Type *PVTy = cast<PointerType>(Ty)->getElementType();
302     Res = 0;
303     while (!Indices.empty() &&
304            Indices.back() == Constant::getNullValue(Indices.back()->getType())){
305       Indices.pop_back();
306       if (GetElementPtrInst::getIndexedType(BaseType, Indices, true) == PVTy) {
307         if (Indices.size() == 0)
308           Res = new CastInst(GEP->getPointerOperand(), BaseType); // NOOP CAST
309         else
310           Res = new GetElementPtrInst(GEP->getPointerOperand(), Indices, Name);
311         break;
312       }
313     }
314
315     // Otherwise, it could be that we have something like this:
316     //     getelementptr [[sbyte] *] * %reg115, uint %reg138    ; [sbyte]**
317     // and want to convert it into something like this:
318     //     getelemenptr [[int] *] * %reg115, uint %reg138      ; [int]**
319     //
320     if (Res == 0) {
321       const PointerType *NewSrcTy = PointerType::get(PVTy);
322       std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
323       Res = new GetElementPtrInst(Constant::getNullValue(NewSrcTy),
324                                   Indices, Name);
325       VMC.ExprMap[I] = Res;
326       Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
327                                                  NewSrcTy, VMC, TD));
328     }
329
330
331     assert(Res && "Didn't find match!");
332     break;
333   }
334
335   case Instruction::Call: {
336     assert(!isa<Function>(I->getOperand(0)));
337
338     // If this is a function pointer, we can convert the return type if we can
339     // convert the source function pointer.
340     //
341     const PointerType *PT = cast<PointerType>(I->getOperand(0)->getType());
342     const FunctionType *FT = cast<FunctionType>(PT->getElementType());
343     std::vector<const Type *> ArgTys(FT->param_begin(), FT->param_end());
344     const FunctionType *NewTy =
345       FunctionType::get(Ty, ArgTys, FT->isVarArg());
346     const PointerType *NewPTy = PointerType::get(NewTy);
347     if (Ty == Type::VoidTy)
348       Name = "";  // Make sure not to name calls that now return void!
349
350     Res = new CallInst(Constant::getNullValue(NewPTy),
351                        std::vector<Value*>(I->op_begin()+1, I->op_end()),
352                        Name);
353     if (cast<CallInst>(I)->isTailCall())
354       cast<CallInst>(Res)->setTailCall();
355     cast<CallInst>(Res)->setCallingConv(cast<CallInst>(I)->getCallingConv());
356     VMC.ExprMap[I] = Res;
357     Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),NewPTy,VMC,TD));
358     break;
359   }
360   default:
361     assert(0 && "Expression convertible, but don't know how to convert?");
362     return 0;
363   }
364
365   assert(Res->getType() == Ty && "Didn't convert expr to correct type!");
366
367   BB->getInstList().insert(I, Res);
368
369   // Add the instruction to the expression map
370   VMC.ExprMap[I] = Res;
371
372
373   //// WTF is this code!  FIXME: remove this.
374   unsigned NumUses = I->getNumUses();
375   for (unsigned It = 0; It < NumUses; ) {
376     unsigned OldSize = NumUses;
377     Value::use_iterator UI = I->use_begin();
378     std::advance(UI, It);
379     ConvertOperandToType(*UI, I, Res, VMC, TD);
380     NumUses = I->getNumUses();
381     if (NumUses == OldSize) ++It;
382   }
383
384   DEBUG(std::cerr << "ExpIn: " << (void*)I << " " << *I
385                   << "ExpOut: " << (void*)Res << " " << *Res);
386
387   return Res;
388 }
389
390
391
392 // ValueConvertibleToType - Return true if it is possible
393 bool llvm::ValueConvertibleToType(Value *V, const Type *Ty,
394                                   ValueTypeCache &ConvertedTypes,
395                                   const TargetData &TD) {
396   ValueTypeCache::iterator I = ConvertedTypes.find(V);
397   if (I != ConvertedTypes.end()) return I->second == Ty;
398   ConvertedTypes[V] = Ty;
399
400   // It is safe to convert the specified value to the specified type IFF all of
401   // the uses of the value can be converted to accept the new typed value.
402   //
403   if (V->getType() != Ty) {
404     for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I)
405       if (!OperandConvertibleToType(*I, V, Ty, ConvertedTypes, TD))
406         return false;
407   }
408
409   return true;
410 }
411
412
413
414
415
416 // OperandConvertibleToType - Return true if it is possible to convert operand
417 // V of User (instruction) U to the specified type.  This is true iff it is
418 // possible to change the specified instruction to accept this.  CTMap is a map
419 // of converted types, so that circular definitions will see the future type of
420 // the expression, not the static current type.
421 //
422 static bool OperandConvertibleToType(User *U, Value *V, const Type *Ty,
423                                      ValueTypeCache &CTMap,
424                                      const TargetData &TD) {
425   //  if (V->getType() == Ty) return true;   // Operand already the right type?
426
427   // Expression type must be holdable in a register.
428   if (!Ty->isFirstClassType())
429     return false;
430
431   Instruction *I = dyn_cast<Instruction>(U);
432   if (I == 0) return false;              // We can't convert!
433
434   switch (I->getOpcode()) {
435   case Instruction::Cast:
436     assert(I->getOperand(0) == V);
437     // We can convert the expr if the cast destination type is losslessly
438     // convertible to the requested type.
439     // Also, do not change a cast that is a noop cast.  For all intents and
440     // purposes it should be eliminated.
441     if (!Ty->isLosslesslyConvertibleTo(I->getOperand(0)->getType()) ||
442         I->getType() == I->getOperand(0)->getType())
443       return false;
444
445     // Do not allow a 'cast ushort %V to uint' to have it's first operand be
446     // converted to a 'short' type.  Doing so changes the way sign promotion
447     // happens, and breaks things.  Only allow the cast to take place if the
448     // signedness doesn't change... or if the current cast is not a lossy
449     // conversion.
450     //
451     if (!I->getType()->isLosslesslyConvertibleTo(I->getOperand(0)->getType()) &&
452         I->getOperand(0)->getType()->isSigned() != Ty->isSigned())
453       return false;
454
455     // We also do not allow conversion of a cast that casts from a ptr to array
456     // of X to a *X.  For example: cast [4 x %List *] * %val to %List * *
457     //
458     if (const PointerType *SPT =
459         dyn_cast<PointerType>(I->getOperand(0)->getType()))
460       if (const PointerType *DPT = dyn_cast<PointerType>(I->getType()))
461         if (const ArrayType *AT = dyn_cast<ArrayType>(SPT->getElementType()))
462           if (AT->getElementType() == DPT->getElementType())
463             return false;
464     return true;
465
466   case Instruction::Add:
467   case Instruction::Sub: {
468     if (!Ty->isInteger() && !Ty->isFloatingPoint()) return false;
469
470     Value *OtherOp = I->getOperand((V == I->getOperand(0)) ? 1 : 0);
471     return ValueConvertibleToType(I, Ty, CTMap, TD) &&
472            ExpressionConvertibleToType(OtherOp, Ty, CTMap, TD);
473   }
474   case Instruction::SetEQ:
475   case Instruction::SetNE: {
476     Value *OtherOp = I->getOperand((V == I->getOperand(0)) ? 1 : 0);
477     return ExpressionConvertibleToType(OtherOp, Ty, CTMap, TD);
478   }
479   case Instruction::Shr:
480     if (Ty->isSigned() != V->getType()->isSigned()) return false;
481     // FALL THROUGH
482   case Instruction::Shl:
483     if (I->getOperand(1) == V) return false;  // Cannot change shift amount type
484     if (!Ty->isInteger()) return false;
485     return ValueConvertibleToType(I, Ty, CTMap, TD);
486
487   case Instruction::Free:
488     assert(I->getOperand(0) == V);
489     return isa<PointerType>(Ty);    // Free can free any pointer type!
490
491   case Instruction::Load:
492     // Cannot convert the types of any subscripts...
493     if (I->getOperand(0) != V) return false;
494
495     if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
496       LoadInst *LI = cast<LoadInst>(I);
497
498       const Type *LoadedTy = PT->getElementType();
499
500       // They could be loading the first element of a composite type...
501       if (const CompositeType *CT = dyn_cast<CompositeType>(LoadedTy)) {
502         unsigned Offset = 0;     // No offset, get first leaf.
503         std::vector<Value*> Indices;  // Discarded...
504         LoadedTy = getStructOffsetType(CT, Offset, Indices, TD, false);
505         assert(Offset == 0 && "Offset changed from zero???");
506       }
507
508       if (!LoadedTy->isFirstClassType())
509         return false;
510
511       if (TD.getTypeSize(LoadedTy) != TD.getTypeSize(LI->getType()))
512         return false;
513
514       return ValueConvertibleToType(LI, LoadedTy, CTMap, TD);
515     }
516     return false;
517
518   case Instruction::Store: {
519     if (V == I->getOperand(0)) {
520       ValueTypeCache::iterator CTMI = CTMap.find(I->getOperand(1));
521       if (CTMI != CTMap.end()) {   // Operand #1 is in the table already?
522         // If so, check to see if it's Ty*, or, more importantly, if it is a
523         // pointer to a structure where the first element is a Ty... this code
524         // is necessary because we might be trying to change the source and
525         // destination type of the store (they might be related) and the dest
526         // pointer type might be a pointer to structure.  Below we allow pointer
527         // to structures where the 0th element is compatible with the value,
528         // now we have to support the symmetrical part of this.
529         //
530         const Type *ElTy = cast<PointerType>(CTMI->second)->getElementType();
531
532         // Already a pointer to what we want?  Trivially accept...
533         if (ElTy == Ty) return true;
534
535         // Tricky case now, if the destination is a pointer to structure,
536         // obviously the source is not allowed to be a structure (cannot copy
537         // a whole structure at a time), so the level raiser must be trying to
538         // store into the first field.  Check for this and allow it now:
539         //
540         if (const StructType *SElTy = dyn_cast<StructType>(ElTy)) {
541           unsigned Offset = 0;
542           std::vector<Value*> Indices;
543           ElTy = getStructOffsetType(ElTy, Offset, Indices, TD, false);
544           assert(Offset == 0 && "Offset changed!");
545           if (ElTy == 0)    // Element at offset zero in struct doesn't exist!
546             return false;   // Can only happen for {}*
547
548           if (ElTy == Ty)   // Looks like the 0th element of structure is
549             return true;    // compatible!  Accept now!
550
551           // Otherwise we know that we can't work, so just stop trying now.
552           return false;
553         }
554       }
555
556       // Can convert the store if we can convert the pointer operand to match
557       // the new  value type...
558       return ExpressionConvertibleToType(I->getOperand(1), PointerType::get(Ty),
559                                          CTMap, TD);
560     } else if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
561       const Type *ElTy = PT->getElementType();
562       assert(V == I->getOperand(1));
563
564       if (isa<StructType>(ElTy)) {
565         // We can change the destination pointer if we can store our first
566         // argument into the first element of the structure...
567         //
568         unsigned Offset = 0;
569         std::vector<Value*> Indices;
570         ElTy = getStructOffsetType(ElTy, Offset, Indices, TD, false);
571         assert(Offset == 0 && "Offset changed!");
572         if (ElTy == 0)    // Element at offset zero in struct doesn't exist!
573           return false;   // Can only happen for {}*
574       }
575
576       // Must move the same amount of data...
577       if (!ElTy->isSized() ||
578           TD.getTypeSize(ElTy) != TD.getTypeSize(I->getOperand(0)->getType()))
579         return false;
580
581       // Can convert store if the incoming value is convertible and if the
582       // result will preserve semantics...
583       const Type *Op0Ty = I->getOperand(0)->getType();
584       if (!(Op0Ty->isIntegral() ^ ElTy->isIntegral()) &&
585           !(Op0Ty->isFloatingPoint() ^ ElTy->isFloatingPoint()))
586         return ExpressionConvertibleToType(I->getOperand(0), ElTy, CTMap, TD);
587     }
588     return false;
589   }
590
591   case Instruction::PHI: {
592     PHINode *PN = cast<PHINode>(I);
593     // Be conservative if we find a giant PHI node.
594     if (PN->getNumIncomingValues() > 32) return false;
595
596     for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i)
597       if (!ExpressionConvertibleToType(PN->getIncomingValue(i), Ty, CTMap, TD))
598         return false;
599     return ValueConvertibleToType(PN, Ty, CTMap, TD);
600   }
601
602   case Instruction::Call: {
603     User::op_iterator OI = std::find(I->op_begin(), I->op_end(), V);
604     assert (OI != I->op_end() && "Not using value!");
605     unsigned OpNum = OI - I->op_begin();
606
607     // Are we trying to change the function pointer value to a new type?
608     if (OpNum == 0) {
609       const PointerType *PTy = dyn_cast<PointerType>(Ty);
610       if (PTy == 0) return false;  // Can't convert to a non-pointer type...
611       const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
612       if (FTy == 0) return false;  // Can't convert to a non ptr to function...
613
614       // Do not allow converting to a call where all of the operands are ...'s
615       if (FTy->getNumParams() == 0 && FTy->isVarArg())
616         return false;              // Do not permit this conversion!
617
618       // Perform sanity checks to make sure that new function type has the
619       // correct number of arguments...
620       //
621       unsigned NumArgs = I->getNumOperands()-1;  // Don't include function ptr
622
623       // Cannot convert to a type that requires more fixed arguments than
624       // the call provides...
625       //
626       if (NumArgs < FTy->getNumParams()) return false;
627
628       // Unless this is a vararg function type, we cannot provide more arguments
629       // than are desired...
630       //
631       if (!FTy->isVarArg() && NumArgs > FTy->getNumParams())
632         return false;
633
634       // Okay, at this point, we know that the call and the function type match
635       // number of arguments.  Now we see if we can convert the arguments
636       // themselves.  Note that we do not require operands to be convertible,
637       // we can insert casts if they are convertible but not compatible.  The
638       // reason for this is that we prefer to have resolved functions but casted
639       // arguments if possible.
640       //
641       for (unsigned i = 0, NA = FTy->getNumParams(); i < NA; ++i)
642         if (!FTy->getParamType(i)->isLosslesslyConvertibleTo(I->getOperand(i+1)->getType()))
643           return false;   // Operands must have compatible types!
644
645       // Okay, at this point, we know that all of the arguments can be
646       // converted.  We succeed if we can change the return type if
647       // necessary...
648       //
649       return ValueConvertibleToType(I, FTy->getReturnType(), CTMap, TD);
650     }
651
652     const PointerType *MPtr = cast<PointerType>(I->getOperand(0)->getType());
653     const FunctionType *FTy = cast<FunctionType>(MPtr->getElementType());
654     if (!FTy->isVarArg()) return false;
655
656     if ((OpNum-1) < FTy->getNumParams())
657       return false;  // It's not in the varargs section...
658
659     // If we get this far, we know the value is in the varargs section of the
660     // function!  We can convert if we don't reinterpret the value...
661     //
662     return Ty->isLosslesslyConvertibleTo(V->getType());
663   }
664   }
665   return false;
666 }
667
668
669 void llvm::ConvertValueToNewType(Value *V, Value *NewVal, ValueMapCache &VMC,
670                                  const TargetData &TD) {
671   ValueHandle VH(VMC, V);
672
673   // FIXME: This is horrible!
674   unsigned NumUses = V->getNumUses();
675   for (unsigned It = 0; It < NumUses; ) {
676     unsigned OldSize = NumUses;
677     Value::use_iterator UI = V->use_begin();
678     std::advance(UI, It);
679     ConvertOperandToType(*UI, V, NewVal, VMC, TD);
680     NumUses = V->getNumUses();
681     if (NumUses == OldSize) ++It;
682   }
683 }
684
685
686
687 static void ConvertOperandToType(User *U, Value *OldVal, Value *NewVal,
688                                  ValueMapCache &VMC, const TargetData &TD) {
689   if (isa<ValueHandle>(U)) return;  // Valuehandles don't let go of operands...
690
691   if (VMC.OperandsMapped.count(U)) return;
692   VMC.OperandsMapped.insert(U);
693
694   ValueMapCache::ExprMapTy::iterator VMCI = VMC.ExprMap.find(U);
695   if (VMCI != VMC.ExprMap.end())
696     return;
697
698
699   Instruction *I = cast<Instruction>(U);  // Only Instructions convertible
700
701   BasicBlock *BB = I->getParent();
702   assert(BB != 0 && "Instruction not embedded in basic block!");
703   std::string Name = I->getName();
704   I->setName("");
705   Instruction *Res;     // Result of conversion
706
707   //std::cerr << endl << endl << "Type:\t" << Ty << "\nInst: " << I
708   //          << "BB Before: " << BB << endl;
709
710   // Prevent I from being removed...
711   ValueHandle IHandle(VMC, I);
712
713   const Type *NewTy = NewVal->getType();
714   Constant *Dummy = (NewTy != Type::VoidTy) ?
715                   Constant::getNullValue(NewTy) : 0;
716
717   switch (I->getOpcode()) {
718   case Instruction::Cast:
719     if (VMC.NewCasts.count(ValueHandle(VMC, I))) {
720       // This cast has already had it's value converted, causing a new cast to
721       // be created.  We don't want to create YET ANOTHER cast instruction
722       // representing the original one, so just modify the operand of this cast
723       // instruction, which we know is newly created.
724       I->setOperand(0, NewVal);
725       I->setName(Name);  // give I its name back
726       return;
727
728     } else {
729       Res = new CastInst(NewVal, I->getType(), Name);
730     }
731     break;
732
733   case Instruction::Add:
734   case Instruction::Sub:
735   case Instruction::SetEQ:
736   case Instruction::SetNE: {
737     Res = BinaryOperator::create(cast<BinaryOperator>(I)->getOpcode(),
738                                  Dummy, Dummy, Name);
739     VMC.ExprMap[I] = Res;   // Add node to expression eagerly
740
741     unsigned OtherIdx = (OldVal == I->getOperand(0)) ? 1 : 0;
742     Value *OtherOp    = I->getOperand(OtherIdx);
743     Res->setOperand(!OtherIdx, NewVal);
744     Value *NewOther   = ConvertExpressionToType(OtherOp, NewTy, VMC, TD);
745     Res->setOperand(OtherIdx, NewOther);
746     break;
747   }
748   case Instruction::Shl:
749   case Instruction::Shr:
750     assert(I->getOperand(0) == OldVal);
751     Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(), NewVal,
752                         I->getOperand(1), Name);
753     break;
754
755   case Instruction::Free:            // Free can free any pointer type!
756     assert(I->getOperand(0) == OldVal);
757     Res = new FreeInst(NewVal);
758     break;
759
760
761   case Instruction::Load: {
762     assert(I->getOperand(0) == OldVal && isa<PointerType>(NewVal->getType()));
763     const Type *LoadedTy =
764       cast<PointerType>(NewVal->getType())->getElementType();
765
766     Value *Src = NewVal;
767
768     if (const CompositeType *CT = dyn_cast<CompositeType>(LoadedTy)) {
769       std::vector<Value*> Indices;
770       Indices.push_back(Constant::getNullValue(Type::UIntTy));
771
772       unsigned Offset = 0;   // No offset, get first leaf.
773       LoadedTy = getStructOffsetType(CT, Offset, Indices, TD, false);
774       assert(LoadedTy->isFirstClassType());
775
776       if (Indices.size() != 1) {     // Do not generate load X, 0
777         // Insert the GEP instruction before this load.
778         Src = new GetElementPtrInst(Src, Indices, Name+".idx", I);
779       }
780     }
781
782     Res = new LoadInst(Src, Name);
783     assert(Res->getType()->isFirstClassType() && "Load of structure or array!");
784     break;
785   }
786
787   case Instruction::Store: {
788     if (I->getOperand(0) == OldVal) {  // Replace the source value
789       // Check to see if operand #1 has already been converted...
790       ValueMapCache::ExprMapTy::iterator VMCI =
791         VMC.ExprMap.find(I->getOperand(1));
792       if (VMCI != VMC.ExprMap.end()) {
793         // Comments describing this stuff are in the OperandConvertibleToType
794         // switch statement for Store...
795         //
796         const Type *ElTy =
797           cast<PointerType>(VMCI->second->getType())->getElementType();
798
799         Value *SrcPtr = VMCI->second;
800
801         if (ElTy != NewTy) {
802           // We check that this is a struct in the initial scan...
803           const StructType *SElTy = cast<StructType>(ElTy);
804
805           std::vector<Value*> Indices;
806           Indices.push_back(Constant::getNullValue(Type::UIntTy));
807
808           unsigned Offset = 0;
809           const Type *Ty = getStructOffsetType(ElTy, Offset, Indices, TD,false);
810           assert(Offset == 0 && "Offset changed!");
811           assert(NewTy == Ty && "Did not convert to correct type!");
812
813           // Insert the GEP instruction before this store.
814           SrcPtr = new GetElementPtrInst(SrcPtr, Indices,
815                                          SrcPtr->getName()+".idx", I);
816         }
817         Res = new StoreInst(NewVal, SrcPtr);
818
819         VMC.ExprMap[I] = Res;
820       } else {
821         // Otherwise, we haven't converted Operand #1 over yet...
822         const PointerType *NewPT = PointerType::get(NewTy);
823         Res = new StoreInst(NewVal, Constant::getNullValue(NewPT));
824         VMC.ExprMap[I] = Res;
825         Res->setOperand(1, ConvertExpressionToType(I->getOperand(1),
826                                                    NewPT, VMC, TD));
827       }
828     } else {                           // Replace the source pointer
829       const Type *ValTy = cast<PointerType>(NewTy)->getElementType();
830
831       Value *SrcPtr = NewVal;
832
833       if (isa<StructType>(ValTy)) {
834         std::vector<Value*> Indices;
835         Indices.push_back(Constant::getNullValue(Type::UIntTy));
836
837         unsigned Offset = 0;
838         ValTy = getStructOffsetType(ValTy, Offset, Indices, TD, false);
839
840         assert(Offset == 0 && ValTy);
841
842         // Insert the GEP instruction before this store.
843         SrcPtr = new GetElementPtrInst(SrcPtr, Indices,
844                                        SrcPtr->getName()+".idx", I);
845       }
846
847       Res = new StoreInst(Constant::getNullValue(ValTy), SrcPtr);
848       VMC.ExprMap[I] = Res;
849       Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
850                                                  ValTy, VMC, TD));
851     }
852     break;
853   }
854
855   case Instruction::PHI: {
856     PHINode *OldPN = cast<PHINode>(I);
857     PHINode *NewPN = new PHINode(NewTy, Name);
858     VMC.ExprMap[I] = NewPN;
859
860     while (OldPN->getNumOperands()) {
861       BasicBlock *BB = OldPN->getIncomingBlock(0);
862       Value *OldVal = OldPN->getIncomingValue(0);
863       ValueHandle OldValHandle(VMC, OldVal);
864       OldPN->removeIncomingValue(BB, false);
865       Value *V = ConvertExpressionToType(OldVal, NewTy, VMC, TD);
866       NewPN->addIncoming(V, BB);
867     }
868     Res = NewPN;
869     break;
870   }
871
872   case Instruction::Call: {
873     Value *Meth = I->getOperand(0);
874     std::vector<Value*> Params(I->op_begin()+1, I->op_end());
875
876     if (Meth == OldVal) {   // Changing the function pointer?
877       const PointerType *NewPTy = cast<PointerType>(NewVal->getType());
878       const FunctionType *NewTy = cast<FunctionType>(NewPTy->getElementType());
879
880       if (NewTy->getReturnType() == Type::VoidTy)
881         Name = "";  // Make sure not to name a void call!
882
883       // Get an iterator to the call instruction so that we can insert casts for
884       // operands if need be.  Note that we do not require operands to be
885       // convertible, we can insert casts if they are convertible but not
886       // compatible.  The reason for this is that we prefer to have resolved
887       // functions but casted arguments if possible.
888       //
889       BasicBlock::iterator It = I;
890
891       // Convert over all of the call operands to their new types... but only
892       // convert over the part that is not in the vararg section of the call.
893       //
894       for (unsigned i = 0; i != NewTy->getNumParams(); ++i)
895         if (Params[i]->getType() != NewTy->getParamType(i)) {
896           // Create a cast to convert it to the right type, we know that this
897           // is a lossless cast...
898           //
899           Params[i] = new CastInst(Params[i], NewTy->getParamType(i),
900                                    "callarg.cast." +
901                                    Params[i]->getName(), It);
902         }
903       Meth = NewVal;  // Update call destination to new value
904
905     } else {                   // Changing an argument, must be in vararg area
906       std::vector<Value*>::iterator OI =
907         std::find(Params.begin(), Params.end(), OldVal);
908       assert (OI != Params.end() && "Not using value!");
909
910       *OI = NewVal;
911     }
912
913     Res = new CallInst(Meth, Params, Name);
914     if (cast<CallInst>(I)->isTailCall())
915       cast<CallInst>(Res)->setTailCall();
916     cast<CallInst>(Res)->setCallingConv(cast<CallInst>(I)->getCallingConv());
917     break;
918   }
919   default:
920     assert(0 && "Expression convertible, but don't know how to convert?");
921     return;
922   }
923
924   // If the instruction was newly created, insert it into the instruction
925   // stream.
926   //
927   BasicBlock::iterator It = I;
928   assert(It != BB->end() && "Instruction not in own basic block??");
929   BB->getInstList().insert(It, Res);   // Keep It pointing to old instruction
930
931   DEBUG(std::cerr << "COT CREATED: "  << (void*)Res << " " << *Res
932                   << "In: " << (void*)I << " " << *I << "Out: " << (void*)Res
933                   << " " << *Res);
934
935   // Add the instruction to the expression map
936   VMC.ExprMap[I] = Res;
937
938   if (I->getType() != Res->getType())
939     ConvertValueToNewType(I, Res, VMC, TD);
940   else {
941     for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
942          UI != E; )
943       if (isa<ValueHandle>(*UI)) {
944         ++UI;
945       } else {
946         Use &U = UI.getUse();
947         ++UI;  // Do not invalidate UI.
948         U.set(Res);
949       }
950   }
951 }
952
953
954 ValueHandle::ValueHandle(ValueMapCache &VMC, Value *V)
955   : Instruction(Type::VoidTy, UserOp1, &Op, 1, ""), Op(V, this), Cache(VMC) {
956   //DEBUG(std::cerr << "VH AQUIRING: " << (void*)V << " " << V);
957 }
958
959 ValueHandle::ValueHandle(const ValueHandle &VH)
960   : Instruction(Type::VoidTy, UserOp1, &Op, 1, ""),
961     Op(VH.Op, this), Cache(VH.Cache) {
962   //DEBUG(std::cerr << "VH AQUIRING: " << (void*)V << " " << V);
963 }
964
965 static void RecursiveDelete(ValueMapCache &Cache, Instruction *I) {
966   if (!I || !I->use_empty()) return;
967
968   assert(I->getParent() && "Inst not in basic block!");
969
970   //DEBUG(std::cerr << "VH DELETING: " << (void*)I << " " << I);
971
972   for (User::op_iterator OI = I->op_begin(), OE = I->op_end();
973        OI != OE; ++OI)
974     if (Instruction *U = dyn_cast<Instruction>(OI)) {
975       *OI = 0;
976       RecursiveDelete(Cache, U);
977     }
978
979   I->getParent()->getInstList().remove(I);
980
981   Cache.OperandsMapped.erase(I);
982   Cache.ExprMap.erase(I);
983   delete I;
984 }
985
986 ValueHandle::~ValueHandle() {
987   if (Op->hasOneUse()) {
988     Value *V = Op;
989     Op.set(0);   // Drop use!
990
991     // Now we just need to remove the old instruction so we don't get infinite
992     // loops.  Note that we cannot use DCE because DCE won't remove a store
993     // instruction, for example.
994     //
995     RecursiveDelete(Cache, dyn_cast<Instruction>(V));
996   } else {
997     //DEBUG(std::cerr << "VH RELEASING: " << (void*)Operands[0].get() << " "
998     //                << Operands[0]->getNumUses() << " " << Operands[0]);
999   }
1000 }
1001