LLVM  6.0.0svn
ModuleSymbolTable.cpp
Go to the documentation of this file.
1 //===- ModuleSymbolTable.cpp - symbol table for in-memory IR --------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This class represents a symbol table built from in-memory IR. It provides
11 // access to GlobalValues and should only be used if such access is required
12 // (e.g. in the LTO implementation).
13 //
14 //===----------------------------------------------------------------------===//
15 
17 #include "RecordStreamer.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/ADT/StringMap.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/IR/Function.h"
24 #include "llvm/IR/GlobalAlias.h"
25 #include "llvm/IR/GlobalValue.h"
26 #include "llvm/IR/GlobalVariable.h"
27 #include "llvm/IR/Mangler.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/MC/MCAsmInfo.h"
30 #include "llvm/MC/MCContext.h"
31 #include "llvm/MC/MCDirectives.h"
32 #include "llvm/MC/MCInstrInfo.h"
36 #include "llvm/MC/MCRegisterInfo.h"
38 #include "llvm/MC/MCSymbol.h"
41 #include "llvm/Support/Casting.h"
42 #include "llvm/Support/CodeGen.h"
45 #include "llvm/Support/SMLoc.h"
46 #include "llvm/Support/SourceMgr.h"
49 #include <algorithm>
50 #include <cassert>
51 #include <cstdint>
52 #include <memory>
53 #include <string>
54 
55 using namespace llvm;
56 using namespace object;
57 
59  if (FirstMod)
60  assert(FirstMod->getTargetTriple() == M->getTargetTriple());
61  else
62  FirstMod = M;
63 
64  for (GlobalValue &GV : M->global_values())
65  SymTab.push_back(&GV);
66 
67  CollectAsmSymbols(*M, [this](StringRef Name, BasicSymbolRef::Flags Flags) {
68  SymTab.push_back(new (AsmSymbols.Allocate()) AsmSymbol(Name, Flags));
69  });
70 }
71 
72 // Ensure ELF .symver aliases get the same binding as the defined symbol
73 // they alias with.
74 static void handleSymverAliases(const Module &M, RecordStreamer &Streamer) {
75  if (Streamer.symverAliases().empty())
76  return;
77 
78  // The name in the assembler will be mangled, but the name in the IR
79  // might not, so we first compute a mapping from mangled name to GV.
80  Mangler Mang;
81  SmallString<64> MangledName;
82  StringMap<const GlobalValue *> MangledNameMap;
83  auto GetMangledName = [&](const GlobalValue &GV) {
84  if (!GV.hasName())
85  return;
86 
87  MangledName.clear();
88  MangledName.reserve(GV.getName().size() + 1);
89  Mang.getNameWithPrefix(MangledName, &GV, /*CannotUsePrivateLabel=*/false);
90  MangledNameMap[MangledName] = &GV;
91  };
92  for (const Function &F : M)
93  GetMangledName(F);
94  for (const GlobalVariable &GV : M.globals())
95  GetMangledName(GV);
96  for (const GlobalAlias &GA : M.aliases())
97  GetMangledName(GA);
98 
99  // Walk all the recorded .symver aliases, and set up the binding
100  // for each alias.
101  for (auto &Symver : Streamer.symverAliases()) {
102  const MCSymbol *Aliasee = Symver.first;
103  MCSymbolAttr Attr = MCSA_Invalid;
104 
105  // First check if the aliasee binding was recorded in the asm.
106  RecordStreamer::State state = Streamer.getSymbolState(Aliasee);
107  switch (state) {
110  Attr = MCSA_Global;
111  break;
114  Attr = MCSA_Weak;
115  break;
116  default:
117  break;
118  }
119 
120  // If we don't have a symbol attribute from assembly, then check if
121  // the aliasee was defined in the IR.
122  if (Attr == MCSA_Invalid) {
123  const auto *GV = M.getNamedValue(Aliasee->getName());
124  if (!GV) {
125  auto MI = MangledNameMap.find(Aliasee->getName());
126  if (MI != MangledNameMap.end())
127  GV = MI->second;
128  else
129  continue;
130  }
131  if (GV->hasExternalLinkage())
132  Attr = MCSA_Global;
133  else if (GV->hasLocalLinkage())
134  Attr = MCSA_Local;
135  else if (GV->isWeakForLinker())
136  Attr = MCSA_Weak;
137  }
138  if (Attr == MCSA_Invalid)
139  continue;
140 
141  // Set the detected binding on each alias with this aliasee.
142  for (auto &Alias : Symver.second)
143  Streamer.EmitSymbolAttribute(Alias, Attr);
144  }
145 }
146 
148  const Module &M,
151  if (InlineAsm.empty())
152  return;
153 
154  std::string Err;
155  const Triple TT(M.getTargetTriple());
156  const Target *T = TargetRegistry::lookupTarget(TT.str(), Err);
157  assert(T && T->hasMCAsmParser());
158 
159  std::unique_ptr<MCRegisterInfo> MRI(T->createMCRegInfo(TT.str()));
160  if (!MRI)
161  return;
162 
163  std::unique_ptr<MCAsmInfo> MAI(T->createMCAsmInfo(*MRI, TT.str()));
164  if (!MAI)
165  return;
166 
167  std::unique_ptr<MCSubtargetInfo> STI(
168  T->createMCSubtargetInfo(TT.str(), "", ""));
169  if (!STI)
170  return;
171 
172  std::unique_ptr<MCInstrInfo> MCII(T->createMCInstrInfo());
173  if (!MCII)
174  return;
175 
176  MCObjectFileInfo MOFI;
177  MCContext MCCtx(MAI.get(), MRI.get(), &MOFI);
178  MOFI.InitMCObjectFileInfo(TT, /*PIC*/ false, MCCtx);
179  RecordStreamer Streamer(MCCtx);
180  T->createNullTargetStreamer(Streamer);
181 
182  std::unique_ptr<MemoryBuffer> Buffer(MemoryBuffer::getMemBuffer(InlineAsm));
184  SrcMgr.AddNewSourceBuffer(std::move(Buffer), SMLoc());
185  std::unique_ptr<MCAsmParser> Parser(
186  createMCAsmParser(SrcMgr, MCCtx, Streamer, *MAI));
187 
188  MCTargetOptions MCOptions;
189  std::unique_ptr<MCTargetAsmParser> TAP(
190  T->createMCAsmParser(*STI, *Parser, *MCII, MCOptions));
191  if (!TAP)
192  return;
193 
194  Parser->setTargetParser(*TAP);
195  if (Parser->Run(false))
196  return;
197 
198  handleSymverAliases(M, Streamer);
199 
200  for (auto &KV : Streamer) {
201  StringRef Key = KV.first();
202  RecordStreamer::State Value = KV.second;
203  // FIXME: For now we just assume that all asm symbols are executable.
205  switch (Value) {
207  llvm_unreachable("NeverSeen should have been replaced earlier");
210  break;
212  break;
217  break;
221  break;
225  }
226  AsmSymbol(Key, BasicSymbolRef::Flags(Res));
227  }
228 }
229 
231  if (S.is<AsmSymbol *>()) {
232  OS << S.get<AsmSymbol *>()->first;
233  return;
234  }
235 
236  auto *GV = S.get<GlobalValue *>();
237  if (GV->hasDLLImportStorageClass())
238  OS << "__imp_";
239 
240  Mang.getNameWithPrefix(OS, GV, false);
241 }
242 
244  if (S.is<AsmSymbol *>())
245  return S.get<AsmSymbol *>()->second;
246 
247  auto *GV = S.get<GlobalValue *>();
248 
250  if (GV->isDeclarationForLinker())
252  else if (GV->hasHiddenVisibility() && !GV->hasLocalLinkage())
254  if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV)) {
255  if (GVar->isConstant())
257  }
258  if (dyn_cast_or_null<Function>(GV->getBaseObject()))
260  if (isa<GlobalAlias>(GV))
262  if (GV->hasPrivateLinkage())
264  if (!GV->hasLocalLinkage())
266  if (GV->hasCommonLinkage())
268  if (GV->hasLinkOnceLinkage() || GV->hasWeakLinkage() ||
269  GV->hasExternalWeakLinkage())
271 
272  if (GV->getName().startswith("llvm."))
274  else if (auto *Var = dyn_cast<GlobalVariable>(GV)) {
275  if (Var->getSection() == "llvm.metadata")
277  }
278 
279  return Res;
280 }
const std::string & getTargetTriple() const
Get the target triple which is a string describing the target host.
Definition: Module.h:233
uint32_t getSymbolFlags(Symbol S) const
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:42
Not a valid directive.
Definition: MCDirectives.h:20
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:63
bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) override
Add the given Attribute to Symbol.
SourceMgr SrcMgr
Definition: Error.cpp:23
static std::unique_ptr< MemoryBuffer > getMemBuffer(StringRef InputData, StringRef BufferName="", bool RequiresNullTerminator=true)
Open the specified memory range as a MemoryBuffer.
An efficient, type-erasing, non-owning reference to a callable.
Definition: STLExtras.h:89
iterator find(StringRef Key)
Definition: StringMap.h:337
unsigned second
F(f)
static const Target * lookupTarget(const std::string &Triple, std::string &Error)
lookupTarget - Lookup a target based on a target triple.
void reserve(size_type N)
Definition: SmallVector.h:380
MCAsmParser * createMCAsmParser(SourceMgr &, MCContext &, MCStreamer &, const MCAsmInfo &, unsigned CB=0)
Create an MCAsmParser instance.
Definition: AsmParser.cpp:5830
.local (ELF)
Definition: MCDirectives.h:35
static 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...
Context object for machine code objects.
Definition: MCContext.h:59
Key
PAL metadata keys.
unsigned AddNewSourceBuffer(std::unique_ptr< MemoryBuffer > F, SMLoc IncludeLoc)
Add a new source buffer to this source manager.
Definition: SourceMgr.h:125
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:133
std::pair< std::string, uint32_t > AsmSymbol
unsigned const MachineRegisterInfo * MRI
static void handleSymverAliases(const Module &M, RecordStreamer &Streamer)
This owns the files read by a parser, handles include stacks, and handles diagnostic wrangling...
Definition: SourceMgr.h:41
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
unsigned first
State getSymbolState(const MCSymbol *Sym)
Get the state recorded for the given symbol.
Module.h This file contains the declarations for the Module class.
MCSymbolAttr
Definition: MCDirectives.h:19
StringMap - This is an unconventional map that is specialized for handling keys that are "strings"...
Definition: StringMap.h:224
Target - Wrapper for Target specific information.
void printSymbolName(raw_ostream &OS, Symbol S) const
DenseMap< const MCSymbol *, std::vector< MCSymbol * > > & symverAliases()
Return the map of .symver aliasee to associated aliases.
void InitMCObjectFileInfo(const Triple &TT, bool PIC, MCContext &ctx, bool LargeCodeModel=false)
.type _foo,
Definition: MCDirectives.h:30
const std::string & getModuleInlineAsm() const
Get any module-scope inline assembly blocks.
Definition: Module.h:241
StringRef getName() const
getName - Get the symbol name.
Definition: MCSymbol.h:203
T get() const
Returns the value of the specified pointer type.
Definition: PointerUnion.h:135
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
Definition: Value.h:73
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:44
void getNameWithPrefix(raw_ostream &OS, const GlobalValue *GV, bool CannotUsePrivateLabel) const
Print the appropriate prefix and the specified global variable&#39;s name.
Definition: Mangler.cpp:109
IRTranslator LLVM IR MI
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
int is() const
Test if the Union currently holds the type matching T.
Definition: PointerUnion.h:123
Represents a location in source code.
Definition: SMLoc.h:24
iterator_range< global_value_iterator > global_values()
Definition: Module.h:662
iterator end()
Definition: StringMap.h:322
A discriminated union of two pointer types, with the discriminator in the low bit of the pointer...
Definition: PointerUnion.h:87