Skip to content

Commit 27a8852

Browse files
committed
MoveOnlyAddressChecker: More robust checking for consume-during-borrow.
- While an opaque borrow access occurs to part of a value, the entire scope of the access needs to be treated as a liveness range, so add the `EndAccess`es to the liveness range. - The SIL verifier may crash the compiler on SILGen-generated code when the developer's source contains consume-during-borrow code patterns. Allow `load_borrow` instructions to be marked `[unchecked]`, which suppresses verifier checks until the move checker runs and gets a chance to properly diagnose these errors. Fixes rdar://124360175.
1 parent b7b93a1 commit 27a8852

File tree

13 files changed

+153
-28
lines changed

13 files changed

+153
-28
lines changed

include/swift/SIL/SILInstruction.h

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4591,14 +4591,29 @@ class StoreInst
45914591
/// instruction in its use-def list.
45924592
class LoadBorrowInst :
45934593
public UnaryInstructionBase<SILInstructionKind::LoadBorrowInst,
4594-
SingleValueInstruction> {
4594+
SingleValueInstruction>
4595+
{
45954596
friend class SILBuilder;
45964597

4598+
bool Unchecked = false;
4599+
45974600
public:
45984601
LoadBorrowInst(SILDebugLocation DebugLoc, SILValue LValue)
45994602
: UnaryInstructionBase(DebugLoc, LValue,
46004603
LValue->getType().getObjectType()) {}
46014604

4605+
// True if the invariants on `load_borrow` have not been checked and
4606+
// should not be strictly enforced.
4607+
//
4608+
// This can only occur during raw SIL before move-only checking occurs.
4609+
// Developers can write incorrect code using noncopyable types that
4610+
// consumes or mutates a memory location while that location is borrowed,
4611+
// but the move-only checker must diagnose those problems before canonical
4612+
// SIL is formed.
4613+
bool isUnchecked() const { return Unchecked; }
4614+
4615+
void setUnchecked(bool value) { Unchecked = value; }
4616+
46024617
using EndBorrowRange =
46034618
decltype(std::declval<ValueBase>().getUsersOfType<EndBorrowInst>());
46044619

lib/SIL/IR/SILPrinter.cpp

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1733,6 +1733,9 @@ class SILPrinter : public SILInstructionVisitor<SILPrinter> {
17331733
}
17341734

17351735
void visitLoadBorrowInst(LoadBorrowInst *LBI) {
1736+
if (LBI->isUnchecked()) {
1737+
*this << "[unchecked] ";
1738+
}
17361739
*this << getIDAndType(LBI->getOperand());
17371740
}
17381741

lib/SIL/Parser/ParseSIL.cpp

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3733,12 +3733,28 @@ bool SILParser::parseSpecificSILInstruction(SILBuilder &B,
37333733

37343734
case SILInstructionKind::LoadBorrowInst: {
37353735
SourceLoc AddrLoc;
3736+
3737+
bool IsUnchecked = false;
3738+
StringRef AttrName;
3739+
SourceLoc AttrLoc;
3740+
if (parseSILOptional(AttrName, AttrLoc, *this)) {
3741+
if (AttrName == "unchecked") {
3742+
IsUnchecked = true;
3743+
} else {
3744+
P.diagnose(InstLoc.getSourceLoc(),
3745+
diag::sil_invalid_attribute_for_instruction, AttrName,
3746+
"load_borrow");
3747+
return true;
3748+
}
3749+
}
37363750

37373751
if (parseTypedValueRef(Val, AddrLoc, B) ||
37383752
parseSILDebugLocation(InstLoc, B))
37393753
return true;
37403754

3741-
ResultVal = B.createLoadBorrow(InstLoc, Val);
3755+
auto LB = B.createLoadBorrow(InstLoc, Val);
3756+
LB->setUnchecked(IsUnchecked);
3757+
ResultVal = LB;
37423758
break;
37433759
}
37443760

lib/SIL/Verifier/MemoryLifetimeVerifier.cpp

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -788,7 +788,9 @@ void MemoryLifetimeVerifier::checkBlock(SILBasicBlock *block, Bits &bits) {
788788
requireBitsSet(bits, sbi->getDest(), &I);
789789
locations.clearBits(bits, sbi->getDest());
790790
} else if (auto *lbi = dyn_cast<LoadBorrowInst>(ebi->getOperand())) {
791-
requireBitsSet(bits, lbi->getOperand(), &I);
791+
if (!lbi->isUnchecked()) {
792+
requireBitsSet(bits, lbi->getOperand(), &I);
793+
}
792794
}
793795
break;
794796
}

lib/SIL/Verifier/SILVerifier.cpp

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2623,8 +2623,13 @@ class SILVerifier : public SILVerifierBase<SILVerifier> {
26232623
requireSameType(LBI->getOperand()->getType().getObjectType(),
26242624
LBI->getType(),
26252625
"Load operand type and result type mismatch");
2626-
require(loadBorrowImmutabilityAnalysis.isImmutable(LBI),
2627-
"Found load borrow that is invalidated by a local write?!");
2626+
if (LBI->isUnchecked()) {
2627+
require(LBI->getModule().getStage() == SILStage::Raw,
2628+
"load_borrow can only be [unchecked] in raw SIL");
2629+
} else {
2630+
require(loadBorrowImmutabilityAnalysis.isImmutable(LBI),
2631+
"Found load borrow that is invalidated by a local write?!");
2632+
}
26282633
}
26292634

26302635
void checkBeginBorrowInst(BeginBorrowInst *bbi) {

lib/SILGen/SILGenLValue.cpp

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1231,6 +1231,11 @@ namespace {
12311231
return base;
12321232
}
12331233
auto result = SGF.B.createLoadBorrow(loc, base.getValue());
1234+
// Mark the load_borrow as unchecked. We can't stop the source code from
1235+
// trying to mutate or consume the same lvalue during this borrow, so
1236+
// we don't want verifiers to trip before the move checker gets a chance
1237+
// to diagnose these situations.
1238+
result->setUnchecked(true);
12341239
return SGF.emitFormalEvaluationManagedBorrowedRValueWithCleanup(loc,
12351240
base.getValue(), result);
12361241
}

lib/SILOptimizer/Mandatory/MoveOnlyAddressCheckerUtils.cpp

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1258,23 +1258,29 @@ void UseState::initializeLiveness(
12581258
<< *livenessInstAndValue.first;
12591259
liveness.print(llvm::dbgs()));
12601260
}
1261+
1262+
auto updateForLivenessAccess = [&](BeginAccessInst *beginAccess,
1263+
const SmallBitVector &livenessMask) {
1264+
for (auto *endAccess : beginAccess->getEndAccesses()) {
1265+
liveness.updateForUse(endAccess, livenessMask, false /*lifetime ending*/);
1266+
}
1267+
};
12611268

12621269
for (auto livenessInstAndValue : nonconsumingUses) {
12631270
if (auto *lbi = dyn_cast<LoadBorrowInst>(livenessInstAndValue.first)) {
12641271
auto accessPathWithBase =
12651272
AccessPathWithBase::computeInScope(lbi->getOperand());
12661273
if (auto *beginAccess =
12671274
dyn_cast_or_null<BeginAccessInst>(accessPathWithBase.base)) {
1268-
for (auto *endAccess : beginAccess->getEndAccesses()) {
1269-
liveness.updateForUse(endAccess, livenessInstAndValue.second,
1270-
false /*lifetime ending*/);
1271-
}
1275+
updateForLivenessAccess(beginAccess, livenessInstAndValue.second);
12721276
} else {
12731277
for (auto *ebi : lbi->getEndBorrows()) {
12741278
liveness.updateForUse(ebi, livenessInstAndValue.second,
12751279
false /*lifetime ending*/);
12761280
}
12771281
}
1282+
} else if (auto *bai = dyn_cast<BeginAccessInst>(livenessInstAndValue.first)) {
1283+
updateForLivenessAccess(bai, livenessInstAndValue.second);
12781284
} else {
12791285
liveness.updateForUse(livenessInstAndValue.first,
12801286
livenessInstAndValue.second,

lib/SILOptimizer/Mandatory/MoveOnlyChecker.cpp

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -214,6 +214,22 @@ void MoveOnlyChecker::checkAddresses() {
214214

215215
namespace {
216216

217+
static bool canonicalizeLoadBorrows(SILFunction *F) {
218+
bool changed = false;
219+
for (auto &block : *F) {
220+
for (auto &inst : block) {
221+
if (auto *lbi = dyn_cast<LoadBorrowInst>(&inst)) {
222+
if (lbi->isUnchecked()) {
223+
changed = true;
224+
lbi->setUnchecked(false);
225+
}
226+
}
227+
}
228+
}
229+
230+
return changed;
231+
}
232+
217233
class MoveOnlyCheckerPass : public SILFunctionTransform {
218234
void run() override {
219235
auto *fn = getFunction();
@@ -228,8 +244,11 @@ class MoveOnlyCheckerPass : public SILFunctionTransform {
228244
// If an earlier pass told use to not emit diagnostics for this function,
229245
// clean up any copies, invalidate the analysis, and return early.
230246
if (fn->hasSemanticsAttr(semantics::NO_MOVEONLY_DIAGNOSTICS)) {
231-
if (cleanupNonCopyableCopiesAfterEmittingDiagnostic(getFunction()))
247+
bool didChange = canonicalizeLoadBorrows(fn);
248+
didChange |= cleanupNonCopyableCopiesAfterEmittingDiagnostic(getFunction());
249+
if (didChange) {
232250
invalidateAnalysis(SILAnalysis::InvalidationKind::Instructions);
251+
}
233252
return;
234253
}
235254

@@ -252,6 +271,11 @@ class MoveOnlyCheckerPass : public SILFunctionTransform {
252271
checker.diagnosticEmitter);
253272
}
254273

274+
// Remaining borrows
275+
// should be correctly immutable. We can canonicalize any remaining
276+
// `load_borrow [unchecked]` instructions.
277+
checker.madeChange |= canonicalizeLoadBorrows(fn);
278+
255279
checker.madeChange |=
256280
cleanupNonCopyableCopiesAfterEmittingDiagnostic(fn);
257281

lib/Serialization/DeserializeSIL.cpp

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2260,7 +2260,6 @@ bool SILDeserializer::readSILInstruction(SILFunction *Fn,
22602260
UNARY_INSTRUCTION(EndLifetime)
22612261
UNARY_INSTRUCTION(ExtendLifetime)
22622262
UNARY_INSTRUCTION(CopyBlock)
2263-
UNARY_INSTRUCTION(LoadBorrow)
22642263
UNARY_INSTRUCTION(EndInitLetRef)
22652264
REFCOUNTING_INSTRUCTION(StrongRetain)
22662265
REFCOUNTING_INSTRUCTION(StrongRelease)
@@ -2271,6 +2270,17 @@ bool SILDeserializer::readSILInstruction(SILFunction *Fn,
22712270
#undef UNARY_INSTRUCTION
22722271
#undef REFCOUNTING_INSTRUCTION
22732272

2273+
case SILInstructionKind::LoadBorrowInst: {
2274+
assert(RecordKind == SIL_ONE_OPERAND && "Layout should be OneOperand.");
2275+
auto LB = Builder.createLoadBorrow(
2276+
Loc, getLocalValue(Builder.maybeGetFunction(), ValID,
2277+
getSILType(MF->getType(TyID),
2278+
(SILValueCategory)TyCategory, Fn)));
2279+
LB->setUnchecked(Attr != 0);
2280+
ResultInst = LB;
2281+
break;
2282+
}
2283+
22742284
case SILInstructionKind::BeginBorrowInst: {
22752285
assert(RecordKind == SIL_ONE_OPERAND && "Layout should be OneOperand.");
22762286
auto isLexical = IsLexical_t(Attr & 0x1);

lib/Serialization/SerializeSIL.cpp

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1601,6 +1601,8 @@ void SILSerializer::writeSILInstruction(const SILInstruction &SI) {
16011601
} else if (auto *I = dyn_cast<CopyableToMoveOnlyWrapperValueInst>(&SI)) {
16021602
Attr = I->getForwardingOwnershipKind() == OwnershipKind::Owned ? true
16031603
: false;
1604+
} else if (auto *LB = dyn_cast<LoadBorrowInst>(&SI)) {
1605+
Attr = LB->isUnchecked();
16041606
}
16051607
writeOneOperandLayout(SI.getKind(), Attr, SI.getOperand(0));
16061608
break;

0 commit comments

Comments
 (0)