LLVM 24.0.0git
Parser.cpp
Go to the documentation of this file.
1//===- Parser.cpp - Main dispatch module for the Parser library -----------===//
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 library implements the functionality defined in llvm/AsmParser/Parser.h
10//
11//===----------------------------------------------------------------------===//
12
17#include "llvm/IR/Module.h"
21#include <algorithm>
22#include <system_error>
23
24using namespace llvm;
25
28 SlotMapping *Slots, bool UpgradeDebugInfo,
29 DataLayoutCallbackTy DataLayoutCallback,
30 AsmParserContext *ParserContext = nullptr) {
31 SourceMgr SM;
32 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(F);
33 SM.AddNewSourceBuffer(std::move(Buf), SMLoc());
34
35 std::optional<LLVMContext> OptContext;
36 return LLParser(F.getBuffer(), SM, Err, M, Index,
37 M ? M->getContext() : OptContext.emplace(), Slots,
38 ParserContext)
39 .Run(UpgradeDebugInfo, DataLayoutCallback);
40}
41
44 SlotMapping *Slots,
45 DataLayoutCallbackTy DataLayoutCallback,
46 AsmParserContext *ParserContext) {
47 return ::parseAssemblyInto(F, M, Index, Err, Slots,
48 /*UpgradeDebugInfo*/ true, DataLayoutCallback,
49 ParserContext);
50}
51
52std::unique_ptr<Module>
54 SlotMapping *Slots, DataLayoutCallbackTy DataLayoutCallback,
55 AsmParserContext *ParserContext) {
56 std::unique_ptr<Module> M =
57 std::make_unique<Module>(F.getBufferIdentifier(), Context);
58
59 if (parseAssemblyInto(F, M.get(), nullptr, Err, Slots, DataLayoutCallback,
60 ParserContext))
61 return nullptr;
62
63 return M;
64}
65
67 SMDiagnostic &Err,
68 LLVMContext &Context,
69 SlotMapping *Slots) {
71 MemoryBuffer::getFileOrSTDIN(Filename, /*IsText=*/true);
72 if (std::error_code EC = FileOrErr.getError()) {
74 "Could not open input file: " + EC.message());
75 return nullptr;
76 }
77
78 return parseAssembly(FileOrErr.get()->getMemBufferRef(), Err, Context, Slots);
79}
80
83 LLVMContext &Context, SlotMapping *Slots,
85 DataLayoutCallbackTy DataLayoutCallback) {
86 std::unique_ptr<Module> M =
87 std::make_unique<Module>(F.getBufferIdentifier(), Context);
88 std::unique_ptr<ModuleSummaryIndex> Index =
89 std::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/true);
90
91 if (parseAssemblyInto(F, M.get(), Index.get(), Err, Slots, UpgradeDebugInfo,
92 DataLayoutCallback))
93 return {nullptr, nullptr};
94
95 return {std::move(M), std::move(Index)};
96}
97
99 SMDiagnostic &Err,
100 LLVMContext &Context,
101 SlotMapping *Slots) {
102 return ::parseAssemblyWithIndex(
103 F, Err, Context, Slots,
104 /*UpgradeDebugInfo*/ true,
105 [](StringRef, StringRef) { return std::nullopt; });
106}
107
110 LLVMContext &Context, SlotMapping *Slots,
111 bool UpgradeDebugInfo,
112 DataLayoutCallbackTy DataLayoutCallback) {
114 MemoryBuffer::getFileOrSTDIN(Filename, /*IsText=*/true);
115 if (std::error_code EC = FileOrErr.getError()) {
117 "Could not open input file: " + EC.message());
118 return {nullptr, nullptr};
119 }
120
121 return parseAssemblyWithIndex(FileOrErr.get()->getMemBufferRef(), Err,
122 Context, Slots, UpgradeDebugInfo,
123 DataLayoutCallback);
124}
125
128 LLVMContext &Context, SlotMapping *Slots,
129 DataLayoutCallbackTy DataLayoutCallback) {
130 return ::parseAssemblyFileWithIndex(Filename, Err, Context, Slots,
131 /*UpgradeDebugInfo*/ true,
132 DataLayoutCallback);
133}
134
137 SlotMapping *Slots, DataLayoutCallbackTy DataLayoutCallback) {
138 return ::parseAssemblyFileWithIndex(Filename, Err, Context, Slots,
139 /*UpgradeDebugInfo*/ false,
140 DataLayoutCallback);
141}
142
143std::unique_ptr<Module>
145 LLVMContext &Context, SlotMapping *Slots,
146 AsmParserContext *ParserContext) {
147 MemoryBufferRef F(AsmString, "<string>");
148 return parseAssembly(
149 F, Err, Context, Slots, [](StringRef, StringRef) { return std::nullopt; },
150 ParserContext);
151}
152
154 ModuleSummaryIndex &Index,
155 SMDiagnostic &Err) {
156 SourceMgr SM;
157 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(F);
158 SM.AddNewSourceBuffer(std::move(Buf), SMLoc());
159
160 // The parser holds a reference to a context that is unused when parsing the
161 // index, but we need to initialize it.
162 LLVMContext unusedContext;
163 return LLParser(F.getBuffer(), SM, Err, nullptr, &Index, unusedContext)
164 .Run(true, [](StringRef, StringRef) { return std::nullopt; });
165}
166
167std::unique_ptr<ModuleSummaryIndex>
169 std::unique_ptr<ModuleSummaryIndex> Index =
170 std::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false);
171
172 if (parseSummaryIndexAssemblyInto(F, *Index, Err))
173 return nullptr;
174
175 return Index;
176}
177
178std::unique_ptr<ModuleSummaryIndex>
182 if (std::error_code EC = FileOrErr.getError()) {
184 "Could not open input file: " + EC.message());
185 return nullptr;
186 }
187
188 return parseSummaryIndexAssembly(FileOrErr.get()->getMemBufferRef(), Err);
189}
190
191std::unique_ptr<ModuleSummaryIndex>
193 MemoryBufferRef F(AsmString, "<string>");
194 return parseSummaryIndexAssembly(F, Err);
195}
196
198 const Module &M, const SlotMapping *Slots) {
199 SourceMgr SM;
200 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Asm);
201 SM.AddNewSourceBuffer(std::move(Buf), SMLoc());
202 Constant *C;
203 if (LLParser(Asm, SM, Err, const_cast<Module *>(&M), nullptr, M.getContext())
205 return nullptr;
206 return C;
207}
208
210 const SlotMapping *Slots) {
211 unsigned Read;
212 Type *Ty = parseTypeAtBeginning(Asm, Read, Err, M, Slots);
213 if (!Ty)
214 return nullptr;
215 if (Read != Asm.size()) {
216 SourceMgr SM;
217 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Asm);
218 SM.AddNewSourceBuffer(std::move(Buf), SMLoc());
219 Err = SM.GetMessage(SMLoc::getFromPointer(Asm.begin() + Read),
220 SourceMgr::DK_Error, "expected end of string");
221 return nullptr;
222 }
223 return Ty;
224}
226 SMDiagnostic &Err, const Module &M,
227 const SlotMapping *Slots) {
228 SourceMgr SM;
229 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Asm);
230 SM.AddNewSourceBuffer(std::move(Buf), SMLoc());
231 Type *Ty;
232 if (LLParser(Asm, SM, Err, const_cast<Module *>(&M), nullptr, M.getContext())
233 .parseTypeAtBeginning(Ty, Read, Slots))
234 return nullptr;
235 return Ty;
236}
237
239 unsigned &Read,
240 SMDiagnostic &Err,
241 const Module &M,
242 const SlotMapping *Slots) {
243 SourceMgr SM;
244 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Asm);
245 SM.AddNewSourceBuffer(std::move(Buf), SMLoc());
246 MDNode *MD;
247 if (LLParser(Asm, SM, Err, const_cast<Module *>(&M), nullptr, M.getContext())
249 return nullptr;
250 return dyn_cast<DIExpression>(MD);
251}
252
254 SMDiagnostic &Err, const Module &M,
255 SlotMapping &Slots,
256 unsigned &ErrorDefinitionIndex) {
257 std::string Asm;
259 for (StringRef Definition : Definitions) {
260 size_t Start = Asm.size();
261 Asm.append(Definition);
262 DefinitionRanges.emplace_back(Start, Asm.size());
263 Asm.push_back('\n');
264 }
265
266 SourceMgr SM;
267 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Asm);
268 SM.AddNewSourceBuffer(std::move(Buf), SMLoc());
269 SmallVector<SMLoc> DefinitionEnds;
270 for (auto [_, End] : DefinitionRanges)
271 DefinitionEnds.push_back(SMLoc::getFromPointer(Asm.data() + End));
272 if (!LLParser(Asm, SM, Err, const_cast<Module *>(&M), nullptr, M.getContext())
273 .parseMetadataDefinitions(Slots, DefinitionEnds))
274 return false;
275
276 const char *ErrorPtr = Err.getLoc().getPointer();
277 size_t ErrorOffset =
278 ErrorPtr ? std::min<size_t>(ErrorPtr - Asm.data(), Asm.size()) : 0;
279 ErrorDefinitionIndex = DefinitionRanges.size() - 1;
280 for (unsigned I = 0; I != DefinitionRanges.size(); ++I) {
281 if (ErrorOffset <= DefinitionRanges[I].second) {
282 ErrorDefinitionIndex = I;
283 break;
284 }
285 }
286
287 auto [Start, End] = DefinitionRanges[ErrorDefinitionIndex];
288 size_t DefinitionOffset = std::clamp(ErrorOffset, Start, End) - Start;
289 SourceMgr DefinitionSM;
290 std::unique_ptr<MemoryBuffer> DefinitionBuf = MemoryBuffer::getMemBuffer(
291 Definitions[ErrorDefinitionIndex], "", /*RequiresNullTerminator=*/false);
292 StringRef Definition = DefinitionBuf->getBuffer();
293 DefinitionSM.AddNewSourceBuffer(std::move(DefinitionBuf), SMLoc());
294 Err = DefinitionSM.GetMessage(
295 SMLoc::getFromPointer(Definition.data() + DefinitionOffset),
296 Err.getKind(), Err.getMessage());
297 return true;
298}
static bool parseSummaryIndexAssemblyInto(MemoryBufferRef F, ModuleSummaryIndex &Index, SMDiagnostic &Err)
Definition Parser.cpp:153
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
#define _
Module.h This file contains the declarations for the Module class.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
ModuleSummaryIndex.h This file contains the declarations the classes that hold the module index and s...
static constexpr StringLiteral Filename
This file defines the SmallVector class.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
Registry of file location information for LLVM IR constructs.
This is an important base class in LLVM.
Definition Constant.h:43
DWARF expression.
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
LLVM_ABI bool parseDIExpressionBodyAtBeginning(MDNode *&Result, unsigned &Read, const SlotMapping *Slots)
Definition LLParser.cpp:170
LLVM_ABI bool parseTypeAtBeginning(Type *&Ty, unsigned &Read, const SlotMapping *Slots)
Definition LLParser.cpp:154
LLVM_ABI bool parseStandaloneConstantValue(Constant *&C, const SlotMapping *Slots)
Definition LLParser.cpp:141
LLVM_ABI bool parseMetadataDefinitions(SlotMapping &Slots, ArrayRef< SMLoc > DefinitionEnds)
Definition LLParser.cpp:185
LLVM_ABI bool Run(bool UpgradeDebugInfo, DataLayoutCallbackTy DataLayoutCallback=[](StringRef, StringRef) { return std::nullopt;})
Run: module ::= toplevelentity*.
Definition LLParser.cpp:122
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
Metadata node.
Definition Metadata.h:1069
static std::unique_ptr< MemoryBuffer > getMemBuffer(StringRef InputData, StringRef BufferName="", bool RequiresNullTerminator=true)
Open the specified memory range as a MemoryBuffer.
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 "-".
Class to hold module path string table and global value map, and encapsulate methods for operating on...
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
LLVMContext & getContext() const
Get the global data context.
Definition Module.h:327
Instances of this class encapsulate one diagnostic report, allowing printing to a raw_ostream as a ca...
Definition SourceMgr.h:308
Represents a location in source code.
Definition SMLoc.h:22
static SMLoc getFromPointer(const char *Ptr)
Definition SMLoc.h:35
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This owns the files read by a parser, handles include stacks, and handles diagnostic wrangling.
Definition SourceMgr.h:37
LLVM_ABI SMDiagnostic GetMessage(SMLoc Loc, DiagKind Kind, const Twine &Msg, ArrayRef< SMRange > Ranges={}, ArrayRef< SMFixIt > FixIts={}) const
Return an SMDiagnostic at the specified location with the specified string.
unsigned AddNewSourceBuffer(std::unique_ptr< MemoryBuffer > F, SMLoc IncludeLoc)
Add a new source buffer to this source manager.
Definition SourceMgr.h:163
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr const char * data() const
Get a pointer to the start of the string (which may not be null terminated).
Definition StringRef.h:138
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI std::unique_ptr< Module > parseAssemblyString(StringRef AsmString, SMDiagnostic &Err, LLVMContext &Context, SlotMapping *Slots=nullptr, AsmParserContext *ParserContext=nullptr)
The function is a secondary interface to the LLVM Assembly Parser.
Definition Parser.cpp:144
LLVM_ABI std::unique_ptr< ModuleSummaryIndex > parseSummaryIndexAssemblyString(StringRef AsmString, SMDiagnostic &Err)
The function is a secondary interface to the LLVM Assembly Parser.
Definition Parser.cpp:192
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI Type * parseTypeAtBeginning(StringRef Asm, unsigned &Read, SMDiagnostic &Err, const Module &M, const SlotMapping *Slots=nullptr)
Parse a string Asm that starts with a type.
Definition Parser.cpp:225
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:53
LLVM_ABI bool parseMetadataDefinitions(ArrayRef< StringRef > Definitions, SMDiagnostic &Err, const Module &M, SlotMapping &Slots, unsigned &ErrorDefinitionIndex)
Parse standalone metadata definitions using and updating the supplied slot mapping.
Definition Parser.cpp:253
LLVM_ABI std::unique_ptr< ModuleSummaryIndex > parseSummaryIndexAssemblyFile(StringRef Filename, SMDiagnostic &Err)
This function is a main interface to the LLVM Assembly Parser.
Definition Parser.cpp:179
LLVM_ABI DIExpression * parseDIExpressionBodyAtBeginning(StringRef Asm, unsigned &Read, SMDiagnostic &Err, const Module &M, const SlotMapping *Slots)
Definition Parser.cpp:238
LLVM_ABI bool parseAssemblyInto(MemoryBufferRef F, Module *M, ModuleSummaryIndex *Index, SMDiagnostic &Err, SlotMapping *Slots=nullptr, DataLayoutCallbackTy DataLayoutCallback=[](StringRef, StringRef) { return std::nullopt;}, AsmParserContext *ParserContext=nullptr)
This function is the low-level interface to the LLVM Assembly Parser.
Definition Parser.cpp:42
LLVM_ABI ParsedModuleAndIndex parseAssemblyFileWithIndexNoUpgradeDebugInfo(StringRef Filename, SMDiagnostic &Err, LLVMContext &Context, SlotMapping *Slots, DataLayoutCallbackTy DataLayoutCallback)
Only for use in llvm-as for testing; this does not produce a valid module.
Definition Parser.cpp:135
llvm::function_ref< std::optional< std::string >(StringRef, StringRef)> DataLayoutCallbackTy
Definition Parser.h:37
LLVM_ABI ParsedModuleAndIndex parseAssemblyWithIndex(MemoryBufferRef F, SMDiagnostic &Err, LLVMContext &Context, SlotMapping *Slots=nullptr)
Parse LLVM Assembly including the summary index from a MemoryBuffer.
Definition Parser.cpp:98
LLVM_ABI std::unique_ptr< Module > parseAssemblyFile(StringRef Filename, SMDiagnostic &Err, LLVMContext &Context, SlotMapping *Slots=nullptr)
This function is a main interface to the LLVM Assembly Parser.
Definition Parser.cpp:66
LLVM_ABI Constant * parseConstantValue(StringRef Asm, SMDiagnostic &Err, const Module &M, const SlotMapping *Slots=nullptr)
Parse a type and a constant value in the given string.
Definition Parser.cpp:197
LLVM_ABI bool UpgradeDebugInfo(Module &M)
Check the debug info version number, if it is out-dated, drop the debug info.
LLVM_ABI Type * parseType(StringRef Asm, SMDiagnostic &Err, const Module &M, const SlotMapping *Slots=nullptr)
Parse a type in the given string.
Definition Parser.cpp:209
LLVM_ABI ParsedModuleAndIndex parseAssemblyFileWithIndex(StringRef Filename, SMDiagnostic &Err, LLVMContext &Context, SlotMapping *Slots=nullptr, DataLayoutCallbackTy DataLayoutCallback=[](StringRef, StringRef) { return std::nullopt;})
This function is a main interface to the LLVM Assembly Parser.
Definition Parser.cpp:127
LLVM_ABI std::unique_ptr< ModuleSummaryIndex > parseSummaryIndexAssembly(MemoryBufferRef F, SMDiagnostic &Err)
Parse LLVM Assembly for summary index from a MemoryBuffer.
Definition Parser.cpp:168
Holds the Module and ModuleSummaryIndex returned by the interfaces that parse both.
Definition Parser.h:72
This struct contains the mappings from the slot numbers to unnamed metadata nodes,...
Definition SlotMapping.h:32