LLVM 23.0.0git
ModuleSymbolTable.cpp
Go to the documentation of this file.
1//===- ModuleSymbolTable.cpp - symbol table for in-memory IR --------------===//
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 class represents a symbol table built from in-memory IR. It provides
10// access to GlobalValues and should only be used if such access is required
11// (e.g. in the LTO implementation).
12//
13//===----------------------------------------------------------------------===//
14
16#include "RecordStreamer.h"
17#include "llvm/ADT/StringRef.h"
19#include "llvm/IR/Function.h"
20#include "llvm/IR/GlobalAlias.h"
21#include "llvm/IR/GlobalValue.h"
23#include "llvm/IR/InlineAsm.h"
24#include "llvm/IR/Module.h"
25#include "llvm/MC/MCAsmInfo.h"
26#include "llvm/MC/MCContext.h"
27#include "llvm/MC/MCInstrInfo.h"
33#include "llvm/MC/MCSymbol.h"
40#include "llvm/Support/SMLoc.h"
44#include <cassert>
45#include <cstdint>
46#include <memory>
47#include <string>
48
49using namespace llvm;
50using namespace object;
51
53 if (FirstMod)
54 assert(FirstMod->getTargetTriple() == M->getTargetTriple());
55 else
56 FirstMod = M;
57
58 for (GlobalValue &GV : M->global_values())
59 SymTab.push_back(&GV);
60
61 CollectAsmSymbols(*M, [this](StringRef Name, BasicSymbolRef::Flags Flags) {
62 SymTab.push_back(new (AsmSymbols.Allocate())
63 AsmSymbol(std::string(Name), Flags));
64 });
65}
66
67static void
70 // This function may be called twice, once for ModuleSummaryIndexAnalysis and
71 // the other when writing the IR symbol table. If parsing inline assembly has
72 // caused errors in the first run, suppress the second run.
73 if (M.getContext().getDiagHandlerPtr()->HasErrors)
74 return;
75 StringRef InlineAsm = M.getModuleInlineAsm();
76 if (InlineAsm.empty())
77 return;
78
79 std::string Err;
80 const Triple TT(M.getTargetTriple());
81 const Target *T = TargetRegistry::lookupTarget(TT, Err);
82 assert(T && T->hasMCAsmParser());
83
84 std::unique_ptr<MCRegisterInfo> MRI(T->createMCRegInfo(TT));
85 if (!MRI)
86 return;
87
88 MCTargetOptions MCOptions;
89 std::unique_ptr<MCAsmInfo> MAI(T->createMCAsmInfo(*MRI, TT, MCOptions));
90 if (!MAI)
91 return;
92
93 std::unique_ptr<MCSubtargetInfo> STI(T->createMCSubtargetInfo(TT, "", ""));
94 if (!STI)
95 return;
96
97 std::unique_ptr<MCInstrInfo> MCII(T->createMCInstrInfo());
98 if (!MCII)
99 return;
100
101 std::unique_ptr<MemoryBuffer> Buffer(
102 MemoryBuffer::getMemBuffer(InlineAsm, "<inline asm>"));
104 SrcMgr.AddNewSourceBuffer(std::move(Buffer), SMLoc());
105
106 MCContext MCCtx(TT, MAI.get(), MRI.get(), STI.get(), &SrcMgr);
107 std::unique_ptr<MCObjectFileInfo> MOFI(
108 T->createMCObjectFileInfo(MCCtx, /*PIC=*/false));
109 MCCtx.setObjectFileInfo(MOFI.get());
110 RecordStreamer Streamer(MCCtx, M);
111 T->createNullTargetStreamer(Streamer);
112
113 std::unique_ptr<MCAsmParser> Parser(
114 createMCAsmParser(SrcMgr, MCCtx, Streamer, *MAI));
115
116 std::unique_ptr<MCTargetAsmParser> TAP(
117 T->createMCAsmParser(*STI, *Parser, *MCII, MCOptions));
118 if (!TAP)
119 return;
120
121 MCCtx.setDiagnosticHandler([&](const SMDiagnostic &SMD, bool IsInlineAsm,
122 const SourceMgr &SrcMgr,
123 std::vector<const MDNode *> &LocInfos) {
124 M.getContext().diagnose(
125 DiagnosticInfoSrcMgr(SMD, M.getName(), IsInlineAsm, /*LocCookie=*/0));
126 });
127
128 // Module-level inline asm is assumed to use At&t syntax (see
129 // AsmPrinter::doInitialization()).
130 Parser->setAssemblerDialect(InlineAsm::AD_ATT);
131
132 Parser->setSymbolScanningMode(true);
133
134 Parser->setTargetParser(*TAP);
135 if (Parser->Run(false))
136 return;
137
138 Init(Streamer);
139}
140
142 const Module &M,
144 initializeRecordStreamer(M, [&](RecordStreamer &Streamer) {
145 Streamer.flushSymverDirectives();
146
147 for (auto &KV : Streamer) {
148 StringRef Key = KV.first();
149 RecordStreamer::State Value = KV.second;
150 // FIXME: For now we just assume that all asm symbols are executable.
152 switch (Value) {
154 llvm_unreachable("NeverSeen should have been replaced earlier");
157 break;
159 break;
164 break;
168 break;
172 }
174 }
175 });
176
177 // In ELF, object code generated for x86-32 and some code models of x86-64 may
178 // reference the special symbol _GLOBAL_OFFSET_TABLE_ that is not used in the
179 // IR. Record it like inline asm symbols.
180 Triple TT(M.getTargetTriple());
181 if (!TT.isOSBinFormatELF() || !TT.isX86())
182 return;
183 auto CM = M.getCodeModel();
184 if (TT.getArch() == Triple::x86 || CM == CodeModel::Medium ||
185 CM == CodeModel::Large) {
186 AsmSymbol("_GLOBAL_OFFSET_TABLE_",
189 }
190}
191
193 const Module &M, function_ref<void(StringRef, StringRef)> AsmSymver) {
194 initializeRecordStreamer(M, [&](RecordStreamer &Streamer) {
195 for (auto &KV : Streamer.symverAliases())
196 for (auto &Alias : KV.second)
197 AsmSymver(KV.first->getName(), Alias);
198 });
199}
200
202 if (isa<AsmSymbol *>(S)) {
203 OS << cast<AsmSymbol *>(S)->first;
204 return;
205 }
206
207 auto *GV = cast<GlobalValue *>(S);
208 if (GV->hasDLLImportStorageClass())
209 OS << "__imp_";
210
211 Mang.getNameWithPrefix(OS, GV, false);
212}
213
215 if (isa<AsmSymbol *>(S))
216 return cast<AsmSymbol *>(S)->second;
217
218 auto *GV = cast<GlobalValue *>(S);
219
221 if (GV->isDeclarationForLinker())
223 else if (GV->hasHiddenVisibility() && !GV->hasLocalLinkage())
225 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV)) {
226 if (GVar->isConstant())
228 }
229 if (const GlobalObject *GO = GV->getAliaseeObject())
230 if (isa<Function>(GO) || isa<GlobalIFunc>(GO))
232 if (isa<GlobalAlias>(GV))
234 if (GV->hasPrivateLinkage())
236 if (!GV->hasLocalLinkage())
238 if (GV->hasCommonLinkage())
240 if (GV->hasLinkOnceLinkage() || GV->hasWeakLinkage() ||
241 GV->hasExternalWeakLinkage())
243
244 if (GV->getName().starts_with("llvm."))
246 else if (auto *Var = dyn_cast<GlobalVariable>(GV)) {
247 if (Var->getSection() == "llvm.metadata")
249 }
250
251 return Res;
252}
unsigned const MachineRegisterInfo * MRI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Module.h This file contains the declarations for the Module class.
#define T
static void initializeRecordStreamer(const Module &M, function_ref< void(RecordStreamer &)> Init)
Diagnostic information for SMDiagnostic reporting.
LLVM_ABI const GlobalObject * getAliaseeObject() const
Definition Globals.cpp:442
Context object for machine code objects.
Definition MCContext.h:83
void setObjectFileInfo(const MCObjectFileInfo *Mofi)
Definition MCContext.h:410
void setDiagnosticHandler(DiagHandlerTy DiagHandler)
Definition MCContext.h:406
static std::unique_ptr< MemoryBuffer > getMemBuffer(StringRef InputData, StringRef BufferName="", bool RequiresNullTerminator=true)
Open the specified memory range as a MemoryBuffer.
LLVM_ABI void addModule(Module *M)
static LLVM_ABI void CollectAsmSymvers(const Module &M, function_ref< void(StringRef, StringRef)> AsmSymver)
Parse inline ASM and collect the symvers directives that are defined in the current module.
std::pair< std::string, uint32_t > AsmSymbol
LLVM_ABI void printSymbolName(raw_ostream &OS, Symbol S) const
PointerUnion< GlobalValue *, AsmSymbol * > Symbol
LLVM_ABI uint32_t getSymbolFlags(Symbol S) const
static LLVM_ABI void CollectAsmSymbols(const Module &M, function_ref< void(StringRef, object::BasicSymbolRef::Flags)> AsmSymbol)
Parse inline ASM and collect the symbols that are defined or referenced in the current module.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
iterator_range< const_symver_iterator > symverAliases()
Instances of this class encapsulate one diagnostic report, allowing printing to a raw_ostream as a ca...
Definition SourceMgr.h:297
Represents a location in source code.
Definition SMLoc.h:22
This owns the files read by a parser, handles include stacks, and handles diagnostic wrangling.
Definition SourceMgr.h:37
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
Target - Wrapper for Target specific information.
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:47
LLVM Value Representation.
Definition Value.h:75
An efficient, type-erasing, non-owning reference to a callable.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
SourceMgr SrcMgr
Definition Error.cpp:24
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:547
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
LLVM_ABI MCAsmParser * createMCAsmParser(SourceMgr &, MCContext &, MCStreamer &, const MCAsmInfo &, unsigned CB=0)
Create an MCAsmParser instance for parsing assembly similar to gas syntax.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
static const Target * lookupTarget(StringRef TripleStr, std::string &Error)
lookupTarget - Lookup a target based on a target triple.