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/Constants.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Analysis/Expressions.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/Support/Debug.h"
25 static bool OperandConvertibleToType(User *U, Value *V, const Type *Ty,
26 ValueTypeCache &ConvertedTypes,
27 const TargetData &TD);
29 static void ConvertOperandToType(User *U, Value *OldVal, Value *NewVal,
30 ValueMapCache &VMC, const TargetData &TD);
32 // Peephole Malloc instructions: we take a look at the use chain of the
33 // malloc instruction, and try to find out if the following conditions hold:
34 // 1. The malloc is of the form: 'malloc [sbyte], uint <constant>'
35 // 2. The only users of the malloc are cast & add instructions
36 // 3. Of the cast instructions, there is only one destination pointer type
37 // [RTy] where the size of the pointed to object is equal to the number
38 // of bytes allocated.
40 // If these conditions hold, we convert the malloc to allocate an [RTy]
41 // element. TODO: This comment is out of date WRT arrays
43 static bool MallocConvertibleToType(MallocInst *MI, const Type *Ty,
44 ValueTypeCache &CTMap,
45 const TargetData &TD) {
46 if (!isa<PointerType>(Ty)) return false; // Malloc always returns pointers
48 // Deal with the type to allocate, not the pointer type...
49 Ty = cast<PointerType>(Ty)->getElementType();
50 if (!Ty->isSized() || !MI->getType()->getElementType()->isSized())
51 return false; // Can only alloc something with a size
53 // Analyze the number of bytes allocated...
54 ExprType Expr = ClassifyExpr(MI->getArraySize());
56 // Get information about the base datatype being allocated, before & after
57 uint64_t ReqTypeSize = TD.getTypeSize(Ty);
58 if (ReqTypeSize == 0) return false;
59 uint64_t OldTypeSize = TD.getTypeSize(MI->getType()->getElementType());
61 // Must have a scale or offset to analyze it...
62 if (!Expr.Offset && !Expr.Scale && OldTypeSize == 1) return false;
64 // Get the offset and scale of the allocation...
65 int64_t OffsetVal = Expr.Offset ? getConstantValue(Expr.Offset) : 0;
66 int64_t ScaleVal = Expr.Scale ? getConstantValue(Expr.Scale) :(Expr.Var != 0);
68 // The old type might not be of unit size, take old size into consideration
70 uint64_t Offset = OffsetVal * OldTypeSize;
71 uint64_t Scale = ScaleVal * OldTypeSize;
73 // In order to be successful, both the scale and the offset must be a multiple
74 // of the requested data type's size.
76 if (Offset/ReqTypeSize*ReqTypeSize != Offset ||
77 Scale/ReqTypeSize*ReqTypeSize != Scale)
78 return false; // Nope.
83 static Instruction *ConvertMallocToType(MallocInst *MI, const Type *Ty,
84 const std::string &Name,
86 const TargetData &TD){
87 BasicBlock *BB = MI->getParent();
88 BasicBlock::iterator It = BB->end();
90 // Analyze the number of bytes allocated...
91 ExprType Expr = ClassifyExpr(MI->getArraySize());
93 const PointerType *AllocTy = cast<PointerType>(Ty);
94 const Type *ElType = AllocTy->getElementType();
96 uint64_t DataSize = TD.getTypeSize(ElType);
97 uint64_t OldTypeSize = TD.getTypeSize(MI->getType()->getElementType());
99 // Get the offset and scale coefficients that we are allocating...
100 int64_t OffsetVal = (Expr.Offset ? getConstantValue(Expr.Offset) : 0);
101 int64_t ScaleVal = Expr.Scale ? getConstantValue(Expr.Scale) : (Expr.Var !=0);
103 // The old type might not be of unit size, take old size into consideration
105 unsigned Offset = OffsetVal * OldTypeSize / DataSize;
106 unsigned Scale = ScaleVal * OldTypeSize / DataSize;
108 // Locate the malloc instruction, because we may be inserting instructions
111 // If we have a scale, apply it first...
113 // Expr.Var is not necessarily unsigned right now, insert a cast now.
114 if (Expr.Var->getType() != Type::UIntTy)
115 Expr.Var = new CastInst(Expr.Var, Type::UIntTy,
116 Expr.Var->getName()+"-uint", It);
119 Expr.Var = BinaryOperator::create(Instruction::Mul, Expr.Var,
120 ConstantUInt::get(Type::UIntTy, Scale),
121 Expr.Var->getName()+"-scl", It);
124 // If we are not scaling anything, just make the offset be the "var"...
125 Expr.Var = ConstantUInt::get(Type::UIntTy, Offset);
126 Offset = 0; Scale = 1;
129 // If we have an offset now, add it in...
131 assert(Expr.Var && "Var must be nonnull by now!");
132 Expr.Var = BinaryOperator::create(Instruction::Add, Expr.Var,
133 ConstantUInt::get(Type::UIntTy, Offset),
134 Expr.Var->getName()+"-off", It);
137 assert(AllocTy == Ty);
138 return new MallocInst(AllocTy->getElementType(), Expr.Var, Name);
142 // ExpressionConvertibleToType - Return true if it is possible
143 bool llvm::ExpressionConvertibleToType(Value *V, const Type *Ty,
144 ValueTypeCache &CTMap, const TargetData &TD) {
145 // Expression type must be holdable in a register.
146 if (!Ty->isFirstClassType())
149 ValueTypeCache::iterator CTMI = CTMap.find(V);
150 if (CTMI != CTMap.end()) return CTMI->second == Ty;
152 // If it's a constant... all constants can be converted to a different
155 if (isa<Constant>(V) && !isa<GlobalValue>(V))
159 if (V->getType() == Ty) return true; // Expression already correct type!
161 Instruction *I = dyn_cast<Instruction>(V);
162 if (I == 0) return false; // Otherwise, we can't convert!
164 switch (I->getOpcode()) {
165 case Instruction::Cast:
166 // We can convert the expr if the cast destination type is losslessly
167 // convertible to the requested type.
168 if (!Ty->isLosslesslyConvertibleTo(I->getType())) return false;
170 // We also do not allow conversion of a cast that casts from a ptr to array
171 // of X to a *X. For example: cast [4 x %List *] * %val to %List * *
173 if (const PointerType *SPT =
174 dyn_cast<PointerType>(I->getOperand(0)->getType()))
175 if (const PointerType *DPT = dyn_cast<PointerType>(I->getType()))
176 if (const ArrayType *AT = dyn_cast<ArrayType>(SPT->getElementType()))
177 if (AT->getElementType() == DPT->getElementType())
181 case Instruction::Add:
182 case Instruction::Sub:
183 if (!Ty->isInteger() && !Ty->isFloatingPoint()) return false;
184 if (!ExpressionConvertibleToType(I->getOperand(0), Ty, CTMap, TD) ||
185 !ExpressionConvertibleToType(I->getOperand(1), Ty, CTMap, TD))
188 case Instruction::Shr:
189 if (!Ty->isInteger()) return false;
190 if (Ty->isSigned() != V->getType()->isSigned()) return false;
192 case Instruction::Shl:
193 if (!Ty->isInteger()) return false;
194 if (!ExpressionConvertibleToType(I->getOperand(0), Ty, CTMap, TD))
198 case Instruction::Load: {
199 LoadInst *LI = cast<LoadInst>(I);
200 if (!ExpressionConvertibleToType(LI->getPointerOperand(),
201 PointerType::get(Ty), CTMap, TD))
205 case Instruction::PHI: {
206 PHINode *PN = cast<PHINode>(I);
207 // Be conservative if we find a giant PHI node.
208 if (PN->getNumIncomingValues() > 32) return false;
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->getType() == PointerType::get(Type::SByteTy)) {
262 // Do not Check to see if our incoming pointer can be converted
263 // to be a ptr to an array of the right type... because in more cases than
264 // not, it is simply not analyzable because of pointer/array
265 // discrepancies. To fix this, we will insert a cast before the GEP.
268 // Check to see if 'N' is an expression that can be converted to
269 // the appropriate size... if so, allow it.
271 std::vector<Value*> Indices;
272 const Type *ElTy = ConvertibleToGEP(PTy, I->getOperand(1), Indices, TD);
274 if (!ExpressionConvertibleToType(I->getOperand(0),
275 PointerType::get(ElTy), CTMap, TD))
276 return false; // Can't continue, ExConToTy might have polluted set!
281 // Otherwise, it could be that we have something like this:
282 // getelementptr [[sbyte] *] * %reg115, long %reg138 ; [sbyte]**
283 // and want to convert it into something like this:
284 // getelemenptr [[int] *] * %reg115, long %reg138 ; [int]**
286 if (GEP->getNumOperands() == 2 &&
287 PTy->getElementType()->isSized() &&
288 TD.getTypeSize(PTy->getElementType()) ==
289 TD.getTypeSize(GEP->getType()->getElementType())) {
290 const PointerType *NewSrcTy = PointerType::get(PVTy);
291 if (!ExpressionConvertibleToType(I->getOperand(0), NewSrcTy, CTMap, TD))
296 return false; // No match, maybe next time.
299 case Instruction::Call: {
300 if (isa<Function>(I->getOperand(0)))
301 return false; // Don't even try to change direct calls.
303 // If this is a function pointer, we can convert the return type if we can
304 // convert the source function pointer.
306 const PointerType *PT = cast<PointerType>(I->getOperand(0)->getType());
307 const FunctionType *FT = cast<FunctionType>(PT->getElementType());
308 std::vector<const Type *> ArgTys(FT->param_begin(), FT->param_end());
309 const FunctionType *NewTy =
310 FunctionType::get(Ty, ArgTys, FT->isVarArg());
311 if (!ExpressionConvertibleToType(I->getOperand(0),
312 PointerType::get(NewTy), CTMap, TD))
320 // Expressions are only convertible if all of the users of the expression can
321 // have this value converted. This makes use of the map to avoid infinite
324 for (Value::use_iterator It = I->use_begin(), E = I->use_end(); It != E; ++It)
325 if (!OperandConvertibleToType(*It, I, Ty, CTMap, TD))
332 Value *llvm::ConvertExpressionToType(Value *V, const Type *Ty,
333 ValueMapCache &VMC, const TargetData &TD) {
334 if (V->getType() == Ty) return V; // Already where we need to be?
336 ValueMapCache::ExprMapTy::iterator VMCI = VMC.ExprMap.find(V);
337 if (VMCI != VMC.ExprMap.end()) {
338 const Value *GV = VMCI->second;
339 const Type *GTy = VMCI->second->getType();
340 assert(VMCI->second->getType() == Ty);
342 if (Instruction *I = dyn_cast<Instruction>(V))
343 ValueHandle IHandle(VMC, I); // Remove I if it is unused now!
348 DEBUG(std::cerr << "CETT: " << (void*)V << " " << *V);
350 Instruction *I = dyn_cast<Instruction>(V);
352 Constant *CPV = cast<Constant>(V);
353 // Constants are converted by constant folding the cast that is required.
354 // We assume here that all casts are implemented for constant prop.
355 Value *Result = ConstantExpr::getCast(CPV, Ty);
356 // Add the instruction to the expression map
357 //VMC.ExprMap[V] = Result;
362 BasicBlock *BB = I->getParent();
363 std::string Name = I->getName(); if (!Name.empty()) I->setName("");
364 Instruction *Res; // Result of conversion
366 ValueHandle IHandle(VMC, I); // Prevent I from being removed!
368 Constant *Dummy = Constant::getNullValue(Ty);
370 switch (I->getOpcode()) {
371 case Instruction::Cast:
372 assert(VMC.NewCasts.count(ValueHandle(VMC, I)) == 0);
373 Res = new CastInst(I->getOperand(0), Ty, Name);
374 VMC.NewCasts.insert(ValueHandle(VMC, Res));
377 case Instruction::Add:
378 case Instruction::Sub:
379 Res = BinaryOperator::create(cast<BinaryOperator>(I)->getOpcode(),
381 VMC.ExprMap[I] = Res; // Add node to expression eagerly
383 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), Ty, VMC, TD));
384 Res->setOperand(1, ConvertExpressionToType(I->getOperand(1), Ty, VMC, TD));
387 case Instruction::Shl:
388 case Instruction::Shr:
389 Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(), Dummy,
390 I->getOperand(1), Name);
391 VMC.ExprMap[I] = Res;
392 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), Ty, VMC, TD));
395 case Instruction::Load: {
396 LoadInst *LI = cast<LoadInst>(I);
398 Res = new LoadInst(Constant::getNullValue(PointerType::get(Ty)), Name);
399 VMC.ExprMap[I] = Res;
400 Res->setOperand(0, ConvertExpressionToType(LI->getPointerOperand(),
401 PointerType::get(Ty), VMC, TD));
402 assert(Res->getOperand(0)->getType() == PointerType::get(Ty));
403 assert(Ty == Res->getType());
404 assert(Res->getType()->isFirstClassType() && "Load of structure or array!");
408 case Instruction::PHI: {
409 PHINode *OldPN = cast<PHINode>(I);
410 PHINode *NewPN = new PHINode(Ty, Name);
412 VMC.ExprMap[I] = NewPN; // Add node to expression eagerly
413 while (OldPN->getNumOperands()) {
414 BasicBlock *BB = OldPN->getIncomingBlock(0);
415 Value *OldVal = OldPN->getIncomingValue(0);
416 ValueHandle OldValHandle(VMC, OldVal);
417 OldPN->removeIncomingValue(BB, false);
418 Value *V = ConvertExpressionToType(OldVal, Ty, VMC, TD);
419 NewPN->addIncoming(V, BB);
425 case Instruction::Malloc: {
426 Res = ConvertMallocToType(cast<MallocInst>(I), Ty, Name, VMC, TD);
430 case Instruction::GetElementPtr: {
431 // GetElementPtr's are directly convertible to a pointer type if they have
432 // a number of zeros at the end. Because removing these values does not
433 // change the logical offset of the GEP, it is okay and fair to remove them.
434 // This can change this:
435 // %t1 = getelementptr %Hosp * %hosp, ubyte 4, ubyte 0 ; <%List **>
436 // %t2 = cast %List * * %t1 to %List *
438 // %t2 = getelementptr %Hosp * %hosp, ubyte 4 ; <%List *>
440 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
442 // Check to see if there are zero elements that we can remove from the
443 // index array. If there are, check to see if removing them causes us to
444 // get to the right type...
446 std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
447 const Type *BaseType = GEP->getPointerOperand()->getType();
448 const Type *PVTy = cast<PointerType>(Ty)->getElementType();
450 while (!Indices.empty() &&
451 Indices.back() == Constant::getNullValue(Indices.back()->getType())){
453 if (GetElementPtrInst::getIndexedType(BaseType, Indices, true) == PVTy) {
454 if (Indices.size() == 0)
455 Res = new CastInst(GEP->getPointerOperand(), BaseType); // NOOP CAST
457 Res = new GetElementPtrInst(GEP->getPointerOperand(), Indices, Name);
462 if (Res == 0 && GEP->getNumOperands() == 2 &&
463 GEP->getType() == PointerType::get(Type::SByteTy)) {
465 // Otherwise, we can convert a GEP from one form to the other iff the
466 // current gep is of the form 'getelementptr sbyte*, unsigned N
467 // and we could convert this to an appropriate GEP for the new type.
469 const PointerType *NewSrcTy = PointerType::get(PVTy);
470 BasicBlock::iterator It = I;
472 // Check to see if 'N' is an expression that can be converted to
473 // the appropriate size... if so, allow it.
475 std::vector<Value*> Indices;
476 const Type *ElTy = ConvertibleToGEP(NewSrcTy, I->getOperand(1),
479 assert(ElTy == PVTy && "Internal error, setup wrong!");
480 Res = new GetElementPtrInst(Constant::getNullValue(NewSrcTy),
482 VMC.ExprMap[I] = Res;
483 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
488 // Otherwise, it could be that we have something like this:
489 // getelementptr [[sbyte] *] * %reg115, uint %reg138 ; [sbyte]**
490 // and want to convert it into something like this:
491 // getelemenptr [[int] *] * %reg115, uint %reg138 ; [int]**
494 const PointerType *NewSrcTy = PointerType::get(PVTy);
495 std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
496 Res = new GetElementPtrInst(Constant::getNullValue(NewSrcTy),
498 VMC.ExprMap[I] = Res;
499 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
504 assert(Res && "Didn't find match!");
508 case Instruction::Call: {
509 assert(!isa<Function>(I->getOperand(0)));
511 // If this is a function pointer, we can convert the return type if we can
512 // convert the source function pointer.
514 const PointerType *PT = cast<PointerType>(I->getOperand(0)->getType());
515 const FunctionType *FT = cast<FunctionType>(PT->getElementType());
516 std::vector<const Type *> ArgTys(FT->param_begin(), FT->param_end());
517 const FunctionType *NewTy =
518 FunctionType::get(Ty, ArgTys, FT->isVarArg());
519 const PointerType *NewPTy = PointerType::get(NewTy);
520 if (Ty == Type::VoidTy)
521 Name = ""; // Make sure not to name calls that now return void!
523 Res = new CallInst(Constant::getNullValue(NewPTy),
524 std::vector<Value*>(I->op_begin()+1, I->op_end()),
526 VMC.ExprMap[I] = Res;
527 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),NewPTy,VMC,TD));
531 assert(0 && "Expression convertible, but don't know how to convert?");
535 assert(Res->getType() == Ty && "Didn't convert expr to correct type!");
537 BB->getInstList().insert(I, Res);
539 // Add the instruction to the expression map
540 VMC.ExprMap[I] = Res;
543 //// WTF is this code! FIXME: remove this.
544 unsigned NumUses = I->getNumUses();
545 for (unsigned It = 0; It < NumUses; ) {
546 unsigned OldSize = NumUses;
547 Value::use_iterator UI = I->use_begin();
548 std::advance(UI, It);
549 ConvertOperandToType(*UI, I, Res, VMC, TD);
550 NumUses = I->getNumUses();
551 if (NumUses == OldSize) ++It;
554 DEBUG(std::cerr << "ExpIn: " << (void*)I << " " << *I
555 << "ExpOut: " << (void*)Res << " " << *Res);
562 // ValueConvertibleToType - Return true if it is possible
563 bool llvm::ValueConvertibleToType(Value *V, const Type *Ty,
564 ValueTypeCache &ConvertedTypes,
565 const TargetData &TD) {
566 ValueTypeCache::iterator I = ConvertedTypes.find(V);
567 if (I != ConvertedTypes.end()) return I->second == Ty;
568 ConvertedTypes[V] = Ty;
570 // It is safe to convert the specified value to the specified type IFF all of
571 // the uses of the value can be converted to accept the new typed value.
573 if (V->getType() != Ty) {
574 for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I)
575 if (!OperandConvertibleToType(*I, V, Ty, ConvertedTypes, TD))
586 // OperandConvertibleToType - Return true if it is possible to convert operand
587 // V of User (instruction) U to the specified type. This is true iff it is
588 // possible to change the specified instruction to accept this. CTMap is a map
589 // of converted types, so that circular definitions will see the future type of
590 // the expression, not the static current type.
592 static bool OperandConvertibleToType(User *U, Value *V, const Type *Ty,
593 ValueTypeCache &CTMap,
594 const TargetData &TD) {
595 // if (V->getType() == Ty) return true; // Operand already the right type?
597 // Expression type must be holdable in a register.
598 if (!Ty->isFirstClassType())
601 Instruction *I = dyn_cast<Instruction>(U);
602 if (I == 0) return false; // We can't convert!
604 switch (I->getOpcode()) {
605 case Instruction::Cast:
606 assert(I->getOperand(0) == V);
607 // We can convert the expr if the cast destination type is losslessly
608 // convertible to the requested type.
609 // Also, do not change a cast that is a noop cast. For all intents and
610 // purposes it should be eliminated.
611 if (!Ty->isLosslesslyConvertibleTo(I->getOperand(0)->getType()) ||
612 I->getType() == I->getOperand(0)->getType())
615 // Do not allow a 'cast ushort %V to uint' to have it's first operand be
616 // converted to a 'short' type. Doing so changes the way sign promotion
617 // happens, and breaks things. Only allow the cast to take place if the
618 // signedness doesn't change... or if the current cast is not a lossy
621 if (!I->getType()->isLosslesslyConvertibleTo(I->getOperand(0)->getType()) &&
622 I->getOperand(0)->getType()->isSigned() != Ty->isSigned())
625 // We also do not allow conversion of a cast that casts from a ptr to array
626 // of X to a *X. For example: cast [4 x %List *] * %val to %List * *
628 if (const PointerType *SPT =
629 dyn_cast<PointerType>(I->getOperand(0)->getType()))
630 if (const PointerType *DPT = dyn_cast<PointerType>(I->getType()))
631 if (const ArrayType *AT = dyn_cast<ArrayType>(SPT->getElementType()))
632 if (AT->getElementType() == DPT->getElementType())
636 case Instruction::Add:
637 if (isa<PointerType>(Ty)) {
638 Value *IndexVal = I->getOperand(V == I->getOperand(0) ? 1 : 0);
639 std::vector<Value*> Indices;
640 if (const Type *ETy = ConvertibleToGEP(Ty, IndexVal, Indices, TD)) {
641 const Type *RetTy = PointerType::get(ETy);
643 // Only successful if we can convert this type to the required type
644 if (ValueConvertibleToType(I, RetTy, CTMap, TD)) {
648 // We have to return failure here because ValueConvertibleToType could
649 // have polluted our map
654 case Instruction::Sub: {
655 if (!Ty->isInteger() && !Ty->isFloatingPoint()) return false;
657 Value *OtherOp = I->getOperand((V == I->getOperand(0)) ? 1 : 0);
658 return ValueConvertibleToType(I, Ty, CTMap, TD) &&
659 ExpressionConvertibleToType(OtherOp, Ty, CTMap, TD);
661 case Instruction::SetEQ:
662 case Instruction::SetNE: {
663 Value *OtherOp = I->getOperand((V == I->getOperand(0)) ? 1 : 0);
664 return ExpressionConvertibleToType(OtherOp, Ty, CTMap, TD);
666 case Instruction::Shr:
667 if (Ty->isSigned() != V->getType()->isSigned()) return false;
669 case Instruction::Shl:
670 if (I->getOperand(1) == V) return false; // Cannot change shift amount type
671 if (!Ty->isInteger()) return false;
672 return ValueConvertibleToType(I, Ty, CTMap, TD);
674 case Instruction::Free:
675 assert(I->getOperand(0) == V);
676 return isa<PointerType>(Ty); // Free can free any pointer type!
678 case Instruction::Load:
679 // Cannot convert the types of any subscripts...
680 if (I->getOperand(0) != V) return false;
682 if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
683 LoadInst *LI = cast<LoadInst>(I);
685 const Type *LoadedTy = PT->getElementType();
687 // They could be loading the first element of a composite type...
688 if (const CompositeType *CT = dyn_cast<CompositeType>(LoadedTy)) {
689 unsigned Offset = 0; // No offset, get first leaf.
690 std::vector<Value*> Indices; // Discarded...
691 LoadedTy = getStructOffsetType(CT, Offset, Indices, TD, false);
692 assert(Offset == 0 && "Offset changed from zero???");
695 if (!LoadedTy->isFirstClassType())
698 if (TD.getTypeSize(LoadedTy) != TD.getTypeSize(LI->getType()))
701 return ValueConvertibleToType(LI, LoadedTy, CTMap, TD);
705 case Instruction::Store: {
706 StoreInst *SI = cast<StoreInst>(I);
708 if (V == I->getOperand(0)) {
709 ValueTypeCache::iterator CTMI = CTMap.find(I->getOperand(1));
710 if (CTMI != CTMap.end()) { // Operand #1 is in the table already?
711 // If so, check to see if it's Ty*, or, more importantly, if it is a
712 // pointer to a structure where the first element is a Ty... this code
713 // is necessary because we might be trying to change the source and
714 // destination type of the store (they might be related) and the dest
715 // pointer type might be a pointer to structure. Below we allow pointer
716 // to structures where the 0th element is compatible with the value,
717 // now we have to support the symmetrical part of this.
719 const Type *ElTy = cast<PointerType>(CTMI->second)->getElementType();
721 // Already a pointer to what we want? Trivially accept...
722 if (ElTy == Ty) return true;
724 // Tricky case now, if the destination is a pointer to structure,
725 // obviously the source is not allowed to be a structure (cannot copy
726 // a whole structure at a time), so the level raiser must be trying to
727 // store into the first field. Check for this and allow it now:
729 if (const StructType *SElTy = dyn_cast<StructType>(ElTy)) {
731 std::vector<Value*> Indices;
732 ElTy = getStructOffsetType(ElTy, Offset, Indices, TD, false);
733 assert(Offset == 0 && "Offset changed!");
734 if (ElTy == 0) // Element at offset zero in struct doesn't exist!
735 return false; // Can only happen for {}*
737 if (ElTy == Ty) // Looks like the 0th element of structure is
738 return true; // compatible! Accept now!
740 // Otherwise we know that we can't work, so just stop trying now.
745 // Can convert the store if we can convert the pointer operand to match
746 // the new value type...
747 return ExpressionConvertibleToType(I->getOperand(1), PointerType::get(Ty),
749 } else if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
750 const Type *ElTy = PT->getElementType();
751 assert(V == I->getOperand(1));
753 if (isa<StructType>(ElTy)) {
754 // We can change the destination pointer if we can store our first
755 // argument into the first element of the structure...
758 std::vector<Value*> Indices;
759 ElTy = getStructOffsetType(ElTy, Offset, Indices, TD, false);
760 assert(Offset == 0 && "Offset changed!");
761 if (ElTy == 0) // Element at offset zero in struct doesn't exist!
762 return false; // Can only happen for {}*
765 // Must move the same amount of data...
766 if (!ElTy->isSized() ||
767 TD.getTypeSize(ElTy) != TD.getTypeSize(I->getOperand(0)->getType()))
770 // Can convert store if the incoming value is convertible and if the
771 // result will preserve semantics...
772 const Type *Op0Ty = I->getOperand(0)->getType();
773 if (!(Op0Ty->isIntegral() ^ ElTy->isIntegral()) &&
774 !(Op0Ty->isFloatingPoint() ^ ElTy->isFloatingPoint()))
775 return ExpressionConvertibleToType(I->getOperand(0), ElTy, CTMap, TD);
780 case Instruction::GetElementPtr:
781 if (V != I->getOperand(0) || !isa<PointerType>(Ty)) return false;
783 // If we have a two operand form of getelementptr, this is really little
784 // more than a simple addition. As with addition, check to see if the
785 // getelementptr instruction can be changed to index into the new type.
787 if (I->getNumOperands() == 2) {
788 const Type *OldElTy = cast<PointerType>(I->getType())->getElementType();
789 uint64_t DataSize = TD.getTypeSize(OldElTy);
790 Value *Index = I->getOperand(1);
791 Instruction *TempScale = 0;
793 // If the old data element is not unit sized, we have to create a scale
794 // instruction so that ConvertibleToGEP will know the REAL amount we are
795 // indexing by. Note that this is never inserted into the instruction
796 // stream, so we have to delete it when we're done.
800 if (Index->getType()->isSigned())
801 CST = ConstantSInt::get(Index->getType(), DataSize);
803 CST = ConstantUInt::get(Index->getType(), DataSize);
805 TempScale = BinaryOperator::create(Instruction::Mul, Index, CST);
809 // Check to see if the second argument is an expression that can
810 // be converted to the appropriate size... if so, allow it.
812 std::vector<Value*> Indices;
813 const Type *ElTy = ConvertibleToGEP(Ty, Index, Indices, TD);
814 delete TempScale; // Free our temporary multiply if we made it
816 if (ElTy == 0) return false; // Cannot make conversion...
817 return ValueConvertibleToType(I, PointerType::get(ElTy), CTMap, TD);
821 case Instruction::PHI: {
822 PHINode *PN = cast<PHINode>(I);
823 // Be conservative if we find a giant PHI node.
824 if (PN->getNumIncomingValues() > 32) return false;
826 for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i)
827 if (!ExpressionConvertibleToType(PN->getIncomingValue(i), Ty, CTMap, TD))
829 return ValueConvertibleToType(PN, Ty, CTMap, TD);
832 case Instruction::Call: {
833 User::op_iterator OI = std::find(I->op_begin(), I->op_end(), V);
834 assert (OI != I->op_end() && "Not using value!");
835 unsigned OpNum = OI - I->op_begin();
837 // Are we trying to change the function pointer value to a new type?
839 const PointerType *PTy = dyn_cast<PointerType>(Ty);
840 if (PTy == 0) return false; // Can't convert to a non-pointer type...
841 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
842 if (FTy == 0) return false; // Can't convert to a non ptr to function...
844 // Do not allow converting to a call where all of the operands are ...'s
845 if (FTy->getNumParams() == 0 && FTy->isVarArg())
846 return false; // Do not permit this conversion!
848 // Perform sanity checks to make sure that new function type has the
849 // correct number of arguments...
851 unsigned NumArgs = I->getNumOperands()-1; // Don't include function ptr
853 // Cannot convert to a type that requires more fixed arguments than
854 // the call provides...
856 if (NumArgs < FTy->getNumParams()) return false;
858 // Unless this is a vararg function type, we cannot provide more arguments
859 // than are desired...
861 if (!FTy->isVarArg() && NumArgs > FTy->getNumParams())
864 // Okay, at this point, we know that the call and the function type match
865 // number of arguments. Now we see if we can convert the arguments
866 // themselves. Note that we do not require operands to be convertible,
867 // we can insert casts if they are convertible but not compatible. The
868 // reason for this is that we prefer to have resolved functions but casted
869 // arguments if possible.
871 for (unsigned i = 0, NA = FTy->getNumParams(); i < NA; ++i)
872 if (!FTy->getParamType(i)->isLosslesslyConvertibleTo(I->getOperand(i+1)->getType()))
873 return false; // Operands must have compatible types!
875 // Okay, at this point, we know that all of the arguments can be
876 // converted. We succeed if we can change the return type if
879 return ValueConvertibleToType(I, FTy->getReturnType(), CTMap, TD);
882 const PointerType *MPtr = cast<PointerType>(I->getOperand(0)->getType());
883 const FunctionType *FTy = cast<FunctionType>(MPtr->getElementType());
884 if (!FTy->isVarArg()) return false;
886 if ((OpNum-1) < FTy->getNumParams())
887 return false; // It's not in the varargs section...
889 // If we get this far, we know the value is in the varargs section of the
890 // function! We can convert if we don't reinterpret the value...
892 return Ty->isLosslesslyConvertibleTo(V->getType());
899 void llvm::ConvertValueToNewType(Value *V, Value *NewVal, ValueMapCache &VMC,
900 const TargetData &TD) {
901 ValueHandle VH(VMC, V);
903 // FIXME: This is horrible!
904 unsigned NumUses = V->getNumUses();
905 for (unsigned It = 0; It < NumUses; ) {
906 unsigned OldSize = NumUses;
907 Value::use_iterator UI = V->use_begin();
908 std::advance(UI, It);
909 ConvertOperandToType(*UI, V, NewVal, VMC, TD);
910 NumUses = V->getNumUses();
911 if (NumUses == OldSize) ++It;
917 static void ConvertOperandToType(User *U, Value *OldVal, Value *NewVal,
918 ValueMapCache &VMC, const TargetData &TD) {
919 if (isa<ValueHandle>(U)) return; // Valuehandles don't let go of operands...
921 if (VMC.OperandsMapped.count(U)) return;
922 VMC.OperandsMapped.insert(U);
924 ValueMapCache::ExprMapTy::iterator VMCI = VMC.ExprMap.find(U);
925 if (VMCI != VMC.ExprMap.end())
929 Instruction *I = cast<Instruction>(U); // Only Instructions convertible
931 BasicBlock *BB = I->getParent();
932 assert(BB != 0 && "Instruction not embedded in basic block!");
933 std::string Name = I->getName();
935 Instruction *Res; // Result of conversion
937 //std::cerr << endl << endl << "Type:\t" << Ty << "\nInst: " << I
938 // << "BB Before: " << BB << endl;
940 // Prevent I from being removed...
941 ValueHandle IHandle(VMC, I);
943 const Type *NewTy = NewVal->getType();
944 Constant *Dummy = (NewTy != Type::VoidTy) ?
945 Constant::getNullValue(NewTy) : 0;
947 switch (I->getOpcode()) {
948 case Instruction::Cast:
949 if (VMC.NewCasts.count(ValueHandle(VMC, I))) {
950 // This cast has already had it's value converted, causing a new cast to
951 // be created. We don't want to create YET ANOTHER cast instruction
952 // representing the original one, so just modify the operand of this cast
953 // instruction, which we know is newly created.
954 I->setOperand(0, NewVal);
955 I->setName(Name); // give I its name back
959 Res = new CastInst(NewVal, I->getType(), Name);
963 case Instruction::Add:
964 if (isa<PointerType>(NewTy)) {
965 Value *IndexVal = I->getOperand(OldVal == I->getOperand(0) ? 1 : 0);
966 std::vector<Value*> Indices;
967 BasicBlock::iterator It = I;
969 if (const Type *ETy = ConvertibleToGEP(NewTy, IndexVal, Indices, TD,&It)){
970 // If successful, convert the add to a GEP
971 //const Type *RetTy = PointerType::get(ETy);
972 // First operand is actually the given pointer...
973 Res = new GetElementPtrInst(NewVal, Indices, Name);
974 assert(cast<PointerType>(Res->getType())->getElementType() == ETy &&
975 "ConvertibleToGEP broken!");
981 case Instruction::Sub:
982 case Instruction::SetEQ:
983 case Instruction::SetNE: {
984 Res = BinaryOperator::create(cast<BinaryOperator>(I)->getOpcode(),
986 VMC.ExprMap[I] = Res; // Add node to expression eagerly
988 unsigned OtherIdx = (OldVal == I->getOperand(0)) ? 1 : 0;
989 Value *OtherOp = I->getOperand(OtherIdx);
990 Res->setOperand(!OtherIdx, NewVal);
991 Value *NewOther = ConvertExpressionToType(OtherOp, NewTy, VMC, TD);
992 Res->setOperand(OtherIdx, NewOther);
995 case Instruction::Shl:
996 case Instruction::Shr:
997 assert(I->getOperand(0) == OldVal);
998 Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(), NewVal,
999 I->getOperand(1), Name);
1002 case Instruction::Free: // Free can free any pointer type!
1003 assert(I->getOperand(0) == OldVal);
1004 Res = new FreeInst(NewVal);
1008 case Instruction::Load: {
1009 assert(I->getOperand(0) == OldVal && isa<PointerType>(NewVal->getType()));
1010 const Type *LoadedTy =
1011 cast<PointerType>(NewVal->getType())->getElementType();
1013 Value *Src = NewVal;
1015 if (const CompositeType *CT = dyn_cast<CompositeType>(LoadedTy)) {
1016 std::vector<Value*> Indices;
1017 Indices.push_back(Constant::getNullValue(Type::UIntTy));
1019 unsigned Offset = 0; // No offset, get first leaf.
1020 LoadedTy = getStructOffsetType(CT, Offset, Indices, TD, false);
1021 assert(LoadedTy->isFirstClassType());
1023 if (Indices.size() != 1) { // Do not generate load X, 0
1024 // Insert the GEP instruction before this load.
1025 Src = new GetElementPtrInst(Src, Indices, Name+".idx", I);
1029 Res = new LoadInst(Src, Name);
1030 assert(Res->getType()->isFirstClassType() && "Load of structure or array!");
1034 case Instruction::Store: {
1035 if (I->getOperand(0) == OldVal) { // Replace the source value
1036 // Check to see if operand #1 has already been converted...
1037 ValueMapCache::ExprMapTy::iterator VMCI =
1038 VMC.ExprMap.find(I->getOperand(1));
1039 if (VMCI != VMC.ExprMap.end()) {
1040 // Comments describing this stuff are in the OperandConvertibleToType
1041 // switch statement for Store...
1044 cast<PointerType>(VMCI->second->getType())->getElementType();
1046 Value *SrcPtr = VMCI->second;
1048 if (ElTy != NewTy) {
1049 // We check that this is a struct in the initial scan...
1050 const StructType *SElTy = cast<StructType>(ElTy);
1052 std::vector<Value*> Indices;
1053 Indices.push_back(Constant::getNullValue(Type::UIntTy));
1055 unsigned Offset = 0;
1056 const Type *Ty = getStructOffsetType(ElTy, Offset, Indices, TD,false);
1057 assert(Offset == 0 && "Offset changed!");
1058 assert(NewTy == Ty && "Did not convert to correct type!");
1060 // Insert the GEP instruction before this store.
1061 SrcPtr = new GetElementPtrInst(SrcPtr, Indices,
1062 SrcPtr->getName()+".idx", I);
1064 Res = new StoreInst(NewVal, SrcPtr);
1066 VMC.ExprMap[I] = Res;
1068 // Otherwise, we haven't converted Operand #1 over yet...
1069 const PointerType *NewPT = PointerType::get(NewTy);
1070 Res = new StoreInst(NewVal, Constant::getNullValue(NewPT));
1071 VMC.ExprMap[I] = Res;
1072 Res->setOperand(1, ConvertExpressionToType(I->getOperand(1),
1075 } else { // Replace the source pointer
1076 const Type *ValTy = cast<PointerType>(NewTy)->getElementType();
1078 Value *SrcPtr = NewVal;
1080 if (isa<StructType>(ValTy)) {
1081 std::vector<Value*> Indices;
1082 Indices.push_back(Constant::getNullValue(Type::UIntTy));
1084 unsigned Offset = 0;
1085 ValTy = getStructOffsetType(ValTy, Offset, Indices, TD, false);
1087 assert(Offset == 0 && ValTy);
1089 // Insert the GEP instruction before this store.
1090 SrcPtr = new GetElementPtrInst(SrcPtr, Indices,
1091 SrcPtr->getName()+".idx", I);
1094 Res = new StoreInst(Constant::getNullValue(ValTy), SrcPtr);
1095 VMC.ExprMap[I] = Res;
1096 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
1103 case Instruction::GetElementPtr: {
1104 // Convert a one index getelementptr into just about anything that is
1107 BasicBlock::iterator It = I;
1108 const Type *OldElTy = cast<PointerType>(I->getType())->getElementType();
1109 uint64_t DataSize = TD.getTypeSize(OldElTy);
1110 Value *Index = I->getOperand(1);
1112 if (DataSize != 1) {
1113 // Insert a multiply of the old element type is not a unit size...
1115 if (Index->getType()->isSigned())
1116 CST = ConstantSInt::get(Index->getType(), DataSize);
1118 CST = ConstantUInt::get(Index->getType(), DataSize);
1120 Index = BinaryOperator::create(Instruction::Mul, Index, CST, "scale", It);
1123 // Perform the conversion now...
1125 std::vector<Value*> Indices;
1126 const Type *ElTy = ConvertibleToGEP(NewVal->getType(),Index,Indices,TD,&It);
1127 assert(ElTy != 0 && "GEP Conversion Failure!");
1128 Res = new GetElementPtrInst(NewVal, Indices, Name);
1129 assert(Res->getType() == PointerType::get(ElTy) &&
1130 "ConvertibleToGet failed!");
1133 if (I->getType() == PointerType::get(Type::SByteTy)) {
1134 // Convert a getelementptr sbyte * %reg111, uint 16 freely back to
1135 // anything that is a pointer type...
1137 BasicBlock::iterator It = I;
1139 // Check to see if the second argument is an expression that can
1140 // be converted to the appropriate size... if so, allow it.
1142 std::vector<Value*> Indices;
1143 const Type *ElTy = ConvertibleToGEP(NewVal->getType(), I->getOperand(1),
1145 assert(ElTy != 0 && "GEP Conversion Failure!");
1147 Res = new GetElementPtrInst(NewVal, Indices, Name);
1149 // Convert a getelementptr ulong * %reg123, uint %N
1150 // to getelementptr long * %reg123, uint %N
1151 // ... where the type must simply stay the same size...
1153 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
1154 std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
1155 Res = new GetElementPtrInst(NewVal, Indices, Name);
1160 case Instruction::PHI: {
1161 PHINode *OldPN = cast<PHINode>(I);
1162 PHINode *NewPN = new PHINode(NewTy, Name);
1163 VMC.ExprMap[I] = NewPN;
1165 while (OldPN->getNumOperands()) {
1166 BasicBlock *BB = OldPN->getIncomingBlock(0);
1167 Value *OldVal = OldPN->getIncomingValue(0);
1168 ValueHandle OldValHandle(VMC, OldVal);
1169 OldPN->removeIncomingValue(BB, false);
1170 Value *V = ConvertExpressionToType(OldVal, NewTy, VMC, TD);
1171 NewPN->addIncoming(V, BB);
1177 case Instruction::Call: {
1178 Value *Meth = I->getOperand(0);
1179 std::vector<Value*> Params(I->op_begin()+1, I->op_end());
1181 if (Meth == OldVal) { // Changing the function pointer?
1182 const PointerType *NewPTy = cast<PointerType>(NewVal->getType());
1183 const FunctionType *NewTy = cast<FunctionType>(NewPTy->getElementType());
1185 if (NewTy->getReturnType() == Type::VoidTy)
1186 Name = ""; // Make sure not to name a void call!
1188 // Get an iterator to the call instruction so that we can insert casts for
1189 // operands if need be. Note that we do not require operands to be
1190 // convertible, we can insert casts if they are convertible but not
1191 // compatible. The reason for this is that we prefer to have resolved
1192 // functions but casted arguments if possible.
1194 BasicBlock::iterator It = I;
1196 // Convert over all of the call operands to their new types... but only
1197 // convert over the part that is not in the vararg section of the call.
1199 for (unsigned i = 0; i != NewTy->getNumParams(); ++i)
1200 if (Params[i]->getType() != NewTy->getParamType(i)) {
1201 // Create a cast to convert it to the right type, we know that this
1202 // is a lossless cast...
1204 Params[i] = new CastInst(Params[i], NewTy->getParamType(i),
1206 Params[i]->getName(), It);
1208 Meth = NewVal; // Update call destination to new value
1210 } else { // Changing an argument, must be in vararg area
1211 std::vector<Value*>::iterator OI =
1212 std::find(Params.begin(), Params.end(), OldVal);
1213 assert (OI != Params.end() && "Not using value!");
1218 Res = new CallInst(Meth, Params, Name);
1222 assert(0 && "Expression convertible, but don't know how to convert?");
1226 // If the instruction was newly created, insert it into the instruction
1229 BasicBlock::iterator It = I;
1230 assert(It != BB->end() && "Instruction not in own basic block??");
1231 BB->getInstList().insert(It, Res); // Keep It pointing to old instruction
1233 DEBUG(std::cerr << "COT CREATED: " << (void*)Res << " " << *Res
1234 << "In: " << (void*)I << " " << *I << "Out: " << (void*)Res
1237 // Add the instruction to the expression map
1238 VMC.ExprMap[I] = Res;
1240 if (I->getType() != Res->getType())
1241 ConvertValueToNewType(I, Res, VMC, TD);
1243 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1245 if (isa<ValueHandle>(*UI)) {
1248 Use &U = UI.getUse();
1249 ++UI; // Do not invalidate UI.
1256 ValueHandle::ValueHandle(ValueMapCache &VMC, Value *V)
1257 : Instruction(Type::VoidTy, UserOp1, &Op, 1, ""), Op(V, this), Cache(VMC) {
1258 //DEBUG(std::cerr << "VH AQUIRING: " << (void*)V << " " << V);
1261 ValueHandle::ValueHandle(const ValueHandle &VH)
1262 : Instruction(Type::VoidTy, UserOp1, &Op, 1, ""),
1263 Op(VH.Op, this), Cache(VH.Cache) {
1264 //DEBUG(std::cerr << "VH AQUIRING: " << (void*)V << " " << V);
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 (Op->hasOneUse()) {
1291 Op.set(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]->getNumUses() << " " << Operands[0]);