forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Linker.cpp
359 lines (299 loc) · 11.8 KB
/
Linker.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
//===--- Linker.cpp -------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "sil-linker"
#include "Linker.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/FoldingSet.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/Debug.h"
using namespace swift;
using namespace Lowering;
STATISTIC(NumFuncLinked, "Number of SIL functions linked");
//===----------------------------------------------------------------------===//
// Utility
//===----------------------------------------------------------------------===//
/// \return True if the function \p F should be imported into the current
/// module.
static bool shouldImportFunction(SILFunction *F) {
// Skip functions that are marked with the 'no import' tag. These
// are functions that we don't want to copy from the module.
if (F->hasSemanticsString("stdlib_binary_only"))
return false;
return true;
}
//===----------------------------------------------------------------------===//
// Linker Helpers
//===----------------------------------------------------------------------===//
/// Process F, recursively deserializing any thing F may reference.
bool SILLinkerVisitor::processFunction(SILFunction *F) {
if (Mode == LinkingMode::LinkNone)
return false;
if (!shouldImportFunction(F))
return false;
// If F is a declaration, first deserialize it.
auto *NewFn = F->isExternalDeclaration() ? Loader->lookupSILFunction(F) : F;
if (!NewFn || NewFn->empty())
return false;
++NumFuncLinked;
// Try to transitively deserialize everything referenced by NewFn.
Worklist.push_back(NewFn);
process();
// Since we successfully processed at least one function, return true.
return true;
}
/// Process Decl, recursively deserializing any thing Decl may reference.
bool SILLinkerVisitor::processDeclRef(SILDeclRef Decl) {
if (Mode == LinkingMode::LinkNone)
return false;
// If F is a declaration, first deserialize it.
auto Name = Decl.getFuncDecl()->getNameStr();
auto *NewFn =
isAvailableExternally(Decl.getLinkage(ForDefinition_t::NotForDefinition))
? Loader->lookupSILFunction(Name)
: nullptr;
if (!NewFn || NewFn->empty())
return false;
if (!shouldImportFunction(NewFn)) {
return false;
}
++NumFuncLinked;
// Try to transitively deserialize everything referenced by NewFn.
Worklist.push_back(NewFn);
process();
// Since we successfully processed at least one function, return true.
return true;
}
/// Deserialize the VTable mapped to C if it exists and all SIL the VTable
/// transitively references.
///
/// This method assumes that the caller made sure that no vtable existed in
/// Mod.
SILVTable *SILLinkerVisitor::processClassDecl(const ClassDecl *C) {
// If we are not linking anything, bail.
if (Mode == LinkingMode::LinkNone)
return nullptr;
// Attempt to load the VTable from the SerializedSILLoader. If we
// fail... bail...
SILVTable *Vtbl = Loader->lookupVTable(C);
if (!Vtbl)
return nullptr;
// Otherwise, add all the vtable functions in Vtbl to the function
// processing list...
for (auto &E : Vtbl->getEntries())
Worklist.push_back(E.second);
// And then transitively deserialize all SIL referenced by those functions.
process();
// Return the deserialized Vtbl.
return Vtbl;
}
bool SILLinkerVisitor::linkInVTable(ClassDecl *D) {
// Attempt to lookup the Vtbl from the SILModule.
SILVTable *Vtbl = Mod.lookUpVTable(D);
// If the SILModule does not have the VTable, attempt to deserialize the
// VTable. If we fail to do that as well, bail.
if (!Vtbl || !(Vtbl = Loader->lookupVTable(D->getName())))
return false;
// Ok we found our VTable. Visit each function referenced by the VTable. If
// any of the functions are external declarations, add them to the worklist
// for processing.
bool Result = false;
for (auto P : Vtbl->getEntries()) {
if (P.second->isExternalDeclaration()) {
Result = true;
addFunctionToWorklist(P.second);
}
}
return Result;
}
//===----------------------------------------------------------------------===//
// Visitors
//===----------------------------------------------------------------------===//
bool SILLinkerVisitor::visitApplyInst(ApplyInst *AI) {
// If we don't have a function ref inst, just return false. We do not have
// interesting callees.
auto *FRI = dyn_cast<FunctionRefInst>(AI->getCallee());
if (!FRI)
return false;
// Ok we have a function ref inst, grab the callee.
SILFunction *Callee = FRI->getReferencedFunction();
// If the linking mode is not link all, AI is not transparent, and the
// callee is not shared, we don't want to perform any linking.
if (!isLinkAll() && !AI->isTransparent() &&
!hasSharedVisibility(Callee->getLinkage()))
return false;
// Otherwise we want to try and link in the callee... Add it to the callee
// list and return true.
addFunctionToWorklist(Callee);
return true;
}
bool SILLinkerVisitor::visitPartialApplyInst(PartialApplyInst *PAI) {
auto *FRI = dyn_cast<FunctionRefInst>(PAI->getCallee());
if (!FRI)
return false;
SILFunction *Callee = FRI->getReferencedFunction();
if (!isLinkAll() && !Callee->isTransparent() &&
!hasSharedVisibility(Callee->getLinkage()))
return false;
addFunctionToWorklist(Callee);
return true;
}
bool SILLinkerVisitor::visitFunctionRefInst(FunctionRefInst *FRI) {
// Needed to handle closures which are no longer applied, but are left
// behind as dead code. This shouldn't happen, but if it does don't get into
// an inconsistent state.
SILFunction *Callee = FRI->getReferencedFunction();
if (!isLinkAll() && !Callee->isTransparent() &&
!hasSharedVisibility(Callee->getLinkage()))
return false;
addFunctionToWorklist(FRI->getReferencedFunction());
return true;
}
bool SILLinkerVisitor::visitProtocolConformance(
ProtocolConformance *C, const Optional<SILDeclRef> &Member) {
// If a null protocol conformance was passed in, just return false.
if (!C)
return false;
// Otherwise try and lookup a witness table for C.
SILWitnessTable *WT = Mod.lookUpWitnessTable(C).first;
// If we don't find any witness table for the conformance, bail and return
// false.
if (!WT) {
Mod.createWitnessTableDeclaration(
C, TypeConverter::getLinkageForProtocolConformance(
C->getRootNormalConformance(), NotForDefinition));
return false;
}
// If the looked up witness table is a declaration, there is nothing we can
// do here. Just bail and return false.
if (WT->isDeclaration())
return false;
bool performFuncDeserialization = false;
// For each entry in the witness table...
for (auto &E : WT->getEntries()) {
// If the entry is a witness method...
if (E.getKind() == SILWitnessTable::WitnessKind::Method) {
// And we are only interested in deserializing a specific requirement
// and don't have that requirement, don't deserialize this method.
if (Member.hasValue() && E.getMethodWitness().Requirement != *Member)
continue;
// The witness could be removed by dead function elimination.
if (!E.getMethodWitness().Witness)
continue;
// Otherwise if it is the requirement we are looking for or we just want
// to deserialize everything, add the function to the list of functions
// to deserialize.
performFuncDeserialization = true;
addFunctionToWorklist(E.getMethodWitness().Witness);
}
}
return performFuncDeserialization;
}
bool SILLinkerVisitor::visitInitExistentialAddrInst(
InitExistentialAddrInst *IEI) {
// Link in all protocol conformances that this touches.
//
// TODO: There might be a two step solution where the init_existential_inst
// causes the witness table to be brought in as a declaration and then the
// protocol method inst causes the actual deserialization. For now we are
// not going to be smart about this to enable avoiding any issues with
// visiting the open_existential_addr/witness_method before the
// init_existential_inst.
bool performFuncDeserialization = false;
for (ProtocolConformance *C : IEI->getConformances()) {
performFuncDeserialization |=
visitProtocolConformance(C, Optional<SILDeclRef>());
}
return performFuncDeserialization;
}
bool SILLinkerVisitor::visitInitExistentialRefInst(
InitExistentialRefInst *IERI) {
// Link in all protocol conformances that this touches.
//
// TODO: There might be a two step solution where the init_existential_inst
// causes the witness table to be brought in as a declaration and then the
// protocol method inst causes the actual deserialization. For now we are
// not going to be smart about this to enable avoiding any issues with
// visiting the protocol_method before the init_existential_inst.
bool performFuncDeserialization = false;
for (ProtocolConformance *C : IERI->getConformances()) {
performFuncDeserialization |=
visitProtocolConformance(C, Optional<SILDeclRef>());
}
return performFuncDeserialization;
}
bool SILLinkerVisitor::visitAllocRefInst(AllocRefInst *ARI) {
// Grab the class decl from the alloc ref inst.
ClassDecl *D = ARI->getType().getClassOrBoundGenericClass();
if (!D)
return false;
return linkInVTable(D);
}
bool SILLinkerVisitor::visitMetatypeInst(MetatypeInst *MI) {
CanType instTy = MI->getType().castTo<MetatypeType>().getInstanceType();
ClassDecl *C = instTy.getClassOrBoundGenericClass();
if (!C)
return false;
return linkInVTable(C);
}
//===----------------------------------------------------------------------===//
// Top Level Routine
//===----------------------------------------------------------------------===//
// Main loop of the visitor. Called by one of the other *visit* methods.
bool SILLinkerVisitor::process() {
// Process everything transitively referenced by one of the functions in the
// worklist.
bool Result = false;
while (!Worklist.empty()) {
auto *Fn = Worklist.pop_back_val();
if (!shouldImportFunction(Fn))
continue;
for (auto &BB : *Fn) {
for (auto &I : BB) {
// Should we try linking?
if (visit(&I)) {
for (auto *F : FunctionDeserializationWorklist) {
if (!shouldImportFunction(F))
continue;
// The ExternalSource may wish to rewrite non-empty bodies.
if (!F->empty() && ExternalSource) {
if (auto *NewFn = ExternalSource->lookupSILFunction(F)) {
NewFn->verify();
Worklist.push_back(NewFn);
++NumFuncLinked;
Result = true;
continue;
}
}
F->setBare(IsBare);
if (F->empty()) {
if (auto *NewFn = Loader->lookupSILFunction(F)) {
NewFn->verify();
Worklist.push_back(NewFn);
Result = true;
++NumFuncLinked;
}
}
}
FunctionDeserializationWorklist.clear();
} else {
assert(FunctionDeserializationWorklist.empty() &&
"Worklist should "
"always be empty if visit does not return true.");
}
}
}
}
// If we return true, we deserialized at least one function.
return Result;
}