llvm-project/clang/lib/Interpreter/IncrementalAction.cpp
Anutosh Bhat cbce30e0f8
[clang-repl] Skip CodeGen for top-level decls when diagnostics report errors (#169989)
We can see the following while running clang-repl in C mode 
```
anutosh491@vv-nuc:/build/anutosh491/llvm-project/build/bin$ ./clang-repl --Xcc=-x --Xcc=c --Xcc=-std=c23
clang-repl> printf("hi\n");
In file included from <<< inputs >>>:1:
input_line_1:1:1: error: call to undeclared library function 'printf' with type 'int (const char *, ...)'; ISO C99 and
      later do not support implicit function declarations [-Wimplicit-function-declaration]
    1 | printf("hi\n");
      | ^
input_line_1:1:1: note: include the header <stdio.h> or explicitly provide a declaration for 'printf'
error: Parsing failed.
clang-repl> #include <stdio.h>
hi
```

In debug mode while dumping the generated Module, i see this 
```
clang-repl> printf("hi\n");
In file included from <<< inputs >>>:1:
input_line_1:1:1: error: call to undeclared library function 'printf' with type 'int (const char *, ...)'; ISO C99 and
      later do not support implicit function declarations [-Wimplicit-function-declaration]
    1 | printf("hi\n");
      | ^
input_line_1:1:1: note: include the header <stdio.h> or explicitly provide a declaration for 'printf'
error: Parsing failed.
clang-repl> #include <stdio.h>

=== compile-ptu 1 ===
[TU=0x55556cfbf830, M=0x55556cfc13a0 (incr_module_1)]
[LLVM IR]
; ModuleID = 'incr_module_1'
source_filename = "incr_module_1"
target datalayout = "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-i128:128-f80:128-n8:16:32:64-S128"
target triple = "x86_64-unknown-linux-gnu"

@.str = private unnamed_addr constant [4 x i8] c"hi\0A\00", align 1
@llvm.global_ctors = appending global [1 x { i32, ptr, ptr }] [{ i32, ptr, ptr } { i32 65535, ptr @_GLOBAL__sub_I_incr_module_1, ptr null }]

define internal void @__stmts__0() #0 {
entry:
  %call = call i32 (ptr, ...) @printf(ptr noundef @.str)
  ret void
}

declare i32 @printf(ptr noundef, ...) #1

; Function Attrs: noinline nounwind uwtable
define internal void @_GLOBAL__sub_I_incr_module_1() #2 section ".text.startup" {
entry:
  call void @__stmts__0()
  ret void
}

attributes #0 = { "min-legal-vector-width"="0" }
attributes #1 = { "frame-pointer"="all" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+cmov,+cx8,+fxsr,+mmx,+sse,+sse2,+x87" "tune-cpu"="generic" }
attributes #2 = { noinline nounwind uwtable "frame-pointer"="all" "min-legal-vector-width"="0" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+cmov,+cx8,+fxsr,+mmx,+sse,+sse2,+x87" "tune-cpu"="generic" }

!llvm.module.flags = !{!0, !1, !2, !3, !4}
!llvm.ident = !{!5}

!0 = !{i32 1, !"wchar_size", i32 4}
!1 = !{i32 8, !"PIC Level", i32 2}
!2 = !{i32 7, !"PIE Level", i32 2}
!3 = !{i32 7, !"uwtable", i32 2}
!4 = !{i32 7, !"frame-pointer", i32 2}
!5 = !{!"clang version 22.0.0git (https://github.com/anutosh491/llvm-project.git 81ad8fbc2bb09bae61ed59316468011e4a42cf47)"}
=== end compile-ptu ===

execute-ptu 1: [TU=0x55556cfbf830, M=0x55556cfc13a0 (incr_module_1)]
hi
```

Basically I see that CodeGen emits IR for a cell before we know whether
DiagnosticsEngine has an error. For C code like `printf("hi\n");`
without <stdio.h>, Sema emits a diagnostic but still produces a
"codegen-able" `TopLevelStmt`, so the `printf` call is IR-generated into
the current module.

Previously, when `Diags.hasErrorOccurred()` was true, we only cleaned up
the PTU AST and left the CodeGen module untouched. The next successful
cell then called `GenModule()`, which returned that same module (now
also containing the next cell’s IR), causing side effects from the
failed cell (e.g. printf)
2025-12-08 22:23:54 +05:30

159 lines
5.7 KiB
C++

//===--- IncrementalAction.h - Incremental Frontend Action -*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "IncrementalAction.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/CodeGen/CodeGenAction.h"
#include "clang/CodeGen/ModuleBuilder.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/FrontendOptions.h"
#include "clang/FrontendTool/Utils.h"
#include "clang/Interpreter/Interpreter.h"
#include "clang/Lex/PreprocessorOptions.h"
#include "clang/Sema/Sema.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/ErrorHandling.h"
namespace clang {
IncrementalAction::IncrementalAction(CompilerInstance &Instance,
llvm::LLVMContext &LLVMCtx,
llvm::Error &Err, Interpreter &I,
std::unique_ptr<ASTConsumer> Consumer)
: WrapperFrontendAction([&]() {
llvm::ErrorAsOutParameter EAO(&Err);
std::unique_ptr<FrontendAction> Act;
switch (Instance.getFrontendOpts().ProgramAction) {
default:
Err = llvm::createStringError(
std::errc::state_not_recoverable,
"Driver initialization failed. "
"Incremental mode for action %d is not supported",
Instance.getFrontendOpts().ProgramAction);
return Act;
case frontend::ASTDump:
case frontend::ASTPrint:
case frontend::ParseSyntaxOnly:
Act = CreateFrontendAction(Instance);
break;
case frontend::PluginAction:
case frontend::EmitAssembly:
case frontend::EmitBC:
case frontend::EmitObj:
case frontend::PrintPreprocessedInput:
case frontend::EmitLLVMOnly:
Act.reset(new EmitLLVMOnlyAction(&LLVMCtx));
break;
}
return Act;
}()),
Interp(I), CI(Instance), Consumer(std::move(Consumer)) {}
std::unique_ptr<ASTConsumer>
IncrementalAction::CreateASTConsumer(CompilerInstance & /*CI*/,
StringRef InFile) {
std::unique_ptr<ASTConsumer> C =
WrapperFrontendAction::CreateASTConsumer(this->CI, InFile);
if (Consumer) {
std::vector<std::unique_ptr<ASTConsumer>> Cs;
Cs.push_back(std::move(Consumer));
Cs.push_back(std::move(C));
return std::make_unique<MultiplexConsumer>(std::move(Cs));
}
return std::make_unique<InProcessPrintingASTConsumer>(std::move(C), Interp);
}
void IncrementalAction::ExecuteAction() {
WrapperFrontendAction::ExecuteAction();
getCompilerInstance().getSema().CurContext = nullptr;
}
void IncrementalAction::EndSourceFile() {
if (IsTerminating && getWrapped())
WrapperFrontendAction::EndSourceFile();
}
void IncrementalAction::FinalizeAction() {
assert(!IsTerminating && "Already finalized!");
IsTerminating = true;
EndSourceFile();
}
void IncrementalAction::CacheCodeGenModule() {
CachedInCodeGenModule = GenModule();
}
llvm::Module *IncrementalAction::getCachedCodeGenModule() const {
return CachedInCodeGenModule.get();
}
std::unique_ptr<llvm::Module> IncrementalAction::GenModule() {
static unsigned ID = 0;
if (CodeGenerator *CG = getCodeGen()) {
// Clang's CodeGen is designed to work with a single llvm::Module. In many
// cases for convenience various CodeGen parts have a reference to the
// llvm::Module (TheModule or Module) which does not change when a new
// module is pushed. However, the execution engine wants to take ownership
// of the module which does not map well to CodeGen's design. To work this
// around we created an empty module to make CodeGen happy. We should make
// sure it always stays empty.
assert(((!CachedInCodeGenModule ||
!CI.getPreprocessorOpts().Includes.empty() ||
!CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) ||
(CachedInCodeGenModule->empty() &&
CachedInCodeGenModule->global_empty() &&
CachedInCodeGenModule->alias_empty() &&
CachedInCodeGenModule->ifunc_empty())) &&
"CodeGen wrote to a readonly module");
std::unique_ptr<llvm::Module> M(CG->ReleaseModule());
CG->StartModule("incr_module_" + std::to_string(ID++), M->getContext());
return M;
}
return nullptr;
}
CodeGenerator *IncrementalAction::getCodeGen() const {
FrontendAction *WrappedAct = getWrapped();
if (!WrappedAct || !WrappedAct->hasIRSupport())
return nullptr;
return static_cast<CodeGenAction *>(WrappedAct)->getCodeGenerator();
}
InProcessPrintingASTConsumer::InProcessPrintingASTConsumer(
std::unique_ptr<ASTConsumer> C, Interpreter &I)
: MultiplexConsumer(std::move(C)), Interp(I) {}
bool InProcessPrintingASTConsumer::HandleTopLevelDecl(DeclGroupRef DGR) {
if (DGR.isNull())
return true;
CompilerInstance *CI = Interp.getCompilerInstance();
DiagnosticsEngine &Diags = CI->getDiagnostics();
if (Diags.hasErrorOccurred())
return true;
for (Decl *D : DGR)
if (auto *TLSD = llvm::dyn_cast<TopLevelStmtDecl>(D))
if (TLSD && TLSD->isSemiMissing()) {
auto ExprOrErr = Interp.convertExprToValue(cast<Expr>(TLSD->getStmt()));
if (llvm::Error E = ExprOrErr.takeError()) {
llvm::logAllUnhandledErrors(std::move(E), llvm::errs(),
"Value printing failed: ");
return false; // abort parsing
}
TLSD->setStmt(*ExprOrErr);
}
return MultiplexConsumer::HandleTopLevelDecl(DGR);
}
} // namespace clang