Index: clang/lib/CodeGen/CGExpr.cpp =================================================================== --- clang/lib/CodeGen/CGExpr.cpp +++ clang/lib/CodeGen/CGExpr.cpp @@ -3936,10 +3936,44 @@ // Propagate the alignment from the array itself to the result. QualType arrayType = Array->getType(); - Addr = emitArraySubscriptGEP( - *this, ArrayLV.getAddress(*this), {CGM.getSize(CharUnits::Zero()), Idx}, - E->getType(), !getLangOpts().isSignedOverflowDefined(), SignedIndices, - E->getExprLoc(), &arrayType, E->getBase()); + + Address ArrayLVAddr = ArrayLV.getAddress(*this); + + if (!getLangOpts().isSignedOverflowDefined() && + // ISO/IEC 9899:TC3, 6.5.6.8 + (getLangOpts().C99 || getLangOpts().CPlusPlus) && + getContext().getAsConstantArrayType(arrayType)) { + auto *CAT = getContext().getAsConstantArrayType(arrayType); + uint64_t BoundedRegionSize = (Idx->getType()->getScalarSizeInBits() / 8) * + CAT->getSize().getZExtValue(); + + Address BeginOff = emitArraySubscriptGEP( + *this, ArrayLVAddr, + {CGM.getSize(CharUnits::Zero()), CGM.getSize(CharUnits::Zero())}, + E->getType(), !getLangOpts().isSignedOverflowDefined(), SignedIndices, + E->getExprLoc(), &arrayType, E->getBase()); + + llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::memory_region_decl, + BeginOff.getPointer()->getType()); + llvm::Value *Call = Builder.CreateCall(F, + {BeginOff.getPointer(), + llvm::ConstantInt::get(Int64Ty, 0), + llvm::ConstantInt::get(Int64Ty, BoundedRegionSize)}, + "arrayidx.bounded"); + Address RetAddr(Call, BeginOff.getElementType(), + ArrayLVAddr.getAlignment()); + + Addr = emitArraySubscriptGEP( + *this, RetAddr, {Idx}, + E->getType(), !getLangOpts().isSignedOverflowDefined(), SignedIndices, + E->getExprLoc(), &arrayType, E->getBase()); + } else { + Addr = emitArraySubscriptGEP( + *this, ArrayLVAddr, {CGM.getSize(CharUnits::Zero()), Idx}, + E->getType(), !getLangOpts().isSignedOverflowDefined(), SignedIndices, + E->getExprLoc(), &arrayType, E->getBase()); + } + EltBaseInfo = ArrayLV.getBaseInfo(); EltTBAAInfo = CGM.getTBAAInfoForSubobject(ArrayLV, E->getType()); } else {