1 //===- MLIRServer.cpp - MLIR Generic Language Server ----------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "MLIRServer.h" 10 #include "lsp/Logging.h" 11 #include "lsp/Protocol.h" 12 #include "mlir/IR/Operation.h" 13 #include "mlir/Parser.h" 14 #include "mlir/Parser/AsmParserState.h" 15 #include "llvm/Support/SourceMgr.h" 16 17 using namespace mlir; 18 19 /// Returns a language server position for the given source location. 20 static lsp::Position getPosFromLoc(llvm::SourceMgr &mgr, llvm::SMLoc loc) { 21 std::pair<unsigned, unsigned> lineAndCol = mgr.getLineAndColumn(loc); 22 lsp::Position pos; 23 pos.line = lineAndCol.first - 1; 24 pos.character = lineAndCol.second; 25 return pos; 26 } 27 28 /// Returns a source location from the given language server position. 29 static llvm::SMLoc getPosFromLoc(llvm::SourceMgr &mgr, lsp::Position pos) { 30 return mgr.FindLocForLineAndColumn(mgr.getMainFileID(), pos.line + 1, 31 pos.character); 32 } 33 34 /// Returns a language server range for the given source range. 35 static lsp::Range getRangeFromLoc(llvm::SourceMgr &mgr, llvm::SMRange range) { 36 // lsp::Range is an inclusive range, SMRange is half-open. 37 llvm::SMLoc inclusiveEnd = 38 llvm::SMLoc::getFromPointer(range.End.getPointer() - 1); 39 return {getPosFromLoc(mgr, range.Start), getPosFromLoc(mgr, inclusiveEnd)}; 40 } 41 42 /// Returns a language server location from the given source range. 43 static lsp::Location getLocationFromLoc(llvm::SourceMgr &mgr, 44 llvm::SMRange range, 45 const lsp::URIForFile &uri) { 46 return lsp::Location{uri, getRangeFromLoc(mgr, range)}; 47 } 48 49 /// Returns a language server location from the given MLIR file location. 50 static Optional<lsp::Location> getLocationFromLoc(FileLineColLoc loc) { 51 llvm::Expected<lsp::URIForFile> sourceURI = 52 lsp::URIForFile::fromFile(loc.getFilename()); 53 if (!sourceURI) { 54 lsp::Logger::error("Failed to create URI for file `{0}`: {1}", 55 loc.getFilename(), 56 llvm::toString(sourceURI.takeError())); 57 return llvm::None; 58 } 59 60 lsp::Position position; 61 position.line = loc.getLine() - 1; 62 position.character = loc.getColumn(); 63 return lsp::Location{*sourceURI, lsp::Range{position, position}}; 64 } 65 66 /// Collect all of the locations from the given MLIR location that are not 67 /// contained within the given URI. 68 static void collectLocationsFromLoc(Location loc, 69 std::vector<lsp::Location> &locations, 70 const lsp::URIForFile &uri) { 71 SetVector<Location> visitedLocs; 72 loc->walk([&](Location nestedLoc) { 73 FileLineColLoc fileLoc = nestedLoc.dyn_cast<FileLineColLoc>(); 74 if (!fileLoc || !visitedLocs.insert(nestedLoc)) 75 return WalkResult::advance(); 76 77 Optional<lsp::Location> sourceLoc = getLocationFromLoc(fileLoc); 78 if (sourceLoc && sourceLoc->uri != uri) 79 locations.push_back(*sourceLoc); 80 return WalkResult::advance(); 81 }); 82 } 83 84 /// Returns true if the given range contains the given source location. Note 85 /// that this has slightly different behavior than SMRange because it is 86 /// inclusive of the end location. 87 static bool contains(llvm::SMRange range, llvm::SMLoc loc) { 88 return range.Start.getPointer() <= loc.getPointer() && 89 loc.getPointer() <= range.End.getPointer(); 90 } 91 92 /// Returns true if the given location is contained by the definition or one of 93 /// the uses of the given SMDefinition. If provided, `overlappedRange` is set to 94 /// the range within `def` that the provided `loc` overlapped with. 95 static bool isDefOrUse(const AsmParserState::SMDefinition &def, llvm::SMLoc loc, 96 llvm::SMRange *overlappedRange = nullptr) { 97 // Check the main definition. 98 if (contains(def.loc, loc)) { 99 if (overlappedRange) 100 *overlappedRange = def.loc; 101 return true; 102 } 103 104 // Check the uses. 105 auto useIt = llvm::find_if(def.uses, [&](const llvm::SMRange &range) { 106 return contains(range, loc); 107 }); 108 if (useIt != def.uses.end()) { 109 if (overlappedRange) 110 *overlappedRange = *useIt; 111 return true; 112 } 113 return false; 114 } 115 116 /// Given a location pointing to a result, return the result number it refers 117 /// to or None if it refers to all of the results. 118 static Optional<unsigned> getResultNumberFromLoc(llvm::SMLoc loc) { 119 // Skip all of the identifier characters. 120 auto isIdentifierChar = [](char c) { 121 return isalnum(c) || c == '%' || c == '$' || c == '.' || c == '_' || 122 c == '-'; 123 }; 124 const char *curPtr = loc.getPointer(); 125 while (isIdentifierChar(*curPtr)) 126 ++curPtr; 127 128 // Check to see if this location indexes into the result group, via `#`. If it 129 // doesn't, we can't extract a sub result number. 130 if (*curPtr != '#') 131 return llvm::None; 132 133 // Compute the sub result number from the remaining portion of the string. 134 const char *numberStart = ++curPtr; 135 while (llvm::isDigit(*curPtr)) 136 ++curPtr; 137 StringRef numberStr(numberStart, curPtr - numberStart); 138 unsigned resultNumber = 0; 139 return numberStr.consumeInteger(10, resultNumber) ? Optional<unsigned>() 140 : resultNumber; 141 } 142 143 /// Given a source location range, return the text covered by the given range. 144 /// If the range is invalid, returns None. 145 static Optional<StringRef> getTextFromRange(llvm::SMRange range) { 146 if (!range.isValid()) 147 return None; 148 const char *startPtr = range.Start.getPointer(); 149 return StringRef(startPtr, range.End.getPointer() - startPtr); 150 } 151 152 /// Given a block, return its position in its parent region. 153 static unsigned getBlockNumber(Block *block) { 154 return std::distance(block->getParent()->begin(), block->getIterator()); 155 } 156 157 /// Given a block and source location, print the source name of the block to the 158 /// given output stream. 159 static void printDefBlockName(raw_ostream &os, Block *block, 160 llvm::SMRange loc = {}) { 161 // Try to extract a name from the source location. 162 Optional<StringRef> text = getTextFromRange(loc); 163 if (text && text->startswith("^")) { 164 os << *text; 165 return; 166 } 167 168 // Otherwise, we don't have a name so print the block number. 169 os << "<Block #" << getBlockNumber(block) << ">"; 170 } 171 static void printDefBlockName(raw_ostream &os, 172 const AsmParserState::BlockDefinition &def) { 173 printDefBlockName(os, def.block, def.definition.loc); 174 } 175 176 //===----------------------------------------------------------------------===// 177 // MLIRDocument 178 //===----------------------------------------------------------------------===// 179 180 namespace { 181 /// This class represents all of the information pertaining to a specific MLIR 182 /// document. 183 struct MLIRDocument { 184 MLIRDocument(const lsp::URIForFile &uri, StringRef contents, 185 DialectRegistry ®istry); 186 187 //===--------------------------------------------------------------------===// 188 // Definitions and References 189 //===--------------------------------------------------------------------===// 190 191 void getLocationsOf(const lsp::URIForFile &uri, const lsp::Position &defPos, 192 std::vector<lsp::Location> &locations); 193 void findReferencesOf(const lsp::URIForFile &uri, const lsp::Position &pos, 194 std::vector<lsp::Location> &references); 195 196 //===--------------------------------------------------------------------===// 197 // Hover 198 //===--------------------------------------------------------------------===// 199 200 Optional<lsp::Hover> findHover(const lsp::URIForFile &uri, 201 const lsp::Position &hoverPos); 202 Optional<lsp::Hover> 203 buildHoverForOperation(const AsmParserState::OperationDefinition &op); 204 lsp::Hover buildHoverForOperationResult(llvm::SMRange hoverRange, 205 Operation *op, unsigned resultStart, 206 unsigned resultEnd, 207 llvm::SMLoc posLoc); 208 lsp::Hover buildHoverForBlock(llvm::SMRange hoverRange, 209 const AsmParserState::BlockDefinition &block); 210 lsp::Hover 211 buildHoverForBlockArgument(llvm::SMRange hoverRange, BlockArgument arg, 212 const AsmParserState::BlockDefinition &block); 213 214 /// The context used to hold the state contained by the parsed document. 215 MLIRContext context; 216 217 /// The high level parser state used to find definitions and references within 218 /// the source file. 219 AsmParserState asmState; 220 221 /// The container for the IR parsed from the input file. 222 Block parsedIR; 223 224 /// The source manager containing the contents of the input file. 225 llvm::SourceMgr sourceMgr; 226 }; 227 } // namespace 228 229 MLIRDocument::MLIRDocument(const lsp::URIForFile &uri, StringRef contents, 230 DialectRegistry ®istry) 231 : context(registry) { 232 context.allowUnregisteredDialects(); 233 ScopedDiagnosticHandler handler(&context, [&](Diagnostic &diag) { 234 // TODO: What should we do with these diagnostics? 235 // * Cache and show to the user? 236 // * Ignore? 237 lsp::Logger::error("Error when parsing MLIR document `{0}`: `{1}`", 238 uri.file(), diag.str()); 239 }); 240 241 // Try to parsed the given IR string. 242 auto memBuffer = llvm::MemoryBuffer::getMemBufferCopy(contents, uri.file()); 243 if (!memBuffer) { 244 lsp::Logger::error("Failed to create memory buffer for file", uri.file()); 245 return; 246 } 247 248 sourceMgr.AddNewSourceBuffer(std::move(memBuffer), llvm::SMLoc()); 249 if (failed( 250 parseSourceFile(sourceMgr, &parsedIR, &context, nullptr, &asmState))) 251 return; 252 } 253 254 //===----------------------------------------------------------------------===// 255 // MLIRDocument: Definitions and References 256 //===----------------------------------------------------------------------===// 257 258 void MLIRDocument::getLocationsOf(const lsp::URIForFile &uri, 259 const lsp::Position &defPos, 260 std::vector<lsp::Location> &locations) { 261 llvm::SMLoc posLoc = getPosFromLoc(sourceMgr, defPos); 262 263 // Functor used to check if an SM definition contains the position. 264 auto containsPosition = [&](const AsmParserState::SMDefinition &def) { 265 if (!isDefOrUse(def, posLoc)) 266 return false; 267 locations.push_back(getLocationFromLoc(sourceMgr, def.loc, uri)); 268 return true; 269 }; 270 271 // Check all definitions related to operations. 272 for (const AsmParserState::OperationDefinition &op : asmState.getOpDefs()) { 273 if (contains(op.loc, posLoc)) 274 return collectLocationsFromLoc(op.op->getLoc(), locations, uri); 275 for (const auto &result : op.resultGroups) 276 if (containsPosition(result.second)) 277 return collectLocationsFromLoc(op.op->getLoc(), locations, uri); 278 } 279 280 // Check all definitions related to blocks. 281 for (const AsmParserState::BlockDefinition &block : asmState.getBlockDefs()) { 282 if (containsPosition(block.definition)) 283 return; 284 for (const AsmParserState::SMDefinition &arg : block.arguments) 285 if (containsPosition(arg)) 286 return; 287 } 288 } 289 290 void MLIRDocument::findReferencesOf(const lsp::URIForFile &uri, 291 const lsp::Position &pos, 292 std::vector<lsp::Location> &references) { 293 // Functor used to append all of the definitions/uses of the given SM 294 // definition to the reference list. 295 auto appendSMDef = [&](const AsmParserState::SMDefinition &def) { 296 references.push_back(getLocationFromLoc(sourceMgr, def.loc, uri)); 297 for (const llvm::SMRange &use : def.uses) 298 references.push_back(getLocationFromLoc(sourceMgr, use, uri)); 299 }; 300 301 llvm::SMLoc posLoc = getPosFromLoc(sourceMgr, pos); 302 303 // Check all definitions related to operations. 304 for (const AsmParserState::OperationDefinition &op : asmState.getOpDefs()) { 305 if (contains(op.loc, posLoc)) { 306 for (const auto &result : op.resultGroups) 307 appendSMDef(result.second); 308 return; 309 } 310 for (const auto &result : op.resultGroups) 311 if (isDefOrUse(result.second, posLoc)) 312 return appendSMDef(result.second); 313 } 314 315 // Check all definitions related to blocks. 316 for (const AsmParserState::BlockDefinition &block : asmState.getBlockDefs()) { 317 if (isDefOrUse(block.definition, posLoc)) 318 return appendSMDef(block.definition); 319 320 for (const AsmParserState::SMDefinition &arg : block.arguments) 321 if (isDefOrUse(arg, posLoc)) 322 return appendSMDef(arg); 323 } 324 } 325 326 //===----------------------------------------------------------------------===// 327 // MLIRDocument: Hover 328 //===----------------------------------------------------------------------===// 329 330 Optional<lsp::Hover> MLIRDocument::findHover(const lsp::URIForFile &uri, 331 const lsp::Position &hoverPos) { 332 llvm::SMLoc posLoc = getPosFromLoc(sourceMgr, hoverPos); 333 llvm::SMRange hoverRange; 334 335 // Check for Hovers on operations and results. 336 for (const AsmParserState::OperationDefinition &op : asmState.getOpDefs()) { 337 // Check if the position points at this operation. 338 if (contains(op.loc, posLoc)) 339 return buildHoverForOperation(op); 340 341 // Check if the position points at a result group. 342 for (unsigned i = 0, e = op.resultGroups.size(); i < e; ++i) { 343 const auto &result = op.resultGroups[i]; 344 if (!isDefOrUse(result.second, posLoc, &hoverRange)) 345 continue; 346 347 // Get the range of results covered by the over position. 348 unsigned resultStart = result.first; 349 unsigned resultEnd = 350 (i == e - 1) ? op.op->getNumResults() : op.resultGroups[i + 1].first; 351 return buildHoverForOperationResult(hoverRange, op.op, resultStart, 352 resultEnd, posLoc); 353 } 354 } 355 356 // Check to see if the hover is over a block argument. 357 for (const AsmParserState::BlockDefinition &block : asmState.getBlockDefs()) { 358 if (isDefOrUse(block.definition, posLoc, &hoverRange)) 359 return buildHoverForBlock(hoverRange, block); 360 361 for (const auto &arg : llvm::enumerate(block.arguments)) { 362 if (!isDefOrUse(arg.value(), posLoc, &hoverRange)) 363 continue; 364 365 return buildHoverForBlockArgument( 366 hoverRange, block.block->getArgument(arg.index()), block); 367 } 368 } 369 return llvm::None; 370 } 371 372 Optional<lsp::Hover> MLIRDocument::buildHoverForOperation( 373 const AsmParserState::OperationDefinition &op) { 374 // Don't show hovers for operations with regions to avoid huge hover blocks. 375 // TODO: Should we add support for printing an op without its regions? 376 if (llvm::any_of(op.op->getRegions(), 377 [](Region ®ion) { return !region.empty(); })) 378 return llvm::None; 379 380 lsp::Hover hover(getRangeFromLoc(sourceMgr, op.loc)); 381 llvm::raw_string_ostream os(hover.contents.value); 382 383 // For hovers on an operation, show the generic form. 384 os << "```mlir\n"; 385 op.op->print( 386 os, OpPrintingFlags().printGenericOpForm().elideLargeElementsAttrs()); 387 os << "\n```\n"; 388 389 return hover; 390 } 391 392 lsp::Hover MLIRDocument::buildHoverForOperationResult(llvm::SMRange hoverRange, 393 Operation *op, 394 unsigned resultStart, 395 unsigned resultEnd, 396 llvm::SMLoc posLoc) { 397 lsp::Hover hover(getRangeFromLoc(sourceMgr, hoverRange)); 398 llvm::raw_string_ostream os(hover.contents.value); 399 400 // Add the parent operation name to the hover. 401 os << "Operation: \"" << op->getName() << "\"\n\n"; 402 403 // Check to see if the location points to a specific result within the 404 // group. 405 if (Optional<unsigned> resultNumber = getResultNumberFromLoc(posLoc)) { 406 if ((resultStart + *resultNumber) < resultEnd) { 407 resultStart += *resultNumber; 408 resultEnd = resultStart + 1; 409 } 410 } 411 412 // Add the range of results and their types to the hover info. 413 if ((resultStart + 1) == resultEnd) { 414 os << "Result #" << resultStart << "\n\n" 415 << "Type: `" << op->getResult(resultStart).getType() << "`\n\n"; 416 } else { 417 os << "Result #[" << resultStart << ", " << (resultEnd - 1) << "]\n\n" 418 << "Types: "; 419 llvm::interleaveComma( 420 op->getResults().slice(resultStart, resultEnd), os, 421 [&](Value result) { os << "`" << result.getType() << "`"; }); 422 } 423 424 return hover; 425 } 426 427 lsp::Hover 428 MLIRDocument::buildHoverForBlock(llvm::SMRange hoverRange, 429 const AsmParserState::BlockDefinition &block) { 430 lsp::Hover hover(getRangeFromLoc(sourceMgr, hoverRange)); 431 llvm::raw_string_ostream os(hover.contents.value); 432 433 // Print the given block to the hover output stream. 434 auto printBlockToHover = [&](Block *newBlock) { 435 if (const auto *def = asmState.getBlockDef(newBlock)) 436 printDefBlockName(os, *def); 437 else 438 printDefBlockName(os, newBlock); 439 }; 440 441 // Display the parent operation, block number, predecessors, and successors. 442 os << "Operation: \"" << block.block->getParentOp()->getName() << "\"\n\n" 443 << "Block #" << getBlockNumber(block.block) << "\n\n"; 444 if (!block.block->hasNoPredecessors()) { 445 os << "Predecessors: "; 446 llvm::interleaveComma(block.block->getPredecessors(), os, 447 printBlockToHover); 448 os << "\n\n"; 449 } 450 if (!block.block->hasNoSuccessors()) { 451 os << "Successors: "; 452 llvm::interleaveComma(block.block->getSuccessors(), os, printBlockToHover); 453 os << "\n\n"; 454 } 455 456 return hover; 457 } 458 459 lsp::Hover MLIRDocument::buildHoverForBlockArgument( 460 llvm::SMRange hoverRange, BlockArgument arg, 461 const AsmParserState::BlockDefinition &block) { 462 lsp::Hover hover(getRangeFromLoc(sourceMgr, hoverRange)); 463 llvm::raw_string_ostream os(hover.contents.value); 464 465 // Display the parent operation, block, the argument number, and the type. 466 os << "Operation: \"" << block.block->getParentOp()->getName() << "\"\n\n" 467 << "Block: "; 468 printDefBlockName(os, block); 469 os << "\n\nArgument #" << arg.getArgNumber() << "\n\n" 470 << "Type: `" << arg.getType() << "`\n\n"; 471 472 return hover; 473 } 474 475 //===----------------------------------------------------------------------===// 476 // MLIRServer::Impl 477 //===----------------------------------------------------------------------===// 478 479 struct lsp::MLIRServer::Impl { 480 Impl(DialectRegistry ®istry) : registry(registry) {} 481 482 /// The registry containing dialects that can be recognized in parsed .mlir 483 /// files. 484 DialectRegistry ®istry; 485 486 /// The documents held by the server, mapped by their URI file name. 487 llvm::StringMap<std::unique_ptr<MLIRDocument>> documents; 488 }; 489 490 //===----------------------------------------------------------------------===// 491 // MLIRServer 492 //===----------------------------------------------------------------------===// 493 494 lsp::MLIRServer::MLIRServer(DialectRegistry ®istry) 495 : impl(std::make_unique<Impl>(registry)) {} 496 lsp::MLIRServer::~MLIRServer() {} 497 498 void lsp::MLIRServer::addOrUpdateDocument(const URIForFile &uri, 499 StringRef contents) { 500 impl->documents[uri.file()] = 501 std::make_unique<MLIRDocument>(uri, contents, impl->registry); 502 } 503 504 void lsp::MLIRServer::removeDocument(const URIForFile &uri) { 505 impl->documents.erase(uri.file()); 506 } 507 508 void lsp::MLIRServer::getLocationsOf(const URIForFile &uri, 509 const Position &defPos, 510 std::vector<Location> &locations) { 511 auto fileIt = impl->documents.find(uri.file()); 512 if (fileIt != impl->documents.end()) 513 fileIt->second->getLocationsOf(uri, defPos, locations); 514 } 515 516 void lsp::MLIRServer::findReferencesOf(const URIForFile &uri, 517 const Position &pos, 518 std::vector<Location> &references) { 519 auto fileIt = impl->documents.find(uri.file()); 520 if (fileIt != impl->documents.end()) 521 fileIt->second->findReferencesOf(uri, pos, references); 522 } 523 524 Optional<lsp::Hover> lsp::MLIRServer::findHover(const URIForFile &uri, 525 const Position &hoverPos) { 526 auto fileIt = impl->documents.find(uri.file()); 527 if (fileIt != impl->documents.end()) 528 return fileIt->second->findHover(uri, hoverPos); 529 return llvm::None; 530 } 531