File: SimplifyBeginBorrow.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 (227 lines) | stat: -rw-r--r-- 8,829 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
//===--- SimplifyBeginBorrow.swift ----------------------------------------===//
//
// 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

extension BeginBorrowInst : OnoneSimplifyable {
  func simplify(_ context: SimplifyContext) {
    if borrowedValue.ownership == .owned,
       // We need to keep lexical lifetimes in place.
       !isLexical,
       // The same for borrow-scopes which encapsulated pointer escapes.
       !findPointerEscapingUse(of: borrowedValue)
    {
      tryReplaceBorrowWithOwnedOperand(beginBorrow: self, context)
    }
  }
}

private func tryReplaceBorrowWithOwnedOperand(beginBorrow: BeginBorrowInst, _ context: SimplifyContext) {
  // The last value of a (potentially empty) forwarding chain, beginning at the `begin_borrow`.
  let forwardedValue = beginBorrow.lookThroughSingleForwardingUses()
  if forwardedValue.allUsesCanBeConvertedToOwned {
    if tryReplaceCopy(of: forwardedValue, withCopiedOperandOf: beginBorrow, context) {
      return
    }
    if beginBorrow.borrowedValue.isDestroyed(after: beginBorrow) {
      convertAllUsesToOwned(of: beginBorrow, context)
    }
  }
}

/// Replace
/// ```
///   %1 = begin_borrow %0
///   %2 = struct_extract %1     // a chain of forwarding instructions
///   %3 = copy_value %1
///   // ... uses of %3
///   end_borrow %1
/// ```
/// with
/// ```
///   %1 = copy_value %0
///   %3 = destructure_struct %0 // owned version of the forwarding instructions
///   // ... uses of %3
/// ```
private func tryReplaceCopy(
  of forwardedValue: Value,
  withCopiedOperandOf beginBorrow: BeginBorrowInst,
  _ context: SimplifyContext
) -> Bool {
  guard let singleUser = forwardedValue.uses.ignoreUsers(ofType: EndBorrowInst.self).singleUse?.instruction,
        let copy = singleUser as? CopyValueInst,
        copy.parentBlock == beginBorrow.parentBlock else {
    return false
  }
  let builder = Builder(before: beginBorrow, context)
  let copiedOperand = builder.createCopyValue(operand: beginBorrow.borrowedValue)
  let forwardedOwnedValue = replace(guaranteedValue: beginBorrow, withOwnedValue: copiedOperand, context)
  copy.uses.replaceAll(with: forwardedOwnedValue, context)
  context.erase(instruction: copy)
  context.erase(instructionIncludingAllUsers: beginBorrow)
  return true
}

/// Replace
/// ```
///   %1 = begin_borrow %0
///   %2 = struct_extract %1     // a chain of forwarding instructions
///   // ... uses of %2
///   end_borrow %1
///   destroy_value %1           // the only other use of %0 beside begin_borrow
/// ```
/// with
/// ```
///   %2 = destructure_struct %0 // owned version of the forwarding instructions
///   // ... uses of %2
///   destroy_value %2
/// ```
private func convertAllUsesToOwned(of beginBorrow: BeginBorrowInst, _ context: SimplifyContext) {
  let forwardedOwnedValue = replace(guaranteedValue: beginBorrow, withOwnedValue: beginBorrow.borrowedValue, context)
  beginBorrow.borrowedValue.replaceAllDestroys(with: forwardedOwnedValue, context)
  context.erase(instructionIncludingAllUsers: beginBorrow)
}

private extension Value {
  /// Returns the last value of a (potentially empty) forwarding chain.
  /// For example, returns %3 for the following def-use chain:
  /// ```
  ///   %1 = struct_extract %self, #someField
  ///   %2 = tuple_extract %1, 0
  ///   %3 = struct $S(%2)   // %3 has no forwarding users
  /// ```
  /// Returns self if this value has no uses which are ForwardingInstructions.
  func lookThroughSingleForwardingUses() -> Value {
    if let singleUse = uses.ignoreUsers(ofType: EndBorrowInst.self).singleUse,
       let fwdInst = singleUse.instruction as? (SingleValueInstruction & ForwardingInstruction),
       fwdInst.canConvertToOwned,
       fwdInst.isSingleForwardedOperand(singleUse),
       fwdInst.parentBlock == parentBlock
    {
      return fwdInst.lookThroughSingleForwardingUses()
    }
    return self
  }

  var allUsesCanBeConvertedToOwned: Bool {
    let relevantUses = uses.ignoreUsers(ofType: EndBorrowInst.self)
    return relevantUses.allSatisfy { $0.canAccept(ownership: .owned) }
  }

  func isDestroyed(after nonDestroyUser: Instruction) -> Bool {
    return uses.getSingleUser(notOfType: DestroyValueInst.self) == nonDestroyUser &&
           nonDestroyUser.dominates(destroysOf: self)
  }

  func replaceAllDestroys(with replacement: Value, _ context: SimplifyContext) {
    uses.filterUsers(ofType: DestroyValueInst.self).replaceAll(with: replacement, context)
  }
}

private extension Instruction {
  func dominates(destroysOf value: Value) -> Bool {
    // In instruction simplification we don't have a domtree. Therefore do a simple dominance
    // check based on same-block relations.
    if parentBlock == value.parentBlock {
      // The value and instruction are in the same block. All uses are dominanted by both.
      return true
    }
    let destroys = value.uses.filterUsers(ofType: DestroyValueInst.self)
    return destroys.allSatisfy({ $0.instruction.parentBlock == parentBlock})
  }
}

private extension ForwardingInstruction {
  func isSingleForwardedOperand(_ operand: Operand) -> Bool {
    switch self {
    case is StructInst, is TupleInst:
      // TODO: we could move that logic to StructInst/TupleInst.singleForwardedOperand.
      return operands.lazy.map({ $0.value.type }).hasSingleNonTrivialElement(at: operand.index, in: parentFunction)
    default:
      if let sfo = singleForwardedOperand {
        return sfo == operand
      }
      return false
    }
  }
}

/// Replaces a guaranteed value with an owned value.
/// 
/// If the `guaranteedValue`'s use is a ForwardingInstruction (or forwarding instruction chain),
/// it is converted to an owned version of the forwarding instruction (or instruction chain).
///
/// Returns the last owned value in a forwarding-chain or `ownedValue` if `guaranteedValue` has
/// no forwarding uses.
private func replace(guaranteedValue: Value, withOwnedValue ownedValue: Value, _ context: SimplifyContext) -> Value {
  var result = ownedValue
  var numForwardingUses = 0
  for use in guaranteedValue.uses {

    switch use.instruction {
    case let tei as TupleExtractInst:
      numForwardingUses += 1
      let dti = Builder(before: tei, context).createDestructureTuple(tuple: ownedValue)
      result = replace(guaranteedValue: tei, withOwnedValue: dti.results[tei.fieldIndex], context)
      context.erase(instruction: tei)
    case let sei as StructExtractInst:
      numForwardingUses += 1
      let dsi = Builder(before: sei, context).createDestructureStruct(struct: ownedValue)
      result = replace(guaranteedValue: sei, withOwnedValue: dsi.results[sei.fieldIndex], context)
      context.erase(instruction: sei)
    case let fwdInst as (SingleValueInstruction & ForwardingInstruction) where
         fwdInst.isSingleForwardedOperand(use):
      // Other forwarding instructions beside tuple_extract and struct_extract
      numForwardingUses += 1
      use.set(to: ownedValue, context)
      fwdInst.setForwardingOwnership(to: .owned, context)
      result = replace(guaranteedValue: fwdInst, withOwnedValue: fwdInst, context)
    case is EndBorrowInst:
      break
    default:
      precondition(use.canAccept(ownership: .owned))
      use.set(to: ownedValue, context)
    }
  }
  precondition(numForwardingUses <= 1, "guaranteed value must not have multiple forwarding uses")
  return result
}

private extension ForwardingInstruction {
  var canConvertToOwned: Bool {
    switch self {
    case let si as StructExtractInst:
      if si.struct.type.isMoveOnly {
        // We cannot easily convert a struct_extract to a destructure_struct of a move-only type, because
        // the deinit would get lost.
        return false
      }
      let structFields = si.struct.type.getNominalFields(in: parentFunction)
      return structFields?.hasSingleNonTrivialElement(at: si.fieldIndex, in: parentFunction) ?? false
    case let ti as TupleExtractInst:
      return ti.tuple.type.tupleElements.hasSingleNonTrivialElement(at: ti.fieldIndex, in: parentFunction)
    default:
      return canForwardOwnedValues
    }
  }
}

private extension Collection where Element == Type {
  func hasSingleNonTrivialElement(at nonTrivialElementIndex: Int, in function: Function) -> Bool {
    for (elementIdx, elementTy) in self.enumerated() {
      if elementTy.isTrivial(in: function) != (elementIdx != nonTrivialElementIndex) {
        return false
      }
    }
    return true
  }
}