File: LifetimeDependenceDiagnostics.swift

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (382 lines) | stat: -rw-r--r-- 13,250 bytes parent folder | download
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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
//===--- LifetimeDependenceDiagnostics.swift - Lifetime dependence --------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

import SIL

private let verbose = false

private func log(prefix: Bool = true, _ message: @autoclosure () -> String) {
  if verbose {
    print((prefix ? "### " : "") + message())
  }
}

/// Diagnostic pass.
///
/// Find the roots of all non-escapable values in this function. All
/// non-escapable values either depend on a NonEscapingScope, or they
/// are produced by a LifetimeDependentInstruction that has no
/// dependence on a parent value (@_unsafeNonEscapableResult).
let lifetimeDependenceDiagnosticsPass = FunctionPass(
  name: "lifetime-dependence-diagnostics")
{ (function: Function, context: FunctionPassContext) in
  if !context.options.hasFeature(.NonescapableTypes) {
    return
  }
  log(prefix: false, "\n--- Diagnosing lifetime dependence in \(function.name)")
  log("\(function)")

  for argument in function.arguments
      where !argument.type.isEscapable(in: function)
  {
    // Indirect results are not checked here. Type checking ensures
    // that they have a lifetime dependence.
    if let lifetimeDep = LifetimeDependence(argument, context) {
      analyze(dependence: lifetimeDep, context)
    }
  }
  for instruction in function.instructions {
    if let markDep = instruction as? MarkDependenceInst, markDep.isUnresolved {
      if let lifetimeDep = LifetimeDependence(markDep, context) {
        analyze(dependence: lifetimeDep, context)
      }
      continue
    }
    if let apply = instruction as? FullApplySite {
      // Handle ~Escapable results that do not have a lifetime
      // dependence (@_unsafeNonescapableResult).
      apply.resultOrYields.forEach {
        if let lifetimeDep = LifetimeDependence(unsafeApplyResult: $0,
                                                context) {
          analyze(dependence: lifetimeDep, context)
        }
      }
      continue
    }
  }
}

/// Analyze a single Lifetime dependence and trigger diagnostics.
///
/// 1. Compute the LifetimeDependence scope.
///
/// 2. Walk down all dependent values checking that they are within range.
private func analyze(dependence: LifetimeDependence,
  _ context: FunctionPassContext) {
  log("Dependence scope:\n\(dependence)")
    
  // Compute this dependence scope.
  var range = dependence.computeRange(context)
  defer { range?.deinitialize() }

  var error = false
  let diagnostics =
    DiagnoseDependence(dependence: dependence, range: range,
                       onError: { error = true }, context: context)

  // Check each lifetime-dependent use via a def-use visitor
  var walker = DiagnoseDependenceWalker(diagnostics, context)
  defer { walker.deinitialize() }
  _ = walker.walkDown(root: dependence.dependentValue)

  if !error {
    dependence.resolve(context)
  }
}

/// Analyze and diagnose a single LifetimeDependence.
private struct DiagnoseDependence {
  let dependence: LifetimeDependence
  let range: InstructionRange?
  let onError: ()->()
  let context: FunctionPassContext

  var function: Function { dependence.function }

  func diagnose(_ position: SourceLoc?, _ id: DiagID,
                _ args: DiagnosticArgument...) {
    context.diagnosticEngine.diagnose(position, id, args)
  }

  /// Check that this use is inside the dependence scope.
  func checkInScope(operand: Operand) -> WalkResult {
    if let range, !range.inclusiveRangeContains(operand.instruction) {
      log("  out-of-range: \(operand.instruction)")
      reportError(operand: operand, diagID: .lifetime_outside_scope_use)
      return .abortWalk
    }
    log("  contains: \(operand.instruction)")
    return .continueWalk
  }

  func reportEscaping(operand: Operand) {
    log("  escaping: \(operand.instruction)")
    reportError(operand: operand, diagID: .lifetime_outside_scope_escape)
  }

  func reportUnknown(operand: Operand) {
    standardError.write("Unknown use: \(operand)\n\(function)")
    reportEscaping(operand: operand)
  }

  func checkFunctionResult(operand: Operand) -> WalkResult {

    if function.hasUnsafeNonEscapableResult {
      return .continueWalk
    }
    // FIXME: remove this condition once we have a Builtin.dependence,
    // which developers should use to model the unsafe
    // dependence. Builtin.lifetime_dependence will be lowered to
    // mark_dependence [unresolved], which will be checked
    // independently. Instead, of this function result check, allow
    // isUnsafeApplyResult to be used be mark_dependence [unresolved]
    // without checking its dependents.
    //
    // Allow returning an apply result (@_unsafeNonescapableResult) if
    // the calling function has a dependence. This implicitly makes
    // the unsafe nonescapable result dependent on the calling
    // function's lifetime dependence arguments.
    if dependence.isUnsafeApplyResult, function.hasResultDependence {
      return .continueWalk
    }
    // Check that the argument dependence for this result is the same
    // as the current dependence scope.
    if let arg = dependence.scope.parentValue as? FunctionArgument,
       function.argumentConventions[resultDependsOn: arg.index] != nil {
      // The returned value depends on a lifetime that is inherited or
      // borrowed in the caller. The lifetime of the argument value
      // itself is irrelevant here.
      return .continueWalk
    }
    reportEscaping(operand: operand)
    return .abortWalk
  }

  func reportError(operand: Operand, diagID: DiagID) {
    onError()

    // Identify the escaping variable.
    let escapingVar = LifetimeVariable(dependent: operand.value, context)
    let varName = escapingVar.name
    if let varName {
      diagnose(escapingVar.sourceLoc, .lifetime_variable_outside_scope,
               varName)
    } else {
      diagnose(escapingVar.sourceLoc, .lifetime_value_outside_scope)
    }
    reportScope()
    // Identify the use point.
    let userSourceLoc = operand.instruction.location.sourceLoc
    diagnose(userSourceLoc, diagID)
  }

  // Identify the dependence scope.
  func reportScope() {
    if case let .access(beginAccess) = dependence.scope {
      let parentVar = LifetimeVariable(dependent: beginAccess, context)
      if let sourceLoc = beginAccess.location.sourceLoc ?? parentVar.sourceLoc {
        diagnose(sourceLoc, .lifetime_outside_scope_access,
                 parentVar.name ?? "")
      }
      return
    }
    if let arg = dependence.parentValue as? Argument,
       let varDecl = arg.varDecl,
       let sourceLoc = arg.sourceLoc {
      diagnose(sourceLoc, .lifetime_outside_scope_argument,
               varDecl.userFacingName)
      return
    }
    let parentVar = LifetimeVariable(dependent: dependence.parentValue, context)
    if let parentLoc = parentVar.sourceLoc {
      if let parentName = parentVar.name {
        diagnose(parentLoc, .lifetime_outside_scope_variable, parentName)
      } else {
        diagnose(parentLoc, .lifetime_outside_scope_value)
      }
    }
  }
}

private extension Instruction {
  func findVarDecl() -> VarDecl? {
    if let varDeclInst = self as? VarDeclInstruction {
      return varDeclInst.varDecl
    }
    for result in results {
      for use in result.uses {
        if let debugVal = use.instruction as? DebugValueInst {
          return debugVal.varDecl
        }
      }
    }
    return nil
  }
}

// Identify a best-effort variable declaration based on a defining SIL
// value or any lifetime dependent use of that SIL value.
private struct LifetimeVariable {
  var varDecl: VarDecl?
  var sourceLoc: SourceLoc?
  
  var name: String? {
    return varDecl?.userFacingName
  }

  init(dependent value: Value, _ context: some Context) {
    if value.type.isAddress {
      self = Self(accessBase: value.accessBase, context)
      return
    }
    if let firstIntroducer = getFirstVariableIntroducer(of: value, context) {
      self = Self(introducer: firstIntroducer)
      return
    }
    self.varDecl = nil
    self.sourceLoc = nil
  }

  private func getFirstVariableIntroducer(of value: Value, _ context: some Context) -> Value? {
    var introducer: Value?
    var useDefVisitor = VariableIntroducerUseDefWalker(context) {
      introducer = $0
      return .abortWalk
    }
    defer { useDefVisitor.deinitialize() }
    _ = useDefVisitor.walkUp(valueOrAddress: value)
    return introducer
  }

  private init(introducer: Value) {
    if let arg = introducer as? Argument {
      self.varDecl = arg.varDecl
    } else {
      self.sourceLoc = introducer.definingInstruction?.location.sourceLoc
      self.varDecl = introducer.definingInstruction?.findVarDecl()
    }
    if let varDecl {
      sourceLoc = varDecl.sourceLoc
    }
  }

  // Record the source location of the variable decl if possible. The
  // caller will already have a source location for the formal access,
  // which is more relevant for diagnostics.
  private init(accessBase: AccessBase, _ context: some Context) {
    switch accessBase {
    case .box(let projectBox):
      // Note: referenceRoot looks through `begin_borrow [var_decl]` and `move_value [var_decl]`. But the box should
      // never be produced by one of these, except when it is redundant with the `alloc_box` VarDecl. It does not seem
      // possible for a box to be moved/borrowed directly into another variable's box. Reassignment always loads/stores
      // the value.
      self = Self(introducer: projectBox.box.referenceRoot)
    case .stack(let allocStack):
      self = Self(introducer: allocStack)
    case .global(let globalVar):
      self.varDecl = globalVar.varDecl
      self.sourceLoc = nil
    case .class(let refAddr):
      self.varDecl = refAddr.varDecl
      self.sourceLoc = refAddr.location.sourceLoc
    case .tail(let refTail):
      self = Self(introducer: refTail.instance)
    case .argument(let arg):
      self.varDecl = arg.varDecl
      self.sourceLoc = arg.sourceLoc
    case .yield(let result):
      // TODO: bridge VarDecl for FunctionConvention.Yields
      self.varDecl = nil
      self.sourceLoc = result.parentInstruction.location.sourceLoc
    case .storeBorrow(let sb):
      self = .init(dependent: sb.source, context)
    case .pointer(let ptrToAddr):
      self.varDecl = nil
      self.sourceLoc = ptrToAddr.location.sourceLoc
    case .unidentified:
      self.varDecl = nil
      self.sourceLoc = nil
    }
  }
}

/// Walk down lifetime depenence uses. For each check that all dependent
/// leaf uses are non-escaping and within the dependence scope. The walk
/// starts with add address for .access dependencies. The walk can
/// transition from an address to a value at a load. The walk can
/// transition from a value to an address as follows:
///
///     %dependent_addr = mark_dependence [nonescaping] %base_addr on %value
///
/// TODO: handle stores to singly initialized temporaries like copies using a standard reaching-def analysis.
private struct DiagnoseDependenceWalker {
  let context: Context
  var diagnostics: DiagnoseDependence
  let localReachabilityCache = LocalVariableReachabilityCache()
  var visitedValues: ValueSet

  var function: Function { diagnostics.function }
  
  init(_ diagnostics: DiagnoseDependence, _ context: Context) {
    self.context = context
    self.diagnostics = diagnostics
    self.visitedValues = ValueSet(context)
  }
  
  mutating func deinitialize() {
    visitedValues.deinitialize()
  }
}

extension DiagnoseDependenceWalker : LifetimeDependenceDefUseWalker {
  mutating func needWalk(for value: Value) -> Bool {
    visitedValues.insert(value)
  }

  mutating func leafUse(of operand: Operand) -> WalkResult {
    return diagnostics.checkInScope(operand: operand)
  }

  mutating func deadValue(_ value: Value, using operand: Operand?)
    -> WalkResult {
    // Ignore a dead root value. It never escapes.
    if let operand {
      return diagnostics.checkInScope(operand: operand)
    }
    return .continueWalk
  }

  mutating func escapingDependence(on operand: Operand) -> WalkResult {
    diagnostics.reportEscaping(operand: operand)
    return .abortWalk
  }

  mutating func returnedDependence(result: Operand) -> WalkResult {
    return diagnostics.checkFunctionResult(operand: result)
  }

  mutating func returnedDependence(address: FunctionArgument,
                                   using operand: Operand) -> WalkResult {
    return diagnostics.checkFunctionResult(operand: operand)
  }

  mutating func yieldedDependence(result: Operand) -> WalkResult {
    return diagnostics.checkFunctionResult(operand: result)
  }

  // Override AddressUseVisitor here because LifetimeDependenceDefUseWalker
  // returns .abortWalk, and we want a more useful crash report.
  mutating func unknownAddressUse(of operand: Operand) -> WalkResult {
    diagnostics.reportUnknown(operand: operand)
    return .continueWalk
  }
}