Skip to content

Commit

Permalink
[Diagnostics] Check for integer overflow in array size expressions
Browse files Browse the repository at this point in the history
Summary: Fixes PR27439

Reviewers: rsmith, Rakete1111

Reviewed By: rsmith

Subscribers: Rakete1111, cfe-commits

Differential Revision: https://reviews.llvm.org/D52750

llvm-svn: 344759
  • Loading branch information
davidbolvansky committed Oct 18, 2018
1 parent 1b051b2 commit 3b6ae57
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 3 deletions.
9 changes: 7 additions & 2 deletions clang/include/clang/AST/Expr.h
Expand Up @@ -631,8 +631,13 @@ class Expr : public Stmt {
/// EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded
/// integer. This must be called on an expression that constant folds to an
/// integer.
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx,
SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr) const;
llvm::APSInt EvaluateKnownConstInt(
const ASTContext &Ctx,
SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr) const;

llvm::APSInt EvaluateKnownConstIntCheckOverflow(
const ASTContext &Ctx,
SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr) const;

void EvaluateForOverflow(const ASTContext &Ctx) const;

Expand Down
13 changes: 13 additions & 0 deletions clang/lib/AST/ExprConstant.cpp
Expand Up @@ -10851,6 +10851,19 @@ APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
return EvalResult.Val.getInt();
}

APSInt Expr::EvaluateKnownConstIntCheckOverflow(
const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
EvalResult EvalResult;
EvalResult.Diag = Diag;
EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
bool Result = ::EvaluateAsRValue(Info, this, EvalResult.Val);
(void)Result;
assert(Result && "Could not evaluate expression");
assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");

return EvalResult.Val.getInt();
}

void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
bool IsConst;
EvalResult EvalResult;
Expand Down
2 changes: 1 addition & 1 deletion clang/lib/Sema/SemaExpr.cpp
Expand Up @@ -14105,7 +14105,7 @@ Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
// in the non-ICE case.
if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
if (Result)
*Result = E->EvaluateKnownConstInt(Context);
*Result = E->EvaluateKnownConstIntCheckOverflow(Context);
return E;
}

Expand Down
3 changes: 3 additions & 0 deletions clang/test/Sema/integer-overflow.c
Expand Up @@ -172,6 +172,9 @@ void check_integer_overflows_in_function_calls() {
// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
(void)f2(0, f0(4608 * 1024 * 1024));
}
void check_integer_overflows_in_array_size() {
int arr[4608 * 1024 * 1024]; // expected-warning {{overflow in expression; result is 536870912 with type 'int'}}
}

struct s {
unsigned x;
Expand Down

0 comments on commit 3b6ae57

Please sign in to comment.