1 //===- ExprTypeConvert.cpp - Code to change an LLVM Expr Type -------------===//
3 // This file implements the part of level raising that checks to see if it is
4 // possible to coerce an entire expression tree into a different type. If
5 // convertible, other routines from this file will do the conversion.
7 //===----------------------------------------------------------------------===//
9 #include "TransformInternals.h"
10 #include "llvm/iOther.h"
11 #include "llvm/iPHINode.h"
12 #include "llvm/iMemory.h"
13 #include "llvm/ConstantHandling.h"
14 #include "llvm/Analysis/Expressions.h"
15 #include "Support/STLExtras.h"
16 #include "Support/Debug.h"
20 static bool OperandConvertibleToType(User *U, Value *V, const Type *Ty,
21 ValueTypeCache &ConvertedTypes,
22 const TargetData &TD);
24 static void ConvertOperandToType(User *U, Value *OldVal, Value *NewVal,
25 ValueMapCache &VMC, const TargetData &TD);
27 // Peephole Malloc instructions: we take a look at the use chain of the
28 // malloc instruction, and try to find out if the following conditions hold:
29 // 1. The malloc is of the form: 'malloc [sbyte], uint <constant>'
30 // 2. The only users of the malloc are cast & add instructions
31 // 3. Of the cast instructions, there is only one destination pointer type
32 // [RTy] where the size of the pointed to object is equal to the number
33 // of bytes allocated.
35 // If these conditions hold, we convert the malloc to allocate an [RTy]
36 // element. TODO: This comment is out of date WRT arrays
38 static bool MallocConvertibleToType(MallocInst *MI, const Type *Ty,
39 ValueTypeCache &CTMap,
40 const TargetData &TD) {
41 if (!isa<PointerType>(Ty)) return false; // Malloc always returns pointers
43 // Deal with the type to allocate, not the pointer type...
44 Ty = cast<PointerType>(Ty)->getElementType();
45 if (!Ty->isSized()) return false; // Can only alloc something with a size
47 // Analyze the number of bytes allocated...
48 ExprType Expr = ClassifyExpression(MI->getArraySize());
50 // Get information about the base datatype being allocated, before & after
51 int ReqTypeSize = TD.getTypeSize(Ty);
52 if (ReqTypeSize == 0) return false;
53 unsigned OldTypeSize = TD.getTypeSize(MI->getType()->getElementType());
55 // Must have a scale or offset to analyze it...
56 if (!Expr.Offset && !Expr.Scale && OldTypeSize == 1) return false;
58 // Get the offset and scale of the allocation...
59 int64_t OffsetVal = Expr.Offset ? getConstantValue(Expr.Offset) : 0;
60 int64_t ScaleVal = Expr.Scale ? getConstantValue(Expr.Scale) :(Expr.Var != 0);
62 // The old type might not be of unit size, take old size into consideration
64 int64_t Offset = OffsetVal * OldTypeSize;
65 int64_t Scale = ScaleVal * OldTypeSize;
67 // In order to be successful, both the scale and the offset must be a multiple
68 // of the requested data type's size.
70 if (Offset/ReqTypeSize*ReqTypeSize != Offset ||
71 Scale/ReqTypeSize*ReqTypeSize != Scale)
72 return false; // Nope.
77 static Instruction *ConvertMallocToType(MallocInst *MI, const Type *Ty,
78 const std::string &Name,
80 const TargetData &TD){
81 BasicBlock *BB = MI->getParent();
82 BasicBlock::iterator It = BB->end();
84 // Analyze the number of bytes allocated...
85 ExprType Expr = ClassifyExpression(MI->getArraySize());
87 const PointerType *AllocTy = cast<PointerType>(Ty);
88 const Type *ElType = AllocTy->getElementType();
90 unsigned DataSize = TD.getTypeSize(ElType);
91 unsigned OldTypeSize = TD.getTypeSize(MI->getType()->getElementType());
93 // Get the offset and scale coefficients that we are allocating...
94 int64_t OffsetVal = (Expr.Offset ? getConstantValue(Expr.Offset) : 0);
95 int64_t ScaleVal = Expr.Scale ? getConstantValue(Expr.Scale) : (Expr.Var !=0);
97 // The old type might not be of unit size, take old size into consideration
99 unsigned Offset = (uint64_t)OffsetVal * OldTypeSize / DataSize;
100 unsigned Scale = (uint64_t)ScaleVal * OldTypeSize / DataSize;
102 // Locate the malloc instruction, because we may be inserting instructions
105 // If we have a scale, apply it first...
107 // Expr.Var is not neccesarily unsigned right now, insert a cast now.
108 if (Expr.Var->getType() != Type::UIntTy)
109 Expr.Var = new CastInst(Expr.Var, Type::UIntTy,
110 Expr.Var->getName()+"-uint", It);
113 Expr.Var = BinaryOperator::create(Instruction::Mul, Expr.Var,
114 ConstantUInt::get(Type::UIntTy, Scale),
115 Expr.Var->getName()+"-scl", It);
118 // If we are not scaling anything, just make the offset be the "var"...
119 Expr.Var = ConstantUInt::get(Type::UIntTy, Offset);
120 Offset = 0; Scale = 1;
123 // If we have an offset now, add it in...
125 assert(Expr.Var && "Var must be nonnull by now!");
126 Expr.Var = BinaryOperator::create(Instruction::Add, Expr.Var,
127 ConstantUInt::get(Type::UIntTy, Offset),
128 Expr.Var->getName()+"-off", It);
131 assert(AllocTy == Ty);
132 return new MallocInst(AllocTy->getElementType(), Expr.Var, Name);
136 // ExpressionConvertibleToType - Return true if it is possible
137 bool ExpressionConvertibleToType(Value *V, const Type *Ty,
138 ValueTypeCache &CTMap, const TargetData &TD) {
139 // Expression type must be holdable in a register.
140 if (!Ty->isFirstClassType())
143 ValueTypeCache::iterator CTMI = CTMap.find(V);
144 if (CTMI != CTMap.end()) return CTMI->second == Ty;
146 // If it's a constant... all constants can be converted to a different
147 // type. We just ask the constant propagator to see if it can convert the
150 if (Constant *CPV = dyn_cast<Constant>(V))
151 return ConstantFoldCastInstruction(CPV, Ty);
154 if (V->getType() == Ty) return true; // Expression already correct type!
156 Instruction *I = dyn_cast<Instruction>(V);
157 if (I == 0) return false; // Otherwise, we can't convert!
159 switch (I->getOpcode()) {
160 case Instruction::Cast:
161 // We can convert the expr if the cast destination type is losslessly
162 // convertible to the requested type.
163 if (!Ty->isLosslesslyConvertibleTo(I->getType())) return false;
165 // We also do not allow conversion of a cast that casts from a ptr to array
166 // of X to a *X. For example: cast [4 x %List *] * %val to %List * *
168 if (const PointerType *SPT =
169 dyn_cast<PointerType>(I->getOperand(0)->getType()))
170 if (const PointerType *DPT = dyn_cast<PointerType>(I->getType()))
171 if (const ArrayType *AT = dyn_cast<ArrayType>(SPT->getElementType()))
172 if (AT->getElementType() == DPT->getElementType())
176 case Instruction::Add:
177 case Instruction::Sub:
178 if (!Ty->isInteger() && !Ty->isFloatingPoint()) return false;
179 if (!ExpressionConvertibleToType(I->getOperand(0), Ty, CTMap, TD) ||
180 !ExpressionConvertibleToType(I->getOperand(1), Ty, CTMap, TD))
183 case Instruction::Shr:
184 if (!Ty->isInteger()) return false;
185 if (Ty->isSigned() != V->getType()->isSigned()) return false;
187 case Instruction::Shl:
188 if (!Ty->isInteger()) return false;
189 if (!ExpressionConvertibleToType(I->getOperand(0), Ty, CTMap, TD))
193 case Instruction::Load: {
194 LoadInst *LI = cast<LoadInst>(I);
195 if (!ExpressionConvertibleToType(LI->getPointerOperand(),
196 PointerType::get(Ty), CTMap, TD))
200 case Instruction::PHINode: {
201 PHINode *PN = cast<PHINode>(I);
202 for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i)
203 if (!ExpressionConvertibleToType(PN->getIncomingValue(i), Ty, CTMap, TD))
208 case Instruction::Malloc:
209 if (!MallocConvertibleToType(cast<MallocInst>(I), Ty, CTMap, TD))
213 case Instruction::GetElementPtr: {
214 // GetElementPtr's are directly convertible to a pointer type if they have
215 // a number of zeros at the end. Because removing these values does not
216 // change the logical offset of the GEP, it is okay and fair to remove them.
217 // This can change this:
218 // %t1 = getelementptr %Hosp * %hosp, ubyte 4, ubyte 0 ; <%List **>
219 // %t2 = cast %List * * %t1 to %List *
221 // %t2 = getelementptr %Hosp * %hosp, ubyte 4 ; <%List *>
223 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
224 const PointerType *PTy = dyn_cast<PointerType>(Ty);
225 if (!PTy) return false; // GEP must always return a pointer...
226 const Type *PVTy = PTy->getElementType();
228 // Check to see if there are zero elements that we can remove from the
229 // index array. If there are, check to see if removing them causes us to
230 // get to the right type...
232 std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
233 const Type *BaseType = GEP->getPointerOperand()->getType();
234 const Type *ElTy = 0;
236 while (!Indices.empty() &&
237 Indices.back() == Constant::getNullValue(Indices.back()->getType())){
239 ElTy = GetElementPtrInst::getIndexedType(BaseType, Indices, true);
241 break; // Found a match!!
245 if (ElTy) break; // Found a number of zeros we can strip off!
247 // Otherwise, we can convert a GEP from one form to the other iff the
248 // current gep is of the form 'getelementptr sbyte*, long N
249 // and we could convert this to an appropriate GEP for the new type.
251 if (GEP->getNumOperands() == 2 &&
252 GEP->getOperand(1)->getType() == Type::LongTy &&
253 GEP->getType() == PointerType::get(Type::SByteTy)) {
255 // Do not Check to see if our incoming pointer can be converted
256 // to be a ptr to an array of the right type... because in more cases than
257 // not, it is simply not analyzable because of pointer/array
258 // discrepencies. To fix this, we will insert a cast before the GEP.
261 // Check to see if 'N' is an expression that can be converted to
262 // the appropriate size... if so, allow it.
264 std::vector<Value*> Indices;
265 const Type *ElTy = ConvertibleToGEP(PTy, I->getOperand(1), Indices, TD);
267 if (!ExpressionConvertibleToType(I->getOperand(0),
268 PointerType::get(ElTy), CTMap, TD))
269 return false; // Can't continue, ExConToTy might have polluted set!
274 // Otherwise, it could be that we have something like this:
275 // getelementptr [[sbyte] *] * %reg115, long %reg138 ; [sbyte]**
276 // and want to convert it into something like this:
277 // getelemenptr [[int] *] * %reg115, long %reg138 ; [int]**
279 if (GEP->getNumOperands() == 2 &&
280 GEP->getOperand(1)->getType() == Type::LongTy &&
281 PTy->getElementType()->isSized() &&
282 TD.getTypeSize(PTy->getElementType()) ==
283 TD.getTypeSize(GEP->getType()->getElementType())) {
284 const PointerType *NewSrcTy = PointerType::get(PVTy);
285 if (!ExpressionConvertibleToType(I->getOperand(0), NewSrcTy, CTMap, TD))
290 return false; // No match, maybe next time.
293 case Instruction::Call: {
294 if (isa<Function>(I->getOperand(0)))
295 return false; // Don't even try to change direct calls.
297 // If this is a function pointer, we can convert the return type if we can
298 // convert the source function pointer.
300 const PointerType *PT = cast<PointerType>(I->getOperand(0)->getType());
301 const FunctionType *FT = cast<FunctionType>(PT->getElementType());
302 std::vector<const Type *> ArgTys(FT->getParamTypes().begin(),
303 FT->getParamTypes().end());
304 const FunctionType *NewTy =
305 FunctionType::get(Ty, ArgTys, FT->isVarArg());
306 if (!ExpressionConvertibleToType(I->getOperand(0),
307 PointerType::get(NewTy), CTMap, TD))
315 // Expressions are only convertible if all of the users of the expression can
316 // have this value converted. This makes use of the map to avoid infinite
319 for (Value::use_iterator It = I->use_begin(), E = I->use_end(); It != E; ++It)
320 if (!OperandConvertibleToType(*It, I, Ty, CTMap, TD))
327 Value *ConvertExpressionToType(Value *V, const Type *Ty, ValueMapCache &VMC,
328 const TargetData &TD) {
329 if (V->getType() == Ty) return V; // Already where we need to be?
331 ValueMapCache::ExprMapTy::iterator VMCI = VMC.ExprMap.find(V);
332 if (VMCI != VMC.ExprMap.end()) {
333 const Value *GV = VMCI->second;
334 const Type *GTy = VMCI->second->getType();
335 assert(VMCI->second->getType() == Ty);
337 if (Instruction *I = dyn_cast<Instruction>(V))
338 ValueHandle IHandle(VMC, I); // Remove I if it is unused now!
343 DEBUG(cerr << "CETT: " << (void*)V << " " << V);
345 Instruction *I = dyn_cast<Instruction>(V);
347 Constant *CPV = cast<Constant>(V);
348 // Constants are converted by constant folding the cast that is required.
349 // We assume here that all casts are implemented for constant prop.
350 Value *Result = ConstantFoldCastInstruction(CPV, Ty);
351 assert(Result && "ConstantFoldCastInstruction Failed!!!");
352 assert(Result->getType() == Ty && "Const prop of cast failed!");
354 // Add the instruction to the expression map
355 //VMC.ExprMap[V] = Result;
360 BasicBlock *BB = I->getParent();
361 std::string Name = I->getName(); if (!Name.empty()) I->setName("");
362 Instruction *Res; // Result of conversion
364 ValueHandle IHandle(VMC, I); // Prevent I from being removed!
366 Constant *Dummy = Constant::getNullValue(Ty);
368 switch (I->getOpcode()) {
369 case Instruction::Cast:
370 assert(VMC.NewCasts.count(ValueHandle(VMC, I)) == 0);
371 Res = new CastInst(I->getOperand(0), Ty, Name);
372 VMC.NewCasts.insert(ValueHandle(VMC, Res));
375 case Instruction::Add:
376 case Instruction::Sub:
377 Res = BinaryOperator::create(cast<BinaryOperator>(I)->getOpcode(),
379 VMC.ExprMap[I] = Res; // Add node to expression eagerly
381 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), Ty, VMC, TD));
382 Res->setOperand(1, ConvertExpressionToType(I->getOperand(1), Ty, VMC, TD));
385 case Instruction::Shl:
386 case Instruction::Shr:
387 Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(), Dummy,
388 I->getOperand(1), Name);
389 VMC.ExprMap[I] = Res;
390 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), Ty, VMC, TD));
393 case Instruction::Load: {
394 LoadInst *LI = cast<LoadInst>(I);
396 Res = new LoadInst(Constant::getNullValue(PointerType::get(Ty)), Name);
397 VMC.ExprMap[I] = Res;
398 Res->setOperand(0, ConvertExpressionToType(LI->getPointerOperand(),
399 PointerType::get(Ty), VMC, TD));
400 assert(Res->getOperand(0)->getType() == PointerType::get(Ty));
401 assert(Ty == Res->getType());
402 assert(Res->getType()->isFirstClassType() && "Load of structure or array!");
406 case Instruction::PHINode: {
407 PHINode *OldPN = cast<PHINode>(I);
408 PHINode *NewPN = new PHINode(Ty, Name);
410 VMC.ExprMap[I] = NewPN; // Add node to expression eagerly
411 while (OldPN->getNumOperands()) {
412 BasicBlock *BB = OldPN->getIncomingBlock(0);
413 Value *OldVal = OldPN->getIncomingValue(0);
414 ValueHandle OldValHandle(VMC, OldVal);
415 OldPN->removeIncomingValue(BB, false);
416 Value *V = ConvertExpressionToType(OldVal, Ty, VMC, TD);
417 NewPN->addIncoming(V, BB);
423 case Instruction::Malloc: {
424 Res = ConvertMallocToType(cast<MallocInst>(I), Ty, Name, VMC, TD);
428 case Instruction::GetElementPtr: {
429 // GetElementPtr's are directly convertible to a pointer type if they have
430 // a number of zeros at the end. Because removing these values does not
431 // change the logical offset of the GEP, it is okay and fair to remove them.
432 // This can change this:
433 // %t1 = getelementptr %Hosp * %hosp, ubyte 4, ubyte 0 ; <%List **>
434 // %t2 = cast %List * * %t1 to %List *
436 // %t2 = getelementptr %Hosp * %hosp, ubyte 4 ; <%List *>
438 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
440 // Check to see if there are zero elements that we can remove from the
441 // index array. If there are, check to see if removing them causes us to
442 // get to the right type...
444 std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
445 const Type *BaseType = GEP->getPointerOperand()->getType();
446 const Type *PVTy = cast<PointerType>(Ty)->getElementType();
448 while (!Indices.empty() &&
449 Indices.back() == Constant::getNullValue(Indices.back()->getType())){
451 if (GetElementPtrInst::getIndexedType(BaseType, Indices, true) == PVTy) {
452 if (Indices.size() == 0)
453 Res = new CastInst(GEP->getPointerOperand(), BaseType); // NOOP CAST
455 Res = new GetElementPtrInst(GEP->getPointerOperand(), Indices, Name);
460 if (Res == 0 && GEP->getNumOperands() == 2 &&
461 GEP->getOperand(1)->getType() == Type::LongTy &&
462 GEP->getType() == PointerType::get(Type::SByteTy)) {
464 // Otherwise, we can convert a GEP from one form to the other iff the
465 // current gep is of the form 'getelementptr [sbyte]*, unsigned N
466 // and we could convert this to an appropriate GEP for the new type.
468 const PointerType *NewSrcTy = PointerType::get(PVTy);
469 BasicBlock::iterator It = I;
471 // Check to see if 'N' is an expression that can be converted to
472 // the appropriate size... if so, allow it.
474 std::vector<Value*> Indices;
475 const Type *ElTy = ConvertibleToGEP(NewSrcTy, I->getOperand(1),
478 assert(ElTy == PVTy && "Internal error, setup wrong!");
479 Res = new GetElementPtrInst(Constant::getNullValue(NewSrcTy),
481 VMC.ExprMap[I] = Res;
482 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
487 // Otherwise, it could be that we have something like this:
488 // getelementptr [[sbyte] *] * %reg115, uint %reg138 ; [sbyte]**
489 // and want to convert it into something like this:
490 // getelemenptr [[int] *] * %reg115, uint %reg138 ; [int]**
493 const PointerType *NewSrcTy = PointerType::get(PVTy);
494 std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
495 Res = new GetElementPtrInst(Constant::getNullValue(NewSrcTy),
497 VMC.ExprMap[I] = Res;
498 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
503 assert(Res && "Didn't find match!");
507 case Instruction::Call: {
508 assert(!isa<Function>(I->getOperand(0)));
510 // If this is a function pointer, we can convert the return type if we can
511 // convert the source function pointer.
513 const PointerType *PT = cast<PointerType>(I->getOperand(0)->getType());
514 const FunctionType *FT = cast<FunctionType>(PT->getElementType());
515 std::vector<const Type *> ArgTys(FT->getParamTypes().begin(),
516 FT->getParamTypes().end());
517 const FunctionType *NewTy =
518 FunctionType::get(Ty, ArgTys, FT->isVarArg());
519 const PointerType *NewPTy = PointerType::get(NewTy);
520 if (Ty == Type::VoidTy)
521 Name = ""; // Make sure not to name calls that now return void!
523 Res = new CallInst(Constant::getNullValue(NewPTy),
524 std::vector<Value*>(I->op_begin()+1, I->op_end()),
526 VMC.ExprMap[I] = Res;
527 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),NewPTy,VMC,TD));
531 assert(0 && "Expression convertible, but don't know how to convert?");
535 assert(Res->getType() == Ty && "Didn't convert expr to correct type!");
537 BB->getInstList().insert(I, Res);
539 // Add the instruction to the expression map
540 VMC.ExprMap[I] = Res;
542 // Expressions are only convertible if all of the users of the expression can
543 // have this value converted. This makes use of the map to avoid infinite
546 unsigned NumUses = I->use_size();
547 for (unsigned It = 0; It < NumUses; ) {
548 unsigned OldSize = NumUses;
549 ConvertOperandToType(*(I->use_begin()+It), I, Res, VMC, TD);
550 NumUses = I->use_size();
551 if (NumUses == OldSize) ++It;
554 DEBUG(cerr << "ExpIn: " << (void*)I << " " << I
555 << "ExpOut: " << (void*)Res << " " << Res);
562 // ValueConvertibleToType - Return true if it is possible
563 bool ValueConvertibleToType(Value *V, const Type *Ty,
564 ValueTypeCache &ConvertedTypes,
565 const TargetData &TD) {
566 ValueTypeCache::iterator I = ConvertedTypes.find(V);
567 if (I != ConvertedTypes.end()) return I->second == Ty;
568 ConvertedTypes[V] = Ty;
570 // It is safe to convert the specified value to the specified type IFF all of
571 // the uses of the value can be converted to accept the new typed value.
573 if (V->getType() != Ty) {
574 for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I)
575 if (!OperandConvertibleToType(*I, V, Ty, ConvertedTypes, TD))
586 // OperandConvertibleToType - Return true if it is possible to convert operand
587 // V of User (instruction) U to the specified type. This is true iff it is
588 // possible to change the specified instruction to accept this. CTMap is a map
589 // of converted types, so that circular definitions will see the future type of
590 // the expression, not the static current type.
592 static bool OperandConvertibleToType(User *U, Value *V, const Type *Ty,
593 ValueTypeCache &CTMap,
594 const TargetData &TD) {
595 // if (V->getType() == Ty) return true; // Operand already the right type?
597 // Expression type must be holdable in a register.
598 if (!Ty->isFirstClassType())
601 Instruction *I = dyn_cast<Instruction>(U);
602 if (I == 0) return false; // We can't convert!
604 switch (I->getOpcode()) {
605 case Instruction::Cast:
606 assert(I->getOperand(0) == V);
607 // We can convert the expr if the cast destination type is losslessly
608 // convertible to the requested type.
609 // Also, do not change a cast that is a noop cast. For all intents and
610 // purposes it should be eliminated.
611 if (!Ty->isLosslesslyConvertibleTo(I->getOperand(0)->getType()) ||
612 I->getType() == I->getOperand(0)->getType())
615 // Do not allow a 'cast ushort %V to uint' to have it's first operand be
616 // converted to a 'short' type. Doing so changes the way sign promotion
617 // happens, and breaks things. Only allow the cast to take place if the
618 // signedness doesn't change... or if the current cast is not a lossy
621 if (!I->getType()->isLosslesslyConvertibleTo(I->getOperand(0)->getType()) &&
622 I->getOperand(0)->getType()->isSigned() != Ty->isSigned())
625 // We also do not allow conversion of a cast that casts from a ptr to array
626 // of X to a *X. For example: cast [4 x %List *] * %val to %List * *
628 if (const PointerType *SPT =
629 dyn_cast<PointerType>(I->getOperand(0)->getType()))
630 if (const PointerType *DPT = dyn_cast<PointerType>(I->getType()))
631 if (const ArrayType *AT = dyn_cast<ArrayType>(SPT->getElementType()))
632 if (AT->getElementType() == DPT->getElementType())
636 case Instruction::Add:
637 if (isa<PointerType>(Ty)) {
638 Value *IndexVal = I->getOperand(V == I->getOperand(0) ? 1 : 0);
639 std::vector<Value*> Indices;
640 if (const Type *ETy = ConvertibleToGEP(Ty, IndexVal, Indices, TD)) {
641 const Type *RetTy = PointerType::get(ETy);
643 // Only successful if we can convert this type to the required type
644 if (ValueConvertibleToType(I, RetTy, CTMap, TD)) {
648 // We have to return failure here because ValueConvertibleToType could
649 // have polluted our map
654 case Instruction::Sub: {
655 if (!Ty->isInteger() && !Ty->isFloatingPoint()) return false;
657 Value *OtherOp = I->getOperand((V == I->getOperand(0)) ? 1 : 0);
658 return ValueConvertibleToType(I, Ty, CTMap, TD) &&
659 ExpressionConvertibleToType(OtherOp, Ty, CTMap, TD);
661 case Instruction::SetEQ:
662 case Instruction::SetNE: {
663 Value *OtherOp = I->getOperand((V == I->getOperand(0)) ? 1 : 0);
664 return ExpressionConvertibleToType(OtherOp, Ty, CTMap, TD);
666 case Instruction::Shr:
667 if (Ty->isSigned() != V->getType()->isSigned()) return false;
669 case Instruction::Shl:
670 if (I->getOperand(1) == V) return false; // Cannot change shift amount type
671 if (!Ty->isInteger()) return false;
672 return ValueConvertibleToType(I, Ty, CTMap, TD);
674 case Instruction::Free:
675 assert(I->getOperand(0) == V);
676 return isa<PointerType>(Ty); // Free can free any pointer type!
678 case Instruction::Load:
679 // Cannot convert the types of any subscripts...
680 if (I->getOperand(0) != V) return false;
682 if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
683 LoadInst *LI = cast<LoadInst>(I);
685 const Type *LoadedTy = PT->getElementType();
687 // They could be loading the first element of a composite type...
688 if (const CompositeType *CT = dyn_cast<CompositeType>(LoadedTy)) {
689 unsigned Offset = 0; // No offset, get first leaf.
690 std::vector<Value*> Indices; // Discarded...
691 LoadedTy = getStructOffsetType(CT, Offset, Indices, TD, false);
692 assert(Offset == 0 && "Offset changed from zero???");
695 if (!LoadedTy->isFirstClassType())
698 if (TD.getTypeSize(LoadedTy) != TD.getTypeSize(LI->getType()))
701 return ValueConvertibleToType(LI, LoadedTy, CTMap, TD);
705 case Instruction::Store: {
706 StoreInst *SI = cast<StoreInst>(I);
708 if (V == I->getOperand(0)) {
709 ValueTypeCache::iterator CTMI = CTMap.find(I->getOperand(1));
710 if (CTMI != CTMap.end()) { // Operand #1 is in the table already?
711 // If so, check to see if it's Ty*, or, more importantly, if it is a
712 // pointer to a structure where the first element is a Ty... this code
713 // is necessary because we might be trying to change the source and
714 // destination type of the store (they might be related) and the dest
715 // pointer type might be a pointer to structure. Below we allow pointer
716 // to structures where the 0th element is compatible with the value,
717 // now we have to support the symmetrical part of this.
719 const Type *ElTy = cast<PointerType>(CTMI->second)->getElementType();
721 // Already a pointer to what we want? Trivially accept...
722 if (ElTy == Ty) return true;
724 // Tricky case now, if the destination is a pointer to structure,
725 // obviously the source is not allowed to be a structure (cannot copy
726 // a whole structure at a time), so the level raiser must be trying to
727 // store into the first field. Check for this and allow it now:
729 if (const StructType *SElTy = dyn_cast<StructType>(ElTy)) {
731 std::vector<Value*> Indices;
732 ElTy = getStructOffsetType(ElTy, Offset, Indices, TD, false);
733 assert(Offset == 0 && "Offset changed!");
734 if (ElTy == 0) // Element at offset zero in struct doesn't exist!
735 return false; // Can only happen for {}*
737 if (ElTy == Ty) // Looks like the 0th element of structure is
738 return true; // compatible! Accept now!
740 // Otherwise we know that we can't work, so just stop trying now.
745 // Can convert the store if we can convert the pointer operand to match
746 // the new value type...
747 return ExpressionConvertibleToType(I->getOperand(1), PointerType::get(Ty),
749 } else if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
750 const Type *ElTy = PT->getElementType();
751 assert(V == I->getOperand(1));
753 if (isa<StructType>(ElTy)) {
754 // We can change the destination pointer if we can store our first
755 // argument into the first element of the structure...
758 std::vector<Value*> Indices;
759 ElTy = getStructOffsetType(ElTy, Offset, Indices, TD, false);
760 assert(Offset == 0 && "Offset changed!");
761 if (ElTy == 0) // Element at offset zero in struct doesn't exist!
762 return false; // Can only happen for {}*
765 // Must move the same amount of data...
766 if (!ElTy->isSized() ||
767 TD.getTypeSize(ElTy) != TD.getTypeSize(I->getOperand(0)->getType()))
770 // Can convert store if the incoming value is convertible...
771 return ExpressionConvertibleToType(I->getOperand(0), ElTy, CTMap, TD);
776 case Instruction::GetElementPtr:
777 if (V != I->getOperand(0) || !isa<PointerType>(Ty)) return false;
779 // If we have a two operand form of getelementptr, this is really little
780 // more than a simple addition. As with addition, check to see if the
781 // getelementptr instruction can be changed to index into the new type.
783 if (I->getNumOperands() == 2) {
784 const Type *OldElTy = cast<PointerType>(I->getType())->getElementType();
785 unsigned DataSize = TD.getTypeSize(OldElTy);
786 Value *Index = I->getOperand(1);
787 Instruction *TempScale = 0;
789 // If the old data element is not unit sized, we have to create a scale
790 // instruction so that ConvertibleToGEP will know the REAL amount we are
791 // indexing by. Note that this is never inserted into the instruction
792 // stream, so we have to delete it when we're done.
795 TempScale = BinaryOperator::create(Instruction::Mul, Index,
796 ConstantSInt::get(Type::LongTy,
801 // Check to see if the second argument is an expression that can
802 // be converted to the appropriate size... if so, allow it.
804 std::vector<Value*> Indices;
805 const Type *ElTy = ConvertibleToGEP(Ty, Index, Indices, TD);
806 delete TempScale; // Free our temporary multiply if we made it
808 if (ElTy == 0) return false; // Cannot make conversion...
809 return ValueConvertibleToType(I, PointerType::get(ElTy), CTMap, TD);
813 case Instruction::PHINode: {
814 PHINode *PN = cast<PHINode>(I);
815 for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i)
816 if (!ExpressionConvertibleToType(PN->getIncomingValue(i), Ty, CTMap, TD))
818 return ValueConvertibleToType(PN, Ty, CTMap, TD);
821 case Instruction::Call: {
822 User::op_iterator OI = find(I->op_begin(), I->op_end(), V);
823 assert (OI != I->op_end() && "Not using value!");
824 unsigned OpNum = OI - I->op_begin();
826 // Are we trying to change the function pointer value to a new type?
828 const PointerType *PTy = dyn_cast<PointerType>(Ty);
829 if (PTy == 0) return false; // Can't convert to a non-pointer type...
830 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
831 if (FTy == 0) return false; // Can't convert to a non ptr to function...
833 // Do not allow converting to a call where all of the operands are ...'s
834 if (FTy->getNumParams() == 0 && FTy->isVarArg())
835 return false; // Do not permit this conversion!
837 // Perform sanity checks to make sure that new function type has the
838 // correct number of arguments...
840 unsigned NumArgs = I->getNumOperands()-1; // Don't include function ptr
842 // Cannot convert to a type that requires more fixed arguments than
843 // the call provides...
845 if (NumArgs < FTy->getNumParams()) return false;
847 // Unless this is a vararg function type, we cannot provide more arguments
848 // than are desired...
850 if (!FTy->isVarArg() && NumArgs > FTy->getNumParams())
853 // Okay, at this point, we know that the call and the function type match
854 // number of arguments. Now we see if we can convert the arguments
855 // themselves. Note that we do not require operands to be convertible,
856 // we can insert casts if they are convertible but not compatible. The
857 // reason for this is that we prefer to have resolved functions but casted
858 // arguments if possible.
860 const FunctionType::ParamTypes &PTs = FTy->getParamTypes();
861 for (unsigned i = 0, NA = PTs.size(); i < NA; ++i)
862 if (!PTs[i]->isLosslesslyConvertibleTo(I->getOperand(i+1)->getType()))
863 return false; // Operands must have compatible types!
865 // Okay, at this point, we know that all of the arguments can be
866 // converted. We succeed if we can change the return type if
869 return ValueConvertibleToType(I, FTy->getReturnType(), CTMap, TD);
872 const PointerType *MPtr = cast<PointerType>(I->getOperand(0)->getType());
873 const FunctionType *FTy = cast<FunctionType>(MPtr->getElementType());
874 if (!FTy->isVarArg()) return false;
876 if ((OpNum-1) < FTy->getParamTypes().size())
877 return false; // It's not in the varargs section...
879 // If we get this far, we know the value is in the varargs section of the
880 // function! We can convert if we don't reinterpret the value...
882 return Ty->isLosslesslyConvertibleTo(V->getType());
889 void ConvertValueToNewType(Value *V, Value *NewVal, ValueMapCache &VMC,
890 const TargetData &TD) {
891 ValueHandle VH(VMC, V);
893 unsigned NumUses = V->use_size();
894 for (unsigned It = 0; It < NumUses; ) {
895 unsigned OldSize = NumUses;
896 ConvertOperandToType(*(V->use_begin()+It), V, NewVal, VMC, TD);
897 NumUses = V->use_size();
898 if (NumUses == OldSize) ++It;
904 static void ConvertOperandToType(User *U, Value *OldVal, Value *NewVal,
905 ValueMapCache &VMC, const TargetData &TD) {
906 if (isa<ValueHandle>(U)) return; // Valuehandles don't let go of operands...
908 if (VMC.OperandsMapped.count(U)) return;
909 VMC.OperandsMapped.insert(U);
911 ValueMapCache::ExprMapTy::iterator VMCI = VMC.ExprMap.find(U);
912 if (VMCI != VMC.ExprMap.end())
916 Instruction *I = cast<Instruction>(U); // Only Instructions convertible
918 BasicBlock *BB = I->getParent();
919 assert(BB != 0 && "Instruction not embedded in basic block!");
920 std::string Name = I->getName();
922 Instruction *Res; // Result of conversion
924 //cerr << endl << endl << "Type:\t" << Ty << "\nInst: " << I << "BB Before: " << BB << endl;
926 // Prevent I from being removed...
927 ValueHandle IHandle(VMC, I);
929 const Type *NewTy = NewVal->getType();
930 Constant *Dummy = (NewTy != Type::VoidTy) ?
931 Constant::getNullValue(NewTy) : 0;
933 switch (I->getOpcode()) {
934 case Instruction::Cast:
935 if (VMC.NewCasts.count(ValueHandle(VMC, I))) {
936 // This cast has already had it's value converted, causing a new cast to
937 // be created. We don't want to create YET ANOTHER cast instruction
938 // representing the original one, so just modify the operand of this cast
939 // instruction, which we know is newly created.
940 I->setOperand(0, NewVal);
941 I->setName(Name); // give I its name back
945 Res = new CastInst(NewVal, I->getType(), Name);
949 case Instruction::Add:
950 if (isa<PointerType>(NewTy)) {
951 Value *IndexVal = I->getOperand(OldVal == I->getOperand(0) ? 1 : 0);
952 std::vector<Value*> Indices;
953 BasicBlock::iterator It = I;
955 if (const Type *ETy = ConvertibleToGEP(NewTy, IndexVal, Indices, TD,&It)){
956 // If successful, convert the add to a GEP
957 //const Type *RetTy = PointerType::get(ETy);
958 // First operand is actually the given pointer...
959 Res = new GetElementPtrInst(NewVal, Indices, Name);
960 assert(cast<PointerType>(Res->getType())->getElementType() == ETy &&
961 "ConvertibleToGEP broken!");
967 case Instruction::Sub:
968 case Instruction::SetEQ:
969 case Instruction::SetNE: {
970 Res = BinaryOperator::create(cast<BinaryOperator>(I)->getOpcode(),
972 VMC.ExprMap[I] = Res; // Add node to expression eagerly
974 unsigned OtherIdx = (OldVal == I->getOperand(0)) ? 1 : 0;
975 Value *OtherOp = I->getOperand(OtherIdx);
976 Value *NewOther = ConvertExpressionToType(OtherOp, NewTy, VMC, TD);
978 Res->setOperand(OtherIdx, NewOther);
979 Res->setOperand(!OtherIdx, NewVal);
982 case Instruction::Shl:
983 case Instruction::Shr:
984 assert(I->getOperand(0) == OldVal);
985 Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(), NewVal,
986 I->getOperand(1), Name);
989 case Instruction::Free: // Free can free any pointer type!
990 assert(I->getOperand(0) == OldVal);
991 Res = new FreeInst(NewVal);
995 case Instruction::Load: {
996 assert(I->getOperand(0) == OldVal && isa<PointerType>(NewVal->getType()));
997 const Type *LoadedTy =
998 cast<PointerType>(NewVal->getType())->getElementType();
1000 Value *Src = NewVal;
1002 if (const CompositeType *CT = dyn_cast<CompositeType>(LoadedTy)) {
1003 std::vector<Value*> Indices;
1004 Indices.push_back(ConstantSInt::get(Type::LongTy, 0));
1006 unsigned Offset = 0; // No offset, get first leaf.
1007 LoadedTy = getStructOffsetType(CT, Offset, Indices, TD, false);
1008 assert(LoadedTy->isFirstClassType());
1010 if (Indices.size() != 1) { // Do not generate load X, 0
1011 // Insert the GEP instruction before this load.
1012 Src = new GetElementPtrInst(Src, Indices, Name+".idx", I);
1016 Res = new LoadInst(Src, Name);
1017 assert(Res->getType()->isFirstClassType() && "Load of structure or array!");
1021 case Instruction::Store: {
1022 if (I->getOperand(0) == OldVal) { // Replace the source value
1023 // Check to see if operand #1 has already been converted...
1024 ValueMapCache::ExprMapTy::iterator VMCI =
1025 VMC.ExprMap.find(I->getOperand(1));
1026 if (VMCI != VMC.ExprMap.end()) {
1027 // Comments describing this stuff are in the OperandConvertibleToType
1028 // switch statement for Store...
1031 cast<PointerType>(VMCI->second->getType())->getElementType();
1033 Value *SrcPtr = VMCI->second;
1035 if (ElTy != NewTy) {
1036 // We check that this is a struct in the initial scan...
1037 const StructType *SElTy = cast<StructType>(ElTy);
1039 std::vector<Value*> Indices;
1040 Indices.push_back(Constant::getNullValue(Type::LongTy));
1042 unsigned Offset = 0;
1043 const Type *Ty = getStructOffsetType(ElTy, Offset, Indices, TD,false);
1044 assert(Offset == 0 && "Offset changed!");
1045 assert(NewTy == Ty && "Did not convert to correct type!");
1047 // Insert the GEP instruction before this store.
1048 SrcPtr = new GetElementPtrInst(SrcPtr, Indices,
1049 SrcPtr->getName()+".idx", I);
1051 Res = new StoreInst(NewVal, SrcPtr);
1053 VMC.ExprMap[I] = Res;
1055 // Otherwise, we haven't converted Operand #1 over yet...
1056 const PointerType *NewPT = PointerType::get(NewTy);
1057 Res = new StoreInst(NewVal, Constant::getNullValue(NewPT));
1058 VMC.ExprMap[I] = Res;
1059 Res->setOperand(1, ConvertExpressionToType(I->getOperand(1),
1062 } else { // Replace the source pointer
1063 const Type *ValTy = cast<PointerType>(NewTy)->getElementType();
1065 Value *SrcPtr = NewVal;
1067 if (isa<StructType>(ValTy)) {
1068 std::vector<Value*> Indices;
1069 Indices.push_back(Constant::getNullValue(Type::LongTy));
1071 unsigned Offset = 0;
1072 ValTy = getStructOffsetType(ValTy, Offset, Indices, TD, false);
1074 assert(Offset == 0 && ValTy);
1076 // Insert the GEP instruction before this store.
1077 SrcPtr = new GetElementPtrInst(SrcPtr, Indices,
1078 SrcPtr->getName()+".idx", I);
1081 Res = new StoreInst(Constant::getNullValue(ValTy), SrcPtr);
1082 VMC.ExprMap[I] = Res;
1083 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
1090 case Instruction::GetElementPtr: {
1091 // Convert a one index getelementptr into just about anything that is
1094 BasicBlock::iterator It = I;
1095 const Type *OldElTy = cast<PointerType>(I->getType())->getElementType();
1096 unsigned DataSize = TD.getTypeSize(OldElTy);
1097 Value *Index = I->getOperand(1);
1099 if (DataSize != 1) {
1100 // Insert a multiply of the old element type is not a unit size...
1101 Index = BinaryOperator::create(Instruction::Mul, Index,
1102 ConstantSInt::get(Type::LongTy, DataSize),
1106 // Perform the conversion now...
1108 std::vector<Value*> Indices;
1109 const Type *ElTy = ConvertibleToGEP(NewVal->getType(),Index,Indices,TD,&It);
1110 assert(ElTy != 0 && "GEP Conversion Failure!");
1111 Res = new GetElementPtrInst(NewVal, Indices, Name);
1112 assert(Res->getType() == PointerType::get(ElTy) &&
1113 "ConvertibleToGet failed!");
1116 if (I->getType() == PointerType::get(Type::SByteTy)) {
1117 // Convert a getelementptr sbyte * %reg111, uint 16 freely back to
1118 // anything that is a pointer type...
1120 BasicBlock::iterator It = I;
1122 // Check to see if the second argument is an expression that can
1123 // be converted to the appropriate size... if so, allow it.
1125 std::vector<Value*> Indices;
1126 const Type *ElTy = ConvertibleToGEP(NewVal->getType(), I->getOperand(1),
1128 assert(ElTy != 0 && "GEP Conversion Failure!");
1130 Res = new GetElementPtrInst(NewVal, Indices, Name);
1132 // Convert a getelementptr ulong * %reg123, uint %N
1133 // to getelementptr long * %reg123, uint %N
1134 // ... where the type must simply stay the same size...
1136 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
1137 std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
1138 Res = new GetElementPtrInst(NewVal, Indices, Name);
1143 case Instruction::PHINode: {
1144 PHINode *OldPN = cast<PHINode>(I);
1145 PHINode *NewPN = new PHINode(NewTy, Name);
1146 VMC.ExprMap[I] = NewPN;
1148 while (OldPN->getNumOperands()) {
1149 BasicBlock *BB = OldPN->getIncomingBlock(0);
1150 Value *OldVal = OldPN->getIncomingValue(0);
1151 OldPN->removeIncomingValue(BB, false);
1152 Value *V = ConvertExpressionToType(OldVal, NewTy, VMC, TD);
1153 NewPN->addIncoming(V, BB);
1159 case Instruction::Call: {
1160 Value *Meth = I->getOperand(0);
1161 std::vector<Value*> Params(I->op_begin()+1, I->op_end());
1163 if (Meth == OldVal) { // Changing the function pointer?
1164 const PointerType *NewPTy = cast<PointerType>(NewVal->getType());
1165 const FunctionType *NewTy = cast<FunctionType>(NewPTy->getElementType());
1166 const FunctionType::ParamTypes &PTs = NewTy->getParamTypes();
1168 if (NewTy->getReturnType() == Type::VoidTy)
1169 Name = ""; // Make sure not to name a void call!
1171 // Get an iterator to the call instruction so that we can insert casts for
1172 // operands if needbe. Note that we do not require operands to be
1173 // convertible, we can insert casts if they are convertible but not
1174 // compatible. The reason for this is that we prefer to have resolved
1175 // functions but casted arguments if possible.
1177 BasicBlock::iterator It = I;
1179 // Convert over all of the call operands to their new types... but only
1180 // convert over the part that is not in the vararg section of the call.
1182 for (unsigned i = 0; i < PTs.size(); ++i)
1183 if (Params[i]->getType() != PTs[i]) {
1184 // Create a cast to convert it to the right type, we know that this
1185 // is a lossless cast...
1187 Params[i] = new CastInst(Params[i], PTs[i], "callarg.cast." +
1188 Params[i]->getName(), It);
1190 Meth = NewVal; // Update call destination to new value
1192 } else { // Changing an argument, must be in vararg area
1193 std::vector<Value*>::iterator OI =
1194 find(Params.begin(), Params.end(), OldVal);
1195 assert (OI != Params.end() && "Not using value!");
1200 Res = new CallInst(Meth, Params, Name);
1204 assert(0 && "Expression convertible, but don't know how to convert?");
1208 // If the instruction was newly created, insert it into the instruction
1211 BasicBlock::iterator It = I;
1212 assert(It != BB->end() && "Instruction not in own basic block??");
1213 BB->getInstList().insert(It, Res); // Keep It pointing to old instruction
1215 DEBUG(cerr << "COT CREATED: " << (void*)Res << " " << Res
1216 << "In: " << (void*)I << " " << I << "Out: " << (void*)Res
1219 // Add the instruction to the expression map
1220 VMC.ExprMap[I] = Res;
1222 if (I->getType() != Res->getType())
1223 ConvertValueToNewType(I, Res, VMC, TD);
1225 for (unsigned It = 0; It < I->use_size(); ) {
1226 User *Use = *(I->use_begin()+It);
1227 if (isa<ValueHandle>(Use)) // Don't remove ValueHandles!
1230 Use->replaceUsesOfWith(I, Res);
1233 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
1235 assert(isa<ValueHandle>((Value*)*UI) &&"Uses of Instruction remain!!!");
1240 ValueHandle::ValueHandle(ValueMapCache &VMC, Value *V)
1241 : Instruction(Type::VoidTy, UserOp1, ""), Cache(VMC) {
1242 //DEBUG(cerr << "VH AQUIRING: " << (void*)V << " " << V);
1243 Operands.push_back(Use(V, this));
1246 ValueHandle::ValueHandle(const ValueHandle &VH)
1247 : Instruction(Type::VoidTy, UserOp1, ""), Cache(VH.Cache) {
1248 //DEBUG(cerr << "VH AQUIRING: " << (void*)V << " " << V);
1249 Operands.push_back(Use((Value*)VH.getOperand(0), this));
1252 static void RecursiveDelete(ValueMapCache &Cache, Instruction *I) {
1253 if (!I || !I->use_empty()) return;
1255 assert(I->getParent() && "Inst not in basic block!");
1257 //DEBUG(cerr << "VH DELETING: " << (void*)I << " " << I);
1259 for (User::op_iterator OI = I->op_begin(), OE = I->op_end();
1261 if (Instruction *U = dyn_cast<Instruction>(OI)) {
1263 RecursiveDelete(Cache, U);
1266 I->getParent()->getInstList().remove(I);
1268 Cache.OperandsMapped.erase(I);
1269 Cache.ExprMap.erase(I);
1273 ValueHandle::~ValueHandle() {
1274 if (Operands[0]->use_size() == 1) {
1275 Value *V = Operands[0];
1276 Operands[0] = 0; // Drop use!
1278 // Now we just need to remove the old instruction so we don't get infinite
1279 // loops. Note that we cannot use DCE because DCE won't remove a store
1280 // instruction, for example.
1282 RecursiveDelete(Cache, dyn_cast<Instruction>(V));
1284 //DEBUG(cerr << "VH RELEASING: " << (void*)Operands[0].get() << " "
1285 // << Operands[0]->use_size() << " " << Operands[0]);