1 //===- ToolUtilities.cpp - MLIR Tool Utilities ----------------------------===//
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 // This file defines common utilities for implementing MLIR tools.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "mlir/Support/ToolUtilities.h"
14 #include "mlir/Support/LLVM.h"
15 #include "mlir/Support/LogicalResult.h"
16 #include "llvm/Support/SourceMgr.h"
17
18 using namespace mlir;
19
20 LogicalResult
splitAndProcessBuffer(std::unique_ptr<llvm::MemoryBuffer> originalBuffer,ChunkBufferHandler processChunkBuffer,raw_ostream & os)21 mlir::splitAndProcessBuffer(std::unique_ptr<llvm::MemoryBuffer> originalBuffer,
22 ChunkBufferHandler processChunkBuffer,
23 raw_ostream &os) {
24 const char splitMarker[] = "// -----";
25
26 auto *origMemBuffer = originalBuffer.get();
27 SmallVector<StringRef, 8> sourceBuffers;
28 origMemBuffer->getBuffer().split(sourceBuffers, splitMarker);
29
30 // Add the original buffer to the source manager.
31 llvm::SourceMgr fileSourceMgr;
32 fileSourceMgr.AddNewSourceBuffer(std::move(originalBuffer), llvm::SMLoc());
33
34 // Process each chunk in turn.
35 bool hadFailure = false;
36 for (auto &subBuffer : sourceBuffers) {
37 auto splitLoc = llvm::SMLoc::getFromPointer(subBuffer.data());
38 unsigned splitLine = fileSourceMgr.getLineAndColumn(splitLoc).first;
39 auto subMemBuffer = llvm::MemoryBuffer::getMemBufferCopy(
40 subBuffer, origMemBuffer->getBufferIdentifier() +
41 Twine(" split at line #") + Twine(splitLine));
42 if (failed(processChunkBuffer(std::move(subMemBuffer), os)))
43 hadFailure = true;
44 }
45
46 // If any fails, then return a failure of the tool.
47 return failure(hadFailure);
48 }
49