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/Method.h"
11 #include "llvm/Support/STLExtras.h"
12 #include "llvm/iOther.h"
13 #include "llvm/iMemory.h"
14 #include "llvm/ConstPoolVals.h"
15 #include "llvm/Optimizations/ConstantHandling.h"
16 #include "llvm/Optimizations/DCE.h"
20 #include "llvm/Assembly/Writer.h"
22 //#define DEBUG_EXPR_CONVERT 1
24 static inline const Type *getTy(const Value *V, ValueTypeCache &CT) {
25 ValueTypeCache::iterator I = CT.find(V);
26 if (I == CT.end()) return V->getType();
31 static bool OperandConvertableToType(User *U, Value *V, const Type *Ty,
32 ValueTypeCache &ConvertedTypes);
34 static void ConvertOperandToType(User *U, Value *OldVal, Value *NewVal,
38 // ExpressionConvertableToType - Return true if it is possible
39 static bool ExpressionConvertableToType(Value *V, const Type *Ty,
40 ValueTypeCache &CTMap) {
41 // Expression type must be holdable in a register.
42 if (!isFirstClassType(Ty))
45 ValueTypeCache::iterator CTMI = CTMap.find(V);
46 if (CTMI != CTMap.end()) return CTMI->second == Ty;
49 // Expressions are only convertable if all of the users of the expression can
50 // have this value converted. This makes use of the map to avoid infinite
53 for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I)
54 if (!OperandConvertableToType(*I, V, Ty, CTMap))
57 Instruction *I = dyn_cast<Instruction>(V);
59 // It's not an instruction, check to see if it's a constant... all constants
60 // can be converted to an equivalent value (except pointers, they can't be
61 // const prop'd in general).
63 if (isa<ConstPoolVal>(V))
64 if (!isa<PointerType>(V->getType()) && !isa<PointerType>(Ty) &&
65 !isa<StructType>(Ty) && !isa<ArrayType>(Ty))
68 return false; // Otherwise, we can't convert!
70 if (I->getType() == Ty) return false; // Expression already correct type!
72 switch (I->getOpcode()) {
73 case Instruction::Cast:
74 // We can convert the expr if the cast destination type is losslessly
75 // convertable to the requested type.
76 return losslessCastableTypes(Ty, I->getType());
78 case Instruction::Add:
79 case Instruction::Sub:
80 return ExpressionConvertableToType(I->getOperand(0), Ty, CTMap) &&
81 ExpressionConvertableToType(I->getOperand(1), Ty, CTMap);
82 case Instruction::Shr:
83 if (Ty->isSigned() != V->getType()->isSigned()) return false;
85 case Instruction::Shl:
86 return ExpressionConvertableToType(I->getOperand(0), Ty, CTMap);
88 case Instruction::Load: {
89 LoadInst *LI = cast<LoadInst>(I);
90 if (LI->hasIndices()) return false;
91 return ExpressionConvertableToType(LI->getPtrOperand(),
92 PointerType::get(Ty), CTMap);
94 case Instruction::PHINode: {
95 PHINode *PN = cast<PHINode>(I);
96 for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i)
97 if (!ExpressionConvertableToType(PN->getIncomingValue(i), Ty, CTMap))
102 case Instruction::GetElementPtr: {
103 // GetElementPtr's are directly convertable to a pointer type if they have
104 // a number of zeros at the end. Because removing these values does not
105 // change the logical offset of the GEP, it is okay and fair to remove them.
106 // This can change this:
107 // %t1 = getelementptr %Hosp * %hosp, ubyte 4, ubyte 0 ; <%List **>
108 // %t2 = cast %List * * %t1 to %List *
110 // %t2 = getelementptr %Hosp * %hosp, ubyte 4 ; <%List *>
112 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
113 const PointerType *PTy = dyn_cast<PointerType>(Ty);
114 if (!PTy) return false;
116 // Check to see if there are zero elements that we can remove from the
117 // index array. If there are, check to see if removing them causes us to
118 // get to the right type...
120 vector<ConstPoolVal*> Indices = GEP->getIndices();
121 const Type *BaseType = GEP->getPtrOperand()->getType();
123 while (Indices.size() &&
124 cast<ConstPoolUInt>(Indices.back())->getValue() == 0) {
126 const Type *ElTy = GetElementPtrInst::getIndexedType(BaseType, Indices,
128 if (ElTy == PTy->getValueType())
129 return true; // Found a match!!
131 break; // No match, maybe next time.
140 static Value *ConvertExpressionToType(Value *V, const Type *Ty,
141 ValueMapCache &VMC) {
142 ValueMapCache::ExprMapTy::iterator VMCI = VMC.ExprMap.find(V);
143 if (VMCI != VMC.ExprMap.end())
146 #ifdef DEBUG_EXPR_CONVERT
147 cerr << "CETT: " << (void*)V << " " << V;
150 Instruction *I = dyn_cast<Instruction>(V);
152 if (ConstPoolVal *CPV = cast<ConstPoolVal>(V)) {
153 // Constants are converted by constant folding the cast that is required.
154 // We assume here that all casts are implemented for constant prop.
155 Value *Result = opt::ConstantFoldCastInstruction(CPV, Ty);
156 if (!Result) cerr << "Couldn't fold " << CPV << " to " << Ty << endl;
157 assert(Result && "ConstantFoldCastInstruction Failed!!!");
159 // Add the instruction to the expression map
160 VMC.ExprMap[V] = Result;
165 BasicBlock *BB = I->getParent();
166 BasicBlock::InstListType &BIL = BB->getInstList();
167 string Name = I->getName(); if (!Name.empty()) I->setName("");
168 Instruction *Res; // Result of conversion
170 ValueHandle IHandle(I); // Prevent I from being removed!
172 ConstPoolVal *Dummy = ConstPoolVal::getNullConstant(Ty);
174 //cerr << endl << endl << "Type:\t" << Ty << "\nInst: " << I << "BB Before: " << BB << endl;
176 switch (I->getOpcode()) {
177 case Instruction::Cast:
178 Res = new CastInst(I->getOperand(0), Ty, Name);
181 case Instruction::Add:
182 case Instruction::Sub:
183 Res = BinaryOperator::create(cast<BinaryOperator>(I)->getOpcode(),
185 VMC.ExprMap[I] = Res; // Add node to expression eagerly
187 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), Ty, VMC));
188 Res->setOperand(1, ConvertExpressionToType(I->getOperand(1), Ty, VMC));
191 case Instruction::Shl:
192 case Instruction::Shr:
193 Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(),
194 ConvertExpressionToType(I->getOperand(0), Ty, VMC),
195 I->getOperand(1), Name);
198 case Instruction::Load: {
199 LoadInst *LI = cast<LoadInst>(I);
200 assert(!LI->hasIndices());
201 Res = new LoadInst(ConstPoolVal::getNullConstant(PointerType::get(Ty)),
203 VMC.ExprMap[I] = Res;
204 Res->setOperand(0, ConvertExpressionToType(LI->getPtrOperand(),
205 PointerType::get(Ty), VMC));
209 case Instruction::PHINode: {
210 PHINode *OldPN = cast<PHINode>(I);
211 PHINode *NewPN = new PHINode(Ty, Name);
213 VMC.ExprMap[I] = NewPN; // Add node to expression eagerly
214 while (OldPN->getNumOperands()) {
215 BasicBlock *BB = OldPN->getIncomingBlock(0);
216 Value *OldVal = OldPN->getIncomingValue(0);
217 ValueHandle OldValHandle(OldVal);
218 OldPN->removeIncomingValue(BB);
219 Value *V = ConvertExpressionToType(OldVal, Ty, VMC);
220 NewPN->addIncoming(V, BB);
226 case Instruction::GetElementPtr: {
227 // GetElementPtr's are directly convertable to a pointer type if they have
228 // a number of zeros at the end. Because removing these values does not
229 // change the logical offset of the GEP, it is okay and fair to remove them.
230 // This can change this:
231 // %t1 = getelementptr %Hosp * %hosp, ubyte 4, ubyte 0 ; <%List **>
232 // %t2 = cast %List * * %t1 to %List *
234 // %t2 = getelementptr %Hosp * %hosp, ubyte 4 ; <%List *>
236 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
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 vector<ConstPoolVal*> Indices = GEP->getIndices();
243 const Type *BaseType = GEP->getPtrOperand()->getType();
244 const Type *PVTy = cast<PointerType>(Ty)->getValueType();
246 while (Indices.size() &&
247 cast<ConstPoolUInt>(Indices.back())->getValue() == 0) {
249 if (GetElementPtrInst::getIndexedType(BaseType, Indices, true) == PVTy) {
250 if (Indices.size() == 0) {
251 Res = new CastInst(GEP->getPtrOperand(), BaseType); // NOOP
253 Res = new GetElementPtrInst(GEP->getPtrOperand(), Indices, Name);
258 assert(Res && "Didn't find match!");
259 break; // No match, maybe next time.
263 assert(0 && "Expression convertable, but don't know how to convert?");
267 BasicBlock::iterator It = find(BIL.begin(), BIL.end(), I);
268 assert(It != BIL.end() && "Instruction not in own basic block??");
271 // Add the instruction to the expression map
272 VMC.ExprMap[I] = Res;
274 // Expressions are only convertable if all of the users of the expression can
275 // have this value converted. This makes use of the map to avoid infinite
278 unsigned NumUses = I->use_size();
279 for (unsigned It = 0; It < NumUses; ) {
280 unsigned OldSize = NumUses;
281 ConvertOperandToType(*(I->use_begin()+It), I, Res, VMC);
282 NumUses = I->use_size();
283 if (NumUses == OldSize) ++It;
286 #ifdef DEBUG_EXPR_CONVERT
287 cerr << "ExpIn: " << (void*)I << " " << I
288 << "ExpOut: " << (void*)Res << " " << Res;
289 cerr << "ExpCREATED: " << (void*)Res << " " << Res;
292 if (I->use_empty()) {
293 #ifdef DEBUG_EXPR_CONVERT
294 cerr << "EXPR DELETING: " << (void*)I << " " << I;
305 // RetValConvertableToType - Return true if it is possible
306 bool RetValConvertableToType(Value *V, const Type *Ty,
307 ValueTypeCache &ConvertedTypes) {
308 ValueTypeCache::iterator I = ConvertedTypes.find(V);
309 if (I != ConvertedTypes.end()) return I->second == Ty;
310 ConvertedTypes[V] = Ty;
312 // It is safe to convert the specified value to the specified type IFF all of
313 // the uses of the value can be converted to accept the new typed value.
315 for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I)
316 if (!OperandConvertableToType(*I, V, Ty, ConvertedTypes))
328 // OperandConvertableToType - Return true if it is possible to convert operand
329 // V of User (instruction) U to the specified type. This is true iff it is
330 // possible to change the specified instruction to accept this. CTMap is a map
331 // of converted types, so that circular definitions will see the future type of
332 // the expression, not the static current type.
334 static bool OperandConvertableToType(User *U, Value *V, const Type *Ty,
335 ValueTypeCache &CTMap) {
336 assert(V->getType() != Ty &&
337 "OperandConvertableToType: Operand is already right type!");
338 Instruction *I = dyn_cast<Instruction>(U);
339 if (I == 0) return false; // We can't convert!
341 switch (I->getOpcode()) {
342 case Instruction::Cast:
343 assert(I->getOperand(0) == V);
344 // We can convert the expr if the cast destination type is losslessly
345 // convertable to the requested type.
346 return losslessCastableTypes(Ty, I->getOperand(0)->getType());
348 case Instruction::Add:
349 case Instruction::Sub: {
350 Value *OtherOp = I->getOperand((V == I->getOperand(0)) ? 1 : 0);
351 return RetValConvertableToType(I, Ty, CTMap) &&
352 ExpressionConvertableToType(OtherOp, Ty, CTMap);
354 case Instruction::SetEQ:
355 case Instruction::SetNE: {
356 Value *OtherOp = I->getOperand((V == I->getOperand(0)) ? 1 : 0);
357 return ExpressionConvertableToType(OtherOp, Ty, CTMap);
359 case Instruction::Shr:
360 if (Ty->isSigned() != V->getType()->isSigned()) return false;
362 case Instruction::Shl:
363 assert(I->getOperand(0) == V);
364 return RetValConvertableToType(I, Ty, CTMap);
366 case Instruction::Load:
367 assert(I->getOperand(0) == V);
368 if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
369 LoadInst *LI = cast<LoadInst>(I);
370 const Type *PVTy = PT->getValueType();
371 if (LI->hasIndices() || isa<ArrayType>(PVTy) ||
372 TD.getTypeSize(PVTy) != TD.getTypeSize(LI->getType()))
375 return RetValConvertableToType(LI, PT->getValueType(), CTMap);
379 case Instruction::Store: {
380 StoreInst *SI = cast<StoreInst>(I);
381 if (SI->hasIndices()) return false;
383 if (V == I->getOperand(0)) {
384 // Can convert the store if we can convert the pointer operand to match
385 // the new value type...
386 return ExpressionConvertableToType(I->getOperand(1), PointerType::get(Ty),
388 } else if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
389 if (isa<ArrayType>(PT->getValueType()))
390 return false; // Avoid getDataSize on unsized array type!
391 assert(V == I->getOperand(1));
393 // Must move the same amount of data...
394 if (TD.getTypeSize(PT->getValueType()) !=
395 TD.getTypeSize(I->getOperand(0)->getType())) return false;
397 // Can convert store if the incoming value is convertable...
398 return ExpressionConvertableToType(I->getOperand(0), PT->getValueType(),
404 case Instruction::PHINode: {
405 PHINode *PN = cast<PHINode>(I);
406 for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i)
407 if (!ExpressionConvertableToType(PN->getIncomingValue(i), Ty, CTMap))
413 case Instruction::GetElementPtr: {
414 // GetElementPtr's are directly convertable to a pointer type if they have
415 // a number of zeros at the end. Because removing these values does not
416 // change the logical offset of the GEP, it is okay and fair to remove them.
417 // This can change this:
418 // %t1 = getelementptr %Hosp * %hosp, ubyte 4, ubyte 0 ; <%List **>
419 // %t2 = cast %List * * %t1 to %List *
421 // %t2 = getelementptr %Hosp * %hosp, ubyte 4 ; <%List *>
423 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
424 const PointerType *PTy = dyn_cast<PointerType>(Ty);
425 if (!PTy) return false;
427 // Check to see if there are zero elements that we can remove from the
428 // index array. If there are, check to see if removing them causes us to
429 // get to the right type...
431 vector<ConstPoolVal*> Indices = GEP->getIndices();
432 const Type *BaseType = GEP->getPtrOperand()->getType();
434 while (Indices.size() &&
435 cast<ConstPoolUInt>(Indices.back())->getValue() == 0) {
437 const Type *ElTy = GetElementPtrInst::getIndexedType(BaseType, Indices,
439 if (ElTy == PTy->getValueType())
440 return true; // Found a match!!
442 break; // No match, maybe next time.
450 void ConvertUsersType(Value *V, Value *NewVal, ValueMapCache &VMC) {
453 unsigned NumUses = V->use_size();
454 for (unsigned It = 0; It < NumUses; ) {
455 unsigned OldSize = NumUses;
456 ConvertOperandToType(*(V->use_begin()+It), V, NewVal, VMC);
457 NumUses = V->use_size();
458 if (NumUses == OldSize) ++It;
464 static void ConvertOperandToType(User *U, Value *OldVal, Value *NewVal,
465 ValueMapCache &VMC) {
466 if (isa<ValueHandle>(U)) return; // Valuehandles don't let go of operands...
468 if (VMC.OperandsMapped.count(U)) return;
469 VMC.OperandsMapped.insert(U);
471 ValueMapCache::ExprMapTy::iterator VMCI = VMC.ExprMap.find(U);
472 if (VMCI != VMC.ExprMap.end())
476 Instruction *I = cast<Instruction>(U); // Only Instructions convertable
478 BasicBlock *BB = I->getParent();
479 BasicBlock::InstListType &BIL = BB->getInstList();
480 string Name = I->getName(); if (!Name.empty()) I->setName("");
481 Instruction *Res; // Result of conversion
483 //cerr << endl << endl << "Type:\t" << Ty << "\nInst: " << I << "BB Before: " << BB << endl;
485 // Prevent I from being removed...
486 ValueHandle IHandle(I);
488 const Type *NewTy = NewVal->getType();
489 ConstPoolVal *Dummy = (NewTy != Type::VoidTy) ?
490 ConstPoolVal::getNullConstant(NewTy) : 0;
492 switch (I->getOpcode()) {
493 case Instruction::Cast:
494 assert(I->getOperand(0) == OldVal);
495 Res = new CastInst(NewVal, I->getType(), Name);
498 case Instruction::Add:
499 case Instruction::Sub:
500 case Instruction::SetEQ:
501 case Instruction::SetNE: {
502 Res = BinaryOperator::create(cast<BinaryOperator>(I)->getOpcode(),
504 VMC.ExprMap[I] = Res; // Add node to expression eagerly
506 unsigned OtherIdx = (OldVal == I->getOperand(0)) ? 1 : 0;
507 Value *OtherOp = I->getOperand(OtherIdx);
508 Value *NewOther = ConvertExpressionToType(OtherOp, NewTy, VMC);
510 Res->setOperand(OtherIdx, NewOther);
511 Res->setOperand(!OtherIdx, NewVal);
514 case Instruction::Shl:
515 case Instruction::Shr:
516 assert(I->getOperand(0) == OldVal);
517 Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(), NewVal,
518 I->getOperand(1), Name);
521 case Instruction::Load:
522 assert(I->getOperand(0) == OldVal);
523 Res = new LoadInst(NewVal, Name);
526 case Instruction::Store: {
527 if (I->getOperand(0) == OldVal) { // Replace the source value
528 const PointerType *NewPT = PointerType::get(NewTy);
529 Res = new StoreInst(NewVal, ConstPoolVal::getNullConstant(NewPT));
530 VMC.ExprMap[I] = Res;
531 Res->setOperand(1, ConvertExpressionToType(I->getOperand(1), NewPT, VMC));
532 } else { // Replace the source pointer
533 const Type *ValTy = cast<PointerType>(NewTy)->getValueType();
534 Res = new StoreInst(ConstPoolVal::getNullConstant(ValTy), NewVal);
535 VMC.ExprMap[I] = Res;
536 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), ValTy, VMC));
541 case Instruction::PHINode: {
542 PHINode *OldPN = cast<PHINode>(I);
543 PHINode *NewPN = new PHINode(NewTy, Name);
544 VMC.ExprMap[I] = NewPN;
546 while (OldPN->getNumOperands()) {
547 BasicBlock *BB = OldPN->getIncomingBlock(0);
548 Value *OldVal = OldPN->getIncomingValue(0);
549 OldPN->removeIncomingValue(BB);
550 Value *V = ConvertExpressionToType(OldVal, NewTy, VMC);
551 NewPN->addIncoming(V, BB);
558 case Instruction::GetElementPtr: {
559 // GetElementPtr's are directly convertable to a pointer type if they have
560 // a number of zeros at the end. Because removing these values does not
561 // change the logical offset of the GEP, it is okay and fair to remove them.
562 // This can change this:
563 // %t1 = getelementptr %Hosp * %hosp, ubyte 4, ubyte 0 ; <%List **>
564 // %t2 = cast %List * * %t1 to %List *
566 // %t2 = getelementptr %Hosp * %hosp, ubyte 4 ; <%List *>
568 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
570 // Check to see if there are zero elements that we can remove from the
571 // index array. If there are, check to see if removing them causes us to
572 // get to the right type...
574 vector<ConstPoolVal*> Indices = GEP->getIndices();
575 const Type *BaseType = GEP->getPtrOperand()->getType();
576 const Type *PVTy = cast<PointerType>(Ty)->getValueType();
578 while (Indices.size() &&
579 cast<ConstPoolUInt>(Indices.back())->getValue() == 0) {
581 if (GetElementPtrInst::getIndexedType(BaseType, Indices, true) == PVTy) {
582 if (Indices.size() == 0) {
583 Res = new CastInst(GEP->getPtrOperand(), BaseType); // NOOP
585 Res = new GetElementPtrInst(GEP->getPtrOperand(), Indices, Name);
590 assert(Res && "Didn't find match!");
591 break; // No match, maybe next time.
596 assert(0 && "Expression convertable, but don't know how to convert?");
600 BasicBlock::iterator It = find(BIL.begin(), BIL.end(), I);
601 assert(It != BIL.end() && "Instruction not in own basic block??");
602 BIL.insert(It, Res); // Keep It pointing to old instruction
604 #ifdef DEBUG_EXPR_CONVERT
605 cerr << "COT CREATED: " << (void*)Res << " " << Res;
606 cerr << "In: " << (void*)I << " " << I << "Out: " << (void*)Res << " " << Res;
609 // Add the instruction to the expression map
610 VMC.ExprMap[I] = Res;
612 if (I->getType() != Res->getType())
613 ConvertUsersType(I, Res, VMC);
615 for (unsigned It = 0; It < I->use_size(); ) {
616 User *Use = *(I->use_begin()+It);
617 if (isa<ValueHandle>(Use)) // Don't remove ValueHandles!
620 Use->replaceUsesOfWith(I, Res);
623 if (I->use_empty()) {
624 // Now we just need to remove the old instruction so we don't get infinite
625 // loops. Note that we cannot use DCE because DCE won't remove a store
626 // instruction, for example.
628 #ifdef DEBUG_EXPR_CONVERT
629 cerr << "DELETING: " << (void*)I << " " << I;
634 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
636 assert(isa<ValueHandle>((Value*)*UI) && "Uses of Instruction remain!!!");
641 ValueHandle::ValueHandle(Value *V) : Instruction(Type::VoidTy, UserOp1, "") {
642 #ifdef DEBUG_EXPR_CONVERT
643 cerr << "VH AQUIRING: " << (void*)V << " " << V;
645 Operands.push_back(Use(V, this));
648 static void RecursiveDelete(Instruction *I) {
649 if (!I || !I->use_empty()) return;
651 assert(I->getParent() && "Inst not in basic block!");
653 #ifdef DEBUG_EXPR_CONVERT
654 cerr << "VH DELETING: " << (void*)I << " " << I;
657 for (User::op_iterator OI = I->op_begin(), OE = I->op_end();
659 Instruction *U = dyn_cast<Instruction>(*OI);
662 RecursiveDelete(dyn_cast<Instruction>(U));
666 I->getParent()->getInstList().remove(I);
671 ValueHandle::~ValueHandle() {
672 if (Operands[0]->use_size() == 1) {
673 Value *V = Operands[0];
674 Operands[0] = 0; // Drop use!
676 // Now we just need to remove the old instruction so we don't get infinite
677 // loops. Note that we cannot use DCE because DCE won't remove a store
678 // instruction, for example.
680 RecursiveDelete(cast<Instruction>(V));
682 #ifdef DEBUG_EXPR_CONVERT
683 cerr << "VH RELEASING: " << (void*)Operands[0].get() << " " << Operands[0]->use_size() << " " << Operands[0];