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