LLVM 24.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 if (!M.hasModuleInlineAsm())
76 return;
77
78 std::string Err;
79 const Triple TT(M.getTargetTriple());
80 const Target *T = TargetRegistry::lookupTarget(TT, Err);
81 assert(T && T->hasMCAsmParser());
82
83 std::unique_ptr<MCRegisterInfo> MRI(T->createMCRegInfo(TT));
84 if (!MRI)
85 return;
86
87 MCTargetOptions MCOptions;
88 std::unique_ptr<MCAsmInfo> MAI(T->createMCAsmInfo(*MRI, TT, MCOptions));
89 if (!MAI)
90 return;
91
92 std::unique_ptr<MCInstrInfo> MCII(T->createMCInstrInfo());
93 if (!MCII)
94 return;
95
96 for (const Module::GlobalAsmFragment &Frag : M.getModuleInlineAsm()) {
97 std::unique_ptr<MCSubtargetInfo> STI(T->createMCSubtargetInfo(
98 TT, Frag.Props.TargetCPU, Frag.Props.TargetFeatures));
99 if (!STI)
100 return;
101
102 std::unique_ptr<MemoryBuffer> Buffer(
103 MemoryBuffer::getMemBuffer(Frag.Asm, "<inline asm>"));
105 SrcMgr.AddNewSourceBuffer(std::move(Buffer), SMLoc());
106
107 MCContext MCCtx(TT, *MAI, *MRI, *STI, &SrcMgr);
108 std::unique_ptr<MCObjectFileInfo> MOFI(
109 T->createMCObjectFileInfo(MCCtx, /*PIC=*/false));
110 MCCtx.setObjectFileInfo(MOFI.get());
111 RecordStreamer Streamer(MCCtx, M);
112 T->createNullTargetStreamer(Streamer);
113
114 std::unique_ptr<MCAsmParser> Parser(
115 createMCAsmParser(SrcMgr, MCCtx, Streamer, *MAI));
116
117 std::unique_ptr<MCTargetAsmParser> TAP(
118 T->createMCAsmParser(*STI, *Parser, *MCII));
119 if (!TAP)
120 return;
121
122 MCCtx.setDiagnosticHandler([&](const SMDiagnostic &SMD, bool IsInlineAsm,
123 const SourceMgr &SrcMgr,
124 std::vector<const MDNode *> &LocInfos) {
125 M.getContext().diagnose(
126 DiagnosticInfoSrcMgr(SMD, M.getName(), IsInlineAsm, /*LocCookie=*/0));
127 });
128
129 // Module-level inline asm is assumed to use At&t syntax (see
130 // AsmPrinter::doInitialization()).
131 Parser->setAssemblerDialect(InlineAsm::AD_ATT);
132
133 Parser->setSymbolScanningMode(true);
134
135 Parser->setTargetParser(*TAP);
136 if (Parser->Run(false))
137 return;
138
139 Init(Streamer);
140 }
141}
142
144 const Module &M,
146 initializeRecordStreamer(M, [&](RecordStreamer &Streamer) {
147 Streamer.flushSymverDirectives();
148
149 for (auto &KV : Streamer) {
150 StringRef Key = KV.first();
151 RecordStreamer::State Value = KV.second;
152 // FIXME: For now we just assume that all asm symbols are executable.
154 switch (Value) {
156 llvm_unreachable("NeverSeen should have been replaced earlier");
159 break;
161 break;
166 break;
170 break;
174 }
176 }
177 });
178
179 // In ELF, object code generated for x86-32 and some code models of x86-64 may
180 // reference the special symbol _GLOBAL_OFFSET_TABLE_ that is not used in the
181 // IR. Record it like inline asm symbols.
182 Triple TT(M.getTargetTriple());
183 if (!TT.isOSBinFormatELF() || !TT.isX86())
184 return;
185 auto CM = M.getCodeModel();
186 if (TT.getArch() == Triple::x86 || CM == CodeModel::Medium ||
187 CM == CodeModel::Large) {
188 AsmSymbol("_GLOBAL_OFFSET_TABLE_",
191 }
192}
193
195 const Module &M, function_ref<void(StringRef, StringRef)> AsmSymver) {
196 initializeRecordStreamer(M, [&](RecordStreamer &Streamer) {
197 for (auto &KV : Streamer.symverAliases())
198 for (auto &Alias : KV.second)
199 AsmSymver(KV.first->getName(), Alias);
200 });
201}
202
204 if (isa<AsmSymbol *>(S)) {
205 OS << cast<AsmSymbol *>(S)->first;
206 return;
207 }
208
209 auto *GV = cast<GlobalValue *>(S);
210 if (GV->hasDLLImportStorageClass())
211 OS << "__imp_";
212
213 Mang.getNameWithPrefix(OS, GV, false);
214}
215
217 if (isa<AsmSymbol *>(S))
218 return cast<AsmSymbol *>(S)->second;
219
220 auto *GV = cast<GlobalValue *>(S);
221
223 if (GV->isDeclarationForLinker())
225 else if (GV->hasHiddenVisibility() && !GV->hasLocalLinkage())
227 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV)) {
228 if (GVar->isConstant())
230 }
231 if (const GlobalObject *GO = GV->getAliaseeObject())
232 if (isa<Function>(GO) || isa<GlobalIFunc>(GO))
234 if (isa<GlobalAlias>(GV))
236 if (GV->hasPrivateLinkage())
238 if (!GV->hasLocalLinkage())
240 if (GV->hasCommonLinkage())
242 if (GV->hasLinkOnceLinkage() || GV->hasWeakLinkage() ||
243 GV->hasExternalWeakLinkage())
245
246 if (GV->getName().starts_with("llvm."))
248 else if (auto *Var = dyn_cast<GlobalVariable>(GV)) {
249 if (Var->getSection() == "llvm.metadata")
251 }
252
253 return Res;
254}
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:521
Context object for machine code objects.
Definition MCContext.h:83
void setObjectFileInfo(const MCObjectFileInfo *Mofi)
Definition MCContext.h:407
void setDiagnosticHandler(DiagHandlerTy DiagHandler)
Definition MCContext.h:403
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:303
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
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
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.
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 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 LLVM_ABI const Target * lookupTarget(const Triple &TheTriple, std::string &Error)
lookupTarget - Lookup a target based on a target triple.