diff --git a/llvm/lib/IR/Operator.cpp b/llvm/lib/IR/Operator.cpp index 740ad4a8c0a3..39e5463cb6fc 100644 --- a/llvm/lib/IR/Operator.cpp +++ b/llvm/lib/IR/Operator.cpp @@ -125,7 +125,7 @@ bool GEPOperator::accumulateConstantOffset( Type *SourceType, ArrayRef Index, const DataLayout &DL, APInt &Offset, function_ref ExternalAnalysis) { // Fast path for canonical getelementptr i8 form. - if (SourceType->isIntegerTy(8) && !ExternalAnalysis) { + if (SourceType->isIntegerTy(8) && !Index.empty() && !ExternalAnalysis) { auto *CI = dyn_cast(Index.front()); if (CI && CI->getType()->isIntegerTy()) { Offset += CI->getValue().sextOrTrunc(Offset.getBitWidth()); diff --git a/llvm/unittests/IR/InstructionsTest.cpp b/llvm/unittests/IR/InstructionsTest.cpp index b4dbc4ed435a..a46f3ca5ab5e 100644 --- a/llvm/unittests/IR/InstructionsTest.cpp +++ b/llvm/unittests/IR/InstructionsTest.cpp @@ -898,6 +898,20 @@ TEST(InstructionsTest, GEPIndices) { delete GEPI; } +TEST(InstructionsTest, ZeroIndexGEP) { + LLVMContext Context; + DataLayout DL; + Type *PtrTy = PointerType::getUnqual(Context); + auto *GEP = GetElementPtrInst::Create(Type::getInt8Ty(Context), + PoisonValue::get(PtrTy), {}); + + APInt Offset(DL.getIndexTypeSizeInBits(PtrTy), 0); + EXPECT_TRUE(GEP->accumulateConstantOffset(DL, Offset)); + EXPECT_TRUE(Offset.isZero()); + + delete GEP; +} + TEST(InstructionsTest, SwitchInst) { LLVMContext C;