+// InjectSimpleInductionVariable - Insert a cannonical induction variable into
+// the interval header Header. This assumes that the flow graph is in
+// simplified form (so we know that the header block has exactly 2 predecessors)
+//
+// TODO: This should inherit the largest type that is being used by the already
+// present induction variables (instead of always using uint)
+//
+static PHINode *InjectSimpleInductionVariable(cfg::Interval *Int) {
+ string PHIName, AddName;
+
+ BasicBlock *Header = Int->getHeaderNode();
+ Method *M = Header->getParent();
+
+ if (M->hasSymbolTable()) {
+ // Only name the induction variable if the method isn't stripped.
+ PHIName = M->getSymbolTable()->getUniqueName(Type::UIntTy, "ind_var");
+ AddName = M->getSymbolTable()->getUniqueName(Type::UIntTy, "ind_var_next");
+ }
+
+ // Create the neccesary instructions...
+ PHINode *PN = new PHINode(Type::UIntTy, PHIName);
+ ConstPoolVal *One = new ConstPoolUInt(Type::UIntTy, 1);
+ ConstPoolVal *Zero = new ConstPoolUInt(Type::UIntTy, 0);
+ BinaryOperator *AddNode = BinaryOperator::create(Instruction::Add,
+ PN, One, AddName);
+
+ // Figure out which predecessors I have to play with... there should be
+ // exactly two... one of which is a loop predecessor, and one of which is not.
+ //
+ cfg::pred_iterator PI = cfg::pred_begin(Header);
+ assert(PI != cfg::pred_end(Header) && "Header node should have 2 preds!");
+ BasicBlock *Pred1 = *PI; ++PI;
+ assert(PI != cfg::pred_end(Header) && "Header node should have 2 preds!");
+ BasicBlock *Pred2 = *PI;
+ assert(++PI == cfg::pred_end(Header) && "Header node should have 2 preds!");
+
+ // Make Pred1 be the loop entrance predecessor, Pred2 be the Loop predecessor
+ if (Int->contains(Pred1)) swap(Pred1, Pred2);
+
+ assert(!Int->contains(Pred1) && "Pred1 should be loop entrance!");
+ assert( Int->contains(Pred2) && "Pred2 should be looping edge!");
+
+ // Link the instructions into the PHI node...
+ PN->addIncoming(Zero, Pred1); // The initializer is first argument
+ PN->addIncoming(AddNode, Pred2); // The step size is second PHI argument
+
+ // Insert the PHI node into the Header of the loop. It shall be the first
+ // instruction, because the "Simple" Induction Variable must be first in the
+ // block.
+ //
+ BasicBlock::InstListType &IL = Header->getInstList();
+ IL.push_front(PN);
+
+ // Insert the Add instruction as the first (non-phi) instruction in the
+ // header node's basic block.
+ BasicBlock::InstListType::iterator I = IL.begin();
+ while ((*I)->isPHINode()) ++I;
+ IL.insert(I, AddNode);
+
+ // Insert the constants into the constant pool for the method...
+ M->getConstantPool().insert(One);
+ M->getConstantPool().insert(Zero);
+ return PN;
+}
+