Operator.cpp 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. #include "llvm/IR/Operator.h"
  2. #include "llvm/IR/GetElementPtrTypeIterator.h"
  3. #include "llvm/IR/Instructions.h"
  4. #include "llvm/IR/Type.h"
  5. #include "ConstantsContext.h"
  6. namespace llvm {
  7. Type *GEPOperator::getSourceElementType() const {
  8. if (auto *I = dyn_cast<GetElementPtrInst>(this))
  9. return I->getSourceElementType();
  10. return cast<GetElementPtrConstantExpr>(this)->getSourceElementType();
  11. }
  12. Type *GEPOperator::getResultElementType() const {
  13. if (auto *I = dyn_cast<GetElementPtrInst>(this))
  14. return I->getResultElementType();
  15. return cast<GetElementPtrConstantExpr>(this)->getResultElementType();
  16. }
  17. bool GEPOperator::accumulateConstantOffset(const DataLayout &DL,
  18. APInt &Offset) const {
  19. assert(Offset.getBitWidth() ==
  20. DL.getPointerSizeInBits(getPointerAddressSpace()) &&
  21. "The offset must have exactly as many bits as our pointer.");
  22. for (gep_type_iterator GTI = gep_type_begin(this), GTE = gep_type_end(this);
  23. GTI != GTE; ++GTI) {
  24. ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
  25. if (!OpC)
  26. return false;
  27. if (OpC->isZero())
  28. continue;
  29. // Handle a struct index, which adds its field offset to the pointer.
  30. if (StructType *STy = dyn_cast<StructType>(*GTI)) {
  31. unsigned ElementIdx = OpC->getZExtValue();
  32. const StructLayout *SL = DL.getStructLayout(STy);
  33. Offset += APInt(Offset.getBitWidth(), SL->getElementOffset(ElementIdx));
  34. continue;
  35. }
  36. // For array or vector indices, scale the index by the size of the type.
  37. APInt Index = OpC->getValue().sextOrTrunc(Offset.getBitWidth());
  38. Offset += Index * APInt(Offset.getBitWidth(),
  39. DL.getTypeAllocSize(GTI.getIndexedType()));
  40. }
  41. return true;
  42. }
  43. }