1cde4d5a6SJacques Pienaar //===- FileUtilities.cpp - utilities for working with files ---------------===//
26e1a050fSAlex Zinenko //
330857107SMehdi Amini // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
456222a06SMehdi Amini // See https://llvm.org/LICENSE.txt for license information.
556222a06SMehdi Amini // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
66e1a050fSAlex Zinenko //
756222a06SMehdi Amini //===----------------------------------------------------------------------===//
86e1a050fSAlex Zinenko //
96e1a050fSAlex Zinenko // Definitions of common utilities for working with files.
106e1a050fSAlex Zinenko //
116e1a050fSAlex Zinenko //===----------------------------------------------------------------------===//
126e1a050fSAlex Zinenko 
136e1a050fSAlex Zinenko #include "mlir/Support/FileUtilities.h"
14ac5a50e1SLei Zhang #include "mlir/Support/LLVM.h"
156e1a050fSAlex Zinenko #include "llvm/Support/FileUtilities.h"
16ac5a50e1SLei Zhang #include "llvm/Support/MemoryBuffer.h"
176e1a050fSAlex Zinenko #include "llvm/Support/ToolOutputFile.h"
186e1a050fSAlex Zinenko 
196e1a050fSAlex Zinenko using namespace mlir;
206e1a050fSAlex Zinenko 
21ac5a50e1SLei Zhang std::unique_ptr<llvm::MemoryBuffer>
openInputFile(StringRef inputFilename,std::string * errorMessage)22ac5a50e1SLei Zhang mlir::openInputFile(StringRef inputFilename, std::string *errorMessage) {
23ac5a50e1SLei Zhang   auto fileOrErr = llvm::MemoryBuffer::getFileOrSTDIN(inputFilename);
24ac5a50e1SLei Zhang   if (std::error_code error = fileOrErr.getError()) {
25ac5a50e1SLei Zhang     if (errorMessage)
26ac5a50e1SLei Zhang       *errorMessage = "cannot open input file '" + inputFilename.str() +
27ac5a50e1SLei Zhang                       "': " + error.message();
28ac5a50e1SLei Zhang     return nullptr;
29ac5a50e1SLei Zhang   }
30ac5a50e1SLei Zhang 
31ac5a50e1SLei Zhang   return std::move(*fileOrErr);
32ac5a50e1SLei Zhang }
33ac5a50e1SLei Zhang 
346e1a050fSAlex Zinenko std::unique_ptr<llvm::ToolOutputFile>
openOutputFile(StringRef outputFilename,std::string * errorMessage)35ac5a50e1SLei Zhang mlir::openOutputFile(StringRef outputFilename, std::string *errorMessage) {
366e1a050fSAlex Zinenko   std::error_code error;
3779f53b0cSJacques Pienaar   auto result = std::make_unique<llvm::ToolOutputFile>(outputFilename, error,
38*518d955fSDuncan P. N. Exon Smith                                                        llvm::sys::fs::OF_None);
396e1a050fSAlex Zinenko   if (error) {
40ac5a50e1SLei Zhang     if (errorMessage)
41ac5a50e1SLei Zhang       *errorMessage = "cannot open output file '" + outputFilename.str() +
42ac5a50e1SLei Zhang                       "': " + error.message();
436e1a050fSAlex Zinenko     return nullptr;
446e1a050fSAlex Zinenko   }
456e1a050fSAlex Zinenko 
466e1a050fSAlex Zinenko   return result;
476e1a050fSAlex Zinenko }
48