+/// InsertCastOfTo - Insert a cast of V to the specified type, doing what
+/// we can to share the casts.
+Value *SCEVExpander::InsertCastOfTo(Instruction::CastOps opcode, Value *V,
+ const Type *Ty) {
+ // FIXME: keep track of the cast instruction.
+ if (Constant *C = dyn_cast<Constant>(V))
+ return ConstantExpr::getCast(opcode, C, Ty);
+
+ if (Argument *A = dyn_cast<Argument>(V)) {
+ // Check to see if there is already a cast!
+ for (Value::use_iterator UI = A->use_begin(), E = A->use_end();
+ UI != E; ++UI) {
+ if ((*UI)->getType() == Ty)
+ if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI))) {
+ // If the cast isn't the first instruction of the function, move it.
+ if (BasicBlock::iterator(CI) !=
+ A->getParent()->getEntryBlock().begin()) {
+ CI->moveBefore(A->getParent()->getEntryBlock().begin());
+ }
+ return CI;
+ }
+ }
+ return CastInst::create(opcode, V, Ty, V->getName(),
+ A->getParent()->getEntryBlock().begin());
+ }
+
+ Instruction *I = cast<Instruction>(V);
+
+ // Check to see if there is already a cast. If there is, use it.
+ for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
+ UI != E; ++UI) {
+ if ((*UI)->getType() == Ty)
+ if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI))) {
+ BasicBlock::iterator It = I; ++It;
+ if (isa<InvokeInst>(I))
+ It = cast<InvokeInst>(I)->getNormalDest()->begin();
+ while (isa<PHINode>(It)) ++It;
+ if (It != BasicBlock::iterator(CI)) {
+ // Splice the cast immediately after the operand in question.
+ CI->moveBefore(It);
+ }
+ return CI;
+ }
+ }
+ BasicBlock::iterator IP = I; ++IP;
+ if (InvokeInst *II = dyn_cast<InvokeInst>(I))
+ IP = II->getNormalDest()->begin();
+ while (isa<PHINode>(IP)) ++IP;
+ return CastInst::create(opcode, V, Ty, V->getName(), IP);
+}
+
+/// InsertBinop - Insert the specified binary operator, doing a small amount
+/// of work to avoid inserting an obviously redundant operation.
+Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode, Value *LHS,
+ Value *RHS, Instruction *&InsertPt) {
+ // Fold a binop with constant operands.
+ if (Constant *CLHS = dyn_cast<Constant>(LHS))
+ if (Constant *CRHS = dyn_cast<Constant>(RHS))
+ return ConstantExpr::get(Opcode, CLHS, CRHS);
+
+ // Do a quick scan to see if we have this binop nearby. If so, reuse it.
+ unsigned ScanLimit = 6;
+ for (BasicBlock::iterator IP = InsertPt, E = InsertPt->getParent()->begin();
+ ScanLimit; --IP, --ScanLimit) {
+ if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(IP))
+ if (BinOp->getOpcode() == Opcode && BinOp->getOperand(0) == LHS &&
+ BinOp->getOperand(1) == RHS) {
+ // If we found the instruction *at* the insert point, insert later
+ // instructions after it.
+ if (BinOp == InsertPt)
+ InsertPt = ++IP;
+ return BinOp;
+ }
+ if (IP == E) break;
+ }
+
+ // If we don't have
+ return BinaryOperator::create(Opcode, LHS, RHS, "tmp", InsertPt);
+}
+