Skip to content

[CIR] Add option to emit MLIR in LLVM dialect. #1316

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Mar 5, 2025
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions clang/include/clang/CIR/LowerToLLVM.h
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,19 @@ class ModuleOp;
namespace cir {

namespace direct {
mlir::ModuleOp lowerDirectlyFromCIRToLLVMDialect(mlir::ModuleOp theModule,
bool disableVerifier = false,
bool disableCCLowering = false,
bool disableDebugInfo = false);

// Lower directly from pristine CIR to LLVMIR.
std::unique_ptr<llvm::Module> lowerDirectlyFromCIRToLLVMIR(
mlir::ModuleOp theModule, llvm::LLVMContext &llvmCtx,
bool disableVerifier = false, bool disableCCLowering = false,
bool disableDebugInfo = false);
}

// Lower directly from pristine CIR to LLVMIR.
} // namespace direct

std::unique_ptr<llvm::Module>
lowerFromCIRToMLIRToLLVMIR(mlir::ModuleOp theModule,
std::unique_ptr<mlir::MLIRContext> mlirCtx,
Expand Down
6 changes: 6 additions & 0 deletions clang/include/clang/CIR/LowerToMLIR.h
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,16 @@
#ifndef CLANG_CIR_LOWERTOMLIR_H
#define CLANG_CIR_LOWERTOMLIR_H

#include "mlir/Transforms/DialectConversion.h"

namespace cir {

void populateCIRLoopToSCFConversionPatterns(mlir::RewritePatternSet &patterns,
mlir::TypeConverter &converter);

mlir::ModuleOp
lowerFromCIRToMLIRToLLVMDialect(mlir::ModuleOp theModule,
mlir::MLIRContext *mlirCtx = nullptr);
} // namespace cir

#endif // CLANG_CIR_LOWERTOMLIR_H_
11 changes: 10 additions & 1 deletion clang/include/clang/Driver/Options.td
Original file line number Diff line number Diff line change
Expand Up @@ -3120,7 +3120,16 @@ def emit_cir_only : Flag<["-"], "emit-cir-only">,
def emit_cir_flat : Flag<["-"], "emit-cir-flat">, Visibility<[ClangOption, CC1Option]>,
Group<Action_Group>, HelpText<"Similar to -emit-cir but also lowers structured CFG into basic blocks.">;
def emit_mlir : Flag<["-"], "emit-mlir">, Visibility<[CC1Option]>, Group<Action_Group>,
HelpText<"Build ASTs and then lower through ClangIR to MLIR, emit the .milr file">;
HelpText<"Build ASTs and then lower through ClangIR to MLIR (standard dialects "
"when `-fno-clangir-direct-lowering` is used or the LLVM dialect when "
"`-fclangir-direct-lowering` is used), emit the .mlir file.">;
def emit_mlir_EQ : Joined<["-"], "emit-mlir=">, Visibility<[CC1Option]>, Group<Action_Group>,
HelpText<"Build ASTs and then lower through ClangIR to the selected MLIR dialect, emit the .mlir file. "
"Allowed values are `std` for MLIR standard dialects and `llvm` for the LLVM dialect.">,
Values<"std,llvm">,
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can "cir" and "cir-flat" be added here?

Copy link
Member

@bcardosolopes bcardosolopes Feb 20, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I asked to remove it but now in light of upstreaming discussion llvm/llvm-project#127835 (comment), we should probably converge to make upstreaming approach easier. @Jezurko sorry for the noise. We should add cir and cir-flat to match what is likely coming for Flang as part of that discussion. We should also rename std to core.

Andy, should we hold on this until you land to make your life easier or is it enough if @Jezurko applies the changes above?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it makes sense to merge this first, then I can update my upstream patch to align with this and the wishes of the reviewers there.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, I will update the list of values and update the action. No worries about the noise :)

@bcardosolopes what about the non-_EQ situation? The current situation here in the incubator is that the -emit-mlir alias to -emit-fir is simply commented out and the CIR variant of -emit-mlir is defined few lines later. Do we want to somehow resolve that in this PR (probably after discussion in the upstream PR)? Or just land the -emit-mlir= option for now and resolve that separately?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have posted an update in llvm/llvm-project#127835 that uses the -emit-mlir=[cir|core] option. I was referencing this PR when I implemented it, so it shouldn't be too far off. One difference is that I made the MLIR dialect a separate named enum.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added another small discussion point over there

NormalizedValuesScope<"FrontendOptions">,
NormalizedValues<["MLIR_STD", "MLIR_LLVM"]>,
MarshallingInfoEnum<FrontendOpts<"MLIRTargetDialect">, "MLIR_Default">;
/// ClangIR-specific options - END

def flto : Flag<["-"], "flto">,
Expand Down
2 changes: 2 additions & 0 deletions clang/include/clang/Frontend/FrontendOptions.h
Original file line number Diff line number Diff line change
Expand Up @@ -530,6 +530,8 @@ class FrontendOptions {
std::string ClangIRIdiomRecognizerOpts;
std::string ClangIRLibOptOpts;

enum { MLIR_Default, MLIR_STD, MLIR_LLVM } MLIRTargetDialect = MLIR_Default;

/// The input kind, either specified via -x argument or deduced from the input
/// file name.
InputKind DashX;
Expand Down
16 changes: 15 additions & 1 deletion clang/lib/CIR/FrontendAction/CIRGenAction.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
#include "clang/CIR/CIRToCIRPasses.h"
#include "clang/CIR/Dialect/IR/CIRDialect.h"
#include "clang/CIR/LowerToLLVM.h"
#include "clang/CIR/LowerToMLIR.h"
#include "clang/CIR/Passes.h"
#include "clang/CodeGen/BackendUtil.h"
#include "clang/CodeGen/ModuleBuilder.h"
Expand Down Expand Up @@ -273,7 +274,20 @@ class CIRGenConsumer : public clang::ASTConsumer {
}
break;
case CIRGenAction::OutputType::EmitMLIR: {
auto loweredMlirModule = lowerFromCIRToMLIR(mlirMod, mlirCtx.get());
mlir::ModuleOp loweredMlirModule;
if (feOptions.ClangIRDirectLowering) {
// Attempting to emit std with direct lowering is already checked by
// Compiler Invocation
loweredMlirModule = direct::lowerDirectlyFromCIRToLLVMDialect(mlirMod);
} else {
if (feOptions.MLIRTargetDialect == clang::FrontendOptions::MLIR_LLVM)
loweredMlirModule =
lowerFromCIRToMLIRToLLVMDialect(mlirMod, mlirCtx.get());
else // STD and Default cases
loweredMlirModule = lowerFromCIRToMLIR(mlirMod, mlirCtx.get());
}
assert(loweredMlirModule &&
"MLIR module does not exist, but lowering did not fail?");
assert(outputStream && "Why are we here without an output stream?");
// FIXME: we cannot roundtrip prettyForm=true right now.
mlir::OpPrintingFlags flags;
Expand Down
24 changes: 19 additions & 5 deletions clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4689,11 +4689,11 @@ void populateCIRToLLVMPasses(mlir::OpPassManager &pm, bool useCCLowering) {

extern void registerCIRDialectTranslation(mlir::MLIRContext &context);

std::unique_ptr<llvm::Module>
lowerDirectlyFromCIRToLLVMIR(mlir::ModuleOp theModule, LLVMContext &llvmCtx,
bool disableVerifier, bool disableCCLowering,
bool disableDebugInfo) {
llvm::TimeTraceScope scope("lower from CIR to LLVM directly");
mlir::ModuleOp lowerDirectlyFromCIRToLLVMDialect(mlir::ModuleOp theModule,
bool disableVerifier,
bool disableCCLowering,
bool disableDebugInfo) {
llvm::TimeTraceScope scope("lower from CIR to LLVM Dialect");

mlir::MLIRContext *mlirCtx = theModule.getContext();
mlir::PassManager pm(mlirCtx);
Expand Down Expand Up @@ -4722,6 +4722,20 @@ lowerDirectlyFromCIRToLLVMIR(mlir::ModuleOp theModule, LLVMContext &llvmCtx,
if (theModule.verify().failed())
report_fatal_error("Verification of the final LLVMIR dialect failed!");

return theModule;
}

std::unique_ptr<llvm::Module>
lowerDirectlyFromCIRToLLVMIR(mlir::ModuleOp theModule, LLVMContext &llvmCtx,
bool disableVerifier, bool disableCCLowering,
bool disableDebugInfo) {
llvm::TimeTraceScope scope("lower from CIR to LLVM directly");

lowerDirectlyFromCIRToLLVMDialect(theModule, disableVerifier,
disableCCLowering, disableDebugInfo);

mlir::MLIRContext *mlirCtx = theModule.getContext();

mlir::registerBuiltinDialectTranslation(*mlirCtx);
mlir::registerLLVMDialectTranslation(*mlirCtx);
mlir::registerOpenMPDialectTranslation(*mlirCtx);
Expand Down
25 changes: 19 additions & 6 deletions clang/lib/CIR/Lowering/ThroughMLIR/LowerCIRToMLIR.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
#include "mlir/Transforms/DialectConversion.h"
#include "clang/CIR/Dialect/IR/CIRDialect.h"
#include "clang/CIR/Dialect/IR/CIRTypes.h"
#include "clang/CIR/LowerToLLVM.h"
#include "clang/CIR/LowerToMLIR.h"
#include "clang/CIR/LoweringHelpers.h"
#include "clang/CIR/Passes.h"
Expand Down Expand Up @@ -1458,13 +1459,14 @@ void ConvertCIRToMLIRPass::runOnOperation() {
signalPassFailure();
}

std::unique_ptr<llvm::Module>
lowerFromCIRToMLIRToLLVMIR(mlir::ModuleOp theModule,
std::unique_ptr<mlir::MLIRContext> mlirCtx,
LLVMContext &llvmCtx) {
llvm::TimeTraceScope scope("Lower from CIR to MLIR To LLVM");
mlir::ModuleOp lowerFromCIRToMLIRToLLVMDialect(mlir::ModuleOp theModule,
mlir::MLIRContext *mlirCtx) {
llvm::TimeTraceScope scope("Lower from CIR to MLIR To LLVM Dialect");
if (!mlirCtx) {
mlirCtx = theModule.getContext();
}

mlir::PassManager pm(mlirCtx.get());
mlir::PassManager pm(mlirCtx);

pm.addPass(createConvertCIRToMLIRPass());
pm.addPass(createConvertMLIRToLLVMPass());
Expand All @@ -1478,6 +1480,17 @@ lowerFromCIRToMLIRToLLVMIR(mlir::ModuleOp theModule,
if (theModule.verify().failed())
report_fatal_error("Verification of the final LLVMIR dialect failed!");

return theModule;
}

std::unique_ptr<llvm::Module>
lowerFromCIRToMLIRToLLVMIR(mlir::ModuleOp theModule,
std::unique_ptr<mlir::MLIRContext> mlirCtx,
LLVMContext &llvmCtx) {
llvm::TimeTraceScope scope("Lower from CIR to MLIR To LLVM");

lowerFromCIRToMLIRToLLVMDialect(theModule, mlirCtx.get());

mlir::registerBuiltinDialectTranslation(*mlirCtx);
mlir::registerLLVMDialectTranslation(*mlirCtx);
mlir::registerOpenMPDialectTranslation(*mlirCtx);
Expand Down
8 changes: 8 additions & 0 deletions clang/lib/Frontend/CompilerInvocation.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2738,6 +2738,7 @@ static const auto &getFrontendActionTable() {
{frontend::EmitCIRFlat, OPT_emit_cir_flat},
{frontend::EmitCIROnly, OPT_emit_cir_only},
{frontend::EmitMLIR, OPT_emit_mlir},
{frontend::EmitMLIR, OPT_emit_mlir_EQ},
{frontend::EmitHTML, OPT_emit_html},
{frontend::EmitLLVM, OPT_emit_llvm},
{frontend::EmitLLVMOnly, OPT_emit_llvm_only},
Expand Down Expand Up @@ -2849,6 +2850,13 @@ static void GenerateFrontendArgs(const FrontendOptions &Opts,
};
}

if (Opts.ProgramAction == frontend::EmitMLIR) {
GenerateProgramAction = [&]() {
if (Opts.MLIRTargetDialect == FrontendOptions::MLIR_Default)
GenerateArg(Consumer, OPT_emit_mlir);
};
}

if (Opts.ProgramAction == frontend::FixIt && !Opts.FixItSuffix.empty()) {
GenerateProgramAction = [&]() {
GenerateArg(Consumer, OPT_fixit_EQ, Opts.FixItSuffix);
Expand Down
7 changes: 4 additions & 3 deletions clang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,10 @@ CreateFrontendBaseAction(CompilerInstance &CI) {
llvm::report_fatal_error(
"-emit-cir and -emit-cir-only only valid when using -fclangir");

if (CI.getFrontendOpts().ClangIRDirectLowering && Act == EmitMLIR)
llvm::report_fatal_error(
"ClangIR direct lowering is incompatible with -emit-mlir");
if (Act == EmitMLIR && CI.getFrontendOpts().ClangIRDirectLowering &&
CI.getFrontendOpts().MLIRTargetDialect == FrontendOptions::MLIR_STD)
llvm::report_fatal_error("ClangIR direct lowering is incompatible with "
"emitting of MLIR standard dialects");

switch (CI.getFrontendOpts().ProgramAction) {
case ASTDeclList: return std::make_unique<ASTDeclListAction>();
Expand Down
23 changes: 23 additions & 0 deletions clang/test/CIR/emit-mlir.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -fclangir -emit-mlir %s -o - | FileCheck %s -check-prefix=LLVM
// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -fno-clangir-direct-lowering -emit-mlir %s -o - | FileCheck %s -check-prefix=STD

// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -fclangir -emit-mlir=llvm %s -o - | FileCheck %s -check-prefix=LLVM
// RUN: not %clang_cc1 -triple x86_64-unknown-linux-gnu -fclangir -emit-mlir=std %s -o - 2>&1 | FileCheck %s -check-prefix=STD_ERR

// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -fno-clangir-direct-lowering -emit-mlir=llvm %s -o - | FileCheck %s -check-prefix=LLVM
// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -fno-clangir-direct-lowering -emit-mlir=std %s -o - | FileCheck %s -check-prefix=STD

// RUN: %clang -fclangir -Xclang -emit-mlir %s -o - -### 2>&1 | FileCheck %s -check-prefix=OPTS_NO_VALUE
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the updates! Almost there, few more changes needed (sorry for not catching early):

  • The version without the EQ should be driver only.
  • cc1 only accepts the EQ version, requiring either llvm/std.
  • We can ditch MLIR_Default by picking one of the EQ values at driver time.

// RUN: %clang -fclangir -Xclang -emit-mlir=llvm %s -o - -### 2>&1 | FileCheck %s -check-prefix=OPTS_LLVM
// RUN: %clang -fno-clangir-direct-lowering -Xclang -emit-mlir=std %s -o - -### 2>&1 | FileCheck %s -check-prefix=OPTS_STD

int foo(int a, int b) {
return a + b;
}

// LLVM: llvm.func @foo
// STD: func.func @foo
// STD_ERR: ClangIR direct lowering is incompatible with emitting of MLIR standard dialects
// OPTS_NO_VALUE: "-emit-mlir"
// OPTS_LLVM: "-emit-mlir=llvm"
// OPTS_STD: "-emit-mlir=std"
Loading