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"
20 static bool OperandConvertableToType(User *U, Value *V, const Type *Ty,
21 ValueTypeCache &ConvertedTypes);
23 static void ConvertOperandToType(User *U, Value *OldVal, Value *NewVal,
26 // Peephole Malloc instructions: we take a look at the use chain of the
27 // malloc instruction, and try to find out if the following conditions hold:
28 // 1. The malloc is of the form: 'malloc [sbyte], uint <constant>'
29 // 2. The only users of the malloc are cast & add instructions
30 // 3. Of the cast instructions, there is only one destination pointer type
31 // [RTy] where the size of the pointed to object is equal to the number
32 // of bytes allocated.
34 // If these conditions hold, we convert the malloc to allocate an [RTy]
35 // element. TODO: This comment is out of date WRT arrays
37 static bool MallocConvertableToType(MallocInst *MI, const Type *Ty,
38 ValueTypeCache &CTMap) {
39 if (!isa<PointerType>(Ty)) return false; // Malloc always returns pointers
41 // Deal with the type to allocate, not the pointer type...
42 Ty = cast<PointerType>(Ty)->getElementType();
43 if (!Ty->isSized()) return false; // Can only alloc something with a size
45 // Analyze the number of bytes allocated...
46 ExprType Expr = ClassifyExpression(MI->getArraySize());
48 // Get information about the base datatype being allocated, before & after
49 int ReqTypeSize = TD.getTypeSize(Ty);
50 unsigned OldTypeSize = TD.getTypeSize(MI->getType()->getElementType());
52 // Must have a scale or offset to analyze it...
53 if (!Expr.Offset && !Expr.Scale && OldTypeSize == 1) return false;
55 // Get the offset and scale of the allocation...
56 int OffsetVal = Expr.Offset ? getConstantValue(Expr.Offset) : 0;
57 int ScaleVal = Expr.Scale ? getConstantValue(Expr.Scale) : (Expr.Var ? 1 : 0);
59 // The old type might not be of unit size, take old size into consideration
61 int Offset = OffsetVal * OldTypeSize;
62 int Scale = ScaleVal * OldTypeSize;
64 // In order to be successful, both the scale and the offset must be a multiple
65 // of the requested data type's size.
67 if (Offset/ReqTypeSize*ReqTypeSize != Offset ||
68 Scale/ReqTypeSize*ReqTypeSize != Scale)
69 return false; // Nope.
74 static Instruction *ConvertMallocToType(MallocInst *MI, const Type *Ty,
75 const std::string &Name,
77 BasicBlock *BB = MI->getParent();
78 BasicBlock::iterator It = BB->end();
80 // Analyze the number of bytes allocated...
81 ExprType Expr = ClassifyExpression(MI->getArraySize());
83 const PointerType *AllocTy = cast<PointerType>(Ty);
84 const Type *ElType = AllocTy->getElementType();
86 unsigned DataSize = TD.getTypeSize(ElType);
87 unsigned OldTypeSize = TD.getTypeSize(MI->getType()->getElementType());
89 // Get the offset and scale coefficients that we are allocating...
90 int OffsetVal = (Expr.Offset ? getConstantValue(Expr.Offset) : 0);
91 int ScaleVal = Expr.Scale ? getConstantValue(Expr.Scale) : (Expr.Var ? 1 : 0);
93 // The old type might not be of unit size, take old size into consideration
95 unsigned Offset = (unsigned)OffsetVal * OldTypeSize / DataSize;
96 unsigned Scale = (unsigned)ScaleVal * OldTypeSize / DataSize;
98 // Locate the malloc instruction, because we may be inserting instructions
101 // If we have a scale, apply it first...
103 // Expr.Var is not neccesarily unsigned right now, insert a cast now.
104 if (Expr.Var->getType() != Type::UIntTy) {
105 Instruction *CI = new CastInst(Expr.Var, Type::UIntTy);
106 if (Expr.Var->hasName()) CI->setName(Expr.Var->getName()+"-uint");
107 It = ++BB->getInstList().insert(It, CI);
113 BinaryOperator::create(Instruction::Mul, Expr.Var,
114 ConstantUInt::get(Type::UIntTy, Scale));
115 if (Expr.Var->hasName()) ScI->setName(Expr.Var->getName()+"-scl");
116 It = ++BB->getInstList().insert(It, ScI);
121 // If we are not scaling anything, just make the offset be the "var"...
122 Expr.Var = ConstantUInt::get(Type::UIntTy, Offset);
123 Offset = 0; Scale = 1;
126 // If we have an offset now, add it in...
128 assert(Expr.Var && "Var must be nonnull by now!");
131 BinaryOperator::create(Instruction::Add, Expr.Var,
132 ConstantUInt::get(Type::UIntTy, Offset));
133 if (Expr.Var->hasName()) AddI->setName(Expr.Var->getName()+"-off");
134 It = ++BB->getInstList().insert(It, AddI);
138 Instruction *NewI = new MallocInst(AllocTy, Expr.Var, Name);
140 assert(AllocTy == Ty);
145 // ExpressionConvertableToType - Return true if it is possible
146 bool ExpressionConvertableToType(Value *V, const Type *Ty,
147 ValueTypeCache &CTMap) {
148 // Expression type must be holdable in a register.
149 if (!Ty->isFirstClassType())
152 ValueTypeCache::iterator CTMI = CTMap.find(V);
153 if (CTMI != CTMap.end()) return CTMI->second == Ty;
156 if (V->getType() == Ty) return true; // Expression already correct type!
158 Instruction *I = dyn_cast<Instruction>(V);
160 // It's not an instruction, check to see if it's a constant... all constants
161 // can be converted to an equivalent value (except pointers, they can't be
162 // const prop'd in general). We just ask the constant propogator to see if
163 // it can convert the value...
165 if (Constant *CPV = dyn_cast<Constant>(V))
166 if (ConstantFoldCastInstruction(CPV, Ty))
167 return true; // Don't worry about deallocating, it's a constant.
169 return false; // Otherwise, we can't convert!
172 switch (I->getOpcode()) {
173 case Instruction::Cast:
174 // We can convert the expr if the cast destination type is losslessly
175 // convertable to the requested type.
176 if (!Ty->isLosslesslyConvertableTo(I->getType())) return false;
178 // We also do not allow conversion of a cast that casts from a ptr to array
179 // of X to a *X. For example: cast [4 x %List *] * %val to %List * *
181 if (const PointerType *SPT =
182 dyn_cast<PointerType>(I->getOperand(0)->getType()))
183 if (const PointerType *DPT = dyn_cast<PointerType>(I->getType()))
184 if (const ArrayType *AT = dyn_cast<ArrayType>(SPT->getElementType()))
185 if (AT->getElementType() == DPT->getElementType())
189 case Instruction::Add:
190 case Instruction::Sub:
191 if (!ExpressionConvertableToType(I->getOperand(0), Ty, CTMap) ||
192 !ExpressionConvertableToType(I->getOperand(1), Ty, CTMap))
195 case Instruction::Shr:
196 if (Ty->isSigned() != V->getType()->isSigned()) return false;
198 case Instruction::Shl:
199 if (!ExpressionConvertableToType(I->getOperand(0), Ty, CTMap))
203 case Instruction::Load: {
204 LoadInst *LI = cast<LoadInst>(I);
205 if (!ExpressionConvertableToType(LI->getPointerOperand(),
206 PointerType::get(Ty), CTMap))
210 case Instruction::PHINode: {
211 PHINode *PN = cast<PHINode>(I);
212 for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i)
213 if (!ExpressionConvertableToType(PN->getIncomingValue(i), Ty, CTMap))
218 case Instruction::Malloc:
219 if (!MallocConvertableToType(cast<MallocInst>(I), Ty, CTMap))
223 case Instruction::GetElementPtr: {
224 // GetElementPtr's are directly convertable to a pointer type if they have
225 // a number of zeros at the end. Because removing these values does not
226 // change the logical offset of the GEP, it is okay and fair to remove them.
227 // This can change this:
228 // %t1 = getelementptr %Hosp * %hosp, ubyte 4, ubyte 0 ; <%List **>
229 // %t2 = cast %List * * %t1 to %List *
231 // %t2 = getelementptr %Hosp * %hosp, ubyte 4 ; <%List *>
233 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
234 const PointerType *PTy = dyn_cast<PointerType>(Ty);
235 if (!PTy) return false; // GEP must always return a pointer...
236 const Type *PVTy = PTy->getElementType();
238 // Check to see if there are zero elements that we can remove from the
239 // index array. If there are, check to see if removing them causes us to
240 // get to the right type...
242 std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
243 const Type *BaseType = GEP->getPointerOperand()->getType();
244 const Type *ElTy = 0;
246 while (!Indices.empty() && isa<ConstantUInt>(Indices.back()) &&
247 cast<ConstantUInt>(Indices.back())->getValue() == 0) {
249 ElTy = GetElementPtrInst::getIndexedType(BaseType, Indices, true);
251 break; // Found a match!!
255 if (ElTy) break; // Found a number of zeros we can strip off!
257 // Otherwise, we can convert a GEP from one form to the other iff the
258 // current gep is of the form 'getelementptr sbyte*, unsigned N
259 // and we could convert this to an appropriate GEP for the new type.
261 if (GEP->getNumOperands() == 2 &&
262 GEP->getOperand(1)->getType() == Type::UIntTy &&
263 GEP->getType() == PointerType::get(Type::SByteTy)) {
265 // Do not Check to see if our incoming pointer can be converted
266 // to be a ptr to an array of the right type... because in more cases than
267 // not, it is simply not analyzable because of pointer/array
268 // discrepencies. To fix this, we will insert a cast before the GEP.
271 // Check to see if 'N' is an expression that can be converted to
272 // the appropriate size... if so, allow it.
274 std::vector<Value*> Indices;
275 const Type *ElTy = ConvertableToGEP(PTy, I->getOperand(1), Indices);
277 if (!ExpressionConvertableToType(I->getOperand(0),
278 PointerType::get(ElTy), CTMap))
279 return false; // Can't continue, ExConToTy might have polluted set!
284 // Otherwise, it could be that we have something like this:
285 // getelementptr [[sbyte] *] * %reg115, uint %reg138 ; [sbyte]**
286 // and want to convert it into something like this:
287 // getelemenptr [[int] *] * %reg115, uint %reg138 ; [int]**
289 if (GEP->getNumOperands() == 2 &&
290 GEP->getOperand(1)->getType() == Type::UIntTy &&
291 TD.getTypeSize(PTy->getElementType()) ==
292 TD.getTypeSize(GEP->getType()->getElementType())) {
293 const PointerType *NewSrcTy = PointerType::get(PVTy);
294 if (!ExpressionConvertableToType(I->getOperand(0), NewSrcTy, CTMap))
299 return false; // No match, maybe next time.
306 // Expressions are only convertable if all of the users of the expression can
307 // have this value converted. This makes use of the map to avoid infinite
310 for (Value::use_iterator It = I->use_begin(), E = I->use_end(); It != E; ++It)
311 if (!OperandConvertableToType(*It, I, Ty, CTMap))
318 Value *ConvertExpressionToType(Value *V, const Type *Ty, ValueMapCache &VMC) {
319 if (V->getType() == Ty) return V; // Already where we need to be?
321 ValueMapCache::ExprMapTy::iterator VMCI = VMC.ExprMap.find(V);
322 if (VMCI != VMC.ExprMap.end()) {
323 const Value *GV = VMCI->second;
324 const Type *GTy = VMCI->second->getType();
325 assert(VMCI->second->getType() == Ty);
327 if (Instruction *I = dyn_cast<Instruction>(V))
328 ValueHandle IHandle(VMC, I); // Remove I if it is unused now!
333 DEBUG(cerr << "CETT: " << (void*)V << " " << V);
335 Instruction *I = dyn_cast<Instruction>(V);
337 if (Constant *CPV = cast<Constant>(V)) {
338 // Constants are converted by constant folding the cast that is required.
339 // We assume here that all casts are implemented for constant prop.
340 Value *Result = ConstantFoldCastInstruction(CPV, Ty);
341 assert(Result && "ConstantFoldCastInstruction Failed!!!");
342 assert(Result->getType() == Ty && "Const prop of cast failed!");
344 // Add the instruction to the expression map
345 VMC.ExprMap[V] = Result;
350 BasicBlock *BB = I->getParent();
351 BasicBlock::InstListType &BIL = BB->getInstList();
352 std::string Name = I->getName(); if (!Name.empty()) I->setName("");
353 Instruction *Res; // Result of conversion
355 ValueHandle IHandle(VMC, I); // Prevent I from being removed!
357 Constant *Dummy = Constant::getNullValue(Ty);
359 switch (I->getOpcode()) {
360 case Instruction::Cast:
361 assert(VMC.NewCasts.count(ValueHandle(VMC, I)) == 0);
362 Res = new CastInst(I->getOperand(0), Ty, Name);
363 VMC.NewCasts.insert(ValueHandle(VMC, Res));
366 case Instruction::Add:
367 case Instruction::Sub:
368 Res = BinaryOperator::create(cast<BinaryOperator>(I)->getOpcode(),
370 VMC.ExprMap[I] = Res; // Add node to expression eagerly
372 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), Ty, VMC));
373 Res->setOperand(1, ConvertExpressionToType(I->getOperand(1), Ty, VMC));
376 case Instruction::Shl:
377 case Instruction::Shr:
378 Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(), Dummy,
379 I->getOperand(1), Name);
380 VMC.ExprMap[I] = Res;
381 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), Ty, VMC));
384 case Instruction::Load: {
385 LoadInst *LI = cast<LoadInst>(I);
387 Res = new LoadInst(Constant::getNullValue(PointerType::get(Ty)), Name);
388 VMC.ExprMap[I] = Res;
389 Res->setOperand(0, ConvertExpressionToType(LI->getPointerOperand(),
390 PointerType::get(Ty), VMC));
391 assert(Res->getOperand(0)->getType() == PointerType::get(Ty));
392 assert(Ty == Res->getType());
393 assert(Res->getType()->isFirstClassType() && "Load of structure or array!");
397 case Instruction::PHINode: {
398 PHINode *OldPN = cast<PHINode>(I);
399 PHINode *NewPN = new PHINode(Ty, Name);
401 VMC.ExprMap[I] = NewPN; // Add node to expression eagerly
402 while (OldPN->getNumOperands()) {
403 BasicBlock *BB = OldPN->getIncomingBlock(0);
404 Value *OldVal = OldPN->getIncomingValue(0);
405 ValueHandle OldValHandle(VMC, OldVal);
406 OldPN->removeIncomingValue(BB);
407 Value *V = ConvertExpressionToType(OldVal, Ty, VMC);
408 NewPN->addIncoming(V, BB);
414 case Instruction::Malloc: {
415 Res = ConvertMallocToType(cast<MallocInst>(I), Ty, Name, VMC);
419 case Instruction::GetElementPtr: {
420 // GetElementPtr's are directly convertable to a pointer type if they have
421 // a number of zeros at the end. Because removing these values does not
422 // change the logical offset of the GEP, it is okay and fair to remove them.
423 // This can change this:
424 // %t1 = getelementptr %Hosp * %hosp, ubyte 4, ubyte 0 ; <%List **>
425 // %t2 = cast %List * * %t1 to %List *
427 // %t2 = getelementptr %Hosp * %hosp, ubyte 4 ; <%List *>
429 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
431 // Check to see if there are zero elements that we can remove from the
432 // index array. If there are, check to see if removing them causes us to
433 // get to the right type...
435 std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
436 const Type *BaseType = GEP->getPointerOperand()->getType();
437 const Type *PVTy = cast<PointerType>(Ty)->getElementType();
439 while (!Indices.empty() && isa<ConstantUInt>(Indices.back()) &&
440 cast<ConstantUInt>(Indices.back())->getValue() == 0) {
442 if (GetElementPtrInst::getIndexedType(BaseType, Indices, true) == PVTy) {
443 if (Indices.size() == 0) {
444 Res = new CastInst(GEP->getPointerOperand(), BaseType); // NOOP
446 Res = new GetElementPtrInst(GEP->getPointerOperand(), Indices, Name);
452 if (Res == 0 && GEP->getNumOperands() == 2 &&
453 GEP->getOperand(1)->getType() == Type::UIntTy &&
454 GEP->getType() == PointerType::get(Type::SByteTy)) {
456 // Otherwise, we can convert a GEP from one form to the other iff the
457 // current gep is of the form 'getelementptr [sbyte]*, unsigned N
458 // and we could convert this to an appropriate GEP for the new type.
460 const PointerType *NewSrcTy = PointerType::get(PVTy);
461 BasicBlock::iterator It = I;
463 // Check to see if 'N' is an expression that can be converted to
464 // the appropriate size... if so, allow it.
466 std::vector<Value*> Indices;
467 const Type *ElTy = ConvertableToGEP(NewSrcTy, I->getOperand(1),
470 assert(ElTy == PVTy && "Internal error, setup wrong!");
471 Res = new GetElementPtrInst(Constant::getNullValue(NewSrcTy),
473 VMC.ExprMap[I] = Res;
474 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
479 // Otherwise, it could be that we have something like this:
480 // getelementptr [[sbyte] *] * %reg115, uint %reg138 ; [sbyte]**
481 // and want to convert it into something like this:
482 // getelemenptr [[int] *] * %reg115, uint %reg138 ; [int]**
485 const PointerType *NewSrcTy = PointerType::get(PVTy);
486 std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
487 Res = new GetElementPtrInst(Constant::getNullValue(NewSrcTy),
489 VMC.ExprMap[I] = Res;
490 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
495 assert(Res && "Didn't find match!");
496 break; // No match, maybe next time.
500 assert(0 && "Expression convertable, but don't know how to convert?");
504 assert(Res->getType() == Ty && "Didn't convert expr to correct type!");
508 // Add the instruction to the expression map
509 VMC.ExprMap[I] = Res;
511 // Expressions are only convertable if all of the users of the expression can
512 // have this value converted. This makes use of the map to avoid infinite
515 unsigned NumUses = I->use_size();
516 for (unsigned It = 0; It < NumUses; ) {
517 unsigned OldSize = NumUses;
518 ConvertOperandToType(*(I->use_begin()+It), I, Res, VMC);
519 NumUses = I->use_size();
520 if (NumUses == OldSize) ++It;
523 DEBUG(cerr << "ExpIn: " << (void*)I << " " << I
524 << "ExpOut: " << (void*)Res << " " << Res);
531 // ValueConvertableToType - Return true if it is possible
532 bool ValueConvertableToType(Value *V, const Type *Ty,
533 ValueTypeCache &ConvertedTypes) {
534 ValueTypeCache::iterator I = ConvertedTypes.find(V);
535 if (I != ConvertedTypes.end()) return I->second == Ty;
536 ConvertedTypes[V] = Ty;
538 // It is safe to convert the specified value to the specified type IFF all of
539 // the uses of the value can be converted to accept the new typed value.
541 if (V->getType() != Ty) {
542 for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I)
543 if (!OperandConvertableToType(*I, V, Ty, ConvertedTypes))
554 // OperandConvertableToType - Return true if it is possible to convert operand
555 // V of User (instruction) U to the specified type. This is true iff it is
556 // possible to change the specified instruction to accept this. CTMap is a map
557 // of converted types, so that circular definitions will see the future type of
558 // the expression, not the static current type.
560 static bool OperandConvertableToType(User *U, Value *V, const Type *Ty,
561 ValueTypeCache &CTMap) {
562 // if (V->getType() == Ty) return true; // Operand already the right type?
564 // Expression type must be holdable in a register.
565 if (!Ty->isFirstClassType())
568 Instruction *I = dyn_cast<Instruction>(U);
569 if (I == 0) return false; // We can't convert!
571 switch (I->getOpcode()) {
572 case Instruction::Cast:
573 assert(I->getOperand(0) == V);
574 // We can convert the expr if the cast destination type is losslessly
575 // convertable to the requested type.
576 // Also, do not change a cast that is a noop cast. For all intents and
577 // purposes it should be eliminated.
578 if (!Ty->isLosslesslyConvertableTo(I->getOperand(0)->getType()) ||
579 I->getType() == I->getOperand(0)->getType())
582 // Do not allow a 'cast ushort %V to uint' to have it's first operand be
583 // converted to a 'short' type. Doing so changes the way sign promotion
584 // happens, and breaks things. Only allow the cast to take place if the
585 // signedness doesn't change... or if the current cast is not a lossy
588 if (!I->getType()->isLosslesslyConvertableTo(I->getOperand(0)->getType()) &&
589 I->getOperand(0)->getType()->isSigned() != Ty->isSigned())
592 // We also do not allow conversion of a cast that casts from a ptr to array
593 // of X to a *X. For example: cast [4 x %List *] * %val to %List * *
595 if (const PointerType *SPT =
596 dyn_cast<PointerType>(I->getOperand(0)->getType()))
597 if (const PointerType *DPT = dyn_cast<PointerType>(I->getType()))
598 if (const ArrayType *AT = dyn_cast<ArrayType>(SPT->getElementType()))
599 if (AT->getElementType() == DPT->getElementType())
603 case Instruction::Add:
604 if (isa<PointerType>(Ty)) {
605 Value *IndexVal = I->getOperand(V == I->getOperand(0) ? 1 : 0);
606 std::vector<Value*> Indices;
607 if (const Type *ETy = ConvertableToGEP(Ty, IndexVal, Indices)) {
608 const Type *RetTy = PointerType::get(ETy);
610 // Only successful if we can convert this type to the required type
611 if (ValueConvertableToType(I, RetTy, CTMap)) {
615 // We have to return failure here because ValueConvertableToType could
616 // have polluted our map
621 case Instruction::Sub: {
622 Value *OtherOp = I->getOperand((V == I->getOperand(0)) ? 1 : 0);
623 return ValueConvertableToType(I, Ty, CTMap) &&
624 ExpressionConvertableToType(OtherOp, Ty, CTMap);
626 case Instruction::SetEQ:
627 case Instruction::SetNE: {
628 Value *OtherOp = I->getOperand((V == I->getOperand(0)) ? 1 : 0);
629 return ExpressionConvertableToType(OtherOp, Ty, CTMap);
631 case Instruction::Shr:
632 if (Ty->isSigned() != V->getType()->isSigned()) return false;
634 case Instruction::Shl:
635 assert(I->getOperand(0) == V);
636 return ValueConvertableToType(I, Ty, CTMap);
638 case Instruction::Free:
639 assert(I->getOperand(0) == V);
640 return isa<PointerType>(Ty); // Free can free any pointer type!
642 case Instruction::Load:
643 // Cannot convert the types of any subscripts...
644 if (I->getOperand(0) != V) return false;
646 if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
647 LoadInst *LI = cast<LoadInst>(I);
649 const Type *LoadedTy = PT->getElementType();
651 // They could be loading the first element of a composite type...
652 if (const CompositeType *CT = dyn_cast<CompositeType>(LoadedTy)) {
653 unsigned Offset = 0; // No offset, get first leaf.
654 std::vector<Value*> Indices; // Discarded...
655 LoadedTy = getStructOffsetType(CT, Offset, Indices, false);
656 assert(Offset == 0 && "Offset changed from zero???");
659 if (!LoadedTy->isFirstClassType())
662 if (TD.getTypeSize(LoadedTy) != TD.getTypeSize(LI->getType()))
665 return ValueConvertableToType(LI, LoadedTy, CTMap);
669 case Instruction::Store: {
670 StoreInst *SI = cast<StoreInst>(I);
672 if (V == I->getOperand(0)) {
673 ValueTypeCache::iterator CTMI = CTMap.find(I->getOperand(1));
674 if (CTMI != CTMap.end()) { // Operand #1 is in the table already?
675 // If so, check to see if it's Ty*, or, more importantly, if it is a
676 // pointer to a structure where the first element is a Ty... this code
677 // is neccesary because we might be trying to change the source and
678 // destination type of the store (they might be related) and the dest
679 // pointer type might be a pointer to structure. Below we allow pointer
680 // to structures where the 0th element is compatible with the value,
681 // now we have to support the symmetrical part of this.
683 const Type *ElTy = cast<PointerType>(CTMI->second)->getElementType();
685 // Already a pointer to what we want? Trivially accept...
686 if (ElTy == Ty) return true;
688 // Tricky case now, if the destination is a pointer to structure,
689 // obviously the source is not allowed to be a structure (cannot copy
690 // a whole structure at a time), so the level raiser must be trying to
691 // store into the first field. Check for this and allow it now:
693 if (const StructType *SElTy = dyn_cast<StructType>(ElTy)) {
695 std::vector<Value*> Indices;
696 ElTy = getStructOffsetType(ElTy, Offset, Indices, false);
697 assert(Offset == 0 && "Offset changed!");
698 if (ElTy == 0) // Element at offset zero in struct doesn't exist!
699 return false; // Can only happen for {}*
701 if (ElTy == Ty) // Looks like the 0th element of structure is
702 return true; // compatible! Accept now!
704 // Otherwise we know that we can't work, so just stop trying now.
709 // Can convert the store if we can convert the pointer operand to match
710 // the new value type...
711 return ExpressionConvertableToType(I->getOperand(1), PointerType::get(Ty),
713 } else if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
714 const Type *ElTy = PT->getElementType();
715 assert(V == I->getOperand(1));
717 if (isa<StructType>(ElTy)) {
718 // We can change the destination pointer if we can store our first
719 // argument into the first element of the structure...
722 std::vector<Value*> Indices;
723 ElTy = getStructOffsetType(ElTy, Offset, Indices, false);
724 assert(Offset == 0 && "Offset changed!");
725 if (ElTy == 0) // Element at offset zero in struct doesn't exist!
726 return false; // Can only happen for {}*
729 // Must move the same amount of data...
730 if (!ElTy->isSized() ||
731 TD.getTypeSize(ElTy) != TD.getTypeSize(I->getOperand(0)->getType()))
734 // Can convert store if the incoming value is convertable...
735 return ExpressionConvertableToType(I->getOperand(0), ElTy, CTMap);
740 case Instruction::GetElementPtr:
741 if (V != I->getOperand(0) || !isa<PointerType>(Ty)) return false;
743 // If we have a two operand form of getelementptr, this is really little
744 // more than a simple addition. As with addition, check to see if the
745 // getelementptr instruction can be changed to index into the new type.
747 if (I->getNumOperands() == 2) {
748 const Type *OldElTy = cast<PointerType>(I->getType())->getElementType();
749 unsigned DataSize = TD.getTypeSize(OldElTy);
750 Value *Index = I->getOperand(1);
751 Instruction *TempScale = 0;
753 // If the old data element is not unit sized, we have to create a scale
754 // instruction so that ConvertableToGEP will know the REAL amount we are
755 // indexing by. Note that this is never inserted into the instruction
756 // stream, so we have to delete it when we're done.
759 TempScale = BinaryOperator::create(Instruction::Mul, Index,
760 ConstantUInt::get(Type::UIntTy,
765 // Check to see if the second argument is an expression that can
766 // be converted to the appropriate size... if so, allow it.
768 std::vector<Value*> Indices;
769 const Type *ElTy = ConvertableToGEP(Ty, Index, Indices);
770 delete TempScale; // Free our temporary multiply if we made it
772 if (ElTy == 0) return false; // Cannot make conversion...
773 return ValueConvertableToType(I, PointerType::get(ElTy), CTMap);
777 case Instruction::PHINode: {
778 PHINode *PN = cast<PHINode>(I);
779 for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i)
780 if (!ExpressionConvertableToType(PN->getIncomingValue(i), Ty, CTMap))
782 return ValueConvertableToType(PN, Ty, CTMap);
785 case Instruction::Call: {
786 User::op_iterator OI = find(I->op_begin(), I->op_end(), V);
787 assert (OI != I->op_end() && "Not using value!");
788 unsigned OpNum = OI - I->op_begin();
790 // Are we trying to change the function pointer value to a new type?
792 const PointerType *PTy = dyn_cast<PointerType>(Ty);
793 if (PTy == 0) return false; // Can't convert to a non-pointer type...
794 const FunctionType *MTy = dyn_cast<FunctionType>(PTy->getElementType());
795 if (MTy == 0) return false; // Can't convert to a non ptr to function...
797 // Perform sanity checks to make sure that new function type has the
798 // correct number of arguments...
800 unsigned NumArgs = I->getNumOperands()-1; // Don't include function ptr
802 // Cannot convert to a type that requires more fixed arguments than
803 // the call provides...
805 if (NumArgs < MTy->getParamTypes().size()) return false;
807 // Unless this is a vararg function type, we cannot provide more arguments
808 // than are desired...
810 if (!MTy->isVarArg() && NumArgs > MTy->getParamTypes().size())
813 // Okay, at this point, we know that the call and the function type match
814 // number of arguments. Now we see if we can convert the arguments
815 // themselves. Note that we do not require operands to be convertable,
816 // we can insert casts if they are convertible but not compatible. The
817 // reason for this is that we prefer to have resolved functions but casted
818 // arguments if possible.
820 const FunctionType::ParamTypes &PTs = MTy->getParamTypes();
821 for (unsigned i = 0, NA = PTs.size(); i < NA; ++i)
822 if (!PTs[i]->isLosslesslyConvertableTo(I->getOperand(i+1)->getType()))
823 return false; // Operands must have compatible types!
825 // Okay, at this point, we know that all of the arguments can be
826 // converted. We succeed if we can change the return type if
829 return ValueConvertableToType(I, MTy->getReturnType(), CTMap);
832 const PointerType *MPtr = cast<PointerType>(I->getOperand(0)->getType());
833 const FunctionType *MTy = cast<FunctionType>(MPtr->getElementType());
834 if (!MTy->isVarArg()) return false;
836 if ((OpNum-1) < MTy->getParamTypes().size())
837 return false; // It's not in the varargs section...
839 // If we get this far, we know the value is in the varargs section of the
840 // function! We can convert if we don't reinterpret the value...
842 return Ty->isLosslesslyConvertableTo(V->getType());
849 void ConvertValueToNewType(Value *V, Value *NewVal, ValueMapCache &VMC) {
850 ValueHandle VH(VMC, V);
852 unsigned NumUses = V->use_size();
853 for (unsigned It = 0; It < NumUses; ) {
854 unsigned OldSize = NumUses;
855 ConvertOperandToType(*(V->use_begin()+It), V, NewVal, VMC);
856 NumUses = V->use_size();
857 if (NumUses == OldSize) ++It;
863 static void ConvertOperandToType(User *U, Value *OldVal, Value *NewVal,
864 ValueMapCache &VMC) {
865 if (isa<ValueHandle>(U)) return; // Valuehandles don't let go of operands...
867 if (VMC.OperandsMapped.count(U)) return;
868 VMC.OperandsMapped.insert(U);
870 ValueMapCache::ExprMapTy::iterator VMCI = VMC.ExprMap.find(U);
871 if (VMCI != VMC.ExprMap.end())
875 Instruction *I = cast<Instruction>(U); // Only Instructions convertable
877 BasicBlock *BB = I->getParent();
878 assert(BB != 0 && "Instruction not embedded in basic block!");
879 BasicBlock::InstListType &BIL = BB->getInstList();
880 std::string Name = I->getName();
882 Instruction *Res; // Result of conversion
884 //cerr << endl << endl << "Type:\t" << Ty << "\nInst: " << I << "BB Before: " << BB << endl;
886 // Prevent I from being removed...
887 ValueHandle IHandle(VMC, I);
889 const Type *NewTy = NewVal->getType();
890 Constant *Dummy = (NewTy != Type::VoidTy) ?
891 Constant::getNullValue(NewTy) : 0;
893 switch (I->getOpcode()) {
894 case Instruction::Cast:
895 if (VMC.NewCasts.count(ValueHandle(VMC, I))) {
896 // This cast has already had it's value converted, causing a new cast to
897 // be created. We don't want to create YET ANOTHER cast instruction
898 // representing the original one, so just modify the operand of this cast
899 // instruction, which we know is newly created.
900 I->setOperand(0, NewVal);
901 I->setName(Name); // give I its name back
905 Res = new CastInst(NewVal, I->getType(), Name);
909 case Instruction::Add:
910 if (isa<PointerType>(NewTy)) {
911 Value *IndexVal = I->getOperand(OldVal == I->getOperand(0) ? 1 : 0);
912 std::vector<Value*> Indices;
913 BasicBlock::iterator It = I;
915 if (const Type *ETy = ConvertableToGEP(NewTy, IndexVal, Indices, &It)) {
916 // If successful, convert the add to a GEP
917 //const Type *RetTy = PointerType::get(ETy);
918 // First operand is actually the given pointer...
919 Res = new GetElementPtrInst(NewVal, Indices, Name);
920 assert(cast<PointerType>(Res->getType())->getElementType() == ETy &&
921 "ConvertableToGEP broken!");
927 case Instruction::Sub:
928 case Instruction::SetEQ:
929 case Instruction::SetNE: {
930 Res = BinaryOperator::create(cast<BinaryOperator>(I)->getOpcode(),
932 VMC.ExprMap[I] = Res; // Add node to expression eagerly
934 unsigned OtherIdx = (OldVal == I->getOperand(0)) ? 1 : 0;
935 Value *OtherOp = I->getOperand(OtherIdx);
936 Value *NewOther = ConvertExpressionToType(OtherOp, NewTy, VMC);
938 Res->setOperand(OtherIdx, NewOther);
939 Res->setOperand(!OtherIdx, NewVal);
942 case Instruction::Shl:
943 case Instruction::Shr:
944 assert(I->getOperand(0) == OldVal);
945 Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(), NewVal,
946 I->getOperand(1), Name);
949 case Instruction::Free: // Free can free any pointer type!
950 assert(I->getOperand(0) == OldVal);
951 Res = new FreeInst(NewVal);
955 case Instruction::Load: {
956 assert(I->getOperand(0) == OldVal && isa<PointerType>(NewVal->getType()));
957 const Type *LoadedTy =
958 cast<PointerType>(NewVal->getType())->getElementType();
962 if (const CompositeType *CT = dyn_cast<CompositeType>(LoadedTy)) {
963 std::vector<Value*> Indices;
964 Indices.push_back(ConstantUInt::get(Type::UIntTy, 0));
966 unsigned Offset = 0; // No offset, get first leaf.
967 LoadedTy = getStructOffsetType(CT, Offset, Indices, false);
968 assert(LoadedTy->isFirstClassType());
970 if (Indices.size() != 1) { // Do not generate load X, 0
971 Src = new GetElementPtrInst(Src, Indices, Name+".idx");
972 // Insert the GEP instruction before this load.
973 BIL.insert(I, cast<Instruction>(Src));
977 Res = new LoadInst(Src, Name);
978 assert(Res->getType()->isFirstClassType() && "Load of structure or array!");
982 case Instruction::Store: {
983 if (I->getOperand(0) == OldVal) { // Replace the source value
984 // Check to see if operand #1 has already been converted...
985 ValueMapCache::ExprMapTy::iterator VMCI =
986 VMC.ExprMap.find(I->getOperand(1));
987 if (VMCI != VMC.ExprMap.end()) {
988 // Comments describing this stuff are in the OperandConvertableToType
989 // switch statement for Store...
992 cast<PointerType>(VMCI->second->getType())->getElementType();
994 Value *SrcPtr = VMCI->second;
997 // We check that this is a struct in the initial scan...
998 const StructType *SElTy = cast<StructType>(ElTy);
1000 std::vector<Value*> Indices;
1001 Indices.push_back(ConstantUInt::get(Type::UIntTy, 0));
1003 unsigned Offset = 0;
1004 const Type *Ty = getStructOffsetType(ElTy, Offset, Indices, false);
1005 assert(Offset == 0 && "Offset changed!");
1006 assert(NewTy == Ty && "Did not convert to correct type!");
1008 SrcPtr = new GetElementPtrInst(SrcPtr, Indices,
1009 SrcPtr->getName()+".idx");
1010 // Insert the GEP instruction before this load.
1011 BIL.insert(I, cast<Instruction>(SrcPtr));
1013 Res = new StoreInst(NewVal, SrcPtr);
1015 VMC.ExprMap[I] = Res;
1017 // Otherwise, we haven't converted Operand #1 over yet...
1018 const PointerType *NewPT = PointerType::get(NewTy);
1019 Res = new StoreInst(NewVal, Constant::getNullValue(NewPT));
1020 VMC.ExprMap[I] = Res;
1021 Res->setOperand(1, ConvertExpressionToType(I->getOperand(1),
1024 } else { // Replace the source pointer
1025 const Type *ValTy = cast<PointerType>(NewTy)->getElementType();
1027 Value *SrcPtr = NewVal;
1029 if (isa<StructType>(ValTy)) {
1030 std::vector<Value*> Indices;
1031 Indices.push_back(ConstantUInt::get(Type::UIntTy, 0));
1033 unsigned Offset = 0;
1034 ValTy = getStructOffsetType(ValTy, Offset, Indices, false);
1036 assert(Offset == 0 && ValTy);
1038 SrcPtr = new GetElementPtrInst(SrcPtr, Indices,
1039 SrcPtr->getName()+".idx");
1040 // Insert the GEP instruction before this load.
1041 BIL.insert(I, cast<Instruction>(SrcPtr));
1044 Res = new StoreInst(Constant::getNullValue(ValTy), SrcPtr);
1045 VMC.ExprMap[I] = Res;
1046 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), ValTy, VMC));
1052 case Instruction::GetElementPtr: {
1053 // Convert a one index getelementptr into just about anything that is
1056 BasicBlock::iterator It = I;
1057 const Type *OldElTy = cast<PointerType>(I->getType())->getElementType();
1058 unsigned DataSize = TD.getTypeSize(OldElTy);
1059 Value *Index = I->getOperand(1);
1061 if (DataSize != 1) {
1062 // Insert a multiply of the old element type is not a unit size...
1063 Index = BinaryOperator::create(Instruction::Mul, Index,
1064 ConstantUInt::get(Type::UIntTy, DataSize));
1065 It = ++BIL.insert(It, cast<Instruction>(Index));
1068 // Perform the conversion now...
1070 std::vector<Value*> Indices;
1071 const Type *ElTy = ConvertableToGEP(NewVal->getType(), Index, Indices, &It);
1072 assert(ElTy != 0 && "GEP Conversion Failure!");
1073 Res = new GetElementPtrInst(NewVal, Indices, Name);
1074 assert(Res->getType() == PointerType::get(ElTy) &&
1075 "ConvertableToGet failed!");
1078 if (I->getType() == PointerType::get(Type::SByteTy)) {
1079 // Convert a getelementptr sbyte * %reg111, uint 16 freely back to
1080 // anything that is a pointer type...
1082 BasicBlock::iterator It = I;
1084 // Check to see if the second argument is an expression that can
1085 // be converted to the appropriate size... if so, allow it.
1087 std::vector<Value*> Indices;
1088 const Type *ElTy = ConvertableToGEP(NewVal->getType(), I->getOperand(1),
1090 assert(ElTy != 0 && "GEP Conversion Failure!");
1092 Res = new GetElementPtrInst(NewVal, Indices, Name);
1094 // Convert a getelementptr ulong * %reg123, uint %N
1095 // to getelementptr long * %reg123, uint %N
1096 // ... where the type must simply stay the same size...
1098 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
1099 std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
1100 Res = new GetElementPtrInst(NewVal, Indices, Name);
1105 case Instruction::PHINode: {
1106 PHINode *OldPN = cast<PHINode>(I);
1107 PHINode *NewPN = new PHINode(NewTy, Name);
1108 VMC.ExprMap[I] = NewPN;
1110 while (OldPN->getNumOperands()) {
1111 BasicBlock *BB = OldPN->getIncomingBlock(0);
1112 Value *OldVal = OldPN->getIncomingValue(0);
1113 OldPN->removeIncomingValue(BB);
1114 Value *V = ConvertExpressionToType(OldVal, NewTy, VMC);
1115 NewPN->addIncoming(V, BB);
1121 case Instruction::Call: {
1122 Value *Meth = I->getOperand(0);
1123 std::vector<Value*> Params(I->op_begin()+1, I->op_end());
1125 if (Meth == OldVal) { // Changing the function pointer?
1126 const PointerType *NewPTy = cast<PointerType>(NewVal->getType());
1127 const FunctionType *NewTy = cast<FunctionType>(NewPTy->getElementType());
1128 const FunctionType::ParamTypes &PTs = NewTy->getParamTypes();
1130 // Get an iterator to the call instruction so that we can insert casts for
1131 // operands if needbe. Note that we do not require operands to be
1132 // convertable, we can insert casts if they are convertible but not
1133 // compatible. The reason for this is that we prefer to have resolved
1134 // functions but casted arguments if possible.
1136 BasicBlock::iterator It = I;
1138 // Convert over all of the call operands to their new types... but only
1139 // convert over the part that is not in the vararg section of the call.
1141 for (unsigned i = 0; i < PTs.size(); ++i)
1142 if (Params[i]->getType() != PTs[i]) {
1143 // Create a cast to convert it to the right type, we know that this
1144 // is a lossless cast...
1146 Params[i] = new CastInst(Params[i], PTs[i], "call.resolve.cast");
1147 It = ++BIL.insert(It, cast<Instruction>(Params[i]));
1149 Meth = NewVal; // Update call destination to new value
1151 } else { // Changing an argument, must be in vararg area
1152 std::vector<Value*>::iterator OI =
1153 find(Params.begin(), Params.end(), OldVal);
1154 assert (OI != Params.end() && "Not using value!");
1159 Res = new CallInst(Meth, Params, Name);
1163 assert(0 && "Expression convertable, but don't know how to convert?");
1167 // If the instruction was newly created, insert it into the instruction
1170 BasicBlock::iterator It = I;
1171 assert(It != BIL.end() && "Instruction not in own basic block??");
1172 BIL.insert(It, Res); // Keep It pointing to old instruction
1174 DEBUG(cerr << "COT CREATED: " << (void*)Res << " " << Res
1175 << "In: " << (void*)I << " " << I << "Out: " << (void*)Res
1178 // Add the instruction to the expression map
1179 VMC.ExprMap[I] = Res;
1181 if (I->getType() != Res->getType())
1182 ConvertValueToNewType(I, Res, VMC);
1184 for (unsigned It = 0; It < I->use_size(); ) {
1185 User *Use = *(I->use_begin()+It);
1186 if (isa<ValueHandle>(Use)) // Don't remove ValueHandles!
1189 Use->replaceUsesOfWith(I, Res);
1192 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
1194 assert(isa<ValueHandle>((Value*)*UI) &&"Uses of Instruction remain!!!");
1199 ValueHandle::ValueHandle(ValueMapCache &VMC, Value *V)
1200 : Instruction(Type::VoidTy, UserOp1, ""), Cache(VMC) {
1201 //DEBUG(cerr << "VH AQUIRING: " << (void*)V << " " << V);
1202 Operands.push_back(Use(V, this));
1205 ValueHandle::ValueHandle(const ValueHandle &VH)
1206 : Instruction(Type::VoidTy, UserOp1, ""), Cache(VH.Cache) {
1207 //DEBUG(cerr << "VH AQUIRING: " << (void*)V << " " << V);
1208 Operands.push_back(Use((Value*)VH.getOperand(0), this));
1211 static void RecursiveDelete(ValueMapCache &Cache, Instruction *I) {
1212 if (!I || !I->use_empty()) return;
1214 assert(I->getParent() && "Inst not in basic block!");
1216 //DEBUG(cerr << "VH DELETING: " << (void*)I << " " << I);
1218 for (User::op_iterator OI = I->op_begin(), OE = I->op_end();
1220 if (Instruction *U = dyn_cast<Instruction>(OI->get())) {
1222 RecursiveDelete(Cache, U);
1225 I->getParent()->getInstList().remove(I);
1227 Cache.OperandsMapped.erase(I);
1228 Cache.ExprMap.erase(I);
1232 ValueHandle::~ValueHandle() {
1233 if (Operands[0]->use_size() == 1) {
1234 Value *V = Operands[0];
1235 Operands[0] = 0; // Drop use!
1237 // Now we just need to remove the old instruction so we don't get infinite
1238 // loops. Note that we cannot use DCE because DCE won't remove a store
1239 // instruction, for example.
1241 RecursiveDelete(Cache, dyn_cast<Instruction>(V));
1243 //DEBUG(cerr << "VH RELEASING: " << (void*)Operands[0].get() << " "
1244 // << Operands[0]->use_size() << " " << Operands[0]);