]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - llvm/lib/ExecutionEngine/Orc/Layer.cpp
Vendor import of llvm-project branch release/10.x
[FreeBSD/FreeBSD.git] / llvm / lib / ExecutionEngine / Orc / Layer.cpp
1 //===-------------------- Layer.cpp - Layer interfaces --------------------===//
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 #include "llvm/ExecutionEngine/Orc/Layer.h"
10 #include "llvm/IR/Constants.h"
11 #include "llvm/Object/ObjectFile.h"
12 #include "llvm/Support/Debug.h"
13
14 #define DEBUG_TYPE "orc"
15
16 namespace llvm {
17 namespace orc {
18
19 IRLayer::~IRLayer() {}
20
21 Error IRLayer::add(JITDylib &JD, ThreadSafeModule TSM, VModuleKey K) {
22   return JD.define(std::make_unique<BasicIRLayerMaterializationUnit>(
23       *this, *getManglingOptions(), std::move(TSM), std::move(K)));
24 }
25
26 IRMaterializationUnit::IRMaterializationUnit(ExecutionSession &ES,
27                                              const ManglingOptions &MO,
28                                              ThreadSafeModule TSM, VModuleKey K)
29     : MaterializationUnit(SymbolFlagsMap(), std::move(K)), TSM(std::move(TSM)) {
30
31   assert(this->TSM && "Module must not be null");
32
33   MangleAndInterner Mangle(ES, this->TSM.getModuleUnlocked()->getDataLayout());
34   this->TSM.withModuleDo([&](Module &M) {
35     for (auto &G : M.global_values()) {
36       // Skip globals that don't generate symbols.
37       if (!G.hasName() || G.isDeclaration() || G.hasLocalLinkage() ||
38           G.hasAvailableExternallyLinkage() || G.hasAppendingLinkage())
39         continue;
40
41       // thread locals generate different symbols depending on whether or not
42       // emulated TLS is enabled.
43       if (G.isThreadLocal() && MO.EmulatedTLS) {
44         auto &GV = cast<GlobalVariable>(G);
45
46         auto Flags = JITSymbolFlags::fromGlobalValue(GV);
47
48         auto EmuTLSV = Mangle(("__emutls_v." + GV.getName()).str());
49         SymbolFlags[EmuTLSV] = Flags;
50         SymbolToDefinition[EmuTLSV] = &GV;
51
52         // If this GV has a non-zero initializer we'll need to emit an
53         // __emutls.t symbol too.
54         if (GV.hasInitializer()) {
55           const auto *InitVal = GV.getInitializer();
56
57           // Skip zero-initializers.
58           if (isa<ConstantAggregateZero>(InitVal))
59             continue;
60           const auto *InitIntValue = dyn_cast<ConstantInt>(InitVal);
61           if (InitIntValue && InitIntValue->isZero())
62             continue;
63
64           auto EmuTLST = Mangle(("__emutls_t." + GV.getName()).str());
65           SymbolFlags[EmuTLST] = Flags;
66         }
67         continue;
68       }
69
70       // Otherwise we just need a normal linker mangling.
71       auto MangledName = Mangle(G.getName());
72       SymbolFlags[MangledName] = JITSymbolFlags::fromGlobalValue(G);
73       SymbolToDefinition[MangledName] = &G;
74     }
75   });
76 }
77
78 IRMaterializationUnit::IRMaterializationUnit(
79     ThreadSafeModule TSM, VModuleKey K, SymbolFlagsMap SymbolFlags,
80     SymbolNameToDefinitionMap SymbolToDefinition)
81     : MaterializationUnit(std::move(SymbolFlags), std::move(K)),
82       TSM(std::move(TSM)), SymbolToDefinition(std::move(SymbolToDefinition)) {}
83
84 StringRef IRMaterializationUnit::getName() const {
85   if (TSM)
86     return TSM.withModuleDo(
87         [](const Module &M) -> StringRef { return M.getModuleIdentifier(); });
88   return "<null module>";
89 }
90
91 void IRMaterializationUnit::discard(const JITDylib &JD,
92                                     const SymbolStringPtr &Name) {
93   LLVM_DEBUG(JD.getExecutionSession().runSessionLocked([&]() {
94     dbgs() << "In " << JD.getName() << " discarding " << *Name << " from MU@"
95            << this << " (" << getName() << ")\n";
96   }););
97
98   auto I = SymbolToDefinition.find(Name);
99   assert(I != SymbolToDefinition.end() &&
100          "Symbol not provided by this MU, or previously discarded");
101   assert(!I->second->isDeclaration() &&
102          "Discard should only apply to definitions");
103   I->second->setLinkage(GlobalValue::AvailableExternallyLinkage);
104   SymbolToDefinition.erase(I);
105 }
106
107 BasicIRLayerMaterializationUnit::BasicIRLayerMaterializationUnit(
108     IRLayer &L, const ManglingOptions &MO, ThreadSafeModule TSM, VModuleKey K)
109     : IRMaterializationUnit(L.getExecutionSession(), MO, std::move(TSM),
110                             std::move(K)),
111       L(L), K(std::move(K)) {}
112
113 void BasicIRLayerMaterializationUnit::materialize(
114     MaterializationResponsibility R) {
115
116   // Throw away the SymbolToDefinition map: it's not usable after we hand
117   // off the module.
118   SymbolToDefinition.clear();
119
120   // If cloneToNewContextOnEmit is set, clone the module now.
121   if (L.getCloneToNewContextOnEmit())
122     TSM = cloneToNewContext(TSM);
123
124 #ifndef NDEBUG
125   auto &ES = R.getTargetJITDylib().getExecutionSession();
126   auto &N = R.getTargetJITDylib().getName();
127 #endif // NDEBUG
128
129   LLVM_DEBUG(ES.runSessionLocked(
130       [&]() { dbgs() << "Emitting, for " << N << ", " << *this << "\n"; }););
131   L.emit(std::move(R), std::move(TSM));
132   LLVM_DEBUG(ES.runSessionLocked([&]() {
133     dbgs() << "Finished emitting, for " << N << ", " << *this << "\n";
134   }););
135 }
136
137 ObjectLayer::ObjectLayer(ExecutionSession &ES) : ES(ES) {}
138
139 ObjectLayer::~ObjectLayer() {}
140
141 Error ObjectLayer::add(JITDylib &JD, std::unique_ptr<MemoryBuffer> O,
142                        VModuleKey K) {
143   auto ObjMU = BasicObjectLayerMaterializationUnit::Create(*this, std::move(K),
144                                                            std::move(O));
145   if (!ObjMU)
146     return ObjMU.takeError();
147   return JD.define(std::move(*ObjMU));
148 }
149
150 Expected<std::unique_ptr<BasicObjectLayerMaterializationUnit>>
151 BasicObjectLayerMaterializationUnit::Create(ObjectLayer &L, VModuleKey K,
152                                             std::unique_ptr<MemoryBuffer> O) {
153   auto SymbolFlags =
154       getObjectSymbolFlags(L.getExecutionSession(), O->getMemBufferRef());
155
156   if (!SymbolFlags)
157     return SymbolFlags.takeError();
158
159   return std::unique_ptr<BasicObjectLayerMaterializationUnit>(
160       new BasicObjectLayerMaterializationUnit(L, K, std::move(O),
161                                               std::move(*SymbolFlags)));
162 }
163
164 BasicObjectLayerMaterializationUnit::BasicObjectLayerMaterializationUnit(
165     ObjectLayer &L, VModuleKey K, std::unique_ptr<MemoryBuffer> O,
166     SymbolFlagsMap SymbolFlags)
167     : MaterializationUnit(std::move(SymbolFlags), std::move(K)), L(L),
168       O(std::move(O)) {}
169
170 StringRef BasicObjectLayerMaterializationUnit::getName() const {
171   if (O)
172     return O->getBufferIdentifier();
173   return "<null object>";
174 }
175
176 void BasicObjectLayerMaterializationUnit::materialize(
177     MaterializationResponsibility R) {
178   L.emit(std::move(R), std::move(O));
179 }
180
181 void BasicObjectLayerMaterializationUnit::discard(const JITDylib &JD,
182                                                   const SymbolStringPtr &Name) {
183   // FIXME: Support object file level discard. This could be done by building a
184   //        filter to pass to the object layer along with the object itself.
185 }
186
187 Expected<SymbolFlagsMap> getObjectSymbolFlags(ExecutionSession &ES,
188                                               MemoryBufferRef ObjBuffer) {
189   auto Obj = object::ObjectFile::createObjectFile(ObjBuffer);
190
191   if (!Obj)
192     return Obj.takeError();
193
194   SymbolFlagsMap SymbolFlags;
195   for (auto &Sym : (*Obj)->symbols()) {
196     // Skip symbols not defined in this object file.
197     if (Sym.getFlags() & object::BasicSymbolRef::SF_Undefined)
198       continue;
199
200     // Skip symbols that are not global.
201     if (!(Sym.getFlags() & object::BasicSymbolRef::SF_Global))
202       continue;
203
204     auto Name = Sym.getName();
205     if (!Name)
206       return Name.takeError();
207     auto InternedName = ES.intern(*Name);
208     auto SymFlags = JITSymbolFlags::fromObjectSymbol(Sym);
209     if (!SymFlags)
210       return SymFlags.takeError();
211     SymbolFlags[InternedName] = std::move(*SymFlags);
212   }
213
214   return SymbolFlags;
215 }
216
217 } // End namespace orc.
218 } // End namespace llvm.