Index: llvm/include/llvm/Analysis/TargetTransformInfoImpl.h =================================================================== --- llvm/include/llvm/Analysis/TargetTransformInfoImpl.h +++ llvm/include/llvm/Analysis/TargetTransformInfoImpl.h @@ -674,7 +674,9 @@ BaseGV = dyn_cast(Ptr->stripPointerCasts()); } bool HasBaseReg = (BaseGV == nullptr); - int64_t BaseOffset = 0; + + auto PtrSizeBits = DL.getPointerTypeSizeInBits(Ptr->getType()); + APInt BaseOffset(PtrSizeBits, 0); int64_t Scale = 0; auto GTI = gep_type_begin(PointeeType, Operands); @@ -700,9 +702,10 @@ BaseOffset += DL.getStructLayout(STy)->getElementOffset(Field); } else { int64_t ElementSize = DL.getTypeAllocSize(GTI.getIndexedType()); - if (ConstIdx) - BaseOffset += ConstIdx->getSExtValue() * ElementSize; - else { + if (ConstIdx) { + BaseOffset += + APInt(PtrSizeBits, ConstIdx->getSExtValue()) * ElementSize; + } else { // Needs scale register. if (Scale != 0) // No addressing mode takes two scale registers. @@ -716,8 +719,9 @@ unsigned AS = (Ptr == nullptr ? 0 : Ptr->getType()->getPointerAddressSpace()); if (static_cast(this)->isLegalAddressingMode( - TargetType, const_cast(BaseGV), BaseOffset, - HasBaseReg, Scale, AS)) + TargetType, const_cast(BaseGV), + static_cast(BaseOffset.getLimitedValue()), HasBaseReg, + Scale, AS)) return TTI::TCC_Free; return TTI::TCC_Basic; } Index: llvm/test/Analysis/CostModel/X86/gep.ll =================================================================== --- llvm/test/Analysis/CostModel/X86/gep.ll +++ llvm/test/Analysis/CostModel/X86/gep.ll @@ -35,6 +35,11 @@ ;CHECK: cost of 0 for instruction: {{.*}} getelementptr inbounds <4 x double>, <4 x double>* %a12 = getelementptr inbounds <4 x double>, <4 x double>* undef, i32 0 + ; Check that we handle outlandishly large GEPs properly. This is unlikely to + ; be a valid pointer, but LLVM still generates GEPs like this sometimes in + ; dead code. +;CHECK: cost of 1 for instruction: {{.*}} getelementptr inbounds i8, i8* + %giant_gep_idx = getelementptr inbounds i8, i8* undef, i64 9223372036854775807 ret void }