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 
13 #include "mlir/Support/FileUtilities.h"
14 #include "mlir/Support/LLVM.h"
15 #include "llvm/Support/FileUtilities.h"
16 #include "llvm/Support/MemoryBuffer.h"
17 #include "llvm/Support/ToolOutputFile.h"
18 
19 using namespace mlir;
20 
21 std::unique_ptr<llvm::MemoryBuffer>
22 mlir::openInputFile(StringRef inputFilename, std::string *errorMessage) {
23   auto fileOrErr = llvm::MemoryBuffer::getFileOrSTDIN(inputFilename);
24   if (std::error_code error = fileOrErr.getError()) {
25     if (errorMessage)
26       *errorMessage = "cannot open input file '" + inputFilename.str() +
27                       "': " + error.message();
28     return nullptr;
29   }
30 
31   return std::move(*fileOrErr);
32 }
33 
34 std::unique_ptr<llvm::ToolOutputFile>
35 mlir::openOutputFile(StringRef outputFilename, std::string *errorMessage) {
36   std::error_code error;
37   auto result = std::make_unique<llvm::ToolOutputFile>(outputFilename, error,
38                                                        llvm::sys::fs::OF_None);
39   if (error) {
40     if (errorMessage)
41       *errorMessage = "cannot open output file '" + outputFilename.str() +
42                       "': " + error.message();
43     return nullptr;
44   }
45 
46   return result;
47 }
48