19#include "mlir/Conversion/SCFToControlFlow/SCFToControlFlow.h"
20#include "mlir/IR/Diagnostics.h"
21#include "mlir/IR/Verifier.h"
22#include "mlir/Pass/PassManager.h"
23#include "mlir/Support/Timing.h"
24#include "mlir/Tools/mlir-translate/Translation.h"
25#include "mlir/Transforms/Passes.h"
26#include "llvm/ADT/Hashing.h"
27#include "llvm/Support/SourceMgr.h"
29#include "slang/analysis/AnalysisManager.h"
30#include "slang/diagnostics/DiagnosticClient.h"
31#include "slang/driver/Driver.h"
32#include "slang/parsing/Preprocessor.h"
33#include "slang/syntax/SyntaxPrinter.h"
34#include "slang/util/VersionInfo.h"
38using namespace ImportVerilog;
44 llvm::raw_string_ostream os(buffer);
45 os <<
"slang version ";
46 os << slang::VersionInfo::getMajor() <<
".";
47 os << slang::VersionInfo::getMinor() <<
".";
48 os << slang::VersionInfo::getPatch() <<
"+";
49 os << slang::VersionInfo::getHash();
59 const slang::SourceManager &sourceManager,
60 slang::SourceLocation loc) {
61 if (loc && loc.buffer() != slang::SourceLocation::NoLocation.buffer()) {
62 auto fileName = sourceManager.getFileName(loc);
63 auto line = sourceManager.getLineNumber(loc);
64 auto column = sourceManager.getColumnNumber(loc);
65 return FileLineColLoc::get(
context, fileName, line, column);
67 return UnknownLoc::get(
context);
72 const slang::SourceManager &sourceManager,
73 slang::SourceRange range) {
74 auto start = range.start();
75 auto end = range.end();
76 if (start && start.buffer() != slang::SourceLocation::NoLocation.buffer()) {
77 auto fileName = sourceManager.getFileName(start);
78 auto startLine = sourceManager.getLineNumber(start);
79 auto startColumn = sourceManager.getColumnNumber(start);
80 if (end && end.buffer() == start.buffer()) {
81 auto endLine = sourceManager.getLineNumber(end);
82 auto endColumn = sourceManager.getColumnNumber(end);
83 return FileLineColRange::get(
context, fileName, startLine, startColumn,
86 return FileLineColLoc::get(
context, fileName, startLine, startColumn);
88 return UnknownLoc::get(
context);
91Location Context::convertLocation(slang::SourceLocation loc) {
102class MlirDiagnosticClient :
public slang::DiagnosticClient {
106 void report(
const slang::ReportedDiagnostic &diag)
override {
108 auto &diagEngine =
context->getDiagEngine();
112 auto mlirDiag = diagEngine.emit(loc,
getSeverity(diag.severity));
113 mlirDiag << diag.formattedMessage;
117 auto optionName = engine->getOptionName(diag.originalDiagnostic.code);
118 if (!optionName.empty())
119 mlirDiag <<
" [-W" << optionName <<
"]";
122 for (
auto loc : std::views::reverse(diag.expansionLocs)) {
123 auto ¬e = mlirDiag.attachNote(
125 auto macroName = sourceManager->getMacroName(loc);
126 if (macroName.empty())
127 note <<
"expanded from here";
129 note <<
"expanded from macro '" << macroName <<
"'";
133 slang::SmallVector<slang::SourceLocation> includeStack;
134 getIncludeStack(diag.location.buffer(), includeStack);
135 for (
auto &loc : std::views::reverse(includeStack))
141 return ::convertLocation(
context, *sourceManager, loc);
146 return ::convertLocation(
context, *sourceManager, range);
149 static DiagnosticSeverity
getSeverity(slang::DiagnosticSeverity severity) {
151 case slang::DiagnosticSeverity::Fatal:
152 case slang::DiagnosticSeverity::Error:
153 return DiagnosticSeverity::Error;
154 case slang::DiagnosticSeverity::Warning:
155 return DiagnosticSeverity::Warning;
156 case slang::DiagnosticSeverity::Ignored:
157 case slang::DiagnosticSeverity::Note:
158 return DiagnosticSeverity::Remark;
160 llvm_unreachable(
"all slang diagnostic severities should be handled");
161 return DiagnosticSeverity::Error;
173 static slang::BufferID
getEmptyKey() {
return slang::BufferID(); }
175 return slang::BufferID(UINT32_MAX - 1,
""sv);
181 static bool isEqual(slang::BufferID a, slang::BufferID b) {
return a == b; }
193 ImportDriver(MLIRContext *mlirContext, TimingScope &ts,
195 : mlirContext(mlirContext), ts(ts),
196 options(options ? *options : defaultOptions) {}
198 LogicalResult prepareDriver(SourceMgr &sourceMgr);
202 MLIRContext *mlirContext;
208 slang::driver::Driver driver;
215LogicalResult ImportDriver::prepareDriver(SourceMgr &sourceMgr) {
218 auto diagClient = std::make_shared<MlirDiagnosticClient>(mlirContext);
219 driver.diagEngine.addClient(diagClient);
221 for (
const auto &value : options.commandFiles)
222 if (!driver.processCommandFiles(value, true,
231 DenseSet<StringRef> seenBuffers;
232 for (
unsigned i = 0, e = sourceMgr.getNumBuffers(); i < e; ++i) {
233 const llvm::MemoryBuffer *mlirBuffer = sourceMgr.getMemoryBuffer(i + 1);
234 auto name = mlirBuffer->getBufferIdentifier();
235 if (!name.empty() && !seenBuffers.insert(name).second)
238 driver.sourceManager.assignText(name, mlirBuffer->getBuffer());
239 driver.sourceLoader.addBuffer(slangBuffer);
242 for (
const auto &libDir : options.libDirs)
243 driver.sourceLoader.addSearchDirectories(libDir);
245 for (
const auto &libExt : options.libExts)
246 driver.sourceLoader.addSearchExtension(libExt);
248 for (
const auto &[i, f] :
llvm::enumerate(options.libraryFiles)) {
250 auto libName =
"library " + std::to_string(i);
251 driver.sourceLoader.addLibraryFiles(libName, f);
254 for (
const auto &includeDir : options.includeDirs)
255 if (driver.sourceManager.addUserDirectories(includeDir))
258 for (
const auto &includeSystemDir : options.includeSystemDirs)
259 if (driver.sourceManager.addSystemDirectories(includeSystemDir))
263 driver.addStandardArgs();
265 driver.options.excludeExts.insert(options.excludeExts.begin(),
266 options.excludeExts.end());
267 driver.options.ignoreDirectives = options.ignoreDirectives;
269 driver.options.maxIncludeDepth = options.maxIncludeDepth;
270 driver.options.defines = options.defines;
271 driver.options.undefines = options.undefines;
272 driver.options.librariesInheritMacros = options.librariesInheritMacros;
274 driver.options.timeScale = options.timeScale;
276 .compilationFlags[slang::ast::CompilationFlags::AllowUseBeforeDeclare] =
277 options.allowUseBeforeDeclare;
279 .compilationFlags[slang::ast::CompilationFlags::IgnoreUnknownModules] =
280 options.ignoreUnknownModules;
281 driver.options.compilationFlags[slang::ast::CompilationFlags::LintMode] =
284 .compilationFlags[slang::ast::CompilationFlags::DisableInstanceCaching] =
286 driver.options.topModules = options.topModules;
287 driver.options.paramOverrides = options.paramOverrides;
289 driver.options.errorLimit = options.errorLimit;
290 driver.options.warningOptions = options.warningOptions;
292 driver.options.singleUnit = options.singleUnit;
295 if (!options.slangArgs.empty()) {
296 SmallVector<const char *> slangArgs;
297 slangArgs.push_back(
"slang");
298 for (
const auto &arg : options.slangArgs)
299 slangArgs.push_back(arg.c_str());
300 if (!driver.parseCommandLine(slangArgs.size(), slangArgs.data()))
304 return success(driver.processOptions());
309LogicalResult ImportDriver::importVerilog(ModuleOp module) {
311 auto parseTimer = ts.nest(
"Verilog parser");
312 bool parseSuccess = driver.parseAllSources();
316 auto compileTimer = ts.nest(
"Verilog elaboration");
317 auto compilation = driver.createCompilation();
320 auto analysisTimer = ts.nest(
"Semantic analysis");
321 driver.runAnalysis(*compilation);
323 for (
auto &diag : compilation->getAllDiagnostics())
324 driver.diagEngine.issue(diag);
325 if (!parseSuccess || driver.diagEngine.getNumErrors() > 0)
336 ->loadDialect<moore::MooreDialect, hw::HWDialect, cf::ControlFlowDialect,
337 func::FuncDialect, verif::VerifDialect, ltl::LTLDialect,
338 debug::DebugDialect>();
339 auto conversionTimer = ts.nest(
"Verilog to dialect mapping");
340 Context context(options, *compilation, module, driver.sourceManager);
341 if (failed(
context.convertCompilation()))
343 conversionTimer.stop();
346 auto verifierTimer = ts.nest(
"Post-parse verification");
347 return verify(module);
352LogicalResult ImportDriver::preprocessVerilog(llvm::raw_ostream &os) {
353 auto parseTimer = ts.nest(
"Verilog preprocessing");
357 auto preprocessAndPrint = [&](slang::parsing::Preprocessor &preprocessor) {
358 slang::syntax::SyntaxPrinter output;
359 output.setIncludeComments(
false);
361 slang::parsing::Token token = preprocessor.next();
363 if (token.kind == slang::parsing::TokenKind::EndOfFile)
367 for (
auto &diag : preprocessor.getDiagnostics()) {
368 if (diag.isError()) {
369 driver.diagEngine.issue(diag);
381 auto optionBag = driver.createOptionBag();
382 if (driver.options.singleUnit ==
true) {
383 slang::BumpAllocator alloc;
384 slang::Diagnostics diagnostics;
385 slang::parsing::Preprocessor preprocessor(driver.sourceManager, alloc,
386 diagnostics, optionBag);
389 auto sources = driver.sourceLoader.loadSources();
390 for (
auto &buffer : std::views::reverse(sources))
391 preprocessor.pushSource(buffer);
392 if (failed(preprocessAndPrint(preprocessor)))
395 for (
auto &buffer : driver.sourceLoader.loadSources()) {
396 slang::BumpAllocator alloc;
397 slang::Diagnostics diagnostics;
398 slang::parsing::Preprocessor preprocessor(driver.sourceManager, alloc,
399 diagnostics, optionBag);
400 preprocessor.pushSource(buffer);
401 if (failed(preprocessAndPrint(preprocessor)))
415 MLIRContext *mlirContext, TimingScope &ts,
418 ImportDriver importDriver(mlirContext, ts, options);
419 if (failed(importDriver.prepareDriver(sourceMgr)))
421 return importDriver.importVerilog(module);
427 MLIRContext *mlirContext,
428 TimingScope &ts, llvm::raw_ostream &os,
430 ImportDriver importDriver(mlirContext, ts, options);
431 if (failed(importDriver.prepareDriver(sourceMgr)))
433 return importDriver.preprocessVerilog(os);
438 static TranslateToMLIRRegistration fromVerilog(
439 "import-verilog",
"import Verilog or SystemVerilog",
440 [](llvm::SourceMgr &sourceMgr, MLIRContext *
context) {
443 ModuleOp::create(UnknownLoc::get(
context)));
463 auto &anyPM = pm.nestAny();
464 anyPM.addPass(mlir::createCSEPass());
465 anyPM.addPass(mlir::createCanonicalizerPass());
471 pm.addPass(mlir::createSymbolDCEPass());
475 auto &modulePM = pm.nest<moore::SVModuleOp>();
482 modulePM.addPass(mlir::createSROA());
487 auto &anyPM = pm.nestAny();
488 anyPM.addPass(mlir::createMem2Reg());
489 anyPM.addPass(mlir::createCSEPass());
490 anyPM.addPass(mlir::createCanonicalizerPass());
502 auto &anyPM = pm.nestAny();
503 anyPM.addPass(mlir::createCSEPass());
504 anyPM.addPass(mlir::createCanonicalizerPass());
512 pm.addNestedPass<
hw::HWModuleOp>(llhd::createWrapProceduralOpsPass());
513 pm.addPass(mlir::createSCFToControlFlowPass());
514 pm.addPass(llhd::createInlineCallsPass());
515 pm.addPass(mlir::createSymbolDCEPass());
522 modulePM.addPass(mlir::createSROA());
524 modulePM.addPass(llhd::createMem2RegPass());
525 modulePM.addPass(llhd::createHoistSignalsPass());
526 modulePM.addPass(llhd::createDeseqPass());
527 modulePM.addPass(llhd::createLowerProcessesPass());
528 modulePM.addPass(mlir::createCSEPass());
529 modulePM.addPass(mlir::createCanonicalizerPass());
532 modulePM.addPass(llhd::createUnrollLoopsPass());
533 modulePM.addPass(mlir::createCSEPass());
534 modulePM.addPass(mlir::createCanonicalizerPass());
535 modulePM.addPass(llhd::createRemoveControlFlowPass());
536 modulePM.addPass(mlir::createCSEPass());
537 modulePM.addPass(mlir::createCanonicalizerPass());
544 modulePM.addPass(llhd::createCombineDrivesPass());
545 modulePM.addPass(llhd::createSig2Reg());
546 modulePM.addPass(mlir::createCSEPass());
547 modulePM.addPass(mlir::createCanonicalizerPass());
552 modulePM.addPass(seq::createRegOfVecToMem());
553 modulePM.addPass(mlir::createCSEPass());
554 modulePM.addPass(mlir::createCanonicalizerPass());
static std::unique_ptr< Context > context
static Location convertLocation(MLIRContext *context, const slang::SourceManager &sourceManager, slang::SourceLocation loc)
Convert a slang SourceLocation to an MLIR Location.
static llvm::lsp::DiagnosticSeverity getSeverity(slang::DiagnosticSeverity severity)
std::unique_ptr< mlir::Pass > createSimplifyRefsPass()
std::unique_ptr< mlir::Pass > createVTablesPass()
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
std::unique_ptr< mlir::Pass > createMapArithToCombPass(bool enableBestEffortLowering=false)
void populateVerilogToMoorePipeline(mlir::OpPassManager &pm)
Optimize and simplify the Moore dialect IR.
void populateMooreToCorePipeline(mlir::OpPassManager &pm)
Convert Moore dialect IR into core dialect IR.
void populateLlhdToCorePipeline(mlir::OpPassManager &pm, const LlhdToCorePipelineOptions &options)
std::string getSlangVersion()
Return a human-readable string describing the slang frontend version linked into CIRCT.
std::unique_ptr< OperationPass< ModuleOp > > createConvertMooreToCorePass()
Create an Moore to Comb/HW/LLHD conversion pass.
mlir::LogicalResult importVerilog(llvm::SourceMgr &sourceMgr, mlir::MLIRContext *context, mlir::TimingScope &ts, mlir::ModuleOp module, const ImportVerilogOptions *options=nullptr)
Parse files in a source manager as Verilog source code and populate the given MLIR module with corres...
mlir::LogicalResult preprocessVerilog(llvm::SourceMgr &sourceMgr, mlir::MLIRContext *context, mlir::TimingScope &ts, llvm::raw_ostream &os, const ImportVerilogOptions *options=nullptr)
Run the files in a source manager through Slang's Verilog preprocessor and emit the result to the giv...
void registerFromVerilogTranslation()
Register the import-verilog MLIR translation.
llvm::hash_code hash_value(const DenseSet< T > &set)
Options that control how Verilog input files are parsed and processed.
std::vector< std::string > warningOptions
A list of warning options that will be passed to the DiagnosticEngine.
@ OnlyLint
Only lint the input, without elaboration and lowering to CIRCT IR.
bool debugInfo
Generate debug information in the form of debug dialect ops in the IR.
A helper class to facilitate the conversion from a Slang AST to MLIR operations.
const slang::SourceManager & sourceManager
MLIRContext * getContext()
Return the MLIR context.
Location convertLocation(slang::SourceLocation loc)
Convert a slang SourceLocation into an MLIR Location.
Convert LLHD dialect IR into core dialect IR.
Option< bool > detectMemories
static bool isEqual(slang::BufferID a, slang::BufferID b)
static slang::BufferID getEmptyKey()
static slang::BufferID getTombstoneKey()
static unsigned getHashValue(slang::BufferID id)