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