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/Transforms/Scalar/DCE.h"
15 #include "llvm/Analysis/Expressions.h"
16 #include "Support/STLExtras.h"
21 //#define DEBUG_EXPR_CONVERT 1
23 static bool OperandConvertableToType(User *U, Value *V, const Type *Ty,
24 ValueTypeCache &ConvertedTypes);
26 static void ConvertOperandToType(User *U, Value *OldVal, Value *NewVal,
29 // AllIndicesZero - Return true if all of the indices of the specified memory
30 // access instruction are zero, indicating an effectively nil offset to the
33 static bool AllIndicesZero(const MemAccessInst *MAI) {
34 for (User::const_op_iterator S = MAI->idx_begin(), E = MAI->idx_end();
36 if (!isa<Constant>(*S) || !cast<Constant>(*S)->isNullValue())
42 // Peephole Malloc instructions: we take a look at the use chain of the
43 // malloc instruction, and try to find out if the following conditions hold:
44 // 1. The malloc is of the form: 'malloc [sbyte], uint <constant>'
45 // 2. The only users of the malloc are cast & add instructions
46 // 3. Of the cast instructions, there is only one destination pointer type
47 // [RTy] where the size of the pointed to object is equal to the number
48 // of bytes allocated.
50 // If these conditions hold, we convert the malloc to allocate an [RTy]
51 // element. TODO: This comment is out of date WRT arrays
53 static bool MallocConvertableToType(MallocInst *MI, const Type *Ty,
54 ValueTypeCache &CTMap) {
55 if (!isa<PointerType>(Ty)) return false; // Malloc always returns pointers
57 // Deal with the type to allocate, not the pointer type...
58 Ty = cast<PointerType>(Ty)->getElementType();
59 if (!Ty->isSized()) return false; // Can only alloc something with a size
61 // Analyze the number of bytes allocated...
62 analysis::ExprType Expr = analysis::ClassifyExpression(MI->getArraySize());
64 // Get information about the base datatype being allocated, before & after
65 unsigned ReqTypeSize = TD.getTypeSize(Ty);
66 unsigned OldTypeSize = TD.getTypeSize(MI->getType()->getElementType());
68 // Must have a scale or offset to analyze it...
69 if (!Expr.Offset && !Expr.Scale && OldTypeSize == 1) return false;
71 // Get the offset and scale of the allocation...
72 int OffsetVal = Expr.Offset ? getConstantValue(Expr.Offset) : 0;
73 int ScaleVal = Expr.Scale ? getConstantValue(Expr.Scale) : (Expr.Var ? 1 : 0);
74 if (ScaleVal < 0 || OffsetVal < 0) {
75 cerr << "malloc of a negative number???\n";
79 // The old type might not be of unit size, take old size into consideration
81 unsigned Offset = (unsigned)OffsetVal * OldTypeSize;
82 unsigned Scale = (unsigned)ScaleVal * OldTypeSize;
84 // In order to be successful, both the scale and the offset must be a multiple
85 // of the requested data type's size.
87 if (Offset/ReqTypeSize*ReqTypeSize != Offset ||
88 Scale/ReqTypeSize*ReqTypeSize != Scale)
89 return false; // Nope.
94 static Instruction *ConvertMallocToType(MallocInst *MI, const Type *Ty,
95 const std::string &Name,
97 BasicBlock *BB = MI->getParent();
98 BasicBlock::iterator It = BB->end();
100 // Analyze the number of bytes allocated...
101 analysis::ExprType Expr = analysis::ClassifyExpression(MI->getArraySize());
103 const PointerType *AllocTy = cast<PointerType>(Ty);
104 const Type *ElType = AllocTy->getElementType();
106 unsigned DataSize = TD.getTypeSize(ElType);
107 unsigned OldTypeSize = TD.getTypeSize(MI->getType()->getElementType());
109 // Get the offset and scale coefficients that we are allocating...
110 int OffsetVal = (Expr.Offset ? getConstantValue(Expr.Offset) : 0);
111 int ScaleVal = Expr.Scale ? getConstantValue(Expr.Scale) : (Expr.Var ? 1 : 0);
113 // The old type might not be of unit size, take old size into consideration
115 unsigned Offset = (unsigned)OffsetVal * OldTypeSize / DataSize;
116 unsigned Scale = (unsigned)ScaleVal * OldTypeSize / DataSize;
118 // Locate the malloc instruction, because we may be inserting instructions
119 It = find(BB->getInstList().begin(), BB->getInstList().end(), MI);
121 // If we have a scale, apply it first...
123 // Expr.Var is not neccesarily unsigned right now, insert a cast now.
124 if (Expr.Var->getType() != Type::UIntTy) {
125 Instruction *CI = new CastInst(Expr.Var, Type::UIntTy);
126 if (Expr.Var->hasName()) CI->setName(Expr.Var->getName()+"-uint");
127 It = BB->getInstList().insert(It, CI)+1;
133 BinaryOperator::create(Instruction::Mul, Expr.Var,
134 ConstantUInt::get(Type::UIntTy, Scale));
135 if (Expr.Var->hasName()) ScI->setName(Expr.Var->getName()+"-scl");
136 It = BB->getInstList().insert(It, ScI)+1;
141 // If we are not scaling anything, just make the offset be the "var"...
142 Expr.Var = ConstantUInt::get(Type::UIntTy, Offset);
143 Offset = 0; Scale = 1;
146 // If we have an offset now, add it in...
148 assert(Expr.Var && "Var must be nonnull by now!");
151 BinaryOperator::create(Instruction::Add, Expr.Var,
152 ConstantUInt::get(Type::UIntTy, Offset));
153 if (Expr.Var->hasName()) AddI->setName(Expr.Var->getName()+"-off");
154 It = BB->getInstList().insert(It, AddI)+1;
158 Instruction *NewI = new MallocInst(AllocTy, Expr.Var, Name);
160 assert(AllocTy == Ty);
165 // ExpressionConvertableToType - Return true if it is possible
166 bool ExpressionConvertableToType(Value *V, const Type *Ty,
167 ValueTypeCache &CTMap) {
168 if (V->getType() == Ty) return true; // Expression already correct type!
170 // Expression type must be holdable in a register.
171 if (!Ty->isFirstClassType())
174 ValueTypeCache::iterator CTMI = CTMap.find(V);
175 if (CTMI != CTMap.end()) return CTMI->second == Ty;
179 Instruction *I = dyn_cast<Instruction>(V);
181 // It's not an instruction, check to see if it's a constant... all constants
182 // can be converted to an equivalent value (except pointers, they can't be
183 // const prop'd in general). We just ask the constant propogator to see if
184 // it can convert the value...
186 if (Constant *CPV = dyn_cast<Constant>(V))
187 if (ConstantFoldCastInstruction(CPV, Ty))
188 return true; // Don't worry about deallocating, it's a constant.
190 return false; // Otherwise, we can't convert!
193 switch (I->getOpcode()) {
194 case Instruction::Cast:
195 // We can convert the expr if the cast destination type is losslessly
196 // convertable to the requested type.
197 if (!Ty->isLosslesslyConvertableTo(I->getType())) return false;
199 // We also do not allow conversion of a cast that casts from a ptr to array
200 // of X to a *X. For example: cast [4 x %List *] * %val to %List * *
202 if (PointerType *SPT = dyn_cast<PointerType>(I->getOperand(0)->getType()))
203 if (PointerType *DPT = dyn_cast<PointerType>(I->getType()))
204 if (ArrayType *AT = dyn_cast<ArrayType>(SPT->getElementType()))
205 if (AT->getElementType() == DPT->getElementType())
210 case Instruction::Add:
211 case Instruction::Sub:
212 if (!ExpressionConvertableToType(I->getOperand(0), Ty, CTMap) ||
213 !ExpressionConvertableToType(I->getOperand(1), Ty, CTMap))
216 case Instruction::Shr:
217 if (Ty->isSigned() != V->getType()->isSigned()) return false;
219 case Instruction::Shl:
220 if (!ExpressionConvertableToType(I->getOperand(0), Ty, CTMap))
224 case Instruction::Load: {
225 LoadInst *LI = cast<LoadInst>(I);
226 if (LI->hasIndices() && !AllIndicesZero(LI)) {
227 // We can't convert a load expression if it has indices... unless they are
232 if (!ExpressionConvertableToType(LI->getPointerOperand(),
233 PointerType::get(Ty), CTMap))
237 case Instruction::PHINode: {
238 PHINode *PN = cast<PHINode>(I);
239 for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i)
240 if (!ExpressionConvertableToType(PN->getIncomingValue(i), Ty, CTMap))
245 case Instruction::Malloc:
246 if (!MallocConvertableToType(cast<MallocInst>(I), Ty, CTMap))
251 case Instruction::GetElementPtr: {
252 // GetElementPtr's are directly convertable to a pointer type if they have
253 // a number of zeros at the end. Because removing these values does not
254 // change the logical offset of the GEP, it is okay and fair to remove them.
255 // This can change this:
256 // %t1 = getelementptr %Hosp * %hosp, ubyte 4, ubyte 0 ; <%List **>
257 // %t2 = cast %List * * %t1 to %List *
259 // %t2 = getelementptr %Hosp * %hosp, ubyte 4 ; <%List *>
261 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
262 const PointerType *PTy = dyn_cast<PointerType>(Ty);
263 if (!PTy) return false; // GEP must always return a pointer...
264 const Type *PVTy = PTy->getElementType();
266 // Check to see if there are zero elements that we can remove from the
267 // index array. If there are, check to see if removing them causes us to
268 // get to the right type...
270 std::vector<Value*> Indices = GEP->copyIndices();
271 const Type *BaseType = GEP->getPointerOperand()->getType();
272 const Type *ElTy = 0;
274 while (!Indices.empty() && isa<ConstantUInt>(Indices.back()) &&
275 cast<ConstantUInt>(Indices.back())->getValue() == 0) {
277 ElTy = GetElementPtrInst::getIndexedType(BaseType, Indices, true);
279 break; // Found a match!!
283 if (ElTy) break; // Found a number of zeros we can strip off!
285 // Otherwise, we can convert a GEP from one form to the other iff the
286 // current gep is of the form 'getelementptr sbyte*, unsigned N
287 // and we could convert this to an appropriate GEP for the new type.
289 if (GEP->getNumOperands() == 2 &&
290 GEP->getOperand(1)->getType() == Type::UIntTy &&
291 GEP->getType() == PointerType::get(Type::SByteTy)) {
293 // Do not Check to see if our incoming pointer can be converted
294 // to be a ptr to an array of the right type... because in more cases than
295 // not, it is simply not analyzable because of pointer/array
296 // discrepencies. To fix this, we will insert a cast before the GEP.
299 // Check to see if 'N' is an expression that can be converted to
300 // the appropriate size... if so, allow it.
302 std::vector<Value*> Indices;
303 const Type *ElTy = ConvertableToGEP(PTy, I->getOperand(1), Indices);
305 if (!ExpressionConvertableToType(I->getOperand(0),
306 PointerType::get(ElTy), CTMap))
307 return false; // Can't continue, ExConToTy might have polluted set!
312 // Otherwise, it could be that we have something like this:
313 // getelementptr [[sbyte] *] * %reg115, uint %reg138 ; [sbyte]**
314 // and want to convert it into something like this:
315 // getelemenptr [[int] *] * %reg115, uint %reg138 ; [int]**
317 if (GEP->getNumOperands() == 2 &&
318 GEP->getOperand(1)->getType() == Type::UIntTy &&
319 TD.getTypeSize(PTy->getElementType()) ==
320 TD.getTypeSize(GEP->getType()->getElementType())) {
321 const PointerType *NewSrcTy = PointerType::get(PVTy);
322 if (!ExpressionConvertableToType(I->getOperand(0), NewSrcTy, CTMap))
327 return false; // No match, maybe next time.
335 // Expressions are only convertable if all of the users of the expression can
336 // have this value converted. This makes use of the map to avoid infinite
339 for (Value::use_iterator It = I->use_begin(), E = I->use_end(); It != E; ++It)
340 if (!OperandConvertableToType(*It, I, Ty, CTMap))
347 Value *ConvertExpressionToType(Value *V, const Type *Ty, ValueMapCache &VMC) {
348 if (V->getType() == Ty) return V; // Already where we need to be?
350 ValueMapCache::ExprMapTy::iterator VMCI = VMC.ExprMap.find(V);
351 if (VMCI != VMC.ExprMap.end()) {
352 assert(VMCI->second->getType() == Ty);
354 if (Instruction *I = dyn_cast<Instruction>(V))
355 ValueHandle IHandle(VMC, I); // Remove I if it is unused now!
360 #ifdef DEBUG_EXPR_CONVERT
361 cerr << "CETT: " << (void*)V << " " << V;
364 Instruction *I = dyn_cast<Instruction>(V);
366 if (Constant *CPV = cast<Constant>(V)) {
367 // Constants are converted by constant folding the cast that is required.
368 // We assume here that all casts are implemented for constant prop.
369 Value *Result = ConstantFoldCastInstruction(CPV, Ty);
370 assert(Result && "ConstantFoldCastInstruction Failed!!!");
371 assert(Result->getType() == Ty && "Const prop of cast failed!");
373 // Add the instruction to the expression map
374 VMC.ExprMap[V] = Result;
379 BasicBlock *BB = I->getParent();
380 BasicBlock::InstListType &BIL = BB->getInstList();
381 std::string Name = I->getName(); if (!Name.empty()) I->setName("");
382 Instruction *Res; // Result of conversion
384 ValueHandle IHandle(VMC, I); // Prevent I from being removed!
386 Constant *Dummy = Constant::getNullValue(Ty);
388 switch (I->getOpcode()) {
389 case Instruction::Cast:
390 Res = new CastInst(I->getOperand(0), Ty, Name);
393 case Instruction::Add:
394 case Instruction::Sub:
395 Res = BinaryOperator::create(cast<BinaryOperator>(I)->getOpcode(),
397 VMC.ExprMap[I] = Res; // Add node to expression eagerly
399 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), Ty, VMC));
400 Res->setOperand(1, ConvertExpressionToType(I->getOperand(1), Ty, VMC));
403 case Instruction::Shl:
404 case Instruction::Shr:
405 Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(), Dummy,
406 I->getOperand(1), Name);
407 VMC.ExprMap[I] = Res;
408 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), Ty, VMC));
411 case Instruction::Load: {
412 LoadInst *LI = cast<LoadInst>(I);
413 assert(!LI->hasIndices() || AllIndicesZero(LI));
415 Res = new LoadInst(Constant::getNullValue(PointerType::get(Ty)), Name);
416 VMC.ExprMap[I] = Res;
417 Res->setOperand(0, ConvertExpressionToType(LI->getPointerOperand(),
418 PointerType::get(Ty), VMC));
419 assert(Res->getOperand(0)->getType() == PointerType::get(Ty));
420 assert(Ty == Res->getType());
421 assert(Res->getType()->isFirstClassType() && "Load of structure or array!");
425 case Instruction::PHINode: {
426 PHINode *OldPN = cast<PHINode>(I);
427 PHINode *NewPN = new PHINode(Ty, Name);
429 VMC.ExprMap[I] = NewPN; // Add node to expression eagerly
430 while (OldPN->getNumOperands()) {
431 BasicBlock *BB = OldPN->getIncomingBlock(0);
432 Value *OldVal = OldPN->getIncomingValue(0);
433 ValueHandle OldValHandle(VMC, OldVal);
434 OldPN->removeIncomingValue(BB);
435 Value *V = ConvertExpressionToType(OldVal, Ty, VMC);
436 NewPN->addIncoming(V, BB);
442 case Instruction::Malloc: {
443 Res = ConvertMallocToType(cast<MallocInst>(I), Ty, Name, VMC);
447 case Instruction::GetElementPtr: {
448 // GetElementPtr's are directly convertable to a pointer type if they have
449 // a number of zeros at the end. Because removing these values does not
450 // change the logical offset of the GEP, it is okay and fair to remove them.
451 // This can change this:
452 // %t1 = getelementptr %Hosp * %hosp, ubyte 4, ubyte 0 ; <%List **>
453 // %t2 = cast %List * * %t1 to %List *
455 // %t2 = getelementptr %Hosp * %hosp, ubyte 4 ; <%List *>
457 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
459 // Check to see if there are zero elements that we can remove from the
460 // index array. If there are, check to see if removing them causes us to
461 // get to the right type...
463 std::vector<Value*> Indices = GEP->copyIndices();
464 const Type *BaseType = GEP->getPointerOperand()->getType();
465 const Type *PVTy = cast<PointerType>(Ty)->getElementType();
467 while (!Indices.empty() && isa<ConstantUInt>(Indices.back()) &&
468 cast<ConstantUInt>(Indices.back())->getValue() == 0) {
470 if (GetElementPtrInst::getIndexedType(BaseType, Indices, true) == PVTy) {
471 if (Indices.size() == 0) {
472 Res = new CastInst(GEP->getPointerOperand(), BaseType); // NOOP
474 Res = new GetElementPtrInst(GEP->getPointerOperand(), Indices, Name);
480 if (Res == 0 && GEP->getNumOperands() == 2 &&
481 GEP->getOperand(1)->getType() == Type::UIntTy &&
482 GEP->getType() == PointerType::get(Type::SByteTy)) {
484 // Otherwise, we can convert a GEP from one form to the other iff the
485 // current gep is of the form 'getelementptr [sbyte]*, unsigned N
486 // and we could convert this to an appropriate GEP for the new type.
488 const PointerType *NewSrcTy = PointerType::get(PVTy);
489 BasicBlock::iterator It = find(BIL.begin(), BIL.end(), I);
491 // Check to see if 'N' is an expression that can be converted to
492 // the appropriate size... if so, allow it.
494 std::vector<Value*> Indices;
495 const Type *ElTy = ConvertableToGEP(NewSrcTy, I->getOperand(1),
498 assert(ElTy == PVTy && "Internal error, setup wrong!");
499 Res = new GetElementPtrInst(Constant::getNullValue(NewSrcTy),
501 VMC.ExprMap[I] = Res;
502 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
507 // Otherwise, it could be that we have something like this:
508 // getelementptr [[sbyte] *] * %reg115, uint %reg138 ; [sbyte]**
509 // and want to convert it into something like this:
510 // getelemenptr [[int] *] * %reg115, uint %reg138 ; [int]**
513 const PointerType *NewSrcTy = PointerType::get(PVTy);
514 Res = new GetElementPtrInst(Constant::getNullValue(NewSrcTy),
515 GEP->copyIndices(), Name);
516 VMC.ExprMap[I] = Res;
517 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
522 assert(Res && "Didn't find match!");
523 break; // No match, maybe next time.
527 assert(0 && "Expression convertable, but don't know how to convert?");
531 assert(Res->getType() == Ty && "Didn't convert expr to correct type!");
533 BasicBlock::iterator It = find(BIL.begin(), BIL.end(), I);
534 assert(It != BIL.end() && "Instruction not in own basic block??");
537 // Add the instruction to the expression map
538 VMC.ExprMap[I] = Res;
540 // Expressions are only convertable if all of the users of the expression can
541 // have this value converted. This makes use of the map to avoid infinite
544 unsigned NumUses = I->use_size();
545 for (unsigned It = 0; It < NumUses; ) {
546 unsigned OldSize = NumUses;
547 ConvertOperandToType(*(I->use_begin()+It), I, Res, VMC);
548 NumUses = I->use_size();
549 if (NumUses == OldSize) ++It;
552 #ifdef DEBUG_EXPR_CONVERT
553 cerr << "ExpIn: " << (void*)I << " " << I
554 << "ExpOut: " << (void*)Res << " " << Res;
557 if (I->use_empty()) {
558 #ifdef DEBUG_EXPR_CONVERT
559 cerr << "EXPR DELETING: " << (void*)I << " " << I;
562 VMC.OperandsMapped.erase(I);
563 VMC.ExprMap.erase(I);
572 // ValueConvertableToType - Return true if it is possible
573 bool ValueConvertableToType(Value *V, const Type *Ty,
574 ValueTypeCache &ConvertedTypes) {
575 ValueTypeCache::iterator I = ConvertedTypes.find(V);
576 if (I != ConvertedTypes.end()) return I->second == Ty;
577 ConvertedTypes[V] = Ty;
579 // It is safe to convert the specified value to the specified type IFF all of
580 // the uses of the value can be converted to accept the new typed value.
582 if (V->getType() != Ty) {
583 for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I)
584 if (!OperandConvertableToType(*I, V, Ty, ConvertedTypes))
595 // OperandConvertableToType - Return true if it is possible to convert operand
596 // V of User (instruction) U to the specified type. This is true iff it is
597 // possible to change the specified instruction to accept this. CTMap is a map
598 // of converted types, so that circular definitions will see the future type of
599 // the expression, not the static current type.
601 static bool OperandConvertableToType(User *U, Value *V, const Type *Ty,
602 ValueTypeCache &CTMap) {
603 // if (V->getType() == Ty) return true; // Operand already the right type?
605 // Expression type must be holdable in a register.
606 if (!Ty->isFirstClassType())
609 Instruction *I = dyn_cast<Instruction>(U);
610 if (I == 0) return false; // We can't convert!
612 switch (I->getOpcode()) {
613 case Instruction::Cast:
614 assert(I->getOperand(0) == V);
615 // We can convert the expr if the cast destination type is losslessly
616 // convertable to the requested type.
617 // Also, do not change a cast that is a noop cast. For all intents and
618 // purposes it should be eliminated.
619 if (!Ty->isLosslesslyConvertableTo(I->getOperand(0)->getType()) ||
620 I->getType() == I->getOperand(0)->getType())
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 (PointerType *SPT = dyn_cast<PointerType>(I->getOperand(0)->getType()))
629 if (PointerType *DPT = dyn_cast<PointerType>(I->getType()))
630 if (ArrayType *AT = dyn_cast<ArrayType>(SPT->getElementType()))
631 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 = ConvertableToGEP(Ty, IndexVal, Indices)) {
641 const Type *RetTy = PointerType::get(ETy);
643 // Only successful if we can convert this type to the required type
644 if (ValueConvertableToType(I, RetTy, CTMap)) {
648 // We have to return failure here because ValueConvertableToType could
649 // have polluted our map
654 case Instruction::Sub: {
655 Value *OtherOp = I->getOperand((V == I->getOperand(0)) ? 1 : 0);
656 return ValueConvertableToType(I, Ty, CTMap) &&
657 ExpressionConvertableToType(OtherOp, Ty, CTMap);
659 case Instruction::SetEQ:
660 case Instruction::SetNE: {
661 Value *OtherOp = I->getOperand((V == I->getOperand(0)) ? 1 : 0);
662 return ExpressionConvertableToType(OtherOp, Ty, CTMap);
664 case Instruction::Shr:
665 if (Ty->isSigned() != V->getType()->isSigned()) return false;
667 case Instruction::Shl:
668 assert(I->getOperand(0) == V);
669 return ValueConvertableToType(I, Ty, CTMap);
671 case Instruction::Free:
672 assert(I->getOperand(0) == V);
673 return isa<PointerType>(Ty); // Free can free any pointer type!
675 case Instruction::Load:
676 // Cannot convert the types of any subscripts...
677 if (I->getOperand(0) != V) return false;
679 if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
680 LoadInst *LI = cast<LoadInst>(I);
682 if (LI->hasIndices() && !AllIndicesZero(LI))
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, false);
692 assert(Offset == 0 && "Offset changed from zero???");
695 if (!LoadedTy->isFirstClassType())
698 if (TD.getTypeSize(LoadedTy) != TD.getTypeSize(LI->getType()))
701 return ValueConvertableToType(LI, LoadedTy, CTMap);
705 case Instruction::Store: {
706 StoreInst *SI = cast<StoreInst>(I);
707 if (SI->hasIndices()) return false;
709 if (V == I->getOperand(0)) {
710 ValueTypeCache::iterator CTMI = CTMap.find(I->getOperand(1));
711 if (CTMI != CTMap.end()) { // Operand #1 is in the table already?
712 // If so, check to see if it's Ty*, or, more importantly, if it is a
713 // pointer to a structure where the first element is a Ty... this code
714 // is neccesary because we might be trying to change the source and
715 // destination type of the store (they might be related) and the dest
716 // pointer type might be a pointer to structure. Below we allow pointer
717 // to structures where the 0th element is compatible with the value,
718 // now we have to support the symmetrical part of this.
720 const Type *ElTy = cast<PointerType>(CTMI->second)->getElementType();
722 // Already a pointer to what we want? Trivially accept...
723 if (ElTy == Ty) return true;
725 // Tricky case now, if the destination is a pointer to structure,
726 // obviously the source is not allowed to be a structure (cannot copy
727 // a whole structure at a time), so the level raiser must be trying to
728 // store into the first field. Check for this and allow it now:
730 if (StructType *SElTy = dyn_cast<StructType>(ElTy)) {
732 std::vector<Value*> Indices;
733 ElTy = getStructOffsetType(ElTy, Offset, Indices, false);
734 assert(Offset == 0 && "Offset changed!");
735 if (ElTy == 0) // Element at offset zero in struct doesn't exist!
736 return false; // Can only happen for {}*
738 if (ElTy == Ty) // Looks like the 0th element of structure is
739 return true; // compatible! Accept now!
741 // Otherwise we know that we can't work, so just stop trying now.
746 // Can convert the store if we can convert the pointer operand to match
747 // the new value type...
748 return ExpressionConvertableToType(I->getOperand(1), PointerType::get(Ty),
750 } else if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
751 const Type *ElTy = PT->getElementType();
752 assert(V == I->getOperand(1));
754 if (isa<StructType>(ElTy)) {
755 // We can change the destination pointer if we can store our first
756 // argument into the first element of the structure...
759 std::vector<Value*> Indices;
760 ElTy = getStructOffsetType(ElTy, Offset, Indices, false);
761 assert(Offset == 0 && "Offset changed!");
762 if (ElTy == 0) // Element at offset zero in struct doesn't exist!
763 return false; // Can only happen for {}*
766 // Must move the same amount of data...
767 if (TD.getTypeSize(ElTy) != TD.getTypeSize(I->getOperand(0)->getType()))
770 // Can convert store if the incoming value is convertable...
771 return ExpressionConvertableToType(I->getOperand(0), ElTy, CTMap);
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 ConvertableToGEP 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 ConstantUInt::get(Type::UIntTy,
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 = ConvertableToGEP(Ty, Index, Indices);
806 delete TempScale; // Free our temporary multiply if we made it
808 if (ElTy == 0) return false; // Cannot make conversion...
809 return ValueConvertableToType(I, PointerType::get(ElTy), CTMap);
813 case Instruction::PHINode: {
814 PHINode *PN = cast<PHINode>(I);
815 for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i)
816 if (!ExpressionConvertableToType(PN->getIncomingValue(i), Ty, CTMap))
818 return ValueConvertableToType(PN, Ty, CTMap);
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 PointerType *PTy = dyn_cast<PointerType>(Ty);
829 if (PTy == 0) return false; // Can't convert to a non-pointer type...
830 FunctionType *MTy = dyn_cast<FunctionType>(PTy->getElementType());
831 if (MTy == 0) return false; // Can't convert to a non ptr to function...
833 // Perform sanity checks to make sure that new function type has the
834 // correct number of arguments...
836 unsigned NumArgs = I->getNumOperands()-1; // Don't include function ptr
838 // Cannot convert to a type that requires more fixed arguments than
839 // the call provides...
841 if (NumArgs < MTy->getParamTypes().size()) return false;
843 // Unless this is a vararg function type, we cannot provide more arguments
844 // than are desired...
846 if (!MTy->isVarArg() && NumArgs > MTy->getParamTypes().size())
849 // Okay, at this point, we know that the call and the function type match
850 // number of arguments. Now we see if we can convert the arguments
851 // themselves. Note that we do not require operands to be convertable,
852 // we can insert casts if they are convertible but not compatible. The
853 // reason for this is that we prefer to have resolved functions but casted
854 // arguments if possible.
856 const FunctionType::ParamTypes &PTs = MTy->getParamTypes();
857 for (unsigned i = 0, NA = PTs.size(); i < NA; ++i)
858 if (!PTs[i]->isLosslesslyConvertableTo(I->getOperand(i+1)->getType()))
859 return false; // Operands must have compatible types!
861 // Okay, at this point, we know that all of the arguments can be
862 // converted. We succeed if we can change the return type if
865 return ValueConvertableToType(I, MTy->getReturnType(), CTMap);
868 const PointerType *MPtr = cast<PointerType>(I->getOperand(0)->getType());
869 const FunctionType *MTy = cast<FunctionType>(MPtr->getElementType());
870 if (!MTy->isVarArg()) return false;
872 if ((OpNum-1) < MTy->getParamTypes().size())
873 return false; // It's not in the varargs section...
875 // If we get this far, we know the value is in the varargs section of the
876 // function! We can convert if we don't reinterpret the value...
878 return Ty->isLosslesslyConvertableTo(V->getType());
885 void ConvertValueToNewType(Value *V, Value *NewVal, ValueMapCache &VMC) {
886 ValueHandle VH(VMC, V);
888 unsigned NumUses = V->use_size();
889 for (unsigned It = 0; It < NumUses; ) {
890 unsigned OldSize = NumUses;
891 ConvertOperandToType(*(V->use_begin()+It), V, NewVal, VMC);
892 NumUses = V->use_size();
893 if (NumUses == OldSize) ++It;
899 static void ConvertOperandToType(User *U, Value *OldVal, Value *NewVal,
900 ValueMapCache &VMC) {
901 if (isa<ValueHandle>(U)) return; // Valuehandles don't let go of operands...
903 if (VMC.OperandsMapped.count(U)) return;
904 VMC.OperandsMapped.insert(U);
906 ValueMapCache::ExprMapTy::iterator VMCI = VMC.ExprMap.find(U);
907 if (VMCI != VMC.ExprMap.end())
911 Instruction *I = cast<Instruction>(U); // Only Instructions convertable
913 BasicBlock *BB = I->getParent();
914 BasicBlock::InstListType &BIL = BB->getInstList();
915 std::string Name = I->getName(); if (!Name.empty()) I->setName("");
916 Instruction *Res; // Result of conversion
918 //cerr << endl << endl << "Type:\t" << Ty << "\nInst: " << I << "BB Before: " << BB << endl;
920 // Prevent I from being removed...
921 ValueHandle IHandle(VMC, I);
923 const Type *NewTy = NewVal->getType();
924 Constant *Dummy = (NewTy != Type::VoidTy) ?
925 Constant::getNullValue(NewTy) : 0;
927 switch (I->getOpcode()) {
928 case Instruction::Cast:
929 assert(I->getOperand(0) == OldVal);
930 Res = new CastInst(NewVal, I->getType(), Name);
933 case Instruction::Add:
934 if (isa<PointerType>(NewTy)) {
935 Value *IndexVal = I->getOperand(OldVal == I->getOperand(0) ? 1 : 0);
936 std::vector<Value*> Indices;
937 BasicBlock::iterator It = find(BIL.begin(), BIL.end(), I);
939 if (const Type *ETy = ConvertableToGEP(NewTy, IndexVal, Indices, &It)) {
940 // If successful, convert the add to a GEP
941 //const Type *RetTy = PointerType::get(ETy);
942 // First operand is actually the given pointer...
943 Res = new GetElementPtrInst(NewVal, Indices, Name);
944 assert(cast<PointerType>(Res->getType())->getElementType() == ETy &&
945 "ConvertableToGEP broken!");
951 case Instruction::Sub:
952 case Instruction::SetEQ:
953 case Instruction::SetNE: {
954 Res = BinaryOperator::create(cast<BinaryOperator>(I)->getOpcode(),
956 VMC.ExprMap[I] = Res; // Add node to expression eagerly
958 unsigned OtherIdx = (OldVal == I->getOperand(0)) ? 1 : 0;
959 Value *OtherOp = I->getOperand(OtherIdx);
960 Value *NewOther = ConvertExpressionToType(OtherOp, NewTy, VMC);
962 Res->setOperand(OtherIdx, NewOther);
963 Res->setOperand(!OtherIdx, NewVal);
966 case Instruction::Shl:
967 case Instruction::Shr:
968 assert(I->getOperand(0) == OldVal);
969 Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(), NewVal,
970 I->getOperand(1), Name);
973 case Instruction::Free: // Free can free any pointer type!
974 assert(I->getOperand(0) == OldVal);
975 Res = new FreeInst(NewVal);
979 case Instruction::Load: {
980 assert(I->getOperand(0) == OldVal && isa<PointerType>(NewVal->getType()));
981 const Type *LoadedTy =
982 cast<PointerType>(NewVal->getType())->getElementType();
984 std::vector<Value*> Indices;
985 Indices.push_back(ConstantUInt::get(Type::UIntTy, 0));
987 if (const CompositeType *CT = dyn_cast<CompositeType>(LoadedTy)) {
988 unsigned Offset = 0; // No offset, get first leaf.
989 LoadedTy = getStructOffsetType(CT, Offset, Indices, false);
991 assert(LoadedTy->isFirstClassType());
993 Res = new LoadInst(NewVal, Indices, Name);
994 assert(Res->getType()->isFirstClassType() && "Load of structure or array!");
998 case Instruction::Store: {
999 if (I->getOperand(0) == OldVal) { // Replace the source value
1000 const PointerType *NewPT = PointerType::get(NewTy);
1001 Res = new StoreInst(NewVal, Constant::getNullValue(NewPT));
1002 VMC.ExprMap[I] = Res;
1003 Res->setOperand(1, ConvertExpressionToType(I->getOperand(1), NewPT, VMC));
1004 } else { // Replace the source pointer
1005 const Type *ValTy = cast<PointerType>(NewTy)->getElementType();
1006 std::vector<Value*> Indices;
1008 if (isa<StructType>(ValTy)) {
1009 unsigned Offset = 0;
1010 Indices.push_back(ConstantUInt::get(Type::UIntTy, 0));
1011 ValTy = getStructOffsetType(ValTy, Offset, Indices, false);
1012 assert(Offset == 0 && ValTy);
1015 Res = new StoreInst(Constant::getNullValue(ValTy), NewVal, Indices);
1016 VMC.ExprMap[I] = Res;
1017 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), ValTy, VMC));
1023 case Instruction::GetElementPtr: {
1024 // Convert a one index getelementptr into just about anything that is
1027 BasicBlock::iterator It = find(BIL.begin(), BIL.end(), I);
1028 const Type *OldElTy = cast<PointerType>(I->getType())->getElementType();
1029 unsigned DataSize = TD.getTypeSize(OldElTy);
1030 Value *Index = I->getOperand(1);
1032 if (DataSize != 1) {
1033 // Insert a multiply of the old element type is not a unit size...
1034 Index = BinaryOperator::create(Instruction::Mul, Index,
1035 ConstantUInt::get(Type::UIntTy, DataSize));
1036 It = BIL.insert(It, cast<Instruction>(Index))+1;
1039 // Perform the conversion now...
1041 std::vector<Value*> Indices;
1042 const Type *ElTy = ConvertableToGEP(NewVal->getType(), Index, Indices, &It);
1043 assert(ElTy != 0 && "GEP Conversion Failure!");
1044 Res = new GetElementPtrInst(NewVal, Indices, Name);
1045 assert(Res->getType() == PointerType::get(ElTy) &&
1046 "ConvertableToGet failed!");
1049 if (I->getType() == PointerType::get(Type::SByteTy)) {
1050 // Convert a getelementptr sbyte * %reg111, uint 16 freely back to
1051 // anything that is a pointer type...
1053 BasicBlock::iterator It = find(BIL.begin(), BIL.end(), I);
1055 // Check to see if the second argument is an expression that can
1056 // be converted to the appropriate size... if so, allow it.
1058 std::vector<Value*> Indices;
1059 const Type *ElTy = ConvertableToGEP(NewVal->getType(), I->getOperand(1),
1061 assert(ElTy != 0 && "GEP Conversion Failure!");
1063 Res = new GetElementPtrInst(NewVal, Indices, Name);
1065 // Convert a getelementptr ulong * %reg123, uint %N
1066 // to getelementptr long * %reg123, uint %N
1067 // ... where the type must simply stay the same size...
1069 Res = new GetElementPtrInst(NewVal,
1070 cast<GetElementPtrInst>(I)->copyIndices(),
1076 case Instruction::PHINode: {
1077 PHINode *OldPN = cast<PHINode>(I);
1078 PHINode *NewPN = new PHINode(NewTy, Name);
1079 VMC.ExprMap[I] = NewPN;
1081 while (OldPN->getNumOperands()) {
1082 BasicBlock *BB = OldPN->getIncomingBlock(0);
1083 Value *OldVal = OldPN->getIncomingValue(0);
1084 OldPN->removeIncomingValue(BB);
1085 Value *V = ConvertExpressionToType(OldVal, NewTy, VMC);
1086 NewPN->addIncoming(V, BB);
1092 case Instruction::Call: {
1093 Value *Meth = I->getOperand(0);
1094 std::vector<Value*> Params(I->op_begin()+1, I->op_end());
1096 if (Meth == OldVal) { // Changing the function pointer?
1097 PointerType *NewPTy = cast<PointerType>(NewVal->getType());
1098 FunctionType *NewTy = cast<FunctionType>(NewPTy->getElementType());
1099 const FunctionType::ParamTypes &PTs = NewTy->getParamTypes();
1101 // Get an iterator to the call instruction so that we can insert casts for
1102 // operands if needbe. Note that we do not require operands to be
1103 // convertable, we can insert casts if they are convertible but not
1104 // compatible. The reason for this is that we prefer to have resolved
1105 // functions but casted arguments if possible.
1107 BasicBlock::iterator It = find(BIL.begin(), BIL.end(), I);
1109 // Convert over all of the call operands to their new types... but only
1110 // convert over the part that is not in the vararg section of the call.
1112 for (unsigned i = 0; i < PTs.size(); ++i)
1113 if (Params[i]->getType() != PTs[i]) {
1114 // Create a cast to convert it to the right type, we know that this
1115 // is a lossless cast...
1117 Params[i] = new CastInst(Params[i], PTs[i], "call.resolve.cast");
1118 It = BIL.insert(It, cast<Instruction>(Params[i]))+1;
1120 Meth = NewVal; // Update call destination to new value
1122 } else { // Changing an argument, must be in vararg area
1123 std::vector<Value*>::iterator OI =
1124 find(Params.begin(), Params.end(), OldVal);
1125 assert (OI != Params.end() && "Not using value!");
1130 Res = new CallInst(Meth, Params, Name);
1134 assert(0 && "Expression convertable, but don't know how to convert?");
1138 // If the instruction was newly created, insert it into the instruction
1141 BasicBlock::iterator It = find(BIL.begin(), BIL.end(), I);
1142 assert(It != BIL.end() && "Instruction not in own basic block??");
1143 BIL.insert(It, Res); // Keep It pointing to old instruction
1145 #ifdef DEBUG_EXPR_CONVERT
1146 cerr << "COT CREATED: " << (void*)Res << " " << Res;
1147 cerr << "In: " << (void*)I << " " << I << "Out: " << (void*)Res << " " << Res;
1150 // Add the instruction to the expression map
1151 VMC.ExprMap[I] = Res;
1153 if (I->getType() != Res->getType())
1154 ConvertValueToNewType(I, Res, VMC);
1156 for (unsigned It = 0; It < I->use_size(); ) {
1157 User *Use = *(I->use_begin()+It);
1158 if (isa<ValueHandle>(Use)) // Don't remove ValueHandles!
1161 Use->replaceUsesOfWith(I, Res);
1164 if (I->use_empty()) {
1165 // Now we just need to remove the old instruction so we don't get infinite
1166 // loops. Note that we cannot use DCE because DCE won't remove a store
1167 // instruction, for example.
1169 #ifdef DEBUG_EXPR_CONVERT
1170 cerr << "DELETING: " << (void*)I << " " << I;
1173 VMC.OperandsMapped.erase(I);
1174 VMC.ExprMap.erase(I);
1177 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
1179 assert(isa<ValueHandle>((Value*)*UI) &&"Uses of Instruction remain!!!");
1185 ValueHandle::ValueHandle(ValueMapCache &VMC, Value *V)
1186 : Instruction(Type::VoidTy, UserOp1, ""), Cache(VMC) {
1187 #ifdef DEBUG_EXPR_CONVERT
1188 //cerr << "VH AQUIRING: " << (void*)V << " " << V;
1190 Operands.push_back(Use(V, this));
1193 static void RecursiveDelete(ValueMapCache &Cache, Instruction *I) {
1194 if (!I || !I->use_empty()) return;
1196 assert(I->getParent() && "Inst not in basic block!");
1198 #ifdef DEBUG_EXPR_CONVERT
1199 //cerr << "VH DELETING: " << (void*)I << " " << I;
1202 for (User::op_iterator OI = I->op_begin(), OE = I->op_end();
1204 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
1206 RecursiveDelete(Cache, U);
1209 I->getParent()->getInstList().remove(I);
1211 Cache.OperandsMapped.erase(I);
1212 Cache.ExprMap.erase(I);
1216 ValueHandle::~ValueHandle() {
1217 if (Operands[0]->use_size() == 1) {
1218 Value *V = Operands[0];
1219 Operands[0] = 0; // Drop use!
1221 // Now we just need to remove the old instruction so we don't get infinite
1222 // loops. Note that we cannot use DCE because DCE won't remove a store
1223 // instruction, for example.
1225 RecursiveDelete(Cache, dyn_cast<Instruction>(V));
1227 #ifdef DEBUG_EXPR_CONVERT
1228 //cerr << "VH RELEASING: " << (void*)Operands[0].get() << " " << Operands[0]->use_size() << " " << Operands[0];