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/diagnostics/Diagnostics.h"
32#include "slang/driver/Driver.h"
33#include "slang/parsing/Preprocessor.h"
34#include "slang/syntax/SyntaxPrinter.h"
35#include "slang/syntax/SyntaxTree.h"
36#include "slang/util/VersionInfo.h"
40using namespace ImportVerilog;
46 llvm::raw_string_ostream os(buffer);
47 os <<
"slang version ";
48 os << slang::VersionInfo::getMajor() <<
".";
49 os << slang::VersionInfo::getMinor() <<
".";
50 os << slang::VersionInfo::getPatch() <<
"+";
51 os << slang::VersionInfo::getHash();
61 const slang::SourceManager &sourceManager,
62 slang::SourceLocation loc) {
63 if (loc && loc.buffer() != slang::SourceLocation::NoLocation.buffer()) {
64 auto fileName = sourceManager.getFileName(loc);
65 auto line = sourceManager.getLineNumber(loc);
66 auto column = sourceManager.getColumnNumber(loc);
67 return FileLineColLoc::get(
context, fileName, line, column);
69 return UnknownLoc::get(
context);
74 const slang::SourceManager &sourceManager,
75 slang::SourceRange range) {
76 auto start = range.start();
77 auto end = range.end();
78 if (start && start.buffer() != slang::SourceLocation::NoLocation.buffer()) {
79 auto fileName = sourceManager.getFileName(start);
80 auto startLine = sourceManager.getLineNumber(start);
81 auto startColumn = sourceManager.getColumnNumber(start);
82 if (end && end.buffer() == start.buffer()) {
83 auto endLine = sourceManager.getLineNumber(end);
84 auto endColumn = sourceManager.getColumnNumber(end);
85 return FileLineColRange::get(
context, fileName, startLine, startColumn,
88 return FileLineColLoc::get(
context, fileName, startLine, startColumn);
90 return UnknownLoc::get(
context);
93Location Context::convertLocation(slang::SourceLocation loc) {
104class MlirDiagnosticClient :
public slang::DiagnosticClient {
108 void report(
const slang::ReportedDiagnostic &diag)
override {
110 auto &diagEngine =
context->getDiagEngine();
114 auto mlirDiag = diagEngine.emit(loc,
getSeverity(diag.severity));
115 mlirDiag << diag.formattedMessage;
119 auto optionName = engine->getOptionName(diag.originalDiagnostic.code);
120 if (!optionName.empty())
121 mlirDiag <<
" [-W" << optionName <<
"]";
124 for (
auto loc : std::views::reverse(diag.expansionLocs)) {
125 auto ¬e = mlirDiag.attachNote(
127 auto macroName = sourceManager->getMacroName(loc);
128 if (macroName.empty())
129 note <<
"expanded from here";
131 note <<
"expanded from macro '" << macroName <<
"'";
135 slang::SmallVector<slang::SourceLocation> includeStack;
136 getIncludeStack(diag.location.buffer(), includeStack);
137 for (
auto &loc : std::views::reverse(includeStack))
143 return ::convertLocation(
context, *sourceManager, loc);
148 return ::convertLocation(
context, *sourceManager, range);
151 static DiagnosticSeverity
getSeverity(slang::DiagnosticSeverity severity) {
153 case slang::DiagnosticSeverity::Fatal:
154 case slang::DiagnosticSeverity::Error:
155 return DiagnosticSeverity::Error;
156 case slang::DiagnosticSeverity::Warning:
157 return DiagnosticSeverity::Warning;
158 case slang::DiagnosticSeverity::Ignored:
159 case slang::DiagnosticSeverity::Note:
160 return DiagnosticSeverity::Remark;
162 llvm_unreachable(
"all slang diagnostic severities should be handled");
163 return DiagnosticSeverity::Error;
178 static bool isEqual(slang::BufferID a, slang::BufferID b) {
return a == b; }
190 ImportDriver(MLIRContext *mlirContext, TimingScope &ts,
192 : mlirContext(mlirContext), ts(ts),
193 options(options ? *options : defaultOptions) {}
195 LogicalResult prepareDriver(SourceMgr &sourceMgr);
199 MLIRContext *mlirContext;
205 slang::driver::Driver driver;
212LogicalResult ImportDriver::prepareDriver(SourceMgr &sourceMgr) {
215 auto diagClient = std::make_shared<MlirDiagnosticClient>(mlirContext);
216 driver.diagEngine.addClient(diagClient);
218 for (
const auto &value : options.commandFiles)
219 if (!driver.processCommandFiles(value, true,
228 driver.sourceManager.setDisableProximatePaths(
229 !options.makeLocationPathsProximate);
230 DenseSet<StringRef> seenBuffers;
231 for (
unsigned i = 0, e = sourceMgr.getNumBuffers(); i < e; ++i) {
232 const llvm::MemoryBuffer *mlirBuffer = sourceMgr.getMemoryBuffer(i + 1);
233 auto name = mlirBuffer->getBufferIdentifier();
234 if (!name.empty() && !seenBuffers.insert(name).second)
237 driver.sourceManager.assignText(name, mlirBuffer->getBuffer());
238 driver.sourceLoader.addBuffer(slangBuffer);
241 for (
const auto &libDir : options.libDirs)
242 driver.sourceLoader.addSearchDirectories(libDir);
244 for (
const auto &libExt : options.libExts)
245 driver.sourceLoader.addSearchExtension(libExt);
247 for (
const auto &[i, f] :
llvm::enumerate(options.libraryFiles)) {
249 auto libName =
"library " + std::to_string(i);
250 driver.sourceLoader.addLibraryFiles(libName, f);
253 for (
const auto &includeDir : options.includeDirs)
254 if (driver.sourceManager.addUserDirectories(includeDir))
257 for (
const auto &includeSystemDir : options.includeSystemDirs)
258 if (driver.sourceManager.addSystemDirectories(includeSystemDir))
262 driver.addStandardArgs();
264 driver.options.excludeExts.insert(options.excludeExts.begin(),
265 options.excludeExts.end());
266 driver.options.ignoreDirectives = options.ignoreDirectives;
268 driver.options.maxIncludeDepth = options.maxIncludeDepth;
269 driver.options.defines = options.defines;
270 driver.options.undefines = options.undefines;
271 driver.options.librariesInheritMacros = options.librariesInheritMacros;
273 driver.options.timeScale = options.timeScale;
275 .compilationFlags[slang::ast::CompilationFlags::AllowUseBeforeDeclare] =
276 options.allowUseBeforeDeclare;
278 .compilationFlags[slang::ast::CompilationFlags::IgnoreUnknownModules] =
279 options.ignoreUnknownModules;
280 driver.options.compilationFlags[slang::ast::CompilationFlags::LintMode] =
283 .compilationFlags[slang::ast::CompilationFlags::DisableInstanceCaching] =
285 driver.options.topModules = options.topModules;
286 driver.options.paramOverrides = options.paramOverrides;
288 driver.options.errorLimit = options.errorLimit;
289 driver.options.warningOptions = options.warningOptions;
291 driver.options.singleUnit = options.singleUnit;
294 if (!options.slangArgs.empty()) {
295 SmallVector<const char *> slangArgs;
296 slangArgs.push_back(
"slang");
297 for (
const auto &arg : options.slangArgs)
298 slangArgs.push_back(arg.c_str());
299 if (!driver.parseCommandLine(slangArgs.size(), slangArgs.data()))
303 return success(driver.processOptions());
308LogicalResult ImportDriver::importVerilog(ModuleOp module) {
310 auto parseTimer = ts.nest(
"Verilog parser");
311 bool parseSuccess = driver.parseAllSources();
321 slang::Diagnostics parseDiags;
322 for (
const auto &tree : driver.sourceLoader.getLibraryMaps())
323 parseDiags.append_range(tree->diagnostics());
324 for (
const auto &tree : driver.syntaxTrees)
325 parseDiags.append_range(tree->diagnostics());
326 parseDiags.sort(driver.sourceManager);
327 driver.diagEngine.issue(parseDiags);
328 return success(parseSuccess && driver.diagEngine.getNumErrors() == 0);
332 auto compileTimer = ts.nest(
"Verilog elaboration");
333 auto compilation = driver.createCompilation();
336 auto analysisTimer = ts.nest(
"Semantic analysis");
337 driver.runAnalysis(*compilation);
339 for (
auto &diag : compilation->getAllDiagnostics())
340 driver.diagEngine.issue(diag);
341 if (!parseSuccess || driver.diagEngine.getNumErrors() > 0)
352 ->loadDialect<moore::MooreDialect, hw::HWDialect, cf::ControlFlowDialect,
353 func::FuncDialect, verif::VerifDialect, ltl::LTLDialect,
354 debug::DebugDialect>();
355 auto conversionTimer = ts.nest(
"Verilog to dialect mapping");
356 Context context(options, *compilation, module, driver.sourceManager);
357 if (failed(
context.convertCompilation()))
359 conversionTimer.stop();
362 auto verifierTimer = ts.nest(
"Post-parse verification");
363 return verify(module);
368LogicalResult ImportDriver::preprocessVerilog(llvm::raw_ostream &os) {
369 auto parseTimer = ts.nest(
"Verilog preprocessing");
373 auto preprocessAndPrint = [&](slang::parsing::Preprocessor &preprocessor) {
374 slang::syntax::SyntaxPrinter output;
375 output.setIncludeComments(
false);
377 slang::parsing::Token token = preprocessor.next();
379 if (token.kind == slang::parsing::TokenKind::EndOfFile)
383 for (
auto &diag : preprocessor.getDiagnostics()) {
384 if (diag.isError()) {
385 driver.diagEngine.issue(diag);
397 auto optionBag = driver.createOptionBag();
398 if (driver.options.singleUnit ==
true) {
399 slang::BumpAllocator alloc;
400 slang::Diagnostics diagnostics;
401 slang::parsing::Preprocessor preprocessor(driver.sourceManager, alloc,
402 diagnostics, optionBag);
405 auto sources = driver.sourceLoader.loadSources();
406 for (
auto &buffer : std::views::reverse(sources))
407 preprocessor.pushSource(buffer);
408 if (failed(preprocessAndPrint(preprocessor)))
411 for (
auto &buffer : driver.sourceLoader.loadSources()) {
412 slang::BumpAllocator alloc;
413 slang::Diagnostics diagnostics;
414 slang::parsing::Preprocessor preprocessor(driver.sourceManager, alloc,
415 diagnostics, optionBag);
416 preprocessor.pushSource(buffer);
417 if (failed(preprocessAndPrint(preprocessor)))
431 MLIRContext *mlirContext, TimingScope &ts,
434 ImportDriver importDriver(mlirContext, ts, options);
435 if (failed(importDriver.prepareDriver(sourceMgr)))
437 return importDriver.importVerilog(module);
443 MLIRContext *mlirContext,
444 TimingScope &ts, llvm::raw_ostream &os,
446 ImportDriver importDriver(mlirContext, ts, options);
447 if (failed(importDriver.prepareDriver(sourceMgr)))
449 return importDriver.preprocessVerilog(os);
454 static TranslateToMLIRRegistration fromVerilog(
455 "import-verilog",
"import Verilog or SystemVerilog",
456 [](llvm::SourceMgr &sourceMgr, MLIRContext *
context) {
459 ModuleOp::create(UnknownLoc::get(
context)));
479 auto &anyPM = pm.nestAny();
480 anyPM.addPass(mlir::createCSEPass());
481 anyPM.addPass(mlir::createCanonicalizerPass());
487 pm.addPass(mlir::createSymbolDCEPass());
490 auto &anyPM = pm.nestAny();
496 auto &modulePM = pm.nest<moore::SVModuleOp>();
502 modulePM.addPass(mlir::createSROA());
507 auto &anyPM = pm.nestAny();
508 anyPM.addPass(mlir::createMem2Reg());
509 anyPM.addPass(mlir::createCSEPass());
510 anyPM.addPass(mlir::createCanonicalizerPass());
522 auto &anyPM = pm.nestAny();
523 anyPM.addPass(mlir::createCSEPass());
524 anyPM.addPass(mlir::createCanonicalizerPass());
532 pm.addNestedPass<
hw::HWModuleOp>(llhd::createWrapProceduralOpsPass());
533 pm.addPass(mlir::createSCFToControlFlowPass());
534 pm.addPass(llhd::createInlineCallsPass());
535 pm.addPass(mlir::createSymbolDCEPass());
542 modulePM.addPass(mlir::createSROA());
544 modulePM.addPass(llhd::createMem2RegPass());
545 modulePM.addPass(llhd::createHoistSignalsPass());
546 modulePM.addPass(llhd::createDeseqPass());
547 modulePM.addPass(llhd::createLowerProcessesPass());
548 modulePM.addPass(mlir::createCSEPass());
549 modulePM.addPass(mlir::createCanonicalizerPass());
552 modulePM.addPass(llhd::createUnrollLoopsPass());
553 modulePM.addPass(mlir::createCSEPass());
554 modulePM.addPass(mlir::createCanonicalizerPass());
555 modulePM.addPass(llhd::createRemoveControlFlowPass());
556 modulePM.addPass(mlir::createCSEPass());
557 modulePM.addPass(mlir::createCanonicalizerPass());
564 modulePM.addPass(llhd::createCombineDrivesPass());
565 modulePM.addPass(llhd::createSig2Reg());
566 modulePM.addPass(mlir::createCSEPass());
567 modulePM.addPass(mlir::createCanonicalizerPass());
572 modulePM.addPass(seq::createRegOfVecToMem());
573 modulePM.addPass(mlir::createCSEPass());
574 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.
@ OnlyParse
Only parse the input syntax and report parse diagnostics.
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 unsigned getHashValue(slang::BufferID id)