+/// GetLinearExpression - Analyze the specified value as a linear expression:
+/// "A*V + B". Return the scale and offset values as APInts and return V as a
+/// Value*. The incoming Value is known to be a scalar integer.
+static Value *GetLinearExpression(Value *V, APInt &Scale, APInt &Offset) {
+ assert(isa<IntegerType>(V->getType()) && "Not an integer value");
+
+ if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(V)) {
+ if (ConstantInt *RHSC = dyn_cast<ConstantInt>(BOp->getOperand(1))) {
+ switch (BOp->getOpcode()) {
+ default: break;
+ case Instruction::Add:
+ V = GetLinearExpression(BOp->getOperand(0), Scale, Offset);
+ Offset += RHSC->getValue();
+ return V;
+ // TODO: SHL, MUL, OR.
+ }
+ }
+ }
+
+ Scale = 1;
+ Offset = 0;
+ return V;
+}
+