1 //===- ExprTypeConvert.cpp - Code to change an LLVM Expr Type -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the part of level raising that checks to see if it is
11 // possible to coerce an entire expression tree into a different type. If
12 // convertible, other routines from this file will do the conversion.
14 //===----------------------------------------------------------------------===//
16 #include "TransformInternals.h"
17 #include "llvm/iOther.h"
18 #include "llvm/iPHINode.h"
19 #include "llvm/iMemory.h"
20 #include "llvm/ConstantHandling.h"
21 #include "llvm/Analysis/Expressions.h"
22 #include "Support/STLExtras.h"
23 #include "Support/Debug.h"
28 static bool OperandConvertibleToType(User *U, Value *V, const Type *Ty,
29 ValueTypeCache &ConvertedTypes,
30 const TargetData &TD);
32 static void ConvertOperandToType(User *U, Value *OldVal, Value *NewVal,
33 ValueMapCache &VMC, const TargetData &TD);
35 // Peephole Malloc instructions: we take a look at the use chain of the
36 // malloc instruction, and try to find out if the following conditions hold:
37 // 1. The malloc is of the form: 'malloc [sbyte], uint <constant>'
38 // 2. The only users of the malloc are cast & add instructions
39 // 3. Of the cast instructions, there is only one destination pointer type
40 // [RTy] where the size of the pointed to object is equal to the number
41 // of bytes allocated.
43 // If these conditions hold, we convert the malloc to allocate an [RTy]
44 // element. TODO: This comment is out of date WRT arrays
46 static bool MallocConvertibleToType(MallocInst *MI, const Type *Ty,
47 ValueTypeCache &CTMap,
48 const TargetData &TD) {
49 if (!isa<PointerType>(Ty)) return false; // Malloc always returns pointers
51 // Deal with the type to allocate, not the pointer type...
52 Ty = cast<PointerType>(Ty)->getElementType();
53 if (!Ty->isSized()) return false; // Can only alloc something with a size
55 // Analyze the number of bytes allocated...
56 ExprType Expr = ClassifyExpression(MI->getArraySize());
58 // Get information about the base datatype being allocated, before & after
59 int ReqTypeSize = TD.getTypeSize(Ty);
60 if (ReqTypeSize == 0) return false;
61 unsigned OldTypeSize = TD.getTypeSize(MI->getType()->getElementType());
63 // Must have a scale or offset to analyze it...
64 if (!Expr.Offset && !Expr.Scale && OldTypeSize == 1) return false;
66 // Get the offset and scale of the allocation...
67 int64_t OffsetVal = Expr.Offset ? getConstantValue(Expr.Offset) : 0;
68 int64_t ScaleVal = Expr.Scale ? getConstantValue(Expr.Scale) :(Expr.Var != 0);
70 // The old type might not be of unit size, take old size into consideration
72 int64_t Offset = OffsetVal * OldTypeSize;
73 int64_t Scale = ScaleVal * OldTypeSize;
75 // In order to be successful, both the scale and the offset must be a multiple
76 // of the requested data type's size.
78 if (Offset/ReqTypeSize*ReqTypeSize != Offset ||
79 Scale/ReqTypeSize*ReqTypeSize != Scale)
80 return false; // Nope.
85 static Instruction *ConvertMallocToType(MallocInst *MI, const Type *Ty,
86 const std::string &Name,
88 const TargetData &TD){
89 BasicBlock *BB = MI->getParent();
90 BasicBlock::iterator It = BB->end();
92 // Analyze the number of bytes allocated...
93 ExprType Expr = ClassifyExpression(MI->getArraySize());
95 const PointerType *AllocTy = cast<PointerType>(Ty);
96 const Type *ElType = AllocTy->getElementType();
98 unsigned DataSize = TD.getTypeSize(ElType);
99 unsigned OldTypeSize = TD.getTypeSize(MI->getType()->getElementType());
101 // Get the offset and scale coefficients that we are allocating...
102 int64_t OffsetVal = (Expr.Offset ? getConstantValue(Expr.Offset) : 0);
103 int64_t ScaleVal = Expr.Scale ? getConstantValue(Expr.Scale) : (Expr.Var !=0);
105 // The old type might not be of unit size, take old size into consideration
107 unsigned Offset = (uint64_t)OffsetVal * OldTypeSize / DataSize;
108 unsigned Scale = (uint64_t)ScaleVal * OldTypeSize / DataSize;
110 // Locate the malloc instruction, because we may be inserting instructions
113 // If we have a scale, apply it first...
115 // Expr.Var is not necessarily unsigned right now, insert a cast now.
116 if (Expr.Var->getType() != Type::UIntTy)
117 Expr.Var = new CastInst(Expr.Var, Type::UIntTy,
118 Expr.Var->getName()+"-uint", It);
121 Expr.Var = BinaryOperator::create(Instruction::Mul, Expr.Var,
122 ConstantUInt::get(Type::UIntTy, Scale),
123 Expr.Var->getName()+"-scl", It);
126 // If we are not scaling anything, just make the offset be the "var"...
127 Expr.Var = ConstantUInt::get(Type::UIntTy, Offset);
128 Offset = 0; Scale = 1;
131 // If we have an offset now, add it in...
133 assert(Expr.Var && "Var must be nonnull by now!");
134 Expr.Var = BinaryOperator::create(Instruction::Add, Expr.Var,
135 ConstantUInt::get(Type::UIntTy, Offset),
136 Expr.Var->getName()+"-off", It);
139 assert(AllocTy == Ty);
140 return new MallocInst(AllocTy->getElementType(), Expr.Var, Name);
144 // ExpressionConvertibleToType - Return true if it is possible
145 bool ExpressionConvertibleToType(Value *V, const Type *Ty,
146 ValueTypeCache &CTMap, const TargetData &TD) {
147 // Expression type must be holdable in a register.
148 if (!Ty->isFirstClassType())
151 ValueTypeCache::iterator CTMI = CTMap.find(V);
152 if (CTMI != CTMap.end()) return CTMI->second == Ty;
154 // If it's a constant... all constants can be converted to a different
155 // type. We just ask the constant propagator to see if it can convert the
158 if (Constant *CPV = dyn_cast<Constant>(V))
159 return ConstantFoldCastInstruction(CPV, Ty);
162 if (V->getType() == Ty) return true; // Expression already correct type!
164 Instruction *I = dyn_cast<Instruction>(V);
165 if (I == 0) return false; // Otherwise, we can't convert!
167 switch (I->getOpcode()) {
168 case Instruction::Cast:
169 // We can convert the expr if the cast destination type is losslessly
170 // convertible to the requested type.
171 if (!Ty->isLosslesslyConvertibleTo(I->getType())) return false;
173 // We also do not allow conversion of a cast that casts from a ptr to array
174 // of X to a *X. For example: cast [4 x %List *] * %val to %List * *
176 if (const PointerType *SPT =
177 dyn_cast<PointerType>(I->getOperand(0)->getType()))
178 if (const PointerType *DPT = dyn_cast<PointerType>(I->getType()))
179 if (const ArrayType *AT = dyn_cast<ArrayType>(SPT->getElementType()))
180 if (AT->getElementType() == DPT->getElementType())
184 case Instruction::Add:
185 case Instruction::Sub:
186 if (!Ty->isInteger() && !Ty->isFloatingPoint()) return false;
187 if (!ExpressionConvertibleToType(I->getOperand(0), Ty, CTMap, TD) ||
188 !ExpressionConvertibleToType(I->getOperand(1), Ty, CTMap, TD))
191 case Instruction::Shr:
192 if (!Ty->isInteger()) return false;
193 if (Ty->isSigned() != V->getType()->isSigned()) return false;
195 case Instruction::Shl:
196 if (!Ty->isInteger()) return false;
197 if (!ExpressionConvertibleToType(I->getOperand(0), Ty, CTMap, TD))
201 case Instruction::Load: {
202 LoadInst *LI = cast<LoadInst>(I);
203 if (!ExpressionConvertibleToType(LI->getPointerOperand(),
204 PointerType::get(Ty), CTMap, TD))
208 case Instruction::PHI: {
209 PHINode *PN = cast<PHINode>(I);
210 for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i)
211 if (!ExpressionConvertibleToType(PN->getIncomingValue(i), Ty, CTMap, TD))
216 case Instruction::Malloc:
217 if (!MallocConvertibleToType(cast<MallocInst>(I), Ty, CTMap, TD))
221 case Instruction::GetElementPtr: {
222 // GetElementPtr's are directly convertible to a pointer type if they have
223 // a number of zeros at the end. Because removing these values does not
224 // change the logical offset of the GEP, it is okay and fair to remove them.
225 // This can change this:
226 // %t1 = getelementptr %Hosp * %hosp, ubyte 4, ubyte 0 ; <%List **>
227 // %t2 = cast %List * * %t1 to %List *
229 // %t2 = getelementptr %Hosp * %hosp, ubyte 4 ; <%List *>
231 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
232 const PointerType *PTy = dyn_cast<PointerType>(Ty);
233 if (!PTy) return false; // GEP must always return a pointer...
234 const Type *PVTy = PTy->getElementType();
236 // Check to see if there are zero elements that we can remove from the
237 // index array. If there are, check to see if removing them causes us to
238 // get to the right type...
240 std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
241 const Type *BaseType = GEP->getPointerOperand()->getType();
242 const Type *ElTy = 0;
244 while (!Indices.empty() &&
245 Indices.back() == Constant::getNullValue(Indices.back()->getType())){
247 ElTy = GetElementPtrInst::getIndexedType(BaseType, Indices, true);
249 break; // Found a match!!
253 if (ElTy) break; // Found a number of zeros we can strip off!
255 // Otherwise, we can convert a GEP from one form to the other iff the
256 // current gep is of the form 'getelementptr sbyte*, long N
257 // and we could convert this to an appropriate GEP for the new type.
259 if (GEP->getNumOperands() == 2 &&
260 GEP->getOperand(1)->getType() == Type::LongTy &&
261 GEP->getType() == PointerType::get(Type::SByteTy)) {
263 // Do not Check to see if our incoming pointer can be converted
264 // to be a ptr to an array of the right type... because in more cases than
265 // not, it is simply not analyzable because of pointer/array
266 // discrepancies. To fix this, we will insert a cast before the GEP.
269 // Check to see if 'N' is an expression that can be converted to
270 // the appropriate size... if so, allow it.
272 std::vector<Value*> Indices;
273 const Type *ElTy = ConvertibleToGEP(PTy, I->getOperand(1), Indices, TD);
275 if (!ExpressionConvertibleToType(I->getOperand(0),
276 PointerType::get(ElTy), CTMap, TD))
277 return false; // Can't continue, ExConToTy might have polluted set!
282 // Otherwise, it could be that we have something like this:
283 // getelementptr [[sbyte] *] * %reg115, long %reg138 ; [sbyte]**
284 // and want to convert it into something like this:
285 // getelemenptr [[int] *] * %reg115, long %reg138 ; [int]**
287 if (GEP->getNumOperands() == 2 &&
288 GEP->getOperand(1)->getType() == Type::LongTy &&
289 PTy->getElementType()->isSized() &&
290 TD.getTypeSize(PTy->getElementType()) ==
291 TD.getTypeSize(GEP->getType()->getElementType())) {
292 const PointerType *NewSrcTy = PointerType::get(PVTy);
293 if (!ExpressionConvertibleToType(I->getOperand(0), NewSrcTy, CTMap, TD))
298 return false; // No match, maybe next time.
301 case Instruction::Call: {
302 if (isa<Function>(I->getOperand(0)))
303 return false; // Don't even try to change direct calls.
305 // If this is a function pointer, we can convert the return type if we can
306 // convert the source function pointer.
308 const PointerType *PT = cast<PointerType>(I->getOperand(0)->getType());
309 const FunctionType *FT = cast<FunctionType>(PT->getElementType());
310 std::vector<const Type *> ArgTys(FT->getParamTypes().begin(),
311 FT->getParamTypes().end());
312 const FunctionType *NewTy =
313 FunctionType::get(Ty, ArgTys, FT->isVarArg());
314 if (!ExpressionConvertibleToType(I->getOperand(0),
315 PointerType::get(NewTy), CTMap, TD))
323 // Expressions are only convertible if all of the users of the expression can
324 // have this value converted. This makes use of the map to avoid infinite
327 for (Value::use_iterator It = I->use_begin(), E = I->use_end(); It != E; ++It)
328 if (!OperandConvertibleToType(*It, I, Ty, CTMap, TD))
335 Value *ConvertExpressionToType(Value *V, const Type *Ty, ValueMapCache &VMC,
336 const TargetData &TD) {
337 if (V->getType() == Ty) return V; // Already where we need to be?
339 ValueMapCache::ExprMapTy::iterator VMCI = VMC.ExprMap.find(V);
340 if (VMCI != VMC.ExprMap.end()) {
341 const Value *GV = VMCI->second;
342 const Type *GTy = VMCI->second->getType();
343 assert(VMCI->second->getType() == Ty);
345 if (Instruction *I = dyn_cast<Instruction>(V))
346 ValueHandle IHandle(VMC, I); // Remove I if it is unused now!
351 DEBUG(std::cerr << "CETT: " << (void*)V << " " << V);
353 Instruction *I = dyn_cast<Instruction>(V);
355 Constant *CPV = cast<Constant>(V);
356 // Constants are converted by constant folding the cast that is required.
357 // We assume here that all casts are implemented for constant prop.
358 Value *Result = ConstantFoldCastInstruction(CPV, Ty);
359 assert(Result && "ConstantFoldCastInstruction Failed!!!");
360 assert(Result->getType() == Ty && "Const prop of cast failed!");
362 // Add the instruction to the expression map
363 //VMC.ExprMap[V] = Result;
368 BasicBlock *BB = I->getParent();
369 std::string Name = I->getName(); if (!Name.empty()) I->setName("");
370 Instruction *Res; // Result of conversion
372 ValueHandle IHandle(VMC, I); // Prevent I from being removed!
374 Constant *Dummy = Constant::getNullValue(Ty);
376 switch (I->getOpcode()) {
377 case Instruction::Cast:
378 assert(VMC.NewCasts.count(ValueHandle(VMC, I)) == 0);
379 Res = new CastInst(I->getOperand(0), Ty, Name);
380 VMC.NewCasts.insert(ValueHandle(VMC, Res));
383 case Instruction::Add:
384 case Instruction::Sub:
385 Res = BinaryOperator::create(cast<BinaryOperator>(I)->getOpcode(),
387 VMC.ExprMap[I] = Res; // Add node to expression eagerly
389 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), Ty, VMC, TD));
390 Res->setOperand(1, ConvertExpressionToType(I->getOperand(1), Ty, VMC, TD));
393 case Instruction::Shl:
394 case Instruction::Shr:
395 Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(), Dummy,
396 I->getOperand(1), Name);
397 VMC.ExprMap[I] = Res;
398 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), Ty, VMC, TD));
401 case Instruction::Load: {
402 LoadInst *LI = cast<LoadInst>(I);
404 Res = new LoadInst(Constant::getNullValue(PointerType::get(Ty)), Name);
405 VMC.ExprMap[I] = Res;
406 Res->setOperand(0, ConvertExpressionToType(LI->getPointerOperand(),
407 PointerType::get(Ty), VMC, TD));
408 assert(Res->getOperand(0)->getType() == PointerType::get(Ty));
409 assert(Ty == Res->getType());
410 assert(Res->getType()->isFirstClassType() && "Load of structure or array!");
414 case Instruction::PHI: {
415 PHINode *OldPN = cast<PHINode>(I);
416 PHINode *NewPN = new PHINode(Ty, Name);
418 VMC.ExprMap[I] = NewPN; // Add node to expression eagerly
419 while (OldPN->getNumOperands()) {
420 BasicBlock *BB = OldPN->getIncomingBlock(0);
421 Value *OldVal = OldPN->getIncomingValue(0);
422 ValueHandle OldValHandle(VMC, OldVal);
423 OldPN->removeIncomingValue(BB, false);
424 Value *V = ConvertExpressionToType(OldVal, Ty, VMC, TD);
425 NewPN->addIncoming(V, BB);
431 case Instruction::Malloc: {
432 Res = ConvertMallocToType(cast<MallocInst>(I), Ty, Name, VMC, TD);
436 case Instruction::GetElementPtr: {
437 // GetElementPtr's are directly convertible to a pointer type if they have
438 // a number of zeros at the end. Because removing these values does not
439 // change the logical offset of the GEP, it is okay and fair to remove them.
440 // This can change this:
441 // %t1 = getelementptr %Hosp * %hosp, ubyte 4, ubyte 0 ; <%List **>
442 // %t2 = cast %List * * %t1 to %List *
444 // %t2 = getelementptr %Hosp * %hosp, ubyte 4 ; <%List *>
446 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
448 // Check to see if there are zero elements that we can remove from the
449 // index array. If there are, check to see if removing them causes us to
450 // get to the right type...
452 std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
453 const Type *BaseType = GEP->getPointerOperand()->getType();
454 const Type *PVTy = cast<PointerType>(Ty)->getElementType();
456 while (!Indices.empty() &&
457 Indices.back() == Constant::getNullValue(Indices.back()->getType())){
459 if (GetElementPtrInst::getIndexedType(BaseType, Indices, true) == PVTy) {
460 if (Indices.size() == 0)
461 Res = new CastInst(GEP->getPointerOperand(), BaseType); // NOOP CAST
463 Res = new GetElementPtrInst(GEP->getPointerOperand(), Indices, Name);
468 if (Res == 0 && GEP->getNumOperands() == 2 &&
469 GEP->getOperand(1)->getType() == Type::LongTy &&
470 GEP->getType() == PointerType::get(Type::SByteTy)) {
472 // Otherwise, we can convert a GEP from one form to the other iff the
473 // current gep is of the form 'getelementptr [sbyte]*, unsigned N
474 // and we could convert this to an appropriate GEP for the new type.
476 const PointerType *NewSrcTy = PointerType::get(PVTy);
477 BasicBlock::iterator It = I;
479 // Check to see if 'N' is an expression that can be converted to
480 // the appropriate size... if so, allow it.
482 std::vector<Value*> Indices;
483 const Type *ElTy = ConvertibleToGEP(NewSrcTy, I->getOperand(1),
486 assert(ElTy == PVTy && "Internal error, setup wrong!");
487 Res = new GetElementPtrInst(Constant::getNullValue(NewSrcTy),
489 VMC.ExprMap[I] = Res;
490 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
495 // Otherwise, it could be that we have something like this:
496 // getelementptr [[sbyte] *] * %reg115, uint %reg138 ; [sbyte]**
497 // and want to convert it into something like this:
498 // getelemenptr [[int] *] * %reg115, uint %reg138 ; [int]**
501 const PointerType *NewSrcTy = PointerType::get(PVTy);
502 std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
503 Res = new GetElementPtrInst(Constant::getNullValue(NewSrcTy),
505 VMC.ExprMap[I] = Res;
506 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
511 assert(Res && "Didn't find match!");
515 case Instruction::Call: {
516 assert(!isa<Function>(I->getOperand(0)));
518 // If this is a function pointer, we can convert the return type if we can
519 // convert the source function pointer.
521 const PointerType *PT = cast<PointerType>(I->getOperand(0)->getType());
522 const FunctionType *FT = cast<FunctionType>(PT->getElementType());
523 std::vector<const Type *> ArgTys(FT->getParamTypes().begin(),
524 FT->getParamTypes().end());
525 const FunctionType *NewTy =
526 FunctionType::get(Ty, ArgTys, FT->isVarArg());
527 const PointerType *NewPTy = PointerType::get(NewTy);
528 if (Ty == Type::VoidTy)
529 Name = ""; // Make sure not to name calls that now return void!
531 Res = new CallInst(Constant::getNullValue(NewPTy),
532 std::vector<Value*>(I->op_begin()+1, I->op_end()),
534 VMC.ExprMap[I] = Res;
535 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),NewPTy,VMC,TD));
539 assert(0 && "Expression convertible, but don't know how to convert?");
543 assert(Res->getType() == Ty && "Didn't convert expr to correct type!");
545 BB->getInstList().insert(I, Res);
547 // Add the instruction to the expression map
548 VMC.ExprMap[I] = Res;
551 unsigned NumUses = I->use_size();
552 for (unsigned It = 0; It < NumUses; ) {
553 unsigned OldSize = NumUses;
554 Value::use_iterator UI = I->use_begin();
555 std::advance(UI, It);
556 ConvertOperandToType(*UI, I, Res, VMC, TD);
557 NumUses = I->use_size();
558 if (NumUses == OldSize) ++It;
561 DEBUG(std::cerr << "ExpIn: " << (void*)I << " " << I
562 << "ExpOut: " << (void*)Res << " " << Res);
569 // ValueConvertibleToType - Return true if it is possible
570 bool ValueConvertibleToType(Value *V, const Type *Ty,
571 ValueTypeCache &ConvertedTypes,
572 const TargetData &TD) {
573 ValueTypeCache::iterator I = ConvertedTypes.find(V);
574 if (I != ConvertedTypes.end()) return I->second == Ty;
575 ConvertedTypes[V] = Ty;
577 // It is safe to convert the specified value to the specified type IFF all of
578 // the uses of the value can be converted to accept the new typed value.
580 if (V->getType() != Ty) {
581 for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I)
582 if (!OperandConvertibleToType(*I, V, Ty, ConvertedTypes, TD))
593 // OperandConvertibleToType - Return true if it is possible to convert operand
594 // V of User (instruction) U to the specified type. This is true iff it is
595 // possible to change the specified instruction to accept this. CTMap is a map
596 // of converted types, so that circular definitions will see the future type of
597 // the expression, not the static current type.
599 static bool OperandConvertibleToType(User *U, Value *V, const Type *Ty,
600 ValueTypeCache &CTMap,
601 const TargetData &TD) {
602 // if (V->getType() == Ty) return true; // Operand already the right type?
604 // Expression type must be holdable in a register.
605 if (!Ty->isFirstClassType())
608 Instruction *I = dyn_cast<Instruction>(U);
609 if (I == 0) return false; // We can't convert!
611 switch (I->getOpcode()) {
612 case Instruction::Cast:
613 assert(I->getOperand(0) == V);
614 // We can convert the expr if the cast destination type is losslessly
615 // convertible to the requested type.
616 // Also, do not change a cast that is a noop cast. For all intents and
617 // purposes it should be eliminated.
618 if (!Ty->isLosslesslyConvertibleTo(I->getOperand(0)->getType()) ||
619 I->getType() == I->getOperand(0)->getType())
622 // Do not allow a 'cast ushort %V to uint' to have it's first operand be
623 // converted to a 'short' type. Doing so changes the way sign promotion
624 // happens, and breaks things. Only allow the cast to take place if the
625 // signedness doesn't change... or if the current cast is not a lossy
628 if (!I->getType()->isLosslesslyConvertibleTo(I->getOperand(0)->getType()) &&
629 I->getOperand(0)->getType()->isSigned() != Ty->isSigned())
632 // We also do not allow conversion of a cast that casts from a ptr to array
633 // of X to a *X. For example: cast [4 x %List *] * %val to %List * *
635 if (const PointerType *SPT =
636 dyn_cast<PointerType>(I->getOperand(0)->getType()))
637 if (const PointerType *DPT = dyn_cast<PointerType>(I->getType()))
638 if (const ArrayType *AT = dyn_cast<ArrayType>(SPT->getElementType()))
639 if (AT->getElementType() == DPT->getElementType())
643 case Instruction::Add:
644 if (isa<PointerType>(Ty)) {
645 Value *IndexVal = I->getOperand(V == I->getOperand(0) ? 1 : 0);
646 std::vector<Value*> Indices;
647 if (const Type *ETy = ConvertibleToGEP(Ty, IndexVal, Indices, TD)) {
648 const Type *RetTy = PointerType::get(ETy);
650 // Only successful if we can convert this type to the required type
651 if (ValueConvertibleToType(I, RetTy, CTMap, TD)) {
655 // We have to return failure here because ValueConvertibleToType could
656 // have polluted our map
661 case Instruction::Sub: {
662 if (!Ty->isInteger() && !Ty->isFloatingPoint()) return false;
664 Value *OtherOp = I->getOperand((V == I->getOperand(0)) ? 1 : 0);
665 return ValueConvertibleToType(I, Ty, CTMap, TD) &&
666 ExpressionConvertibleToType(OtherOp, Ty, CTMap, TD);
668 case Instruction::SetEQ:
669 case Instruction::SetNE: {
670 Value *OtherOp = I->getOperand((V == I->getOperand(0)) ? 1 : 0);
671 return ExpressionConvertibleToType(OtherOp, Ty, CTMap, TD);
673 case Instruction::Shr:
674 if (Ty->isSigned() != V->getType()->isSigned()) return false;
676 case Instruction::Shl:
677 if (I->getOperand(1) == V) return false; // Cannot change shift amount type
678 if (!Ty->isInteger()) return false;
679 return ValueConvertibleToType(I, Ty, CTMap, TD);
681 case Instruction::Free:
682 assert(I->getOperand(0) == V);
683 return isa<PointerType>(Ty); // Free can free any pointer type!
685 case Instruction::Load:
686 // Cannot convert the types of any subscripts...
687 if (I->getOperand(0) != V) return false;
689 if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
690 LoadInst *LI = cast<LoadInst>(I);
692 const Type *LoadedTy = PT->getElementType();
694 // They could be loading the first element of a composite type...
695 if (const CompositeType *CT = dyn_cast<CompositeType>(LoadedTy)) {
696 unsigned Offset = 0; // No offset, get first leaf.
697 std::vector<Value*> Indices; // Discarded...
698 LoadedTy = getStructOffsetType(CT, Offset, Indices, TD, false);
699 assert(Offset == 0 && "Offset changed from zero???");
702 if (!LoadedTy->isFirstClassType())
705 if (TD.getTypeSize(LoadedTy) != TD.getTypeSize(LI->getType()))
708 return ValueConvertibleToType(LI, LoadedTy, CTMap, TD);
712 case Instruction::Store: {
713 StoreInst *SI = cast<StoreInst>(I);
715 if (V == I->getOperand(0)) {
716 ValueTypeCache::iterator CTMI = CTMap.find(I->getOperand(1));
717 if (CTMI != CTMap.end()) { // Operand #1 is in the table already?
718 // If so, check to see if it's Ty*, or, more importantly, if it is a
719 // pointer to a structure where the first element is a Ty... this code
720 // is necessary because we might be trying to change the source and
721 // destination type of the store (they might be related) and the dest
722 // pointer type might be a pointer to structure. Below we allow pointer
723 // to structures where the 0th element is compatible with the value,
724 // now we have to support the symmetrical part of this.
726 const Type *ElTy = cast<PointerType>(CTMI->second)->getElementType();
728 // Already a pointer to what we want? Trivially accept...
729 if (ElTy == Ty) return true;
731 // Tricky case now, if the destination is a pointer to structure,
732 // obviously the source is not allowed to be a structure (cannot copy
733 // a whole structure at a time), so the level raiser must be trying to
734 // store into the first field. Check for this and allow it now:
736 if (const StructType *SElTy = dyn_cast<StructType>(ElTy)) {
738 std::vector<Value*> Indices;
739 ElTy = getStructOffsetType(ElTy, Offset, Indices, TD, false);
740 assert(Offset == 0 && "Offset changed!");
741 if (ElTy == 0) // Element at offset zero in struct doesn't exist!
742 return false; // Can only happen for {}*
744 if (ElTy == Ty) // Looks like the 0th element of structure is
745 return true; // compatible! Accept now!
747 // Otherwise we know that we can't work, so just stop trying now.
752 // Can convert the store if we can convert the pointer operand to match
753 // the new value type...
754 return ExpressionConvertibleToType(I->getOperand(1), PointerType::get(Ty),
756 } else if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
757 const Type *ElTy = PT->getElementType();
758 assert(V == I->getOperand(1));
760 if (isa<StructType>(ElTy)) {
761 // We can change the destination pointer if we can store our first
762 // argument into the first element of the structure...
765 std::vector<Value*> Indices;
766 ElTy = getStructOffsetType(ElTy, Offset, Indices, TD, false);
767 assert(Offset == 0 && "Offset changed!");
768 if (ElTy == 0) // Element at offset zero in struct doesn't exist!
769 return false; // Can only happen for {}*
772 // Must move the same amount of data...
773 if (!ElTy->isSized() ||
774 TD.getTypeSize(ElTy) != TD.getTypeSize(I->getOperand(0)->getType()))
777 // Can convert store if the incoming value is convertible...
778 return ExpressionConvertibleToType(I->getOperand(0), ElTy, CTMap, TD);
783 case Instruction::GetElementPtr:
784 if (V != I->getOperand(0) || !isa<PointerType>(Ty)) return false;
786 // If we have a two operand form of getelementptr, this is really little
787 // more than a simple addition. As with addition, check to see if the
788 // getelementptr instruction can be changed to index into the new type.
790 if (I->getNumOperands() == 2) {
791 const Type *OldElTy = cast<PointerType>(I->getType())->getElementType();
792 unsigned DataSize = TD.getTypeSize(OldElTy);
793 Value *Index = I->getOperand(1);
794 Instruction *TempScale = 0;
796 // If the old data element is not unit sized, we have to create a scale
797 // instruction so that ConvertibleToGEP will know the REAL amount we are
798 // indexing by. Note that this is never inserted into the instruction
799 // stream, so we have to delete it when we're done.
802 TempScale = BinaryOperator::create(Instruction::Mul, Index,
803 ConstantSInt::get(Type::LongTy,
808 // Check to see if the second argument is an expression that can
809 // be converted to the appropriate size... if so, allow it.
811 std::vector<Value*> Indices;
812 const Type *ElTy = ConvertibleToGEP(Ty, Index, Indices, TD);
813 delete TempScale; // Free our temporary multiply if we made it
815 if (ElTy == 0) return false; // Cannot make conversion...
816 return ValueConvertibleToType(I, PointerType::get(ElTy), CTMap, TD);
820 case Instruction::PHI: {
821 PHINode *PN = cast<PHINode>(I);
822 for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i)
823 if (!ExpressionConvertibleToType(PN->getIncomingValue(i), Ty, CTMap, TD))
825 return ValueConvertibleToType(PN, Ty, CTMap, TD);
828 case Instruction::Call: {
829 User::op_iterator OI = find(I->op_begin(), I->op_end(), V);
830 assert (OI != I->op_end() && "Not using value!");
831 unsigned OpNum = OI - I->op_begin();
833 // Are we trying to change the function pointer value to a new type?
835 const PointerType *PTy = dyn_cast<PointerType>(Ty);
836 if (PTy == 0) return false; // Can't convert to a non-pointer type...
837 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
838 if (FTy == 0) return false; // Can't convert to a non ptr to function...
840 // Do not allow converting to a call where all of the operands are ...'s
841 if (FTy->getNumParams() == 0 && FTy->isVarArg())
842 return false; // Do not permit this conversion!
844 // Perform sanity checks to make sure that new function type has the
845 // correct number of arguments...
847 unsigned NumArgs = I->getNumOperands()-1; // Don't include function ptr
849 // Cannot convert to a type that requires more fixed arguments than
850 // the call provides...
852 if (NumArgs < FTy->getNumParams()) return false;
854 // Unless this is a vararg function type, we cannot provide more arguments
855 // than are desired...
857 if (!FTy->isVarArg() && NumArgs > FTy->getNumParams())
860 // Okay, at this point, we know that the call and the function type match
861 // number of arguments. Now we see if we can convert the arguments
862 // themselves. Note that we do not require operands to be convertible,
863 // we can insert casts if they are convertible but not compatible. The
864 // reason for this is that we prefer to have resolved functions but casted
865 // arguments if possible.
867 const FunctionType::ParamTypes &PTs = FTy->getParamTypes();
868 for (unsigned i = 0, NA = PTs.size(); i < NA; ++i)
869 if (!PTs[i]->isLosslesslyConvertibleTo(I->getOperand(i+1)->getType()))
870 return false; // Operands must have compatible types!
872 // Okay, at this point, we know that all of the arguments can be
873 // converted. We succeed if we can change the return type if
876 return ValueConvertibleToType(I, FTy->getReturnType(), CTMap, TD);
879 const PointerType *MPtr = cast<PointerType>(I->getOperand(0)->getType());
880 const FunctionType *FTy = cast<FunctionType>(MPtr->getElementType());
881 if (!FTy->isVarArg()) return false;
883 if ((OpNum-1) < FTy->getParamTypes().size())
884 return false; // It's not in the varargs section...
886 // If we get this far, we know the value is in the varargs section of the
887 // function! We can convert if we don't reinterpret the value...
889 return Ty->isLosslesslyConvertibleTo(V->getType());
896 void ConvertValueToNewType(Value *V, Value *NewVal, ValueMapCache &VMC,
897 const TargetData &TD) {
898 ValueHandle VH(VMC, V);
900 unsigned NumUses = V->use_size();
901 for (unsigned It = 0; It < NumUses; ) {
902 unsigned OldSize = NumUses;
903 Value::use_iterator UI = V->use_begin();
904 std::advance(UI, It);
905 ConvertOperandToType(*UI, V, NewVal, VMC, TD);
906 NumUses = V->use_size();
907 if (NumUses == OldSize) ++It;
913 static void ConvertOperandToType(User *U, Value *OldVal, Value *NewVal,
914 ValueMapCache &VMC, const TargetData &TD) {
915 if (isa<ValueHandle>(U)) return; // Valuehandles don't let go of operands...
917 if (VMC.OperandsMapped.count(U)) return;
918 VMC.OperandsMapped.insert(U);
920 ValueMapCache::ExprMapTy::iterator VMCI = VMC.ExprMap.find(U);
921 if (VMCI != VMC.ExprMap.end())
925 Instruction *I = cast<Instruction>(U); // Only Instructions convertible
927 BasicBlock *BB = I->getParent();
928 assert(BB != 0 && "Instruction not embedded in basic block!");
929 std::string Name = I->getName();
931 Instruction *Res; // Result of conversion
933 //std::cerr << endl << endl << "Type:\t" << Ty << "\nInst: " << I
934 // << "BB Before: " << BB << endl;
936 // Prevent I from being removed...
937 ValueHandle IHandle(VMC, I);
939 const Type *NewTy = NewVal->getType();
940 Constant *Dummy = (NewTy != Type::VoidTy) ?
941 Constant::getNullValue(NewTy) : 0;
943 switch (I->getOpcode()) {
944 case Instruction::Cast:
945 if (VMC.NewCasts.count(ValueHandle(VMC, I))) {
946 // This cast has already had it's value converted, causing a new cast to
947 // be created. We don't want to create YET ANOTHER cast instruction
948 // representing the original one, so just modify the operand of this cast
949 // instruction, which we know is newly created.
950 I->setOperand(0, NewVal);
951 I->setName(Name); // give I its name back
955 Res = new CastInst(NewVal, I->getType(), Name);
959 case Instruction::Add:
960 if (isa<PointerType>(NewTy)) {
961 Value *IndexVal = I->getOperand(OldVal == I->getOperand(0) ? 1 : 0);
962 std::vector<Value*> Indices;
963 BasicBlock::iterator It = I;
965 if (const Type *ETy = ConvertibleToGEP(NewTy, IndexVal, Indices, TD,&It)){
966 // If successful, convert the add to a GEP
967 //const Type *RetTy = PointerType::get(ETy);
968 // First operand is actually the given pointer...
969 Res = new GetElementPtrInst(NewVal, Indices, Name);
970 assert(cast<PointerType>(Res->getType())->getElementType() == ETy &&
971 "ConvertibleToGEP broken!");
977 case Instruction::Sub:
978 case Instruction::SetEQ:
979 case Instruction::SetNE: {
980 Res = BinaryOperator::create(cast<BinaryOperator>(I)->getOpcode(),
982 VMC.ExprMap[I] = Res; // Add node to expression eagerly
984 unsigned OtherIdx = (OldVal == I->getOperand(0)) ? 1 : 0;
985 Value *OtherOp = I->getOperand(OtherIdx);
986 Value *NewOther = ConvertExpressionToType(OtherOp, NewTy, VMC, TD);
988 Res->setOperand(OtherIdx, NewOther);
989 Res->setOperand(!OtherIdx, NewVal);
992 case Instruction::Shl:
993 case Instruction::Shr:
994 assert(I->getOperand(0) == OldVal);
995 Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(), NewVal,
996 I->getOperand(1), Name);
999 case Instruction::Free: // Free can free any pointer type!
1000 assert(I->getOperand(0) == OldVal);
1001 Res = new FreeInst(NewVal);
1005 case Instruction::Load: {
1006 assert(I->getOperand(0) == OldVal && isa<PointerType>(NewVal->getType()));
1007 const Type *LoadedTy =
1008 cast<PointerType>(NewVal->getType())->getElementType();
1010 Value *Src = NewVal;
1012 if (const CompositeType *CT = dyn_cast<CompositeType>(LoadedTy)) {
1013 std::vector<Value*> Indices;
1014 Indices.push_back(ConstantSInt::get(Type::LongTy, 0));
1016 unsigned Offset = 0; // No offset, get first leaf.
1017 LoadedTy = getStructOffsetType(CT, Offset, Indices, TD, false);
1018 assert(LoadedTy->isFirstClassType());
1020 if (Indices.size() != 1) { // Do not generate load X, 0
1021 // Insert the GEP instruction before this load.
1022 Src = new GetElementPtrInst(Src, Indices, Name+".idx", I);
1026 Res = new LoadInst(Src, Name);
1027 assert(Res->getType()->isFirstClassType() && "Load of structure or array!");
1031 case Instruction::Store: {
1032 if (I->getOperand(0) == OldVal) { // Replace the source value
1033 // Check to see if operand #1 has already been converted...
1034 ValueMapCache::ExprMapTy::iterator VMCI =
1035 VMC.ExprMap.find(I->getOperand(1));
1036 if (VMCI != VMC.ExprMap.end()) {
1037 // Comments describing this stuff are in the OperandConvertibleToType
1038 // switch statement for Store...
1041 cast<PointerType>(VMCI->second->getType())->getElementType();
1043 Value *SrcPtr = VMCI->second;
1045 if (ElTy != NewTy) {
1046 // We check that this is a struct in the initial scan...
1047 const StructType *SElTy = cast<StructType>(ElTy);
1049 std::vector<Value*> Indices;
1050 Indices.push_back(Constant::getNullValue(Type::LongTy));
1052 unsigned Offset = 0;
1053 const Type *Ty = getStructOffsetType(ElTy, Offset, Indices, TD,false);
1054 assert(Offset == 0 && "Offset changed!");
1055 assert(NewTy == Ty && "Did not convert to correct type!");
1057 // Insert the GEP instruction before this store.
1058 SrcPtr = new GetElementPtrInst(SrcPtr, Indices,
1059 SrcPtr->getName()+".idx", I);
1061 Res = new StoreInst(NewVal, SrcPtr);
1063 VMC.ExprMap[I] = Res;
1065 // Otherwise, we haven't converted Operand #1 over yet...
1066 const PointerType *NewPT = PointerType::get(NewTy);
1067 Res = new StoreInst(NewVal, Constant::getNullValue(NewPT));
1068 VMC.ExprMap[I] = Res;
1069 Res->setOperand(1, ConvertExpressionToType(I->getOperand(1),
1072 } else { // Replace the source pointer
1073 const Type *ValTy = cast<PointerType>(NewTy)->getElementType();
1075 Value *SrcPtr = NewVal;
1077 if (isa<StructType>(ValTy)) {
1078 std::vector<Value*> Indices;
1079 Indices.push_back(Constant::getNullValue(Type::LongTy));
1081 unsigned Offset = 0;
1082 ValTy = getStructOffsetType(ValTy, Offset, Indices, TD, false);
1084 assert(Offset == 0 && ValTy);
1086 // Insert the GEP instruction before this store.
1087 SrcPtr = new GetElementPtrInst(SrcPtr, Indices,
1088 SrcPtr->getName()+".idx", I);
1091 Res = new StoreInst(Constant::getNullValue(ValTy), SrcPtr);
1092 VMC.ExprMap[I] = Res;
1093 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
1100 case Instruction::GetElementPtr: {
1101 // Convert a one index getelementptr into just about anything that is
1104 BasicBlock::iterator It = I;
1105 const Type *OldElTy = cast<PointerType>(I->getType())->getElementType();
1106 unsigned DataSize = TD.getTypeSize(OldElTy);
1107 Value *Index = I->getOperand(1);
1109 if (DataSize != 1) {
1110 // Insert a multiply of the old element type is not a unit size...
1111 Index = BinaryOperator::create(Instruction::Mul, Index,
1112 ConstantSInt::get(Type::LongTy, DataSize),
1116 // Perform the conversion now...
1118 std::vector<Value*> Indices;
1119 const Type *ElTy = ConvertibleToGEP(NewVal->getType(),Index,Indices,TD,&It);
1120 assert(ElTy != 0 && "GEP Conversion Failure!");
1121 Res = new GetElementPtrInst(NewVal, Indices, Name);
1122 assert(Res->getType() == PointerType::get(ElTy) &&
1123 "ConvertibleToGet failed!");
1126 if (I->getType() == PointerType::get(Type::SByteTy)) {
1127 // Convert a getelementptr sbyte * %reg111, uint 16 freely back to
1128 // anything that is a pointer type...
1130 BasicBlock::iterator It = I;
1132 // Check to see if the second argument is an expression that can
1133 // be converted to the appropriate size... if so, allow it.
1135 std::vector<Value*> Indices;
1136 const Type *ElTy = ConvertibleToGEP(NewVal->getType(), I->getOperand(1),
1138 assert(ElTy != 0 && "GEP Conversion Failure!");
1140 Res = new GetElementPtrInst(NewVal, Indices, Name);
1142 // Convert a getelementptr ulong * %reg123, uint %N
1143 // to getelementptr long * %reg123, uint %N
1144 // ... where the type must simply stay the same size...
1146 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
1147 std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
1148 Res = new GetElementPtrInst(NewVal, Indices, Name);
1153 case Instruction::PHI: {
1154 PHINode *OldPN = cast<PHINode>(I);
1155 PHINode *NewPN = new PHINode(NewTy, Name);
1156 VMC.ExprMap[I] = NewPN;
1158 while (OldPN->getNumOperands()) {
1159 BasicBlock *BB = OldPN->getIncomingBlock(0);
1160 Value *OldVal = OldPN->getIncomingValue(0);
1161 OldPN->removeIncomingValue(BB, false);
1162 Value *V = ConvertExpressionToType(OldVal, NewTy, VMC, TD);
1163 NewPN->addIncoming(V, BB);
1169 case Instruction::Call: {
1170 Value *Meth = I->getOperand(0);
1171 std::vector<Value*> Params(I->op_begin()+1, I->op_end());
1173 if (Meth == OldVal) { // Changing the function pointer?
1174 const PointerType *NewPTy = cast<PointerType>(NewVal->getType());
1175 const FunctionType *NewTy = cast<FunctionType>(NewPTy->getElementType());
1176 const FunctionType::ParamTypes &PTs = NewTy->getParamTypes();
1178 if (NewTy->getReturnType() == Type::VoidTy)
1179 Name = ""; // Make sure not to name a void call!
1181 // Get an iterator to the call instruction so that we can insert casts for
1182 // operands if need be. Note that we do not require operands to be
1183 // convertible, we can insert casts if they are convertible but not
1184 // compatible. The reason for this is that we prefer to have resolved
1185 // functions but casted arguments if possible.
1187 BasicBlock::iterator It = I;
1189 // Convert over all of the call operands to their new types... but only
1190 // convert over the part that is not in the vararg section of the call.
1192 for (unsigned i = 0; i < PTs.size(); ++i)
1193 if (Params[i]->getType() != PTs[i]) {
1194 // Create a cast to convert it to the right type, we know that this
1195 // is a lossless cast...
1197 Params[i] = new CastInst(Params[i], PTs[i], "callarg.cast." +
1198 Params[i]->getName(), It);
1200 Meth = NewVal; // Update call destination to new value
1202 } else { // Changing an argument, must be in vararg area
1203 std::vector<Value*>::iterator OI =
1204 find(Params.begin(), Params.end(), OldVal);
1205 assert (OI != Params.end() && "Not using value!");
1210 Res = new CallInst(Meth, Params, Name);
1214 assert(0 && "Expression convertible, but don't know how to convert?");
1218 // If the instruction was newly created, insert it into the instruction
1221 BasicBlock::iterator It = I;
1222 assert(It != BB->end() && "Instruction not in own basic block??");
1223 BB->getInstList().insert(It, Res); // Keep It pointing to old instruction
1225 DEBUG(std::cerr << "COT CREATED: " << (void*)Res << " " << Res
1226 << "In: " << (void*)I << " " << I << "Out: " << (void*)Res
1229 // Add the instruction to the expression map
1230 VMC.ExprMap[I] = Res;
1232 if (I->getType() != Res->getType())
1233 ConvertValueToNewType(I, Res, VMC, TD);
1235 bool FromStart = true;
1236 Value::use_iterator UI;
1238 if (FromStart) UI = I->use_begin();
1239 if (UI == I->use_end()) break;
1241 if (isa<ValueHandle>(*UI)) {
1246 if (!FromStart) --UI;
1247 U->replaceUsesOfWith(I, Res);
1248 if (!FromStart) ++UI;
1255 ValueHandle::ValueHandle(ValueMapCache &VMC, Value *V)
1256 : Instruction(Type::VoidTy, UserOp1, ""), Cache(VMC) {
1257 //DEBUG(std::cerr << "VH AQUIRING: " << (void*)V << " " << V);
1258 Operands.push_back(Use(V, this));
1261 ValueHandle::ValueHandle(const ValueHandle &VH)
1262 : Instruction(Type::VoidTy, UserOp1, ""), Cache(VH.Cache) {
1263 //DEBUG(std::cerr << "VH AQUIRING: " << (void*)V << " " << V);
1264 Operands.push_back(Use((Value*)VH.getOperand(0), this));
1267 static void RecursiveDelete(ValueMapCache &Cache, Instruction *I) {
1268 if (!I || !I->use_empty()) return;
1270 assert(I->getParent() && "Inst not in basic block!");
1272 //DEBUG(std::cerr << "VH DELETING: " << (void*)I << " " << I);
1274 for (User::op_iterator OI = I->op_begin(), OE = I->op_end();
1276 if (Instruction *U = dyn_cast<Instruction>(OI)) {
1278 RecursiveDelete(Cache, U);
1281 I->getParent()->getInstList().remove(I);
1283 Cache.OperandsMapped.erase(I);
1284 Cache.ExprMap.erase(I);
1288 ValueHandle::~ValueHandle() {
1289 if (Operands[0]->hasOneUse()) {
1290 Value *V = Operands[0];
1291 Operands[0] = 0; // Drop use!
1293 // Now we just need to remove the old instruction so we don't get infinite
1294 // loops. Note that we cannot use DCE because DCE won't remove a store
1295 // instruction, for example.
1297 RecursiveDelete(Cache, dyn_cast<Instruction>(V));
1299 //DEBUG(std::cerr << "VH RELEASING: " << (void*)Operands[0].get() << " "
1300 // << Operands[0]->use_size() << " " << Operands[0]);
1304 } // End llvm namespace