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 // convertable, 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/StatisticReporter.h"
21 static bool OperandConvertableToType(User *U, Value *V, const Type *Ty,
22 ValueTypeCache &ConvertedTypes);
24 static void ConvertOperandToType(User *U, Value *OldVal, Value *NewVal,
27 // AllIndicesZero - Return true if all of the indices of the specified memory
28 // access instruction are zero, indicating an effectively nil offset to the
31 static bool AllIndicesZero(const MemAccessInst *MAI) {
32 for (User::const_op_iterator S = MAI->idx_begin(), E = MAI->idx_end();
34 if (!isa<Constant>(S->get()) || !cast<Constant>(S->get())->isNullValue())
40 // Peephole Malloc instructions: we take a look at the use chain of the
41 // malloc instruction, and try to find out if the following conditions hold:
42 // 1. The malloc is of the form: 'malloc [sbyte], uint <constant>'
43 // 2. The only users of the malloc are cast & add instructions
44 // 3. Of the cast instructions, there is only one destination pointer type
45 // [RTy] where the size of the pointed to object is equal to the number
46 // of bytes allocated.
48 // If these conditions hold, we convert the malloc to allocate an [RTy]
49 // element. TODO: This comment is out of date WRT arrays
51 static bool MallocConvertableToType(MallocInst *MI, const Type *Ty,
52 ValueTypeCache &CTMap) {
53 if (!isa<PointerType>(Ty)) return false; // Malloc always returns pointers
55 // Deal with the type to allocate, not the pointer type...
56 Ty = cast<PointerType>(Ty)->getElementType();
57 if (!Ty->isSized()) return false; // Can only alloc something with a size
59 // Analyze the number of bytes allocated...
60 analysis::ExprType Expr = analysis::ClassifyExpression(MI->getArraySize());
62 // Get information about the base datatype being allocated, before & after
63 int ReqTypeSize = TD.getTypeSize(Ty);
64 unsigned OldTypeSize = TD.getTypeSize(MI->getType()->getElementType());
66 // Must have a scale or offset to analyze it...
67 if (!Expr.Offset && !Expr.Scale && OldTypeSize == 1) return false;
69 // Get the offset and scale of the allocation...
70 int OffsetVal = Expr.Offset ? getConstantValue(Expr.Offset) : 0;
71 int ScaleVal = Expr.Scale ? getConstantValue(Expr.Scale) : (Expr.Var ? 1 : 0);
73 // The old type might not be of unit size, take old size into consideration
75 int Offset = OffsetVal * OldTypeSize;
76 int Scale = ScaleVal * OldTypeSize;
78 // In order to be successful, both the scale and the offset must be a multiple
79 // of the requested data type's size.
81 if (Offset/ReqTypeSize*ReqTypeSize != Offset ||
82 Scale/ReqTypeSize*ReqTypeSize != Scale)
83 return false; // Nope.
88 static Instruction *ConvertMallocToType(MallocInst *MI, const Type *Ty,
89 const std::string &Name,
91 BasicBlock *BB = MI->getParent();
92 BasicBlock::iterator It = BB->end();
94 // Analyze the number of bytes allocated...
95 analysis::ExprType Expr = analysis::ClassifyExpression(MI->getArraySize());
97 const PointerType *AllocTy = cast<PointerType>(Ty);
98 const Type *ElType = AllocTy->getElementType();
100 unsigned DataSize = TD.getTypeSize(ElType);
101 unsigned OldTypeSize = TD.getTypeSize(MI->getType()->getElementType());
103 // Get the offset and scale coefficients that we are allocating...
104 int OffsetVal = (Expr.Offset ? getConstantValue(Expr.Offset) : 0);
105 int ScaleVal = Expr.Scale ? getConstantValue(Expr.Scale) : (Expr.Var ? 1 : 0);
107 // The old type might not be of unit size, take old size into consideration
109 unsigned Offset = (unsigned)OffsetVal * OldTypeSize / DataSize;
110 unsigned Scale = (unsigned)ScaleVal * OldTypeSize / DataSize;
112 // Locate the malloc instruction, because we may be inserting instructions
115 // If we have a scale, apply it first...
117 // Expr.Var is not neccesarily unsigned right now, insert a cast now.
118 if (Expr.Var->getType() != Type::UIntTy) {
119 Instruction *CI = new CastInst(Expr.Var, Type::UIntTy);
120 if (Expr.Var->hasName()) CI->setName(Expr.Var->getName()+"-uint");
121 It = ++BB->getInstList().insert(It, CI);
127 BinaryOperator::create(Instruction::Mul, Expr.Var,
128 ConstantUInt::get(Type::UIntTy, Scale));
129 if (Expr.Var->hasName()) ScI->setName(Expr.Var->getName()+"-scl");
130 It = ++BB->getInstList().insert(It, ScI);
135 // If we are not scaling anything, just make the offset be the "var"...
136 Expr.Var = ConstantUInt::get(Type::UIntTy, Offset);
137 Offset = 0; Scale = 1;
140 // If we have an offset now, add it in...
142 assert(Expr.Var && "Var must be nonnull by now!");
145 BinaryOperator::create(Instruction::Add, Expr.Var,
146 ConstantUInt::get(Type::UIntTy, Offset));
147 if (Expr.Var->hasName()) AddI->setName(Expr.Var->getName()+"-off");
148 It = ++BB->getInstList().insert(It, AddI);
152 Instruction *NewI = new MallocInst(AllocTy, Expr.Var, Name);
154 assert(AllocTy == Ty);
159 // ExpressionConvertableToType - Return true if it is possible
160 bool ExpressionConvertableToType(Value *V, const Type *Ty,
161 ValueTypeCache &CTMap) {
162 // Expression type must be holdable in a register.
163 if (!Ty->isFirstClassType())
166 ValueTypeCache::iterator CTMI = CTMap.find(V);
167 if (CTMI != CTMap.end()) return CTMI->second == Ty;
170 if (V->getType() == Ty) return true; // Expression already correct type!
172 Instruction *I = dyn_cast<Instruction>(V);
174 // It's not an instruction, check to see if it's a constant... all constants
175 // can be converted to an equivalent value (except pointers, they can't be
176 // const prop'd in general). We just ask the constant propogator to see if
177 // it can convert the value...
179 if (Constant *CPV = dyn_cast<Constant>(V))
180 if (ConstantFoldCastInstruction(CPV, Ty))
181 return true; // Don't worry about deallocating, it's a constant.
183 return false; // Otherwise, we can't convert!
186 switch (I->getOpcode()) {
187 case Instruction::Cast:
188 // We can convert the expr if the cast destination type is losslessly
189 // convertable to the requested type.
190 if (!Ty->isLosslesslyConvertableTo(I->getType())) return false;
192 // We also do not allow conversion of a cast that casts from a ptr to array
193 // of X to a *X. For example: cast [4 x %List *] * %val to %List * *
195 if (const PointerType *SPT =
196 dyn_cast<PointerType>(I->getOperand(0)->getType()))
197 if (const PointerType *DPT = dyn_cast<PointerType>(I->getType()))
198 if (const ArrayType *AT = dyn_cast<ArrayType>(SPT->getElementType()))
199 if (AT->getElementType() == DPT->getElementType())
203 case Instruction::Add:
204 case Instruction::Sub:
205 if (!ExpressionConvertableToType(I->getOperand(0), Ty, CTMap) ||
206 !ExpressionConvertableToType(I->getOperand(1), Ty, CTMap))
209 case Instruction::Shr:
210 if (Ty->isSigned() != V->getType()->isSigned()) return false;
212 case Instruction::Shl:
213 if (!ExpressionConvertableToType(I->getOperand(0), Ty, CTMap))
217 case Instruction::Load: {
218 LoadInst *LI = cast<LoadInst>(I);
219 if (!ExpressionConvertableToType(LI->getPointerOperand(),
220 PointerType::get(Ty), CTMap))
224 case Instruction::PHINode: {
225 PHINode *PN = cast<PHINode>(I);
226 for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i)
227 if (!ExpressionConvertableToType(PN->getIncomingValue(i), Ty, CTMap))
232 case Instruction::Malloc:
233 if (!MallocConvertableToType(cast<MallocInst>(I), Ty, CTMap))
237 case Instruction::GetElementPtr: {
238 // GetElementPtr's are directly convertable to a pointer type if they have
239 // a number of zeros at the end. Because removing these values does not
240 // change the logical offset of the GEP, it is okay and fair to remove them.
241 // This can change this:
242 // %t1 = getelementptr %Hosp * %hosp, ubyte 4, ubyte 0 ; <%List **>
243 // %t2 = cast %List * * %t1 to %List *
245 // %t2 = getelementptr %Hosp * %hosp, ubyte 4 ; <%List *>
247 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
248 const PointerType *PTy = dyn_cast<PointerType>(Ty);
249 if (!PTy) return false; // GEP must always return a pointer...
250 const Type *PVTy = PTy->getElementType();
252 // Check to see if there are zero elements that we can remove from the
253 // index array. If there are, check to see if removing them causes us to
254 // get to the right type...
256 std::vector<Value*> Indices = GEP->copyIndices();
257 const Type *BaseType = GEP->getPointerOperand()->getType();
258 const Type *ElTy = 0;
260 while (!Indices.empty() && isa<ConstantUInt>(Indices.back()) &&
261 cast<ConstantUInt>(Indices.back())->getValue() == 0) {
263 ElTy = GetElementPtrInst::getIndexedType(BaseType, Indices, true);
265 break; // Found a match!!
269 if (ElTy) break; // Found a number of zeros we can strip off!
271 // Otherwise, we can convert a GEP from one form to the other iff the
272 // current gep is of the form 'getelementptr sbyte*, unsigned N
273 // and we could convert this to an appropriate GEP for the new type.
275 if (GEP->getNumOperands() == 2 &&
276 GEP->getOperand(1)->getType() == Type::UIntTy &&
277 GEP->getType() == PointerType::get(Type::SByteTy)) {
279 // Do not Check to see if our incoming pointer can be converted
280 // to be a ptr to an array of the right type... because in more cases than
281 // not, it is simply not analyzable because of pointer/array
282 // discrepencies. To fix this, we will insert a cast before the GEP.
285 // Check to see if 'N' is an expression that can be converted to
286 // the appropriate size... if so, allow it.
288 std::vector<Value*> Indices;
289 const Type *ElTy = ConvertableToGEP(PTy, I->getOperand(1), Indices);
291 if (!ExpressionConvertableToType(I->getOperand(0),
292 PointerType::get(ElTy), CTMap))
293 return false; // Can't continue, ExConToTy might have polluted set!
298 // Otherwise, it could be that we have something like this:
299 // getelementptr [[sbyte] *] * %reg115, uint %reg138 ; [sbyte]**
300 // and want to convert it into something like this:
301 // getelemenptr [[int] *] * %reg115, uint %reg138 ; [int]**
303 if (GEP->getNumOperands() == 2 &&
304 GEP->getOperand(1)->getType() == Type::UIntTy &&
305 TD.getTypeSize(PTy->getElementType()) ==
306 TD.getTypeSize(GEP->getType()->getElementType())) {
307 const PointerType *NewSrcTy = PointerType::get(PVTy);
308 if (!ExpressionConvertableToType(I->getOperand(0), NewSrcTy, CTMap))
313 return false; // No match, maybe next time.
320 // Expressions are only convertable if all of the users of the expression can
321 // have this value converted. This makes use of the map to avoid infinite
324 for (Value::use_iterator It = I->use_begin(), E = I->use_end(); It != E; ++It)
325 if (!OperandConvertableToType(*It, I, Ty, CTMap))
332 Value *ConvertExpressionToType(Value *V, const Type *Ty, ValueMapCache &VMC) {
333 if (V->getType() == Ty) return V; // Already where we need to be?
335 ValueMapCache::ExprMapTy::iterator VMCI = VMC.ExprMap.find(V);
336 if (VMCI != VMC.ExprMap.end()) {
337 const Value *GV = VMCI->second;
338 const Type *GTy = VMCI->second->getType();
339 assert(VMCI->second->getType() == Ty);
341 if (Instruction *I = dyn_cast<Instruction>(V))
342 ValueHandle IHandle(VMC, I); // Remove I if it is unused now!
347 DEBUG(cerr << "CETT: " << (void*)V << " " << V);
349 Instruction *I = dyn_cast<Instruction>(V);
351 if (Constant *CPV = cast<Constant>(V)) {
352 // Constants are converted by constant folding the cast that is required.
353 // We assume here that all casts are implemented for constant prop.
354 Value *Result = ConstantFoldCastInstruction(CPV, Ty);
355 assert(Result && "ConstantFoldCastInstruction Failed!!!");
356 assert(Result->getType() == Ty && "Const prop of cast failed!");
358 // Add the instruction to the expression map
359 VMC.ExprMap[V] = Result;
364 BasicBlock *BB = I->getParent();
365 BasicBlock::InstListType &BIL = BB->getInstList();
366 std::string Name = I->getName(); if (!Name.empty()) I->setName("");
367 Instruction *Res; // Result of conversion
369 ValueHandle IHandle(VMC, I); // Prevent I from being removed!
371 Constant *Dummy = Constant::getNullValue(Ty);
373 switch (I->getOpcode()) {
374 case Instruction::Cast:
375 assert(VMC.NewCasts.count(ValueHandle(VMC, I)) == 0);
376 Res = new CastInst(I->getOperand(0), Ty, Name);
377 VMC.NewCasts.insert(ValueHandle(VMC, Res));
380 case Instruction::Add:
381 case Instruction::Sub:
382 Res = BinaryOperator::create(cast<BinaryOperator>(I)->getOpcode(),
384 VMC.ExprMap[I] = Res; // Add node to expression eagerly
386 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), Ty, VMC));
387 Res->setOperand(1, ConvertExpressionToType(I->getOperand(1), Ty, VMC));
390 case Instruction::Shl:
391 case Instruction::Shr:
392 Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(), Dummy,
393 I->getOperand(1), Name);
394 VMC.ExprMap[I] = Res;
395 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), Ty, VMC));
398 case Instruction::Load: {
399 LoadInst *LI = cast<LoadInst>(I);
401 Res = new LoadInst(Constant::getNullValue(PointerType::get(Ty)), Name);
402 VMC.ExprMap[I] = Res;
403 Res->setOperand(0, ConvertExpressionToType(LI->getPointerOperand(),
404 PointerType::get(Ty), VMC));
405 assert(Res->getOperand(0)->getType() == PointerType::get(Ty));
406 assert(Ty == Res->getType());
407 assert(Res->getType()->isFirstClassType() && "Load of structure or array!");
411 case Instruction::PHINode: {
412 PHINode *OldPN = cast<PHINode>(I);
413 PHINode *NewPN = new PHINode(Ty, Name);
415 VMC.ExprMap[I] = NewPN; // Add node to expression eagerly
416 while (OldPN->getNumOperands()) {
417 BasicBlock *BB = OldPN->getIncomingBlock(0);
418 Value *OldVal = OldPN->getIncomingValue(0);
419 ValueHandle OldValHandle(VMC, OldVal);
420 OldPN->removeIncomingValue(BB);
421 Value *V = ConvertExpressionToType(OldVal, Ty, VMC);
422 NewPN->addIncoming(V, BB);
428 case Instruction::Malloc: {
429 Res = ConvertMallocToType(cast<MallocInst>(I), Ty, Name, VMC);
433 case Instruction::GetElementPtr: {
434 // GetElementPtr's are directly convertable to a pointer type if they have
435 // a number of zeros at the end. Because removing these values does not
436 // change the logical offset of the GEP, it is okay and fair to remove them.
437 // This can change this:
438 // %t1 = getelementptr %Hosp * %hosp, ubyte 4, ubyte 0 ; <%List **>
439 // %t2 = cast %List * * %t1 to %List *
441 // %t2 = getelementptr %Hosp * %hosp, ubyte 4 ; <%List *>
443 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
445 // Check to see if there are zero elements that we can remove from the
446 // index array. If there are, check to see if removing them causes us to
447 // get to the right type...
449 std::vector<Value*> Indices = GEP->copyIndices();
450 const Type *BaseType = GEP->getPointerOperand()->getType();
451 const Type *PVTy = cast<PointerType>(Ty)->getElementType();
453 while (!Indices.empty() && isa<ConstantUInt>(Indices.back()) &&
454 cast<ConstantUInt>(Indices.back())->getValue() == 0) {
456 if (GetElementPtrInst::getIndexedType(BaseType, Indices, true) == PVTy) {
457 if (Indices.size() == 0) {
458 Res = new CastInst(GEP->getPointerOperand(), BaseType); // NOOP
460 Res = new GetElementPtrInst(GEP->getPointerOperand(), Indices, Name);
466 if (Res == 0 && GEP->getNumOperands() == 2 &&
467 GEP->getOperand(1)->getType() == Type::UIntTy &&
468 GEP->getType() == PointerType::get(Type::SByteTy)) {
470 // Otherwise, we can convert a GEP from one form to the other iff the
471 // current gep is of the form 'getelementptr [sbyte]*, unsigned N
472 // and we could convert this to an appropriate GEP for the new type.
474 const PointerType *NewSrcTy = PointerType::get(PVTy);
475 BasicBlock::iterator It = I;
477 // Check to see if 'N' is an expression that can be converted to
478 // the appropriate size... if so, allow it.
480 std::vector<Value*> Indices;
481 const Type *ElTy = ConvertableToGEP(NewSrcTy, I->getOperand(1),
484 assert(ElTy == PVTy && "Internal error, setup wrong!");
485 Res = new GetElementPtrInst(Constant::getNullValue(NewSrcTy),
487 VMC.ExprMap[I] = Res;
488 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
493 // Otherwise, it could be that we have something like this:
494 // getelementptr [[sbyte] *] * %reg115, uint %reg138 ; [sbyte]**
495 // and want to convert it into something like this:
496 // getelemenptr [[int] *] * %reg115, uint %reg138 ; [int]**
499 const PointerType *NewSrcTy = PointerType::get(PVTy);
500 Res = new GetElementPtrInst(Constant::getNullValue(NewSrcTy),
501 GEP->copyIndices(), Name);
502 VMC.ExprMap[I] = Res;
503 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
508 assert(Res && "Didn't find match!");
509 break; // No match, maybe next time.
513 assert(0 && "Expression convertable, but don't know how to convert?");
517 assert(Res->getType() == Ty && "Didn't convert expr to correct type!");
521 // Add the instruction to the expression map
522 VMC.ExprMap[I] = Res;
524 // Expressions are only convertable if all of the users of the expression can
525 // have this value converted. This makes use of the map to avoid infinite
528 unsigned NumUses = I->use_size();
529 for (unsigned It = 0; It < NumUses; ) {
530 unsigned OldSize = NumUses;
531 ConvertOperandToType(*(I->use_begin()+It), I, Res, VMC);
532 NumUses = I->use_size();
533 if (NumUses == OldSize) ++It;
536 DEBUG(cerr << "ExpIn: " << (void*)I << " " << I
537 << "ExpOut: " << (void*)Res << " " << Res);
544 // ValueConvertableToType - Return true if it is possible
545 bool ValueConvertableToType(Value *V, const Type *Ty,
546 ValueTypeCache &ConvertedTypes) {
547 ValueTypeCache::iterator I = ConvertedTypes.find(V);
548 if (I != ConvertedTypes.end()) return I->second == Ty;
549 ConvertedTypes[V] = Ty;
551 // It is safe to convert the specified value to the specified type IFF all of
552 // the uses of the value can be converted to accept the new typed value.
554 if (V->getType() != Ty) {
555 for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I)
556 if (!OperandConvertableToType(*I, V, Ty, ConvertedTypes))
567 // OperandConvertableToType - Return true if it is possible to convert operand
568 // V of User (instruction) U to the specified type. This is true iff it is
569 // possible to change the specified instruction to accept this. CTMap is a map
570 // of converted types, so that circular definitions will see the future type of
571 // the expression, not the static current type.
573 static bool OperandConvertableToType(User *U, Value *V, const Type *Ty,
574 ValueTypeCache &CTMap) {
575 // if (V->getType() == Ty) return true; // Operand already the right type?
577 // Expression type must be holdable in a register.
578 if (!Ty->isFirstClassType())
581 Instruction *I = dyn_cast<Instruction>(U);
582 if (I == 0) return false; // We can't convert!
584 switch (I->getOpcode()) {
585 case Instruction::Cast:
586 assert(I->getOperand(0) == V);
587 // We can convert the expr if the cast destination type is losslessly
588 // convertable to the requested type.
589 // Also, do not change a cast that is a noop cast. For all intents and
590 // purposes it should be eliminated.
591 if (!Ty->isLosslesslyConvertableTo(I->getOperand(0)->getType()) ||
592 I->getType() == I->getOperand(0)->getType())
595 // Do not allow a 'cast ushort %V to uint' to have it's first operand be
596 // converted to a 'short' type. Doing so changes the way sign promotion
597 // happens, and breaks things. Only allow the cast to take place if the
598 // signedness doesn't change... or if the current cast is not a lossy
601 if (!I->getType()->isLosslesslyConvertableTo(I->getOperand(0)->getType()) &&
602 I->getOperand(0)->getType()->isSigned() != Ty->isSigned())
605 // We also do not allow conversion of a cast that casts from a ptr to array
606 // of X to a *X. For example: cast [4 x %List *] * %val to %List * *
608 if (const PointerType *SPT =
609 dyn_cast<PointerType>(I->getOperand(0)->getType()))
610 if (const PointerType *DPT = dyn_cast<PointerType>(I->getType()))
611 if (const ArrayType *AT = dyn_cast<ArrayType>(SPT->getElementType()))
612 if (AT->getElementType() == DPT->getElementType())
616 case Instruction::Add:
617 if (isa<PointerType>(Ty)) {
618 Value *IndexVal = I->getOperand(V == I->getOperand(0) ? 1 : 0);
619 std::vector<Value*> Indices;
620 if (const Type *ETy = ConvertableToGEP(Ty, IndexVal, Indices)) {
621 const Type *RetTy = PointerType::get(ETy);
623 // Only successful if we can convert this type to the required type
624 if (ValueConvertableToType(I, RetTy, CTMap)) {
628 // We have to return failure here because ValueConvertableToType could
629 // have polluted our map
634 case Instruction::Sub: {
635 Value *OtherOp = I->getOperand((V == I->getOperand(0)) ? 1 : 0);
636 return ValueConvertableToType(I, Ty, CTMap) &&
637 ExpressionConvertableToType(OtherOp, Ty, CTMap);
639 case Instruction::SetEQ:
640 case Instruction::SetNE: {
641 Value *OtherOp = I->getOperand((V == I->getOperand(0)) ? 1 : 0);
642 return ExpressionConvertableToType(OtherOp, Ty, CTMap);
644 case Instruction::Shr:
645 if (Ty->isSigned() != V->getType()->isSigned()) return false;
647 case Instruction::Shl:
648 assert(I->getOperand(0) == V);
649 return ValueConvertableToType(I, Ty, CTMap);
651 case Instruction::Free:
652 assert(I->getOperand(0) == V);
653 return isa<PointerType>(Ty); // Free can free any pointer type!
655 case Instruction::Load:
656 // Cannot convert the types of any subscripts...
657 if (I->getOperand(0) != V) return false;
659 if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
660 LoadInst *LI = cast<LoadInst>(I);
662 const Type *LoadedTy = PT->getElementType();
664 // They could be loading the first element of a composite type...
665 if (const CompositeType *CT = dyn_cast<CompositeType>(LoadedTy)) {
666 unsigned Offset = 0; // No offset, get first leaf.
667 std::vector<Value*> Indices; // Discarded...
668 LoadedTy = getStructOffsetType(CT, Offset, Indices, false);
669 assert(Offset == 0 && "Offset changed from zero???");
672 if (!LoadedTy->isFirstClassType())
675 if (TD.getTypeSize(LoadedTy) != TD.getTypeSize(LI->getType()))
678 return ValueConvertableToType(LI, LoadedTy, CTMap);
682 case Instruction::Store: {
683 StoreInst *SI = cast<StoreInst>(I);
685 if (V == I->getOperand(0)) {
686 ValueTypeCache::iterator CTMI = CTMap.find(I->getOperand(1));
687 if (CTMI != CTMap.end()) { // Operand #1 is in the table already?
688 // If so, check to see if it's Ty*, or, more importantly, if it is a
689 // pointer to a structure where the first element is a Ty... this code
690 // is neccesary because we might be trying to change the source and
691 // destination type of the store (they might be related) and the dest
692 // pointer type might be a pointer to structure. Below we allow pointer
693 // to structures where the 0th element is compatible with the value,
694 // now we have to support the symmetrical part of this.
696 const Type *ElTy = cast<PointerType>(CTMI->second)->getElementType();
698 // Already a pointer to what we want? Trivially accept...
699 if (ElTy == Ty) return true;
701 // Tricky case now, if the destination is a pointer to structure,
702 // obviously the source is not allowed to be a structure (cannot copy
703 // a whole structure at a time), so the level raiser must be trying to
704 // store into the first field. Check for this and allow it now:
706 if (const StructType *SElTy = dyn_cast<StructType>(ElTy)) {
708 std::vector<Value*> Indices;
709 ElTy = getStructOffsetType(ElTy, Offset, Indices, false);
710 assert(Offset == 0 && "Offset changed!");
711 if (ElTy == 0) // Element at offset zero in struct doesn't exist!
712 return false; // Can only happen for {}*
714 if (ElTy == Ty) // Looks like the 0th element of structure is
715 return true; // compatible! Accept now!
717 // Otherwise we know that we can't work, so just stop trying now.
722 // Can convert the store if we can convert the pointer operand to match
723 // the new value type...
724 return ExpressionConvertableToType(I->getOperand(1), PointerType::get(Ty),
726 } else if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
727 const Type *ElTy = PT->getElementType();
728 assert(V == I->getOperand(1));
730 if (isa<StructType>(ElTy)) {
731 // We can change the destination pointer if we can store our first
732 // argument into the first element of the structure...
735 std::vector<Value*> Indices;
736 ElTy = getStructOffsetType(ElTy, Offset, Indices, false);
737 assert(Offset == 0 && "Offset changed!");
738 if (ElTy == 0) // Element at offset zero in struct doesn't exist!
739 return false; // Can only happen for {}*
742 // Must move the same amount of data...
743 if (!ElTy->isSized() ||
744 TD.getTypeSize(ElTy) != TD.getTypeSize(I->getOperand(0)->getType()))
747 // Can convert store if the incoming value is convertable...
748 return ExpressionConvertableToType(I->getOperand(0), ElTy, CTMap);
753 case Instruction::GetElementPtr:
754 if (V != I->getOperand(0) || !isa<PointerType>(Ty)) return false;
756 // If we have a two operand form of getelementptr, this is really little
757 // more than a simple addition. As with addition, check to see if the
758 // getelementptr instruction can be changed to index into the new type.
760 if (I->getNumOperands() == 2) {
761 const Type *OldElTy = cast<PointerType>(I->getType())->getElementType();
762 unsigned DataSize = TD.getTypeSize(OldElTy);
763 Value *Index = I->getOperand(1);
764 Instruction *TempScale = 0;
766 // If the old data element is not unit sized, we have to create a scale
767 // instruction so that ConvertableToGEP will know the REAL amount we are
768 // indexing by. Note that this is never inserted into the instruction
769 // stream, so we have to delete it when we're done.
772 TempScale = BinaryOperator::create(Instruction::Mul, Index,
773 ConstantUInt::get(Type::UIntTy,
778 // Check to see if the second argument is an expression that can
779 // be converted to the appropriate size... if so, allow it.
781 std::vector<Value*> Indices;
782 const Type *ElTy = ConvertableToGEP(Ty, Index, Indices);
783 delete TempScale; // Free our temporary multiply if we made it
785 if (ElTy == 0) return false; // Cannot make conversion...
786 return ValueConvertableToType(I, PointerType::get(ElTy), CTMap);
790 case Instruction::PHINode: {
791 PHINode *PN = cast<PHINode>(I);
792 for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i)
793 if (!ExpressionConvertableToType(PN->getIncomingValue(i), Ty, CTMap))
795 return ValueConvertableToType(PN, Ty, CTMap);
798 case Instruction::Call: {
799 User::op_iterator OI = find(I->op_begin(), I->op_end(), V);
800 assert (OI != I->op_end() && "Not using value!");
801 unsigned OpNum = OI - I->op_begin();
803 // Are we trying to change the function pointer value to a new type?
805 const PointerType *PTy = dyn_cast<PointerType>(Ty);
806 if (PTy == 0) return false; // Can't convert to a non-pointer type...
807 const FunctionType *MTy = dyn_cast<FunctionType>(PTy->getElementType());
808 if (MTy == 0) return false; // Can't convert to a non ptr to function...
810 // Perform sanity checks to make sure that new function type has the
811 // correct number of arguments...
813 unsigned NumArgs = I->getNumOperands()-1; // Don't include function ptr
815 // Cannot convert to a type that requires more fixed arguments than
816 // the call provides...
818 if (NumArgs < MTy->getParamTypes().size()) return false;
820 // Unless this is a vararg function type, we cannot provide more arguments
821 // than are desired...
823 if (!MTy->isVarArg() && NumArgs > MTy->getParamTypes().size())
826 // Okay, at this point, we know that the call and the function type match
827 // number of arguments. Now we see if we can convert the arguments
828 // themselves. Note that we do not require operands to be convertable,
829 // we can insert casts if they are convertible but not compatible. The
830 // reason for this is that we prefer to have resolved functions but casted
831 // arguments if possible.
833 const FunctionType::ParamTypes &PTs = MTy->getParamTypes();
834 for (unsigned i = 0, NA = PTs.size(); i < NA; ++i)
835 if (!PTs[i]->isLosslesslyConvertableTo(I->getOperand(i+1)->getType()))
836 return false; // Operands must have compatible types!
838 // Okay, at this point, we know that all of the arguments can be
839 // converted. We succeed if we can change the return type if
842 return ValueConvertableToType(I, MTy->getReturnType(), CTMap);
845 const PointerType *MPtr = cast<PointerType>(I->getOperand(0)->getType());
846 const FunctionType *MTy = cast<FunctionType>(MPtr->getElementType());
847 if (!MTy->isVarArg()) return false;
849 if ((OpNum-1) < MTy->getParamTypes().size())
850 return false; // It's not in the varargs section...
852 // If we get this far, we know the value is in the varargs section of the
853 // function! We can convert if we don't reinterpret the value...
855 return Ty->isLosslesslyConvertableTo(V->getType());
862 void ConvertValueToNewType(Value *V, Value *NewVal, ValueMapCache &VMC) {
863 ValueHandle VH(VMC, V);
865 unsigned NumUses = V->use_size();
866 for (unsigned It = 0; It < NumUses; ) {
867 unsigned OldSize = NumUses;
868 ConvertOperandToType(*(V->use_begin()+It), V, NewVal, VMC);
869 NumUses = V->use_size();
870 if (NumUses == OldSize) ++It;
876 static void ConvertOperandToType(User *U, Value *OldVal, Value *NewVal,
877 ValueMapCache &VMC) {
878 if (isa<ValueHandle>(U)) return; // Valuehandles don't let go of operands...
880 if (VMC.OperandsMapped.count(U)) return;
881 VMC.OperandsMapped.insert(U);
883 ValueMapCache::ExprMapTy::iterator VMCI = VMC.ExprMap.find(U);
884 if (VMCI != VMC.ExprMap.end())
888 Instruction *I = cast<Instruction>(U); // Only Instructions convertable
890 BasicBlock *BB = I->getParent();
891 assert(BB != 0 && "Instruction not embedded in basic block!");
892 BasicBlock::InstListType &BIL = BB->getInstList();
893 std::string Name = I->getName();
895 Instruction *Res; // Result of conversion
897 //cerr << endl << endl << "Type:\t" << Ty << "\nInst: " << I << "BB Before: " << BB << endl;
899 // Prevent I from being removed...
900 ValueHandle IHandle(VMC, I);
902 const Type *NewTy = NewVal->getType();
903 Constant *Dummy = (NewTy != Type::VoidTy) ?
904 Constant::getNullValue(NewTy) : 0;
906 switch (I->getOpcode()) {
907 case Instruction::Cast:
908 if (VMC.NewCasts.count(ValueHandle(VMC, I))) {
909 // This cast has already had it's value converted, causing a new cast to
910 // be created. We don't want to create YET ANOTHER cast instruction
911 // representing the original one, so just modify the operand of this cast
912 // instruction, which we know is newly created.
913 I->setOperand(0, NewVal);
914 I->setName(Name); // give I its name back
918 Res = new CastInst(NewVal, I->getType(), Name);
922 case Instruction::Add:
923 if (isa<PointerType>(NewTy)) {
924 Value *IndexVal = I->getOperand(OldVal == I->getOperand(0) ? 1 : 0);
925 std::vector<Value*> Indices;
926 BasicBlock::iterator It = I;
928 if (const Type *ETy = ConvertableToGEP(NewTy, IndexVal, Indices, &It)) {
929 // If successful, convert the add to a GEP
930 //const Type *RetTy = PointerType::get(ETy);
931 // First operand is actually the given pointer...
932 Res = new GetElementPtrInst(NewVal, Indices, Name);
933 assert(cast<PointerType>(Res->getType())->getElementType() == ETy &&
934 "ConvertableToGEP broken!");
940 case Instruction::Sub:
941 case Instruction::SetEQ:
942 case Instruction::SetNE: {
943 Res = BinaryOperator::create(cast<BinaryOperator>(I)->getOpcode(),
945 VMC.ExprMap[I] = Res; // Add node to expression eagerly
947 unsigned OtherIdx = (OldVal == I->getOperand(0)) ? 1 : 0;
948 Value *OtherOp = I->getOperand(OtherIdx);
949 Value *NewOther = ConvertExpressionToType(OtherOp, NewTy, VMC);
951 Res->setOperand(OtherIdx, NewOther);
952 Res->setOperand(!OtherIdx, NewVal);
955 case Instruction::Shl:
956 case Instruction::Shr:
957 assert(I->getOperand(0) == OldVal);
958 Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(), NewVal,
959 I->getOperand(1), Name);
962 case Instruction::Free: // Free can free any pointer type!
963 assert(I->getOperand(0) == OldVal);
964 Res = new FreeInst(NewVal);
968 case Instruction::Load: {
969 assert(I->getOperand(0) == OldVal && isa<PointerType>(NewVal->getType()));
970 const Type *LoadedTy =
971 cast<PointerType>(NewVal->getType())->getElementType();
975 if (const CompositeType *CT = dyn_cast<CompositeType>(LoadedTy)) {
976 std::vector<Value*> Indices;
977 Indices.push_back(ConstantUInt::get(Type::UIntTy, 0));
979 unsigned Offset = 0; // No offset, get first leaf.
980 LoadedTy = getStructOffsetType(CT, Offset, Indices, false);
981 assert(LoadedTy->isFirstClassType());
983 if (Indices.size() != 1) { // Do not generate load X, 0
984 Src = new GetElementPtrInst(Src, Indices, Name+".idx");
985 // Insert the GEP instruction before this load.
986 BIL.insert(I, cast<Instruction>(Src));
990 Res = new LoadInst(Src, Name);
991 assert(Res->getType()->isFirstClassType() && "Load of structure or array!");
995 case Instruction::Store: {
996 if (I->getOperand(0) == OldVal) { // Replace the source value
997 // Check to see if operand #1 has already been converted...
998 ValueMapCache::ExprMapTy::iterator VMCI =
999 VMC.ExprMap.find(I->getOperand(1));
1000 if (VMCI != VMC.ExprMap.end()) {
1001 // Comments describing this stuff are in the OperandConvertableToType
1002 // switch statement for Store...
1005 cast<PointerType>(VMCI->second->getType())->getElementType();
1007 Value *SrcPtr = VMCI->second;
1009 if (ElTy != NewTy) {
1010 // We check that this is a struct in the initial scan...
1011 const StructType *SElTy = cast<StructType>(ElTy);
1013 std::vector<Value*> Indices;
1014 Indices.push_back(ConstantUInt::get(Type::UIntTy, 0));
1016 unsigned Offset = 0;
1017 const Type *Ty = getStructOffsetType(ElTy, Offset, Indices, false);
1018 assert(Offset == 0 && "Offset changed!");
1019 assert(NewTy == Ty && "Did not convert to correct type!");
1021 SrcPtr = new GetElementPtrInst(SrcPtr, Indices,
1022 SrcPtr->getName()+".idx");
1023 // Insert the GEP instruction before this load.
1024 BIL.insert(I, cast<Instruction>(SrcPtr));
1026 Res = new StoreInst(NewVal, SrcPtr);
1028 VMC.ExprMap[I] = Res;
1030 // Otherwise, we haven't converted Operand #1 over yet...
1031 const PointerType *NewPT = PointerType::get(NewTy);
1032 Res = new StoreInst(NewVal, Constant::getNullValue(NewPT));
1033 VMC.ExprMap[I] = Res;
1034 Res->setOperand(1, ConvertExpressionToType(I->getOperand(1),
1037 } else { // Replace the source pointer
1038 const Type *ValTy = cast<PointerType>(NewTy)->getElementType();
1040 Value *SrcPtr = NewVal;
1042 if (isa<StructType>(ValTy)) {
1043 std::vector<Value*> Indices;
1044 Indices.push_back(ConstantUInt::get(Type::UIntTy, 0));
1046 unsigned Offset = 0;
1047 ValTy = getStructOffsetType(ValTy, Offset, Indices, false);
1049 assert(Offset == 0 && ValTy);
1051 SrcPtr = new GetElementPtrInst(SrcPtr, Indices,
1052 SrcPtr->getName()+".idx");
1053 // Insert the GEP instruction before this load.
1054 BIL.insert(I, cast<Instruction>(SrcPtr));
1057 Res = new StoreInst(Constant::getNullValue(ValTy), SrcPtr);
1058 VMC.ExprMap[I] = Res;
1059 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), ValTy, VMC));
1065 case Instruction::GetElementPtr: {
1066 // Convert a one index getelementptr into just about anything that is
1069 BasicBlock::iterator It = I;
1070 const Type *OldElTy = cast<PointerType>(I->getType())->getElementType();
1071 unsigned DataSize = TD.getTypeSize(OldElTy);
1072 Value *Index = I->getOperand(1);
1074 if (DataSize != 1) {
1075 // Insert a multiply of the old element type is not a unit size...
1076 Index = BinaryOperator::create(Instruction::Mul, Index,
1077 ConstantUInt::get(Type::UIntTy, DataSize));
1078 It = ++BIL.insert(It, cast<Instruction>(Index));
1081 // Perform the conversion now...
1083 std::vector<Value*> Indices;
1084 const Type *ElTy = ConvertableToGEP(NewVal->getType(), Index, Indices, &It);
1085 assert(ElTy != 0 && "GEP Conversion Failure!");
1086 Res = new GetElementPtrInst(NewVal, Indices, Name);
1087 assert(Res->getType() == PointerType::get(ElTy) &&
1088 "ConvertableToGet failed!");
1091 if (I->getType() == PointerType::get(Type::SByteTy)) {
1092 // Convert a getelementptr sbyte * %reg111, uint 16 freely back to
1093 // anything that is a pointer type...
1095 BasicBlock::iterator It = I;
1097 // Check to see if the second argument is an expression that can
1098 // be converted to the appropriate size... if so, allow it.
1100 std::vector<Value*> Indices;
1101 const Type *ElTy = ConvertableToGEP(NewVal->getType(), I->getOperand(1),
1103 assert(ElTy != 0 && "GEP Conversion Failure!");
1105 Res = new GetElementPtrInst(NewVal, Indices, Name);
1107 // Convert a getelementptr ulong * %reg123, uint %N
1108 // to getelementptr long * %reg123, uint %N
1109 // ... where the type must simply stay the same size...
1111 Res = new GetElementPtrInst(NewVal,
1112 cast<GetElementPtrInst>(I)->copyIndices(),
1118 case Instruction::PHINode: {
1119 PHINode *OldPN = cast<PHINode>(I);
1120 PHINode *NewPN = new PHINode(NewTy, Name);
1121 VMC.ExprMap[I] = NewPN;
1123 while (OldPN->getNumOperands()) {
1124 BasicBlock *BB = OldPN->getIncomingBlock(0);
1125 Value *OldVal = OldPN->getIncomingValue(0);
1126 OldPN->removeIncomingValue(BB);
1127 Value *V = ConvertExpressionToType(OldVal, NewTy, VMC);
1128 NewPN->addIncoming(V, BB);
1134 case Instruction::Call: {
1135 Value *Meth = I->getOperand(0);
1136 std::vector<Value*> Params(I->op_begin()+1, I->op_end());
1138 if (Meth == OldVal) { // Changing the function pointer?
1139 const PointerType *NewPTy = cast<PointerType>(NewVal->getType());
1140 const FunctionType *NewTy = cast<FunctionType>(NewPTy->getElementType());
1141 const FunctionType::ParamTypes &PTs = NewTy->getParamTypes();
1143 // Get an iterator to the call instruction so that we can insert casts for
1144 // operands if needbe. Note that we do not require operands to be
1145 // convertable, we can insert casts if they are convertible but not
1146 // compatible. The reason for this is that we prefer to have resolved
1147 // functions but casted arguments if possible.
1149 BasicBlock::iterator It = I;
1151 // Convert over all of the call operands to their new types... but only
1152 // convert over the part that is not in the vararg section of the call.
1154 for (unsigned i = 0; i < PTs.size(); ++i)
1155 if (Params[i]->getType() != PTs[i]) {
1156 // Create a cast to convert it to the right type, we know that this
1157 // is a lossless cast...
1159 Params[i] = new CastInst(Params[i], PTs[i], "call.resolve.cast");
1160 It = ++BIL.insert(It, cast<Instruction>(Params[i]));
1162 Meth = NewVal; // Update call destination to new value
1164 } else { // Changing an argument, must be in vararg area
1165 std::vector<Value*>::iterator OI =
1166 find(Params.begin(), Params.end(), OldVal);
1167 assert (OI != Params.end() && "Not using value!");
1172 Res = new CallInst(Meth, Params, Name);
1176 assert(0 && "Expression convertable, but don't know how to convert?");
1180 // If the instruction was newly created, insert it into the instruction
1183 BasicBlock::iterator It = I;
1184 assert(It != BIL.end() && "Instruction not in own basic block??");
1185 BIL.insert(It, Res); // Keep It pointing to old instruction
1187 DEBUG(cerr << "COT CREATED: " << (void*)Res << " " << Res
1188 << "In: " << (void*)I << " " << I << "Out: " << (void*)Res
1191 // Add the instruction to the expression map
1192 VMC.ExprMap[I] = Res;
1194 if (I->getType() != Res->getType())
1195 ConvertValueToNewType(I, Res, VMC);
1197 for (unsigned It = 0; It < I->use_size(); ) {
1198 User *Use = *(I->use_begin()+It);
1199 if (isa<ValueHandle>(Use)) // Don't remove ValueHandles!
1202 Use->replaceUsesOfWith(I, Res);
1205 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
1207 assert(isa<ValueHandle>((Value*)*UI) &&"Uses of Instruction remain!!!");
1212 ValueHandle::ValueHandle(ValueMapCache &VMC, Value *V)
1213 : Instruction(Type::VoidTy, UserOp1, ""), Cache(VMC) {
1214 //DEBUG(cerr << "VH AQUIRING: " << (void*)V << " " << V);
1215 Operands.push_back(Use(V, this));
1218 ValueHandle::ValueHandle(const ValueHandle &VH)
1219 : Instruction(Type::VoidTy, UserOp1, ""), Cache(VH.Cache) {
1220 //DEBUG(cerr << "VH AQUIRING: " << (void*)V << " " << V);
1221 Operands.push_back(Use((Value*)VH.getOperand(0), this));
1224 static void RecursiveDelete(ValueMapCache &Cache, Instruction *I) {
1225 if (!I || !I->use_empty()) return;
1227 assert(I->getParent() && "Inst not in basic block!");
1229 //DEBUG(cerr << "VH DELETING: " << (void*)I << " " << I);
1231 for (User::op_iterator OI = I->op_begin(), OE = I->op_end();
1233 if (Instruction *U = dyn_cast<Instruction>(OI->get())) {
1235 RecursiveDelete(Cache, U);
1238 I->getParent()->getInstList().remove(I);
1240 Cache.OperandsMapped.erase(I);
1241 Cache.ExprMap.erase(I);
1245 ValueHandle::~ValueHandle() {
1246 if (Operands[0]->use_size() == 1) {
1247 Value *V = Operands[0];
1248 Operands[0] = 0; // Drop use!
1250 // Now we just need to remove the old instruction so we don't get infinite
1251 // loops. Note that we cannot use DCE because DCE won't remove a store
1252 // instruction, for example.
1254 RecursiveDelete(Cache, dyn_cast<Instruction>(V));
1256 //DEBUG(cerr << "VH RELEASING: " << (void*)Operands[0].get() << " "
1257 // << Operands[0]->use_size() << " " << Operands[0]);