Skip to content

Commit d396330

Browse files
committed
[clang-repl] Clone the llvm::Modules to avoid invalid memory access.
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 clone the module and pass it down. With some effort it is possible to teach CodeGen to ask the CodeGenModule for its current module and that would have an overall positive impact on CodeGen improving the encapsulation of various parts but that's not resilient to future regression. This patch takes a more conservative approach and clones the llvm::Module before passing it to the Jit. That's also not bullet proof because we have to guarantee that CodeGen does not write on the blueprint. At that stage that seems more consistent to what clang-repl already does to map each partial translation unit to a new Module. This change will fixes a long-standing invalid memory access reported by valgrind when we enable the TBAA optimization passes. It also unblock progress on llvm#84758.
1 parent 2685256 commit d396330

File tree

1 file changed

+10
-1
lines changed

1 file changed

+10
-1
lines changed

clang/lib/Interpreter/IncrementalExecutor.cpp

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
#include "llvm/IR/Module.h"
2929
#include "llvm/Support/ManagedStatic.h"
3030
#include "llvm/Support/TargetSelect.h"
31+
#include "llvm/Transforms/Utils/Cloning.h"
3132

3233
// Force linking some of the runtimes that helps attaching to a debugger.
3334
LLVM_ATTRIBUTE_USED void linkComponents() {
@@ -73,7 +74,15 @@ llvm::Error IncrementalExecutor::addModule(PartialTranslationUnit &PTU) {
7374
Jit->getMainJITDylib().createResourceTracker();
7475
ResourceTrackers[&PTU] = RT;
7576

76-
return Jit->addIRModule(RT, {std::move(PTU.TheModule), TSCtx});
77+
// Clang's CodeGen is designed to work with a single llvm::Module. In many
78+
// cases for convenience various CodeGen parts have a reference to the
79+
// llvm::Module (TheModule or Module) which does not change when a new module
80+
// is pushed. However, the execution engine wants to take ownership of the
81+
// module which does not map well to CodeGen's design. To work this around
82+
// we clone the module and pass it down.
83+
std::unique_ptr<llvm::Module> ModuleClone = llvm::CloneModule(*PTU.TheModule);
84+
85+
return Jit->addIRModule(RT, {std::move(ModuleClone), TSCtx});
7786
}
7887

7988
llvm::Error IncrementalExecutor::removeModule(PartialTranslationUnit &PTU) {

0 commit comments

Comments
 (0)