MLIR  20.0.0git
FileUtilities.cpp
Go to the documentation of this file.
1 //===- FileUtilities.cpp - utilities for working with files ---------------===//
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 // Definitions of common utilities for working with files.
10 //
11 //===----------------------------------------------------------------------===//
12 
14 #include "mlir/Support/LLVM.h"
15 #include "llvm/Support/Alignment.h"
16 #include "llvm/Support/FileUtilities.h"
17 #include "llvm/Support/MemoryBuffer.h"
18 #include "llvm/Support/ToolOutputFile.h"
19 
20 using namespace mlir;
21 
22 static std::unique_ptr<llvm::MemoryBuffer>
23 openInputFileImpl(StringRef inputFilename, std::string *errorMessage,
24  std::optional<llvm::Align> alignment) {
25  auto fileOrErr = llvm::MemoryBuffer::getFileOrSTDIN(
26  inputFilename, /*IsText=*/false, /*RequiresNullTerminator=*/true,
27  alignment);
28  if (std::error_code error = fileOrErr.getError()) {
29  if (errorMessage)
30  *errorMessage = "cannot open input file '" + inputFilename.str() +
31  "': " + error.message();
32  return nullptr;
33  }
34 
35  return std::move(*fileOrErr);
36 }
37 std::unique_ptr<llvm::MemoryBuffer>
38 mlir::openInputFile(StringRef inputFilename, std::string *errorMessage) {
39  return openInputFileImpl(inputFilename, errorMessage,
40  /*alignment=*/std::nullopt);
41 }
42 std::unique_ptr<llvm::MemoryBuffer>
43 mlir::openInputFile(llvm::StringRef inputFilename, llvm::Align alignment,
44  std::string *errorMessage) {
45  return openInputFileImpl(inputFilename, errorMessage, alignment);
46 }
47 
48 std::unique_ptr<llvm::ToolOutputFile>
49 mlir::openOutputFile(StringRef outputFilename, std::string *errorMessage) {
50  std::error_code error;
51  auto result = std::make_unique<llvm::ToolOutputFile>(outputFilename, error,
52  llvm::sys::fs::OF_None);
53  if (error) {
54  if (errorMessage)
55  *errorMessage = "cannot open output file '" + outputFilename.str() +
56  "': " + error.message();
57  return nullptr;
58  }
59 
60  return result;
61 }
static std::unique_ptr< llvm::MemoryBuffer > openInputFileImpl(StringRef inputFilename, std::string *errorMessage, std::optional< llvm::Align > alignment)
Include the generated interface declarations.
std::unique_ptr< llvm::MemoryBuffer > openInputFile(llvm::StringRef inputFilename, std::string *errorMessage=nullptr)
Open the file specified by its name for reading.
std::unique_ptr< llvm::ToolOutputFile > openOutputFile(llvm::StringRef outputFilename, std::string *errorMessage=nullptr)
Open the file specified by its name for writing.