- // If 'I' is a constant GEP from an alloca, always fold it. This allows us
- // to get an offset from the stack pointer. If a non-memory use uses this GEP
- // it will just get an add of a constant to the stack pointer. This increases
- // the lifetime of the stack pointer, which is always live anyway.
- if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I))
- // FIXME: This is just a special purpose form of availability hacking.
- if (isa<AllocaInst>(GEPI->getOperand(0)) && GEPI->hasAllConstantIndices())
- return true;
+ // AMBefore is the addressing mode before this instruction was folded into it,
+ // and AMAfter is the addressing mode after the instruction was folded. Get
+ // the set of registers referenced by AMAfter and subtract out those
+ // referenced by AMBefore: this is the set of values which folding in this
+ // address extends the lifetime of.
+ //
+ // Note that there are only two potential values being referenced here,
+ // BaseReg and ScaleReg (global addresses are always available, as are any
+ // folded immediates).
+ Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
+
+ // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
+ // lifetime wasn't extended by adding this instruction.
+ if (ValueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
+ BaseReg = 0;
+ if (ValueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
+ ScaledReg = 0;
+
+ // If folding this instruction (and it's subexprs) didn't extend any live
+ // ranges, we're ok with it.
+ if (BaseReg == 0 && ScaledReg == 0)
+ return true;