Skip to content

Commit ff15d54

Browse files
committed
Deserializer: fix a crash with global variables and cross-module-optimization
In case of cross-module-optimizations it can happen that a private global variable is changed to public, but it's declaration is not available in the module file.
1 parent 19dccf7 commit ff15d54

File tree

3 files changed

+26
-1
lines changed

3 files changed

+26
-1
lines changed

lib/Serialization/DeserializeSIL.cpp

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3651,11 +3651,23 @@ SILGlobalVariable *SILDeserializer::readGlobalVar(StringRef Name) {
36513651
return nullptr;
36523652
}
36533653

3654+
VarDecl *globalDecl = nullptr;
3655+
if (dID) {
3656+
llvm::Expected<Decl *> d = MF->getDeclChecked(dID);
3657+
if (d) {
3658+
globalDecl = cast<VarDecl>(d.get());
3659+
} else {
3660+
// This can happen with cross-module-optimizations, if the linkage of a
3661+
// private global variable is changed to public.
3662+
consumeError(d.takeError());
3663+
}
3664+
}
3665+
36543666
auto Ty = MF->getType(TyID);
36553667
SILGlobalVariable *v = SILGlobalVariable::create(
36563668
SILMod, linkage.value(), SerializedKind_t(serializedKind),
36573669
Name.str(), getSILType(Ty, SILValueCategory::Object, nullptr),
3658-
std::nullopt, dID ? cast<VarDecl>(MF->getDecl(dID)) : nullptr);
3670+
std::nullopt, globalDecl);
36593671
v->setLet(IsLet);
36603672
globalVarOrOffset.set(v, true /*isFullyDeserialized*/);
36613673
v->setDeclaration(IsDeclaration);

test/SILOptimizer/Inputs/cross-module/cross-module.swift

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -287,6 +287,12 @@ public func callCImplementationOnly<T>(_ t: T) -> Int {
287287

288288
public let globalLet = 529387
289289

290+
private var privateVar = Int.random(in: 0..<100)
291+
292+
public func getRandom() -> Int {
293+
return privateVar
294+
}
295+
290296
public struct StructWithClosure {
291297
public static let c = { (x: Int) -> Int in return x }
292298
}

test/SILOptimizer/cross-module-optimization.swift

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,12 @@ func testImplementationOnly() {
165165
// CHECK-SIL2: } // end sil function '$s4Main22testImplementationOnlyyyF'
166166
}
167167

168+
@inline(never)
169+
func testPrivateVar() {
170+
// CHECK-OUTPUT: {{[0-9]+}}
171+
print(getRandom())
172+
}
173+
168174
testNestedTypes()
169175
testClass()
170176
testError()
@@ -175,4 +181,5 @@ testKeypath()
175181
testMisc()
176182
testGlobal()
177183
testImplementationOnly()
184+
testPrivateVar()
178185

0 commit comments

Comments
 (0)