#ifndef LLVM_ANALYSIS_UTILS_LOCAL_H
#define LLVM_ANALYSIS_UTILS_LOCAL_H
#include "llvm/ADT/StringRef.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/GetElementPtrTypeIterator.h"
namespace llvm {
template <typename IRBuilderTy>
Value *EmitGEPOffset(IRBuilderTy *Builder, const DataLayout &DL, User *GEP,
bool NoAssumptions = false) {
GEPOperator *GEPOp = cast<GEPOperator>(GEP);
Type *IntIdxTy = DL.getIndexType(GEP->getType());
Value *Result = nullptr;
bool isInBounds = GEPOp->isInBounds() && !NoAssumptions;
unsigned IntPtrWidth = IntIdxTy->getScalarType()->getIntegerBitWidth();
uint64_t PtrSizeMask =
std::numeric_limits<uint64_t>::max() >> (64 - IntPtrWidth);
gep_type_iterator GTI = gep_type_begin(GEP);
for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
++i, ++GTI) {
Value *Op = *i;
uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
Value *Offset;
if (Constant *OpC = dyn_cast<Constant>(Op)) {
if (OpC->isZeroValue())
continue;
if (StructType *STy = GTI.getStructTypeOrNull()) {
uint64_t OpValue = OpC->getUniqueInteger().getZExtValue();
Size = DL.getStructLayout(STy)->getElementOffset(OpValue);
if (!Size)
continue;
Offset = ConstantInt::get(IntIdxTy, Size);
} else {
if (IntIdxTy->isVectorTy() && !OpC->getType()->isVectorTy())
OpC = ConstantVector::getSplat(
cast<VectorType>(IntIdxTy)->getElementCount(), OpC);
Constant *Scale = ConstantInt::get(IntIdxTy, Size);
Constant *OC =
ConstantExpr::getIntegerCast(OpC, IntIdxTy, true );
Offset =
ConstantExpr::getMul(OC, Scale, false , isInBounds );
}
} else {
if (IntIdxTy->isVectorTy() && !Op->getType()->isVectorTy())
Op = Builder->CreateVectorSplat(
cast<FixedVectorType>(IntIdxTy)->getNumElements(), Op);
if (Op->getType() != IntIdxTy)
Op = Builder->CreateIntCast(Op, IntIdxTy, true, Op->getName().str()+".c");
if (Size != 1) {
Op = Builder->CreateMul(Op, ConstantInt::get(IntIdxTy, Size),
GEP->getName().str() + ".idx", false ,
isInBounds );
}
Offset = Op;
}
if (Result)
Result = Builder->CreateAdd(Result, Offset, GEP->getName().str()+".offs",
false , isInBounds );
else
Result = Offset;
}
return Result ? Result : Constant::getNullValue(IntIdxTy);
}
}
#endif