LLVM 22.0.0git
IRReader.cpp
Go to the documentation of this file.
1//===---- IRReader.cpp - Reader for LLVM IR 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
10#include "llvm-c/IRReader.h"
14#include "llvm/IR/LLVMContext.h"
15#include "llvm/IR/Module.h"
18#include "llvm/Support/Timer.h"
20#include <cstring>
21#include <optional>
22#include <system_error>
23
24using namespace llvm;
25
26namespace llvm {
28}
29
30const char TimeIRParsingGroupName[] = "irparse";
31const char TimeIRParsingGroupDescription[] = "LLVM IR Parsing";
32const char TimeIRParsingName[] = "parse";
33const char TimeIRParsingDescription[] = "Parse IR";
34
35std::unique_ptr<Module>
36llvm::getLazyIRModule(std::unique_ptr<MemoryBuffer> Buffer, SMDiagnostic &Err,
37 LLVMContext &Context, bool ShouldLazyLoadMetadata) {
38 if (isBitcode((const unsigned char *)Buffer->getBufferStart(),
39 (const unsigned char *)Buffer->getBufferEnd())) {
41 std::move(Buffer), Context, ShouldLazyLoadMetadata);
42 if (Error E = ModuleOrErr.takeError()) {
43 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
44 Err = SMDiagnostic(Buffer->getBufferIdentifier(), SourceMgr::DK_Error,
45 EIB.message());
46 });
47 return nullptr;
48 }
49 return std::move(ModuleOrErr.get());
50 }
51
52 return parseAssembly(Buffer->getMemBufferRef(), Err, Context);
53}
54
55std::unique_ptr<Module> llvm::getLazyIRFileModule(StringRef Filename,
56 SMDiagnostic &Err,
57 LLVMContext &Context,
58 bool ShouldLazyLoadMetadata) {
61 if (std::error_code EC = FileOrErr.getError()) {
62 Err = SMDiagnostic(Filename, SourceMgr::DK_Error,
63 "Could not open input file: " + EC.message());
64 return nullptr;
65 }
66
67 return getLazyIRModule(std::move(FileOrErr.get()), Err, Context,
68 ShouldLazyLoadMetadata);
69}
70
71std::unique_ptr<Module> llvm::parseIR(MemoryBufferRef Buffer, SMDiagnostic &Err,
72 LLVMContext &Context,
73 ParserCallbacks Callbacks,
74 llvm::AsmParserContext *ParserContext) {
78 if (isBitcode((const unsigned char *)Buffer.getBufferStart(),
79 (const unsigned char *)Buffer.getBufferEnd())) {
81 parseBitcodeFile(Buffer, Context, Callbacks);
82 if (Error E = ModuleOrErr.takeError()) {
83 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
85 EIB.message());
86 });
87 return nullptr;
88 }
89 return std::move(ModuleOrErr.get());
90 }
91
92 return parseAssembly(Buffer, Err, Context, nullptr,
93 Callbacks.DataLayout.value_or(
94 [](StringRef, StringRef) { return std::nullopt; }),
95 ParserContext);
96}
97
98std::unique_ptr<Module> llvm::parseIRFile(StringRef Filename, SMDiagnostic &Err,
99 LLVMContext &Context,
100 ParserCallbacks Callbacks,
101 AsmParserContext *ParserContext) {
103 MemoryBuffer::getFileOrSTDIN(Filename, /*IsText=*/true);
104 if (std::error_code EC = FileOrErr.getError()) {
105 Err = SMDiagnostic(Filename, SourceMgr::DK_Error,
106 "Could not open input file: " + EC.message());
107 return nullptr;
108 }
109
110 return parseIR(FileOrErr.get()->getMemBufferRef(), Err, Context, Callbacks,
111 ParserContext);
112}
113
114//===----------------------------------------------------------------------===//
115// C API.
116//===----------------------------------------------------------------------===//
117
120 char **OutMessage) {
121 std::unique_ptr<MemoryBuffer> MB(unwrap(MemBuf));
122 return LLVMParseIRInContext2(ContextRef, wrap(MB.get()), OutM, OutMessage);
123}
124
127 char **OutMessage) {
128 SMDiagnostic Diag;
129
130 *OutM = wrap(parseIR(*unwrap(MemBuf), Diag, *unwrap(ContextRef)).release());
131
132 if (*OutM)
133 return 0;
134
135 if (OutMessage) {
136 std::string Buf;
137 raw_string_ostream OS(Buf);
138 Diag.print(nullptr, OS, /*ShowColors=*/false);
139 *OutMessage = strdup(Buf.c_str());
140 }
141
142 return 1;
143}
const char TimeIRParsingDescription[]
Definition IRReader.cpp:33
const char TimeIRParsingGroupDescription[]
Definition IRReader.cpp:31
const char TimeIRParsingName[]
Definition IRReader.cpp:32
const char TimeIRParsingGroupName[]
Definition IRReader.cpp:30
Module.h This file contains the declarations for the Module class.
#define T
Registry of file location information for LLVM IR constructs.
Base class for error info classes.
Definition Error.h:44
virtual std::string message() const
Return the error message as a string.
Definition Error.h:52
Represents either an error or a value T.
Definition ErrorOr.h:56
reference get()
Definition ErrorOr.h:149
std::error_code getError() const
Definition ErrorOr.h:152
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
Tagged union holding either a T or a Error.
Definition Error.h:485
Error takeError()
Take ownership of the stored error.
Definition Error.h:612
reference get()
Returns a reference to the stored T value.
Definition Error.h:582
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
StringRef getBufferIdentifier() const
const char * getBufferStart() const
const char * getBufferEnd() const
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFileOrSTDIN(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, std::optional< Align > Alignment=std::nullopt)
Open the specified file as a MemoryBuffer, or open stdin if the Filename is "-".
Instances of this class encapsulate one diagnostic report, allowing printing to a raw_ostream as a ca...
Definition SourceMgr.h:297
LLVM_ABI void print(const char *ProgName, raw_ostream &S, bool ShowColors=true, bool ShowKindLabel=true, bool ShowLocation=true) const
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
A raw_ostream that writes to an std::string.
LLVMBool LLVMParseIRInContext2(LLVMContextRef ContextRef, LLVMMemoryBufferRef MemBuf, LLVMModuleRef *OutM, char **OutMessage)
Read LLVM IR from a memory buffer and convert it into an in-memory Module object.
Definition IRReader.cpp:125
LLVMBool LLVMParseIRInContext(LLVMContextRef ContextRef, LLVMMemoryBufferRef MemBuf, LLVMModuleRef *OutM, char **OutMessage)
Read LLVM IR from a memory buffer and convert it into an in-memory Module object.
Definition IRReader.cpp:118
int LLVMBool
Definition Types.h:28
struct LLVMOpaqueMemoryBuffer * LLVMMemoryBufferRef
LLVM uses a polymorphic type hierarchy which C cannot represent, therefore parameters must be passed ...
Definition Types.h:48
struct LLVMOpaqueContext * LLVMContextRef
The top-level container for all LLVM global data.
Definition Types.h:53
struct LLVMOpaqueModule * LLVMModuleRef
The top-level container for all other LLVM Intermediate Representation (IR) objects.
Definition Types.h:61
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
LLVM_ABI Expected< std::unique_ptr< Module > > parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context, ParserCallbacks Callbacks={})
Read the specified bitcode file, returning the module.
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
Definition Error.h:990
LLVM_ABI std::unique_ptr< Module > parseAssembly(MemoryBufferRef F, SMDiagnostic &Err, LLVMContext &Context, SlotMapping *Slots=nullptr, DataLayoutCallbackTy DataLayoutCallback=[](StringRef, StringRef) { return std::nullopt;}, AsmParserContext *ParserContext=nullptr)
parseAssemblyFile and parseAssemblyString are wrappers around this function.
Definition Parser.cpp:51
LLVM_ABI bool TimePassesIsEnabled
If the user specifies the -time-passes argument on an LLVM tool command line then the value of this b...
Definition IRReader.cpp:27
LLVM_ABI std::unique_ptr< Module > parseIR(MemoryBufferRef Buffer, SMDiagnostic &Err, LLVMContext &Context, ParserCallbacks Callbacks={}, AsmParserContext *ParserContext=nullptr)
If the given MemoryBuffer holds a bitcode image, return a Module for it.
Definition IRReader.cpp:71
Attribute unwrap(LLVMAttributeRef Attr)
Definition Attributes.h:351
LLVM_ABI std::unique_ptr< Module > getLazyIRFileModule(StringRef Filename, SMDiagnostic &Err, LLVMContext &Context, bool ShouldLazyLoadMetadata=false)
If the given file holds a bitcode image, return a Module for it which does lazy deserialization of fu...
Definition IRReader.cpp:55
LLVMAttributeRef wrap(Attribute Attr)
Definition Attributes.h:346
LLVM_ABI std::unique_ptr< Module > parseIRFile(StringRef Filename, SMDiagnostic &Err, LLVMContext &Context, ParserCallbacks Callbacks={}, AsmParserContext *ParserContext=nullptr)
If the given file holds a bitcode image, return a Module for it.
Definition IRReader.cpp:98
bool isBitcode(const unsigned char *BufPtr, const unsigned char *BufEnd)
isBitcode - Return true if the given bytes are the magic bytes for LLVM IR bitcode,...
LLVM_ABI Expected< std::unique_ptr< Module > > getOwningLazyBitcodeModule(std::unique_ptr< MemoryBuffer > &&Buffer, LLVMContext &Context, bool ShouldLazyLoadMetadata=false, bool IsImporting=false, ParserCallbacks Callbacks={})
Like getLazyBitcodeModule, except that the module takes ownership of the memory buffer if successful.
LLVM_ABI std::unique_ptr< Module > getLazyIRModule(std::unique_ptr< MemoryBuffer > Buffer, SMDiagnostic &Err, LLVMContext &Context, bool ShouldLazyLoadMetadata=false)
If the given MemoryBuffer holds a bitcode image, return a Module for it which does lazy deserializati...
Definition IRReader.cpp:36
This class is basically a combination of TimeRegion and Timer.
Definition Timer.h:175
std::optional< DataLayoutCallbackFuncTy > DataLayout