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, it could be that we have something like this:
256 // getelementptr [[sbyte] *] * %reg115, long %reg138 ; [sbyte]**
257 // and want to convert it into something like this:
258 // getelemenptr [[int] *] * %reg115, long %reg138 ; [int]**
260 if (GEP->getNumOperands() == 2 &&
261 PTy->getElementType()->isSized() &&
262 TD.getTypeSize(PTy->getElementType()) ==
263 TD.getTypeSize(GEP->getType()->getElementType())) {
264 const PointerType *NewSrcTy = PointerType::get(PVTy);
265 if (!ExpressionConvertibleToType(I->getOperand(0), NewSrcTy, CTMap, TD))
270 return false; // No match, maybe next time.
273 case Instruction::Call: {
274 if (isa<Function>(I->getOperand(0)))
275 return false; // Don't even try to change direct calls.
277 // If this is a function pointer, we can convert the return type if we can
278 // convert the source function pointer.
280 const PointerType *PT = cast<PointerType>(I->getOperand(0)->getType());
281 const FunctionType *FT = cast<FunctionType>(PT->getElementType());
282 std::vector<const Type *> ArgTys(FT->param_begin(), FT->param_end());
283 const FunctionType *NewTy =
284 FunctionType::get(Ty, ArgTys, FT->isVarArg());
285 if (!ExpressionConvertibleToType(I->getOperand(0),
286 PointerType::get(NewTy), CTMap, TD))
294 // Expressions are only convertible if all of the users of the expression can
295 // have this value converted. This makes use of the map to avoid infinite
298 for (Value::use_iterator It = I->use_begin(), E = I->use_end(); It != E; ++It)
299 if (!OperandConvertibleToType(*It, I, Ty, CTMap, TD))
306 Value *llvm::ConvertExpressionToType(Value *V, const Type *Ty,
307 ValueMapCache &VMC, const TargetData &TD) {
308 if (V->getType() == Ty) return V; // Already where we need to be?
310 ValueMapCache::ExprMapTy::iterator VMCI = VMC.ExprMap.find(V);
311 if (VMCI != VMC.ExprMap.end()) {
312 const Value *GV = VMCI->second;
313 const Type *GTy = VMCI->second->getType();
314 assert(VMCI->second->getType() == Ty);
316 if (Instruction *I = dyn_cast<Instruction>(V))
317 ValueHandle IHandle(VMC, I); // Remove I if it is unused now!
322 DEBUG(std::cerr << "CETT: " << (void*)V << " " << *V);
324 Instruction *I = dyn_cast<Instruction>(V);
326 Constant *CPV = cast<Constant>(V);
327 // Constants are converted by constant folding the cast that is required.
328 // We assume here that all casts are implemented for constant prop.
329 Value *Result = ConstantExpr::getCast(CPV, Ty);
330 // Add the instruction to the expression map
331 //VMC.ExprMap[V] = Result;
336 BasicBlock *BB = I->getParent();
337 std::string Name = I->getName(); if (!Name.empty()) I->setName("");
338 Instruction *Res; // Result of conversion
340 ValueHandle IHandle(VMC, I); // Prevent I from being removed!
342 Constant *Dummy = Constant::getNullValue(Ty);
344 switch (I->getOpcode()) {
345 case Instruction::Cast:
346 assert(VMC.NewCasts.count(ValueHandle(VMC, I)) == 0);
347 Res = new CastInst(I->getOperand(0), Ty, Name);
348 VMC.NewCasts.insert(ValueHandle(VMC, Res));
351 case Instruction::Add:
352 case Instruction::Sub:
353 Res = BinaryOperator::create(cast<BinaryOperator>(I)->getOpcode(),
355 VMC.ExprMap[I] = Res; // Add node to expression eagerly
357 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), Ty, VMC, TD));
358 Res->setOperand(1, ConvertExpressionToType(I->getOperand(1), Ty, VMC, TD));
361 case Instruction::Shl:
362 case Instruction::Shr:
363 Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(), Dummy,
364 I->getOperand(1), Name);
365 VMC.ExprMap[I] = Res;
366 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), Ty, VMC, TD));
369 case Instruction::Load: {
370 LoadInst *LI = cast<LoadInst>(I);
372 Res = new LoadInst(Constant::getNullValue(PointerType::get(Ty)), Name);
373 VMC.ExprMap[I] = Res;
374 Res->setOperand(0, ConvertExpressionToType(LI->getPointerOperand(),
375 PointerType::get(Ty), VMC, TD));
376 assert(Res->getOperand(0)->getType() == PointerType::get(Ty));
377 assert(Ty == Res->getType());
378 assert(Res->getType()->isFirstClassType() && "Load of structure or array!");
382 case Instruction::PHI: {
383 PHINode *OldPN = cast<PHINode>(I);
384 PHINode *NewPN = new PHINode(Ty, Name);
386 VMC.ExprMap[I] = NewPN; // Add node to expression eagerly
387 while (OldPN->getNumOperands()) {
388 BasicBlock *BB = OldPN->getIncomingBlock(0);
389 Value *OldVal = OldPN->getIncomingValue(0);
390 ValueHandle OldValHandle(VMC, OldVal);
391 OldPN->removeIncomingValue(BB, false);
392 Value *V = ConvertExpressionToType(OldVal, Ty, VMC, TD);
393 NewPN->addIncoming(V, BB);
399 case Instruction::Malloc: {
400 Res = ConvertMallocToType(cast<MallocInst>(I), Ty, Name, VMC, TD);
404 case Instruction::GetElementPtr: {
405 // GetElementPtr's are directly convertible to a pointer type if they have
406 // a number of zeros at the end. Because removing these values does not
407 // change the logical offset of the GEP, it is okay and fair to remove them.
408 // This can change this:
409 // %t1 = getelementptr %Hosp * %hosp, ubyte 4, ubyte 0 ; <%List **>
410 // %t2 = cast %List * * %t1 to %List *
412 // %t2 = getelementptr %Hosp * %hosp, ubyte 4 ; <%List *>
414 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
416 // Check to see if there are zero elements that we can remove from the
417 // index array. If there are, check to see if removing them causes us to
418 // get to the right type...
420 std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
421 const Type *BaseType = GEP->getPointerOperand()->getType();
422 const Type *PVTy = cast<PointerType>(Ty)->getElementType();
424 while (!Indices.empty() &&
425 Indices.back() == Constant::getNullValue(Indices.back()->getType())){
427 if (GetElementPtrInst::getIndexedType(BaseType, Indices, true) == PVTy) {
428 if (Indices.size() == 0)
429 Res = new CastInst(GEP->getPointerOperand(), BaseType); // NOOP CAST
431 Res = new GetElementPtrInst(GEP->getPointerOperand(), Indices, Name);
436 // Otherwise, it could be that we have something like this:
437 // getelementptr [[sbyte] *] * %reg115, uint %reg138 ; [sbyte]**
438 // and want to convert it into something like this:
439 // getelemenptr [[int] *] * %reg115, uint %reg138 ; [int]**
442 const PointerType *NewSrcTy = PointerType::get(PVTy);
443 std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
444 Res = new GetElementPtrInst(Constant::getNullValue(NewSrcTy),
446 VMC.ExprMap[I] = Res;
447 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
452 assert(Res && "Didn't find match!");
456 case Instruction::Call: {
457 assert(!isa<Function>(I->getOperand(0)));
459 // If this is a function pointer, we can convert the return type if we can
460 // convert the source function pointer.
462 const PointerType *PT = cast<PointerType>(I->getOperand(0)->getType());
463 const FunctionType *FT = cast<FunctionType>(PT->getElementType());
464 std::vector<const Type *> ArgTys(FT->param_begin(), FT->param_end());
465 const FunctionType *NewTy =
466 FunctionType::get(Ty, ArgTys, FT->isVarArg());
467 const PointerType *NewPTy = PointerType::get(NewTy);
468 if (Ty == Type::VoidTy)
469 Name = ""; // Make sure not to name calls that now return void!
471 Res = new CallInst(Constant::getNullValue(NewPTy),
472 std::vector<Value*>(I->op_begin()+1, I->op_end()),
474 if (cast<CallInst>(I)->isTailCall())
475 cast<CallInst>(Res)->setTailCall();
476 cast<CallInst>(Res)->setCallingConv(cast<CallInst>(I)->getCallingConv());
477 VMC.ExprMap[I] = Res;
478 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),NewPTy,VMC,TD));
482 assert(0 && "Expression convertible, but don't know how to convert?");
486 assert(Res->getType() == Ty && "Didn't convert expr to correct type!");
488 BB->getInstList().insert(I, Res);
490 // Add the instruction to the expression map
491 VMC.ExprMap[I] = Res;
494 //// WTF is this code! FIXME: remove this.
495 unsigned NumUses = I->getNumUses();
496 for (unsigned It = 0; It < NumUses; ) {
497 unsigned OldSize = NumUses;
498 Value::use_iterator UI = I->use_begin();
499 std::advance(UI, It);
500 ConvertOperandToType(*UI, I, Res, VMC, TD);
501 NumUses = I->getNumUses();
502 if (NumUses == OldSize) ++It;
505 DEBUG(std::cerr << "ExpIn: " << (void*)I << " " << *I
506 << "ExpOut: " << (void*)Res << " " << *Res);
513 // ValueConvertibleToType - Return true if it is possible
514 bool llvm::ValueConvertibleToType(Value *V, const Type *Ty,
515 ValueTypeCache &ConvertedTypes,
516 const TargetData &TD) {
517 ValueTypeCache::iterator I = ConvertedTypes.find(V);
518 if (I != ConvertedTypes.end()) return I->second == Ty;
519 ConvertedTypes[V] = Ty;
521 // It is safe to convert the specified value to the specified type IFF all of
522 // the uses of the value can be converted to accept the new typed value.
524 if (V->getType() != Ty) {
525 for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I)
526 if (!OperandConvertibleToType(*I, V, Ty, ConvertedTypes, TD))
537 // OperandConvertibleToType - Return true if it is possible to convert operand
538 // V of User (instruction) U to the specified type. This is true iff it is
539 // possible to change the specified instruction to accept this. CTMap is a map
540 // of converted types, so that circular definitions will see the future type of
541 // the expression, not the static current type.
543 static bool OperandConvertibleToType(User *U, Value *V, const Type *Ty,
544 ValueTypeCache &CTMap,
545 const TargetData &TD) {
546 // if (V->getType() == Ty) return true; // Operand already the right type?
548 // Expression type must be holdable in a register.
549 if (!Ty->isFirstClassType())
552 Instruction *I = dyn_cast<Instruction>(U);
553 if (I == 0) return false; // We can't convert!
555 switch (I->getOpcode()) {
556 case Instruction::Cast:
557 assert(I->getOperand(0) == V);
558 // We can convert the expr if the cast destination type is losslessly
559 // convertible to the requested type.
560 // Also, do not change a cast that is a noop cast. For all intents and
561 // purposes it should be eliminated.
562 if (!Ty->isLosslesslyConvertibleTo(I->getOperand(0)->getType()) ||
563 I->getType() == I->getOperand(0)->getType())
566 // Do not allow a 'cast ushort %V to uint' to have it's first operand be
567 // converted to a 'short' type. Doing so changes the way sign promotion
568 // happens, and breaks things. Only allow the cast to take place if the
569 // signedness doesn't change... or if the current cast is not a lossy
572 if (!I->getType()->isLosslesslyConvertibleTo(I->getOperand(0)->getType()) &&
573 I->getOperand(0)->getType()->isSigned() != Ty->isSigned())
576 // We also do not allow conversion of a cast that casts from a ptr to array
577 // of X to a *X. For example: cast [4 x %List *] * %val to %List * *
579 if (const PointerType *SPT =
580 dyn_cast<PointerType>(I->getOperand(0)->getType()))
581 if (const PointerType *DPT = dyn_cast<PointerType>(I->getType()))
582 if (const ArrayType *AT = dyn_cast<ArrayType>(SPT->getElementType()))
583 if (AT->getElementType() == DPT->getElementType())
587 case Instruction::Add:
588 case Instruction::Sub: {
589 if (!Ty->isInteger() && !Ty->isFloatingPoint()) return false;
591 Value *OtherOp = I->getOperand((V == I->getOperand(0)) ? 1 : 0);
592 return ValueConvertibleToType(I, Ty, CTMap, TD) &&
593 ExpressionConvertibleToType(OtherOp, Ty, CTMap, TD);
595 case Instruction::SetEQ:
596 case Instruction::SetNE: {
597 Value *OtherOp = I->getOperand((V == I->getOperand(0)) ? 1 : 0);
598 return ExpressionConvertibleToType(OtherOp, Ty, CTMap, TD);
600 case Instruction::Shr:
601 if (Ty->isSigned() != V->getType()->isSigned()) return false;
603 case Instruction::Shl:
604 if (I->getOperand(1) == V) return false; // Cannot change shift amount type
605 if (!Ty->isInteger()) return false;
606 return ValueConvertibleToType(I, Ty, CTMap, TD);
608 case Instruction::Free:
609 assert(I->getOperand(0) == V);
610 return isa<PointerType>(Ty); // Free can free any pointer type!
612 case Instruction::Load:
613 // Cannot convert the types of any subscripts...
614 if (I->getOperand(0) != V) return false;
616 if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
617 LoadInst *LI = cast<LoadInst>(I);
619 const Type *LoadedTy = PT->getElementType();
621 // They could be loading the first element of a composite type...
622 if (const CompositeType *CT = dyn_cast<CompositeType>(LoadedTy)) {
623 unsigned Offset = 0; // No offset, get first leaf.
624 std::vector<Value*> Indices; // Discarded...
625 LoadedTy = getStructOffsetType(CT, Offset, Indices, TD, false);
626 assert(Offset == 0 && "Offset changed from zero???");
629 if (!LoadedTy->isFirstClassType())
632 if (TD.getTypeSize(LoadedTy) != TD.getTypeSize(LI->getType()))
635 return ValueConvertibleToType(LI, LoadedTy, CTMap, TD);
639 case Instruction::Store: {
640 StoreInst *SI = cast<StoreInst>(I);
642 if (V == I->getOperand(0)) {
643 ValueTypeCache::iterator CTMI = CTMap.find(I->getOperand(1));
644 if (CTMI != CTMap.end()) { // Operand #1 is in the table already?
645 // If so, check to see if it's Ty*, or, more importantly, if it is a
646 // pointer to a structure where the first element is a Ty... this code
647 // is necessary because we might be trying to change the source and
648 // destination type of the store (they might be related) and the dest
649 // pointer type might be a pointer to structure. Below we allow pointer
650 // to structures where the 0th element is compatible with the value,
651 // now we have to support the symmetrical part of this.
653 const Type *ElTy = cast<PointerType>(CTMI->second)->getElementType();
655 // Already a pointer to what we want? Trivially accept...
656 if (ElTy == Ty) return true;
658 // Tricky case now, if the destination is a pointer to structure,
659 // obviously the source is not allowed to be a structure (cannot copy
660 // a whole structure at a time), so the level raiser must be trying to
661 // store into the first field. Check for this and allow it now:
663 if (const StructType *SElTy = dyn_cast<StructType>(ElTy)) {
665 std::vector<Value*> Indices;
666 ElTy = getStructOffsetType(ElTy, Offset, Indices, TD, false);
667 assert(Offset == 0 && "Offset changed!");
668 if (ElTy == 0) // Element at offset zero in struct doesn't exist!
669 return false; // Can only happen for {}*
671 if (ElTy == Ty) // Looks like the 0th element of structure is
672 return true; // compatible! Accept now!
674 // Otherwise we know that we can't work, so just stop trying now.
679 // Can convert the store if we can convert the pointer operand to match
680 // the new value type...
681 return ExpressionConvertibleToType(I->getOperand(1), PointerType::get(Ty),
683 } else if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
684 const Type *ElTy = PT->getElementType();
685 assert(V == I->getOperand(1));
687 if (isa<StructType>(ElTy)) {
688 // We can change the destination pointer if we can store our first
689 // argument into the first element of the structure...
692 std::vector<Value*> Indices;
693 ElTy = getStructOffsetType(ElTy, Offset, Indices, TD, false);
694 assert(Offset == 0 && "Offset changed!");
695 if (ElTy == 0) // Element at offset zero in struct doesn't exist!
696 return false; // Can only happen for {}*
699 // Must move the same amount of data...
700 if (!ElTy->isSized() ||
701 TD.getTypeSize(ElTy) != TD.getTypeSize(I->getOperand(0)->getType()))
704 // Can convert store if the incoming value is convertible and if the
705 // result will preserve semantics...
706 const Type *Op0Ty = I->getOperand(0)->getType();
707 if (!(Op0Ty->isIntegral() ^ ElTy->isIntegral()) &&
708 !(Op0Ty->isFloatingPoint() ^ ElTy->isFloatingPoint()))
709 return ExpressionConvertibleToType(I->getOperand(0), ElTy, CTMap, TD);
714 case Instruction::PHI: {
715 PHINode *PN = cast<PHINode>(I);
716 // Be conservative if we find a giant PHI node.
717 if (PN->getNumIncomingValues() > 32) return false;
719 for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i)
720 if (!ExpressionConvertibleToType(PN->getIncomingValue(i), Ty, CTMap, TD))
722 return ValueConvertibleToType(PN, Ty, CTMap, TD);
725 case Instruction::Call: {
726 User::op_iterator OI = std::find(I->op_begin(), I->op_end(), V);
727 assert (OI != I->op_end() && "Not using value!");
728 unsigned OpNum = OI - I->op_begin();
730 // Are we trying to change the function pointer value to a new type?
732 const PointerType *PTy = dyn_cast<PointerType>(Ty);
733 if (PTy == 0) return false; // Can't convert to a non-pointer type...
734 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
735 if (FTy == 0) return false; // Can't convert to a non ptr to function...
737 // Do not allow converting to a call where all of the operands are ...'s
738 if (FTy->getNumParams() == 0 && FTy->isVarArg())
739 return false; // Do not permit this conversion!
741 // Perform sanity checks to make sure that new function type has the
742 // correct number of arguments...
744 unsigned NumArgs = I->getNumOperands()-1; // Don't include function ptr
746 // Cannot convert to a type that requires more fixed arguments than
747 // the call provides...
749 if (NumArgs < FTy->getNumParams()) return false;
751 // Unless this is a vararg function type, we cannot provide more arguments
752 // than are desired...
754 if (!FTy->isVarArg() && NumArgs > FTy->getNumParams())
757 // Okay, at this point, we know that the call and the function type match
758 // number of arguments. Now we see if we can convert the arguments
759 // themselves. Note that we do not require operands to be convertible,
760 // we can insert casts if they are convertible but not compatible. The
761 // reason for this is that we prefer to have resolved functions but casted
762 // arguments if possible.
764 for (unsigned i = 0, NA = FTy->getNumParams(); i < NA; ++i)
765 if (!FTy->getParamType(i)->isLosslesslyConvertibleTo(I->getOperand(i+1)->getType()))
766 return false; // Operands must have compatible types!
768 // Okay, at this point, we know that all of the arguments can be
769 // converted. We succeed if we can change the return type if
772 return ValueConvertibleToType(I, FTy->getReturnType(), CTMap, TD);
775 const PointerType *MPtr = cast<PointerType>(I->getOperand(0)->getType());
776 const FunctionType *FTy = cast<FunctionType>(MPtr->getElementType());
777 if (!FTy->isVarArg()) return false;
779 if ((OpNum-1) < FTy->getNumParams())
780 return false; // It's not in the varargs section...
782 // If we get this far, we know the value is in the varargs section of the
783 // function! We can convert if we don't reinterpret the value...
785 return Ty->isLosslesslyConvertibleTo(V->getType());
792 void llvm::ConvertValueToNewType(Value *V, Value *NewVal, ValueMapCache &VMC,
793 const TargetData &TD) {
794 ValueHandle VH(VMC, V);
796 // FIXME: This is horrible!
797 unsigned NumUses = V->getNumUses();
798 for (unsigned It = 0; It < NumUses; ) {
799 unsigned OldSize = NumUses;
800 Value::use_iterator UI = V->use_begin();
801 std::advance(UI, It);
802 ConvertOperandToType(*UI, V, NewVal, VMC, TD);
803 NumUses = V->getNumUses();
804 if (NumUses == OldSize) ++It;
810 static void ConvertOperandToType(User *U, Value *OldVal, Value *NewVal,
811 ValueMapCache &VMC, const TargetData &TD) {
812 if (isa<ValueHandle>(U)) return; // Valuehandles don't let go of operands...
814 if (VMC.OperandsMapped.count(U)) return;
815 VMC.OperandsMapped.insert(U);
817 ValueMapCache::ExprMapTy::iterator VMCI = VMC.ExprMap.find(U);
818 if (VMCI != VMC.ExprMap.end())
822 Instruction *I = cast<Instruction>(U); // Only Instructions convertible
824 BasicBlock *BB = I->getParent();
825 assert(BB != 0 && "Instruction not embedded in basic block!");
826 std::string Name = I->getName();
828 Instruction *Res; // Result of conversion
830 //std::cerr << endl << endl << "Type:\t" << Ty << "\nInst: " << I
831 // << "BB Before: " << BB << endl;
833 // Prevent I from being removed...
834 ValueHandle IHandle(VMC, I);
836 const Type *NewTy = NewVal->getType();
837 Constant *Dummy = (NewTy != Type::VoidTy) ?
838 Constant::getNullValue(NewTy) : 0;
840 switch (I->getOpcode()) {
841 case Instruction::Cast:
842 if (VMC.NewCasts.count(ValueHandle(VMC, I))) {
843 // This cast has already had it's value converted, causing a new cast to
844 // be created. We don't want to create YET ANOTHER cast instruction
845 // representing the original one, so just modify the operand of this cast
846 // instruction, which we know is newly created.
847 I->setOperand(0, NewVal);
848 I->setName(Name); // give I its name back
852 Res = new CastInst(NewVal, I->getType(), Name);
856 case Instruction::Add:
857 case Instruction::Sub:
858 case Instruction::SetEQ:
859 case Instruction::SetNE: {
860 Res = BinaryOperator::create(cast<BinaryOperator>(I)->getOpcode(),
862 VMC.ExprMap[I] = Res; // Add node to expression eagerly
864 unsigned OtherIdx = (OldVal == I->getOperand(0)) ? 1 : 0;
865 Value *OtherOp = I->getOperand(OtherIdx);
866 Res->setOperand(!OtherIdx, NewVal);
867 Value *NewOther = ConvertExpressionToType(OtherOp, NewTy, VMC, TD);
868 Res->setOperand(OtherIdx, NewOther);
871 case Instruction::Shl:
872 case Instruction::Shr:
873 assert(I->getOperand(0) == OldVal);
874 Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(), NewVal,
875 I->getOperand(1), Name);
878 case Instruction::Free: // Free can free any pointer type!
879 assert(I->getOperand(0) == OldVal);
880 Res = new FreeInst(NewVal);
884 case Instruction::Load: {
885 assert(I->getOperand(0) == OldVal && isa<PointerType>(NewVal->getType()));
886 const Type *LoadedTy =
887 cast<PointerType>(NewVal->getType())->getElementType();
891 if (const CompositeType *CT = dyn_cast<CompositeType>(LoadedTy)) {
892 std::vector<Value*> Indices;
893 Indices.push_back(Constant::getNullValue(Type::UIntTy));
895 unsigned Offset = 0; // No offset, get first leaf.
896 LoadedTy = getStructOffsetType(CT, Offset, Indices, TD, false);
897 assert(LoadedTy->isFirstClassType());
899 if (Indices.size() != 1) { // Do not generate load X, 0
900 // Insert the GEP instruction before this load.
901 Src = new GetElementPtrInst(Src, Indices, Name+".idx", I);
905 Res = new LoadInst(Src, Name);
906 assert(Res->getType()->isFirstClassType() && "Load of structure or array!");
910 case Instruction::Store: {
911 if (I->getOperand(0) == OldVal) { // Replace the source value
912 // Check to see if operand #1 has already been converted...
913 ValueMapCache::ExprMapTy::iterator VMCI =
914 VMC.ExprMap.find(I->getOperand(1));
915 if (VMCI != VMC.ExprMap.end()) {
916 // Comments describing this stuff are in the OperandConvertibleToType
917 // switch statement for Store...
920 cast<PointerType>(VMCI->second->getType())->getElementType();
922 Value *SrcPtr = VMCI->second;
925 // We check that this is a struct in the initial scan...
926 const StructType *SElTy = cast<StructType>(ElTy);
928 std::vector<Value*> Indices;
929 Indices.push_back(Constant::getNullValue(Type::UIntTy));
932 const Type *Ty = getStructOffsetType(ElTy, Offset, Indices, TD,false);
933 assert(Offset == 0 && "Offset changed!");
934 assert(NewTy == Ty && "Did not convert to correct type!");
936 // Insert the GEP instruction before this store.
937 SrcPtr = new GetElementPtrInst(SrcPtr, Indices,
938 SrcPtr->getName()+".idx", I);
940 Res = new StoreInst(NewVal, SrcPtr);
942 VMC.ExprMap[I] = Res;
944 // Otherwise, we haven't converted Operand #1 over yet...
945 const PointerType *NewPT = PointerType::get(NewTy);
946 Res = new StoreInst(NewVal, Constant::getNullValue(NewPT));
947 VMC.ExprMap[I] = Res;
948 Res->setOperand(1, ConvertExpressionToType(I->getOperand(1),
951 } else { // Replace the source pointer
952 const Type *ValTy = cast<PointerType>(NewTy)->getElementType();
954 Value *SrcPtr = NewVal;
956 if (isa<StructType>(ValTy)) {
957 std::vector<Value*> Indices;
958 Indices.push_back(Constant::getNullValue(Type::UIntTy));
961 ValTy = getStructOffsetType(ValTy, Offset, Indices, TD, false);
963 assert(Offset == 0 && ValTy);
965 // Insert the GEP instruction before this store.
966 SrcPtr = new GetElementPtrInst(SrcPtr, Indices,
967 SrcPtr->getName()+".idx", I);
970 Res = new StoreInst(Constant::getNullValue(ValTy), SrcPtr);
971 VMC.ExprMap[I] = Res;
972 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
978 case Instruction::PHI: {
979 PHINode *OldPN = cast<PHINode>(I);
980 PHINode *NewPN = new PHINode(NewTy, Name);
981 VMC.ExprMap[I] = NewPN;
983 while (OldPN->getNumOperands()) {
984 BasicBlock *BB = OldPN->getIncomingBlock(0);
985 Value *OldVal = OldPN->getIncomingValue(0);
986 ValueHandle OldValHandle(VMC, OldVal);
987 OldPN->removeIncomingValue(BB, false);
988 Value *V = ConvertExpressionToType(OldVal, NewTy, VMC, TD);
989 NewPN->addIncoming(V, BB);
995 case Instruction::Call: {
996 Value *Meth = I->getOperand(0);
997 std::vector<Value*> Params(I->op_begin()+1, I->op_end());
999 if (Meth == OldVal) { // Changing the function pointer?
1000 const PointerType *NewPTy = cast<PointerType>(NewVal->getType());
1001 const FunctionType *NewTy = cast<FunctionType>(NewPTy->getElementType());
1003 if (NewTy->getReturnType() == Type::VoidTy)
1004 Name = ""; // Make sure not to name a void call!
1006 // Get an iterator to the call instruction so that we can insert casts for
1007 // operands if need be. Note that we do not require operands to be
1008 // convertible, we can insert casts if they are convertible but not
1009 // compatible. The reason for this is that we prefer to have resolved
1010 // functions but casted arguments if possible.
1012 BasicBlock::iterator It = I;
1014 // Convert over all of the call operands to their new types... but only
1015 // convert over the part that is not in the vararg section of the call.
1017 for (unsigned i = 0; i != NewTy->getNumParams(); ++i)
1018 if (Params[i]->getType() != NewTy->getParamType(i)) {
1019 // Create a cast to convert it to the right type, we know that this
1020 // is a lossless cast...
1022 Params[i] = new CastInst(Params[i], NewTy->getParamType(i),
1024 Params[i]->getName(), It);
1026 Meth = NewVal; // Update call destination to new value
1028 } else { // Changing an argument, must be in vararg area
1029 std::vector<Value*>::iterator OI =
1030 std::find(Params.begin(), Params.end(), OldVal);
1031 assert (OI != Params.end() && "Not using value!");
1036 Res = new CallInst(Meth, Params, Name);
1037 if (cast<CallInst>(I)->isTailCall())
1038 cast<CallInst>(Res)->setTailCall();
1039 cast<CallInst>(Res)->setCallingConv(cast<CallInst>(I)->getCallingConv());
1043 assert(0 && "Expression convertible, but don't know how to convert?");
1047 // If the instruction was newly created, insert it into the instruction
1050 BasicBlock::iterator It = I;
1051 assert(It != BB->end() && "Instruction not in own basic block??");
1052 BB->getInstList().insert(It, Res); // Keep It pointing to old instruction
1054 DEBUG(std::cerr << "COT CREATED: " << (void*)Res << " " << *Res
1055 << "In: " << (void*)I << " " << *I << "Out: " << (void*)Res
1058 // Add the instruction to the expression map
1059 VMC.ExprMap[I] = Res;
1061 if (I->getType() != Res->getType())
1062 ConvertValueToNewType(I, Res, VMC, TD);
1064 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1066 if (isa<ValueHandle>(*UI)) {
1069 Use &U = UI.getUse();
1070 ++UI; // Do not invalidate UI.
1077 ValueHandle::ValueHandle(ValueMapCache &VMC, Value *V)
1078 : Instruction(Type::VoidTy, UserOp1, &Op, 1, ""), Op(V, this), Cache(VMC) {
1079 //DEBUG(std::cerr << "VH AQUIRING: " << (void*)V << " " << V);
1082 ValueHandle::ValueHandle(const ValueHandle &VH)
1083 : Instruction(Type::VoidTy, UserOp1, &Op, 1, ""),
1084 Op(VH.Op, this), Cache(VH.Cache) {
1085 //DEBUG(std::cerr << "VH AQUIRING: " << (void*)V << " " << V);
1088 static void RecursiveDelete(ValueMapCache &Cache, Instruction *I) {
1089 if (!I || !I->use_empty()) return;
1091 assert(I->getParent() && "Inst not in basic block!");
1093 //DEBUG(std::cerr << "VH DELETING: " << (void*)I << " " << I);
1095 for (User::op_iterator OI = I->op_begin(), OE = I->op_end();
1097 if (Instruction *U = dyn_cast<Instruction>(OI)) {
1099 RecursiveDelete(Cache, U);
1102 I->getParent()->getInstList().remove(I);
1104 Cache.OperandsMapped.erase(I);
1105 Cache.ExprMap.erase(I);
1109 ValueHandle::~ValueHandle() {
1110 if (Op->hasOneUse()) {
1112 Op.set(0); // Drop use!
1114 // Now we just need to remove the old instruction so we don't get infinite
1115 // loops. Note that we cannot use DCE because DCE won't remove a store
1116 // instruction, for example.
1118 RecursiveDelete(Cache, dyn_cast<Instruction>(V));
1120 //DEBUG(std::cerr << "VH RELEASING: " << (void*)Operands[0].get() << " "
1121 // << Operands[0]->getNumUses() << " " << Operands[0]);