[clang] [clang-repl] Take the opt level defaults from the driver and cc1 (PR #237999)
Aaron Jomy via cfe-commits
cfe-commits at lists.llvm.org
Thu Nov 5 14:05:12 PST 2026
================
@@ -645,12 +649,42 @@ llvm::Expected<IncrementalExecutor &> Interpreter::getExecutionEngine() {
return *IncrExecutor.get();
}
-void Interpreter::setOptLevel(unsigned OptLevel, unsigned OptSize) {
- CodeGenOptions &CGO = getCompilerInstance()->getCodeGenOpts();
- CGO.OptimizationLevel = OptLevel;
- CGO.OptimizeSize = OptSize;
- CGO.setInlining(OptLevel ? CodeGenOptions::NormalInlining
- : CodeGenOptions::OnlyAlwaysInlining);
+// Obtain the CodeGenOptions generated for a fresh compilation on the
+// CompilerInstance target with the -O flag for Level and Size.
+static llvm::Expected<CodeGenOptions>
+optFlagCodeGenOpts(const CompilerInstance &CI, unsigned Level, unsigned Size) {
+ std::string Flag =
+ Size == 0 ? "-O" + llvm::utostr(Level) : (Size == 1 ? "-Os" : "-Oz");
+ std::string Target = "--target=" + CI.getTargetOpts().Triple;
+ std::unique_ptr<CompilerInvocation> Invocation = createInvocation(
+ {"clang", "-xc++", Flag.c_str(), Target.c_str(), "<<< inputs >>>"});
+ if (!Invocation || Invocation->getCodeGenOpts().OptimizationLevel != Level ||
+ Invocation->getCodeGenOpts().OptimizeSize != Size)
+ return llvm::createStringError(
+ "no -O flag sets optimization level %u with size %u", Level, Size);
+ return Invocation->getCodeGenOpts();
+}
+
+llvm::Error Interpreter::setOptLevel(unsigned OptLevel, unsigned OptSize) {
+ const CodeGenOptions &Initial = *InitialCodeGenOpts;
+ auto To = optFlagCodeGenOpts(*CI, OptLevel, OptSize);
----------------
aaronj0 wrote:
Yes building an invocation per pragma is quite expensive (measured 1.5ms locally, release build) and seems suboptimal. I used createInvocation because currnetly the -O defaults are only computed while parsing command-line flags (in the driver `shouldEnableVectorizerAtOLevel` and in cc1 `ParseCodeGenArgs`). so there seems to be no way to get them from the level alone, afaict.
What do you think about adding helpers in CodeGenOptions that take only the OptLevel, shared by the driver, cc1 and clang-repl? not sure if that direction makes sense, let me know what design you prefer here.
https://github.com/llvm/llvm-project/pull/237999
More information about the cfe-commits
mailing list