LLVM 22.0.0git
LTOModule.cpp
Go to the documentation of this file.
1//===-- LTOModule.cpp - LLVM Link Time Optimizer --------------------------===//
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 file implements the Link Time Optimization library. This library is
10// intended to be used by linker to optimize code at link time.
11//
12//===----------------------------------------------------------------------===//
13
17#include "llvm/IR/Constants.h"
18#include "llvm/IR/LLVMContext.h"
19#include "llvm/IR/Mangler.h"
20#include "llvm/IR/Metadata.h"
21#include "llvm/IR/Module.h"
22#include "llvm/MC/MCExpr.h"
23#include "llvm/MC/MCInst.h"
24#include "llvm/MC/MCSection.h"
25#include "llvm/MC/MCSymbol.h"
28#include "llvm/Object/MachO.h"
38#include <system_error>
39using namespace llvm;
40using namespace llvm::object;
41
42LTOModule::LTOModule(std::unique_ptr<Module> M, MemoryBufferRef MBRef,
44 : Mod(std::move(M)), MBRef(MBRef), _target(TM) {
45 assert(_target && "target machine is null");
46 SymTab.addModule(Mod.get());
47}
48
49LTOModule::~LTOModule() = default;
50
51/// isBitcodeFile - Returns 'true' if the file (or memory contents) is LLVM
52/// bitcode.
53bool LTOModule::isBitcodeFile(const void *Mem, size_t Length) {
55 MemoryBufferRef(StringRef((const char *)Mem, Length), "<mem>"));
56 return !errorToBool(BCData.takeError());
57}
58
62 if (!BufferOrErr)
63 return false;
64
66 BufferOrErr.get()->getMemBufferRef());
67 return !errorToBool(BCData.takeError());
68}
69
72 if (!Result) {
73 logAllUnhandledErrors(Result.takeError(), errs());
74 return false;
75 }
76 return Result->IsThinLTO;
77}
78
80 StringRef TriplePrefix) {
83 if (errorToBool(BCOrErr.takeError()))
84 return false;
85 LLVMContext Context;
86 ErrorOr<std::string> TripleOrErr =
88 if (!TripleOrErr)
89 return false;
90 return StringRef(*TripleOrErr).starts_with(TriplePrefix);
91}
92
96 if (errorToBool(BCOrErr.takeError()))
97 return "";
98 LLVMContext Context;
100 Context, getBitcodeProducerString(*BCOrErr));
101 if (!ProducerOrErr)
102 return "";
103 return *ProducerOrErr;
104}
105
108 const TargetOptions &options) {
111 if (std::error_code EC = BufferOrErr.getError()) {
112 Context.emitError(EC.message());
113 return EC;
114 }
115 std::unique_ptr<MemoryBuffer> Buffer = std::move(BufferOrErr.get());
116 return makeLTOModule(Buffer->getMemBufferRef(), options, Context,
117 /* ShouldBeLazy*/ false);
118}
119
122 size_t size, const TargetOptions &options) {
123 return createFromOpenFileSlice(Context, fd, path, size, 0, options);
124}
125
128 size_t map_size, off_t offset,
129 const TargetOptions &options) {
132 map_size, offset);
133 if (std::error_code EC = BufferOrErr.getError()) {
134 Context.emitError(EC.message());
135 return EC;
136 }
137 std::unique_ptr<MemoryBuffer> Buffer = std::move(BufferOrErr.get());
138 return makeLTOModule(Buffer->getMemBufferRef(), options, Context,
139 /* ShouldBeLazy */ false);
140}
141
143LTOModule::createFromBuffer(LLVMContext &Context, const void *mem,
144 size_t length, const TargetOptions &options,
145 StringRef path) {
146 StringRef Data((const char *)mem, length);
147 MemoryBufferRef Buffer(Data, path);
148 return makeLTOModule(Buffer, options, Context, /* ShouldBeLazy */ false);
149}
150
152LTOModule::createInLocalContext(std::unique_ptr<LLVMContext> Context,
153 const void *mem, size_t length,
154 const TargetOptions &options, StringRef path) {
155 StringRef Data((const char *)mem, length);
156 MemoryBufferRef Buffer(Data, path);
157 // If we own a context, we know this is being used only for symbol extraction,
158 // not linking. Be lazy in that case.
160 makeLTOModule(Buffer, options, *Context, /* ShouldBeLazy */ true);
161 if (Ret)
162 (*Ret)->OwnedContext = std::move(Context);
163 return Ret;
164}
165
168 bool ShouldBeLazy) {
169 // Find the buffer.
172 if (Error E = MBOrErr.takeError()) {
173 std::error_code EC = errorToErrorCode(std::move(E));
174 Context.emitError(EC.message());
175 return EC;
176 }
177
178 if (!ShouldBeLazy) {
179 // Parse the full file.
180 return expectedToErrorOrAndEmitErrors(Context,
181 parseBitcodeFile(*MBOrErr, Context));
182 }
183
184 // Parse lazily.
186 Context,
187 getLazyBitcodeModule(*MBOrErr, Context, true /*ShouldLazyLoadMetadata*/));
188}
189
191LTOModule::makeLTOModule(MemoryBufferRef Buffer, const TargetOptions &options,
192 LLVMContext &Context, bool ShouldBeLazy) {
193 ErrorOr<std::unique_ptr<Module>> MOrErr =
194 parseBitcodeFileImpl(Buffer, Context, ShouldBeLazy);
195 if (std::error_code EC = MOrErr.getError())
196 return EC;
197 std::unique_ptr<Module> &M = *MOrErr;
198
199 llvm::Triple Triple = M->getTargetTriple();
200 if (Triple.empty())
201 Triple = llvm::Triple(sys::getDefaultTargetTriple());
202
203 // find machine architecture for this module
204 std::string errMsg;
205 const Target *march = TargetRegistry::lookupTarget(Triple, errMsg);
206 if (!march) {
207 Context.emitError(errMsg);
209 }
210
211 // construct LTOModule, hand over ownership of module and target
212 SubtargetFeatures Features;
213 Features.getDefaultSubtargetFeatures(Triple);
214 std::string FeatureStr = Features.getString();
215 // Set a default CPU for Darwin triples.
216 std::string CPU;
217 if (Triple.isOSDarwin()) {
218 if (Triple.getArch() == llvm::Triple::x86_64)
219 CPU = "core2";
220 else if (Triple.getArch() == llvm::Triple::x86)
221 CPU = "yonah";
222 else if (Triple.isArm64e())
223 CPU = "apple-a12";
224 else if (Triple.getArch() == llvm::Triple::aarch64 ||
226 CPU = "cyclone";
227 }
228
229 TargetMachine *target = march->createTargetMachine(Triple, CPU, FeatureStr,
230 options, std::nullopt);
231
232 std::unique_ptr<LTOModule> Ret(new LTOModule(std::move(M), Buffer, target));
233 Ret->parseSymbols();
234 Ret->parseMetadata();
235
236 return std::move(Ret);
237}
238
239/// Create a MemoryBuffer from a memory range with an optional name.
240std::unique_ptr<MemoryBuffer>
241LTOModule::makeBuffer(const void *mem, size_t length, StringRef name) {
242 const char *startPtr = (const char*)mem;
243 return MemoryBuffer::getMemBuffer(StringRef(startPtr, length), name, false);
244}
245
246/// objcClassNameFromExpression - Get string that the data pointer points to.
247bool
248LTOModule::objcClassNameFromExpression(const Constant *c, std::string &name) {
249 if (const ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
250 Constant *op = ce->getOperand(0);
252 Constant *cn = gvn->getInitializer();
254 if (ca->isCString()) {
255 name = (".objc_class_name_" + ca->getAsCString()).str();
256 return true;
257 }
258 }
259 }
260 }
261 return false;
262}
263
264/// addObjCClass - Parse i386/ppc ObjC class data structure.
265void LTOModule::addObjCClass(const GlobalVariable *clgv) {
266 const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
267 if (!c) return;
268
269 // second slot in __OBJC,__class is pointer to superclass name
270 std::string superclassName;
271 if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
272 auto IterBool = _undefines.try_emplace(superclassName);
273 if (IterBool.second) {
274 NameAndAttributes &info = IterBool.first->second;
275 info.name = IterBool.first->first();
277 info.isFunction = false;
278 info.symbol = clgv;
279 }
280 }
281
282 // third slot in __OBJC,__class is pointer to class name
283 std::string className;
284 if (objcClassNameFromExpression(c->getOperand(2), className)) {
285 auto Iter = _defines.insert(className).first;
286
287 NameAndAttributes info;
288 info.name = Iter->first();
289 info.attributes = LTO_SYMBOL_PERMISSIONS_DATA |
291 info.isFunction = false;
292 info.symbol = clgv;
293 _symbols.push_back(info);
294 }
295}
296
297/// addObjCCategory - Parse i386/ppc ObjC category data structure.
298void LTOModule::addObjCCategory(const GlobalVariable *clgv) {
299 const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
300 if (!c) return;
301
302 // second slot in __OBJC,__category is pointer to target class name
303 std::string targetclassName;
304 if (!objcClassNameFromExpression(c->getOperand(1), targetclassName))
305 return;
306
307 auto IterBool = _undefines.try_emplace(targetclassName);
308
309 if (!IterBool.second)
310 return;
311
312 NameAndAttributes &info = IterBool.first->second;
313 info.name = IterBool.first->first();
315 info.isFunction = false;
316 info.symbol = clgv;
317}
318
319/// addObjCClassRef - Parse i386/ppc ObjC class list data structure.
320void LTOModule::addObjCClassRef(const GlobalVariable *clgv) {
321 std::string targetclassName;
322 if (!objcClassNameFromExpression(clgv->getInitializer(), targetclassName))
323 return;
324
325 auto IterBool = _undefines.try_emplace(targetclassName);
326
327 if (!IterBool.second)
328 return;
329
330 NameAndAttributes &info = IterBool.first->second;
331 info.name = IterBool.first->first();
333 info.isFunction = false;
334 info.symbol = clgv;
335}
336
337void LTOModule::addDefinedDataSymbol(ModuleSymbolTable::Symbol Sym) {
338 SmallString<64> Buffer;
339 {
340 raw_svector_ostream OS(Buffer);
341 SymTab.printSymbolName(OS, Sym);
342 Buffer.c_str();
343 }
344
345 const GlobalValue *V = cast<GlobalValue *>(Sym);
346 addDefinedDataSymbol(Buffer, V);
347}
348
349void LTOModule::addDefinedDataSymbol(StringRef Name, const GlobalValue *v) {
350 // Add to list of defined symbols.
351 addDefinedSymbol(Name, v, false);
352
353 if (!v->hasSection() /* || !isTargetDarwin */)
354 return;
355
356 // Special case i386/ppc ObjC data structures in magic sections:
357 // The issue is that the old ObjC object format did some strange
358 // contortions to avoid real linker symbols. For instance, the
359 // ObjC class data structure is allocated statically in the executable
360 // that defines that class. That data structures contains a pointer to
361 // its superclass. But instead of just initializing that part of the
362 // struct to the address of its superclass, and letting the static and
363 // dynamic linkers do the rest, the runtime works by having that field
364 // instead point to a C-string that is the name of the superclass.
365 // At runtime the objc initialization updates that pointer and sets
366 // it to point to the actual super class. As far as the linker
367 // knows it is just a pointer to a string. But then someone wanted the
368 // linker to issue errors at build time if the superclass was not found.
369 // So they figured out a way in mach-o object format to use an absolute
370 // symbols (.objc_class_name_Foo = 0) and a floating reference
371 // (.reference .objc_class_name_Bar) to cause the linker into erroring when
372 // a class was missing.
373 // The following synthesizes the implicit .objc_* symbols for the linker
374 // from the ObjC data structures generated by the front end.
375
376 // special case if this data blob is an ObjC class definition
377 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(v)) {
378 StringRef Section = GV->getSection();
379 if (Section.starts_with("__OBJC,__class,")) {
380 addObjCClass(GV);
381 }
382
383 // special case if this data blob is an ObjC category definition
384 else if (Section.starts_with("__OBJC,__category,")) {
385 addObjCCategory(GV);
386 }
387
388 // special case if this data blob is the list of referenced classes
389 else if (Section.starts_with("__OBJC,__cls_refs,")) {
390 addObjCClassRef(GV);
391 }
392 }
393}
394
395void LTOModule::addDefinedFunctionSymbol(ModuleSymbolTable::Symbol Sym) {
396 SmallString<64> Buffer;
397 {
398 raw_svector_ostream OS(Buffer);
399 SymTab.printSymbolName(OS, Sym);
400 Buffer.c_str();
401 }
402
403 auto *GV = cast<GlobalValue *>(Sym);
404 assert((isa<Function>(GV) ||
405 (isa<GlobalAlias>(GV) &&
406 isa<Function>(cast<GlobalAlias>(GV)->getAliasee()))) &&
407 "Not function or function alias");
408
409 addDefinedFunctionSymbol(Buffer, GV);
410}
411
412void LTOModule::addDefinedFunctionSymbol(StringRef Name, const GlobalValue *F) {
413 // add to list of defined symbols
414 addDefinedSymbol(Name, F, true);
415}
416
417void LTOModule::addDefinedSymbol(StringRef Name, const GlobalValue *def,
418 bool isFunction) {
419 uint32_t attr = 0;
420 if (auto *gv = dyn_cast<GlobalVariable>(def))
421 attr = Log2(gv->getAlign().valueOrOne());
422 else if (auto *f = dyn_cast<Function>(def))
423 attr = Log2(f->getAlign().valueOrOne());
424
425 // set permissions part
426 if (isFunction) {
428 } else {
429 const GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
430 if (gv && gv->isConstant())
432 else
434 }
435
436 // set definition part
437 if (def->hasWeakLinkage() || def->hasLinkOnceLinkage())
439 else if (def->hasCommonLinkage())
441 else
443
444 // set scope part
445 if (def->hasLocalLinkage())
446 // Ignore visibility if linkage is local.
448 else if (def->hasHiddenVisibility())
450 else if (def->hasProtectedVisibility())
452 else if (def->canBeOmittedFromSymbolTable())
454 else
456
457 if (def->hasComdat())
458 attr |= LTO_SYMBOL_COMDAT;
459
460 if (isa<GlobalAlias>(def))
461 attr |= LTO_SYMBOL_ALIAS;
462
463 auto Iter = _defines.insert(Name).first;
464
465 // fill information structure
466 NameAndAttributes info;
467 StringRef NameRef = Iter->first();
468 info.name = NameRef;
469 assert(NameRef.data()[NameRef.size()] == '\0');
470 info.attributes = attr;
471 info.isFunction = isFunction;
472 info.symbol = def;
473
474 // add to table of symbols
475 _symbols.push_back(info);
476}
477
478/// addAsmGlobalSymbol - Add a global symbol from module-level ASM to the
479/// defined list.
480void LTOModule::addAsmGlobalSymbol(StringRef name,
481 lto_symbol_attributes scope) {
482 auto IterBool = _defines.insert(name);
483
484 // only add new define if not already defined
485 if (!IterBool.second)
486 return;
487
488 NameAndAttributes &info = _undefines[IterBool.first->first()];
489
490 if (info.symbol == nullptr) {
491 // FIXME: This is trying to take care of module ASM like this:
492 //
493 // module asm ".zerofill __FOO, __foo, _bar_baz_qux, 0"
494 //
495 // but is gross and its mother dresses it funny. Have the ASM parser give us
496 // more details for this type of situation so that we're not guessing so
497 // much.
498
499 // fill information structure
500 info.name = IterBool.first->first();
501 info.attributes =
503 info.isFunction = false;
504 info.symbol = nullptr;
505
506 // add to table of symbols
507 _symbols.push_back(info);
508 return;
509 }
510
511 if (info.isFunction)
512 addDefinedFunctionSymbol(info.name, cast<Function>(info.symbol));
513 else
514 addDefinedDataSymbol(info.name, info.symbol);
515
516 _symbols.back().attributes &= ~LTO_SYMBOL_SCOPE_MASK;
517 _symbols.back().attributes |= scope;
518}
519
520/// addAsmGlobalSymbolUndef - Add a global symbol from module-level ASM to the
521/// undefined list.
522void LTOModule::addAsmGlobalSymbolUndef(StringRef name) {
523 auto IterBool = _undefines.try_emplace(name);
524
525 _asm_undefines.push_back(IterBool.first->first());
526
527 // we already have the symbol
528 if (!IterBool.second)
529 return;
530
531 uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;
533 NameAndAttributes &info = IterBool.first->second;
534 info.name = IterBool.first->first();
535 info.attributes = attr;
536 info.isFunction = false;
537 info.symbol = nullptr;
538}
539
540/// Add a symbol which isn't defined just yet to a list to be resolved later.
541void LTOModule::addPotentialUndefinedSymbol(ModuleSymbolTable::Symbol Sym,
542 bool isFunc) {
543 SmallString<64> name;
544 {
545 raw_svector_ostream OS(name);
546 SymTab.printSymbolName(OS, Sym);
547 name.c_str();
548 }
549
550 auto IterBool = _undefines.try_emplace(name.str());
551
552 // we already have the symbol
553 if (!IterBool.second)
554 return;
555
556 NameAndAttributes &info = IterBool.first->second;
557
558 info.name = IterBool.first->first();
559
560 const GlobalValue *decl = dyn_cast_if_present<GlobalValue *>(Sym);
561
562 if (decl->hasExternalWeakLinkage())
564 else
566
567 info.isFunction = isFunc;
568 info.symbol = decl;
569}
570
571void LTOModule::parseSymbols() {
572 for (auto Sym : SymTab.symbols()) {
574 uint32_t Flags = SymTab.getSymbolFlags(Sym);
576 continue;
577
578 bool IsUndefined = Flags & object::BasicSymbolRef::SF_Undefined;
579
580 if (!GV) {
581 SmallString<64> Buffer;
582 {
583 raw_svector_ostream OS(Buffer);
584 SymTab.printSymbolName(OS, Sym);
585 Buffer.c_str();
586 }
587 StringRef Name = Buffer;
588
589 if (IsUndefined)
590 addAsmGlobalSymbolUndef(Name);
591 else if (Flags & object::BasicSymbolRef::SF_Global)
592 addAsmGlobalSymbol(Name, LTO_SYMBOL_SCOPE_DEFAULT);
593 else
594 addAsmGlobalSymbol(Name, LTO_SYMBOL_SCOPE_INTERNAL);
595 continue;
596 }
597
598 auto *F = dyn_cast<Function>(GV);
599 if (IsUndefined) {
600 addPotentialUndefinedSymbol(Sym, F != nullptr);
601 continue;
602 }
603
604 if (F) {
605 addDefinedFunctionSymbol(Sym);
606 continue;
607 }
608
609 if (isa<GlobalVariable>(GV)) {
610 addDefinedDataSymbol(Sym);
611 continue;
612 }
613
615
616 if (isa<Function>(cast<GlobalAlias>(GV)->getAliasee()))
617 addDefinedFunctionSymbol(Sym);
618 else
619 addDefinedDataSymbol(Sym);
620 }
621
622 // make symbols for all undefines
623 for (StringMap<NameAndAttributes>::iterator u =_undefines.begin(),
624 e = _undefines.end(); u != e; ++u) {
625 // If this symbol also has a definition, then don't make an undefine because
626 // it is a tentative definition.
627 if (_defines.count(u->getKey())) continue;
628 NameAndAttributes info = u->getValue();
629 _symbols.push_back(info);
630 }
631}
632
633/// parseMetadata - Parse metadata from the module
634void LTOModule::parseMetadata() {
635 raw_string_ostream OS(LinkerOpts);
636
637 // Linker Options
638 if (NamedMDNode *LinkerOptions =
639 getModule().getNamedMetadata("llvm.linker.options")) {
640 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
641 MDNode *MDOptions = LinkerOptions->getOperand(i);
642 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
643 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
644 OS << " " << MDOption->getString();
645 }
646 }
647 }
648
649 // Globals - we only need to do this for COFF.
650 const Triple TT(_target->getTargetTriple());
651 if (!TT.isOSBinFormatCOFF())
652 return;
653 Mangler M;
654 for (const NameAndAttributes &Sym : _symbols) {
655 if (!Sym.symbol)
656 continue;
657 emitLinkerFlagsForGlobalCOFF(OS, Sym.symbol, TT, M);
658 }
659}
660
662 size_t buffer_size, const char *path,
663 std::string &outErr) {
664 StringRef Data((const char *)buffer, buffer_size);
665 MemoryBufferRef BufferRef(Data, path);
666
668 lto::InputFile::create(BufferRef);
669
670 if (ObjOrErr)
671 return ObjOrErr->release();
672
673 outErr = std::string(path) +
674 ": Could not read LTO input file: " + toString(ObjOrErr.takeError());
675 return nullptr;
676}
677
679 return input->getDependentLibraries().size();
680}
681
682const char *LTOModule::getDependentLibrary(lto::InputFile *input, size_t index,
683 size_t *size) {
684 StringRef S = input->getDependentLibraries()[index];
685 *size = S.size();
686 return S.data();
687}
688
690 return MachO::getCPUType(Mod->getTargetTriple());
691}
692
694 return MachO::getCPUSubType(Mod->getTargetTriple());
695}
696
698 for (auto Sym : SymTab.symbols()) {
699 if (auto *GV = dyn_cast_if_present<GlobalValue *>(Sym)) {
700 StringRef Name = GV->getName();
701 if (Name.consume_front("llvm.global_")) {
702 if (Name == "ctors" || Name == "dtors")
703 return true;
704 }
705 }
706 }
707 return false;
708}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
#define op(i)
Module.h This file contains the declarations for the Module class.
static ErrorOr< std::unique_ptr< Module > > parseBitcodeFileImpl(MemoryBufferRef Buffer, LLVMContext &Context, bool ShouldBeLazy)
lazy value info
#define F(x, y, z)
Definition MD5.cpp:55
This file contains the declarations for metadata subclasses.
if(auto Err=PB.parsePassPipeline(MPM, Passes)) return wrap(std MPM run * Mod
static const char * name
static bool isFunction(SDValue Op)
An array constant whose element type is a simple 1/2/4/8-byte integer or float/double,...
Definition Constants.h:702
A constant value that is initialized with an expression using other constant values.
Definition Constants.h:1120
This is an important base class in LLVM.
Definition Constant.h:43
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
bool hasLinkOnceLinkage() const
bool hasLocalLinkage() const
bool hasHiddenVisibility() const
bool hasExternalWeakLinkage() const
bool hasComdat() const
bool hasWeakLinkage() const
bool hasCommonLinkage() const
LLVM_ABI bool canBeOmittedFromSymbolTable() const
True if GV can be left out of the object symbol table.
Definition Globals.cpp:444
bool hasProtectedVisibility() const
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1445
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1451
LLVM_ABI StringRef getString() const
Definition Metadata.cpp:617
This interface provides simple read-only access to a block of memory, and provides simple methods for...
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 > > getOpenFileSlice(sys::fs::file_t FD, const Twine &Filename, uint64_t MapSize, int64_t Offset, bool IsVolatile=false, std::optional< Align > Alignment=std::nullopt)
Given an already-open file descriptor, map some slice of it into a MemoryBuffer.
MemoryBufferRef getMemBufferRef() const
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFile(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, bool IsVolatile=false, std::optional< Align > Alignment=std::nullopt)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
PointerUnion< GlobalValue *, AsmSymbol * > Symbol
const char * c_str()
StringMapIterBase< ValueTy, false > iterator
Definition StringMap.h:221
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:269
constexpr size_t size() const
size - Get the string size.
Definition StringRef.h:154
constexpr const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition StringRef.h:148
LLVM_ABI void getDefaultSubtargetFeatures(const Triple &Triple)
Adds the default features for the specified target triple.
LLVM_ABI std::string getString() const
Returns features as a string.
Primary interface to the complete machine description for the target machine.
TargetMachine * createTargetMachine(const Triple &TT, StringRef CPU, StringRef Features, const TargetOptions &Options, std::optional< Reloc::Model > RM, std::optional< CodeModel::Model > CM=std::nullopt, CodeGenOptLevel OL=CodeGenOptLevel::Default, bool JIT=false) const
createTargetMachine - Create a target specific machine implementation for the specified Triple.
bool isArm64e() const
Tests whether the target is the Apple "arm64e" AArch64 subarch.
Definition Triple.h:1122
ArchType getArch() const
Get the parsed architecture type of this triple.
Definition Triple.h:411
bool isOSDarwin() const
Is this a "Darwin" OS (macOS, iOS, tvOS, watchOS, DriverKit, XROS, or bridgeOS).
Definition Triple.h:611
bool empty() const
Whether the triple is empty / default constructed.
Definition Triple.h:483
Value * getOperand(unsigned i) const
Definition User.h:232
An input file.
Definition LTO.h:118
static LLVM_ABI Expected< std::unique_ptr< InputFile > > create(MemoryBufferRef Object)
Create an InputFile.
Definition LTO.cpp:561
ArrayRef< StringRef > getDependentLibraries() const
Returns dependent library specifiers from the input file.
Definition LTO.h:178
static Expected< MemoryBufferRef > findBitcodeInMemBuffer(MemoryBufferRef Object)
Finds and returns bitcode in the given memory buffer (which may be either a bitcode file or a native ...
lto_symbol_attributes
Definition lto.h:54
@ LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN
Definition lto.h:71
@ LTO_SYMBOL_PERMISSIONS_CODE
Definition lto.h:57
@ LTO_SYMBOL_DEFINITION_REGULAR
Definition lto.h:61
@ LTO_SYMBOL_SCOPE_DEFAULT
Definition lto.h:70
@ LTO_SYMBOL_SCOPE_INTERNAL
Definition lto.h:67
@ LTO_SYMBOL_ALIAS
Definition lto.h:73
@ LTO_SYMBOL_SCOPE_HIDDEN
Definition lto.h:68
@ LTO_SYMBOL_DEFINITION_TENTATIVE
Definition lto.h:62
@ LTO_SYMBOL_PERMISSIONS_DATA
Definition lto.h:58
@ LTO_SYMBOL_SCOPE_PROTECTED
Definition lto.h:69
@ LTO_SYMBOL_PERMISSIONS_RODATA
Definition lto.h:59
@ LTO_SYMBOL_COMDAT
Definition lto.h:72
@ LTO_SYMBOL_DEFINITION_WEAKUNDEF
Definition lto.h:65
@ LTO_SYMBOL_DEFINITION_UNDEFINED
Definition lto.h:64
@ LTO_SYMBOL_DEFINITION_WEAK
Definition lto.h:63
LLVM_ABI Expected< uint32_t > getCPUSubType(const Triple &T)
Definition MachO.cpp:95
LLVM_ABI Expected< uint32_t > getCPUType(const Triple &T)
Definition MachO.cpp:77
A private "module" namespace for types and utilities used by GVN.
Definition GVN.h:61
LLVM_ABI file_t convertFDToNativeFile(int FD)
Converts from a Posix file descriptor number to a native file handle.
Definition FileSystem.h:998
LLVM_ABI std::string getDefaultTargetTriple()
getDefaultTargetTriple() - Return the default target triple the compiler has been configured to produ...
This is an optimization pass for GlobalISel generic memory operations.
bool errorToBool(Error Err)
Helper for converting an Error to a bool.
Definition Error.h:1113
@ Length
Definition DWP.cpp:477
LLVM_ABI void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner={})
Log all errors (if any) in E to OS.
Definition Error.cpp:65
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1685
LLVM_ABI Expected< std::unique_ptr< Module > > parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context, ParserCallbacks Callbacks={})
Read the specified bitcode file, returning the module.
std::error_code make_error_code(BitcodeError E)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:649
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:738
LLVM_ABI Expected< std::string > getBitcodeTargetTriple(MemoryBufferRef Buffer)
Read the header of the specified bitcode buffer and extract just the triple information.
ErrorOr< T > expectedToErrorOrAndEmitErrors(LLVMContext &Ctx, Expected< T > Val)
LLVM_ABI Expected< std::string > getBitcodeProducerString(MemoryBufferRef Buffer)
Read the header of the specified bitcode buffer and extract just the producer string information.
LLVM_ABI Expected< std::unique_ptr< Module > > getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context, bool ShouldLazyLoadMetadata=false, bool IsImporting=false, ParserCallbacks Callbacks={})
Read the header of the specified bitcode buffer and prepare for lazy deserialization of function bodi...
LLVM_ABI Expected< BitcodeLTOInfo > getBitcodeLTOInfo(MemoryBufferRef Buffer)
Returns LTO information for the specified bitcode file.
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:548
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
FunctionAddr VTableAddr uintptr_t uintptr_t Data
Definition InstrProf.h:189
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1869
LLVM_ABI void emitLinkerFlagsForGlobalCOFF(raw_ostream &OS, const GlobalValue *GV, const Triple &TT, Mangler &Mangler)
Definition Mangler.cpp:214
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:565
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition Alignment.h:208
LLVM_ABI std::error_code errorToErrorCode(Error Err)
Helper for converting an ECError to a std::error_code.
Definition Error.cpp:117
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:851
static LLVM_ABI ErrorOr< std::unique_ptr< LTOModule > > createFromFile(LLVMContext &Context, StringRef path, const TargetOptions &options)
Create an LTOModule.
static LLVM_ABI bool isBitcodeFile(const void *mem, size_t length)
Returns 'true' if the file or memory contents is LLVM bitcode.
Definition LTOModule.cpp:53
LLVM_ABI Expected< uint32_t > getMachOCPUType() const
static LLVM_ABI std::unique_ptr< MemoryBuffer > makeBuffer(const void *mem, size_t length, StringRef name="")
Create a MemoryBuffer from a memory range with an optional name.
static LLVM_ABI size_t getDependentLibraryCount(lto::InputFile *input)
LLVM_ABI bool hasCtorDtor() const
Returns true if the module has either the @llvm.global_ctors or the @llvm.global_dtors symbol.
static LLVM_ABI const char * getDependentLibrary(lto::InputFile *input, size_t index, size_t *size)
const Module & getModule() const
Definition LTOModule.h:116
static LLVM_ABI ErrorOr< std::unique_ptr< LTOModule > > createFromOpenFileSlice(LLVMContext &Context, int fd, StringRef path, size_t map_size, off_t offset, const TargetOptions &options)
static LLVM_ABI std::string getProducerString(MemoryBuffer *Buffer)
Returns a string representing the producer identification stored in the bitcode, or "" if the bitcode...
Definition LTOModule.cpp:93
static LLVM_ABI bool isBitcodeForTarget(MemoryBuffer *memBuffer, StringRef triplePrefix)
Returns 'true' if the memory buffer is LLVM bitcode for the specified triple.
Definition LTOModule.cpp:79
LLVM_ABI bool isThinLTO()
Returns 'true' if the Module is produced for ThinLTO.
Definition LTOModule.cpp:70
static LLVM_ABI ErrorOr< std::unique_ptr< LTOModule > > createFromOpenFile(LLVMContext &Context, int fd, StringRef path, size_t size, const TargetOptions &options)
static LLVM_ABI ErrorOr< std::unique_ptr< LTOModule > > createInLocalContext(std::unique_ptr< LLVMContext > Context, const void *mem, size_t length, const TargetOptions &options, StringRef path)
static LLVM_ABI ErrorOr< std::unique_ptr< LTOModule > > createFromBuffer(LLVMContext &Context, const void *mem, size_t length, const TargetOptions &options, StringRef path="")
LLVM_ABI Expected< uint32_t > getMachOCPUSubType() const
LLVM_ABI ~LTOModule()
static LLVM_ABI lto::InputFile * createInputFile(const void *buffer, size_t buffer_size, const char *path, std::string &out_error)
static const Target * lookupTarget(StringRef TripleStr, std::string &Error)
lookupTarget - Lookup a target based on a target triple.