Skip to content

Commit

Permalink
[flang] Diagnose REPEAT with negative NCOPIES=
Browse files Browse the repository at this point in the history
Emit an error when the NCOPIES= argument to the intrinsic function
REPEAT has a negative value.  (The current implementation crashes, which
isn't informative.)

Differential Revision: https://reviews.llvm.org/D143820
  • Loading branch information
klausler committed Feb 13, 2023
1 parent ce9ce66 commit 8151d6f
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 2 deletions.
2 changes: 1 addition & 1 deletion flang/lib/Evaluate/character.h
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ template <int KIND> class CharacterUtils {

static Character REPEAT(const Character &str, ConstantSubscript ncopies) {
Character result;
if (!str.empty()) {
if (!str.empty() && ncopies > 0) {
result.reserve(ncopies * str.size());
while (ncopies-- > 0) {
result += str;
Expand Down
6 changes: 5 additions & 1 deletion flang/lib/Evaluate/fold-character.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,11 @@ Expr<Type<TypeCategory::Character, KIND>> FoldIntrinsicFunction(
context, funcRef.arguments())}) {
auto str{std::get<Scalar<T>>(*scalars)};
auto n{std::get<Scalar<SubscriptInteger>>(*scalars).ToInt64()};
if (static_cast<double>(n) * str.size() >
if (n < 0) {
context.messages().Say(
"NCOPIES= argument to REPEAT() should be nonnegative, but is %jd"_err_en_US,
static_cast<std::intmax_t>(n));
} else if (static_cast<double>(n) * str.size() >
(1 << 20)) { // sanity limit of 1MiB
context.messages().Say(
"Result of REPEAT() is too large to compute at compilation time (%g characters)"_port_en_US,
Expand Down
2 changes: 2 additions & 0 deletions flang/test/Evaluate/errors01.f90
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,8 @@ subroutine s12(x,y)
subroutine s13
!CHECK: portability: Result of REPEAT() is too large to compute at compilation time (1.1259e+15 characters)
print *, repeat(repeat(' ', 2**20), 2**30)
!CHECK: error: NCOPIES= argument to REPEAT() should be nonnegative, but is -666
print *, repeat(' ', -666)
end subroutine
subroutine warnings
real, parameter :: ok1 = scale(0.0, 99999) ! 0.0
Expand Down

0 comments on commit 8151d6f

Please sign in to comment.