File: SimplifyBuiltin.swift

package info (click to toggle)
swiftlang 6.1.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,791,532 kB
  • sloc: cpp: 9,901,743; ansic: 2,201,431; asm: 1,091,827; python: 308,252; objc: 82,166; f90: 80,126; lisp: 38,358; pascal: 25,559; sh: 20,429; ml: 5,058; perl: 4,745; makefile: 4,484; awk: 3,535; javascript: 3,018; xml: 918; fortran: 664; cs: 573; ruby: 396
file content (318 lines) | stat: -rw-r--r-- 10,313 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
//===--- SimplifyBuiltin.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 BuiltinInst : OnoneSimplifyable {
  func simplify(_ context: SimplifyContext) {
    switch id {
      case .IsConcrete:
        // Don't constant fold a Builtin.isConcrete of a type with archetypes in the middle
        // of the pipeline, because a generic specializer might run afterwards which turns the
        // type into a concrete type.
        optimizeIsConcrete(allowArchetypes: false, context)
      case .IsSameMetatype:
        optimizeIsSameMetatype(context)
      case .Once:
        optimizeBuiltinOnce(context)
      case .CanBeObjCClass:
        optimizeCanBeClass(context)
      case .AssertConf:
        optimizeAssertConfig(context)
      case .Sizeof,
           .Strideof,
           .Alignof:
        optimizeTargetTypeConst(context)
      case .DestroyArray:
        if let elementType = substitutionMap.replacementTypes[0],
           elementType.isTrivial(in: parentFunction)
        {
          context.erase(instruction: self)
          return
        }
        optimizeArgumentToThinMetatype(argument: 0, context)
      case .CopyArray,
           .TakeArrayNoAlias,
           .TakeArrayFrontToBack,
           .TakeArrayBackToFront,
           .AssignCopyArrayNoAlias,
           .AssignCopyArrayFrontToBack,
           .AssignCopyArrayBackToFront,
           .AssignTakeArray,
           .AllocVector,
           .IsPOD:
        optimizeArgumentToThinMetatype(argument: 0, context)
      case .ICMP_EQ:
        constantFoldIntegerEquality(isEqual: true, context)
      case .ICMP_NE:
        constantFoldIntegerEquality(isEqual: false, context)
      default:
        if let literal = constantFold(context) {
          uses.replaceAll(with: literal, context)
        }
    }
  }
}

extension BuiltinInst : LateOnoneSimplifyable {
  func simplifyLate(_ context: SimplifyContext) {
    if id == .IsConcrete {
      // At the end of the pipeline we can be sure that the isConcrete's type doesn't get "more" concrete.
      optimizeIsConcrete(allowArchetypes: true, context)
    } else {
      simplify(context)
    }
  }
}

private extension BuiltinInst {
  func optimizeIsConcrete(allowArchetypes: Bool, _ context: SimplifyContext) {
    let hasArchetype = operands[0].value.type.hasArchetype
    if hasArchetype && !allowArchetypes {
      return
    }
    let builder = Builder(before: self, context)
    let result = builder.createIntegerLiteral(hasArchetype ? 0 : 1, type: type)
    uses.replaceAll(with: result, context)
    context.erase(instruction: self)
  }

  func optimizeIsSameMetatype(_ context: SimplifyContext) {
    let lhs = operands[0].value
    let rhs = operands[1].value

    guard let equal = typesOfValuesAreEqual(lhs, rhs, in: parentFunction) else {
      return
    }
    let builder = Builder(before: self, context)
    let result = builder.createIntegerLiteral(equal ? 1 : 0, type: type)

    uses.replaceAll(with: result, context)
  }

  func optimizeBuiltinOnce(_ context: SimplifyContext) {
    guard let callee = calleeOfOnce, callee.isDefinition else {
      return
    }
    context.notifyDependency(onBodyOf: callee)

    // If the callee is side effect-free we can remove the whole builtin "once".
    // We don't use the callee's memory effects but instead look at all callee instructions
    // because memory effects are not computed in the Onone pipeline, yet.
    // This is no problem because the callee (usually a global init function )is mostly very small,
    // or contains the side-effect instruction `alloc_global` right at the beginning.
    if callee.instructions.contains(where: hasSideEffectForBuiltinOnce) {
      return
    }
    for use in uses {
      let ga = use.instruction as! GlobalAddrInst
      ga.clearToken(context)
    }
    context.erase(instruction: self)
  }

  var calleeOfOnce: Function? {
    let callee = operands[1].value
    if let fri = callee as? FunctionRefInst {
      return fri.referencedFunction
    }
    return nil
  }

  func optimizeCanBeClass(_ context: SimplifyContext) {
    guard let ty = substitutionMap.replacementTypes[0] else {
      return
    }
    let literal: IntegerLiteralInst
    switch ty.canBeClass {
    case .IsNot:
      let builder = Builder(before: self, context)
      literal = builder.createIntegerLiteral(0,  type: type)
    case .Is:
      let builder = Builder(before: self, context)
      literal = builder.createIntegerLiteral(1,  type: type)
    case .CanBe:
      return
    default:
      fatalError()
    }
    uses.replaceAll(with: literal, context)
    context.erase(instruction: self)
  }

  func optimizeAssertConfig(_ context: SimplifyContext) {
    // The values for the assert_configuration call are:
    // 0: Debug
    // 1: Release
    // 2: Fast / Unchecked
    let config = context.options.assertConfiguration
    switch config {
    case .debug, .release, .unchecked:
      let builder = Builder(before: self, context)
      let literal = builder.createIntegerLiteral(config.integerValue, type: type)
      uses.replaceAll(with: literal, context)
      context.erase(instruction: self)
    case .unknown:
      return
    }
  }
  
  func optimizeTargetTypeConst(_ context: SimplifyContext) {
    guard let ty = substitutionMap.replacementTypes[0] else {
      return
    }
    
    let value: Int?
    switch id {
    case .Sizeof:
      value = ty.getStaticSize(context: context)
    case .Strideof:
      value = ty.getStaticStride(context: context)
    case .Alignof:
      value = ty.getStaticAlignment(context: context)
    default:
      fatalError()
    }
    
    guard let value else {
      return
    }
    
    let builder = Builder(before: self, context)
    let literal = builder.createIntegerLiteral(value, type: type)
    uses.replaceAll(with: literal, context)
    context.erase(instruction: self)
  }
  
  func optimizeArgumentToThinMetatype(argument: Int, _ context: SimplifyContext) {
    let type: Type

    if let metatypeInst = operands[argument].value as? MetatypeInst {
      type = metatypeInst.type
    } else if let initExistentialInst = operands[argument].value as? InitExistentialMetatypeInst {
      type = initExistentialInst.metatype.type
    } else {
      return
    }

    guard type.representationOfMetatype(in: parentFunction) == .Thick else {
      return
    }
    
    let instanceType = type.loweredInstanceTypeOfMetatype(in: parentFunction)
    let builder = Builder(before: self, context)
    let newMetatype = builder.createMetatype(of: instanceType, representation: .Thin)
    operands[argument].set(to: newMetatype, context)
  }

  func constantFoldIntegerEquality(isEqual: Bool, _ context: SimplifyContext) {
    if constantFoldStringNullPointerCheck(isEqual: isEqual, context) {
      return
    }
    if let literal = constantFold(context) {
      uses.replaceAll(with: literal, context)
    }
  }

  func constantFoldStringNullPointerCheck(isEqual: Bool, _ context: SimplifyContext) -> Bool {
    if operands[1].value.isZeroInteger &&
       operands[0].value.lookThroughScalarCasts is StringLiteralInst
    {
      let builder = Builder(before: self, context)
      let result = builder.createIntegerLiteral(isEqual ? 0 : 1, type: type)
      uses.replaceAll(with: result, context)
      context.erase(instruction: self)
      return true
    }
    return false
  }
}

private extension Value {
  var isZeroInteger: Bool {
    if let literal = self as? IntegerLiteralInst,
       let value = literal.value
    {
      return value == 0
    }
    return false
  }

  var lookThroughScalarCasts: Value {
    guard let bi = self as? BuiltinInst else {
      return self
    }
    switch bi.id {
    case .ZExt, .ZExtOrBitCast, .PtrToInt:
      return bi.operands[0].value.lookThroughScalarCasts
    default:
      return self
    }
  }
}

private func hasSideEffectForBuiltinOnce(_ instruction: Instruction) -> Bool {
  switch instruction {
  case is DebugStepInst, is DebugValueInst:
    return false
  default:
    return instruction.mayReadOrWriteMemory ||
           instruction.hasUnspecifiedSideEffects
  }
}

private func typesOfValuesAreEqual(_ lhs: Value, _ rhs: Value, in function: Function) -> Bool? {
  if lhs == rhs {
    return true
  }

  guard let lhsExistential = lhs as? InitExistentialMetatypeInst,
        let rhsExistential = rhs as? InitExistentialMetatypeInst else {
    return nil
  }

  let lhsMetatype = lhsExistential.metatype.type
  let rhsMetatype = rhsExistential.metatype.type
  if lhsMetatype.isDynamicSelfMetatype != rhsMetatype.isDynamicSelfMetatype {
    return nil
  }
  let lhsTy = lhsMetatype.loweredInstanceTypeOfMetatype(in: function)
  let rhsTy = rhsMetatype.loweredInstanceTypeOfMetatype(in: function)

  // Do we know the exact types? This is not the case e.g. if a type is passed as metatype
  // to the function.
  let typesAreExact = lhsExistential.metatype is MetatypeInst &&
                      rhsExistential.metatype is MetatypeInst

  if typesAreExact {
    // We need to compare the not lowered types, because function types may differ in their original version
    // but are equal in the lowered version, e.g.
    //   ((Int, Int) -> ())
    //   (((Int, Int)) -> ())
    //
    if lhsMetatype == rhsMetatype {
      return true
    }
    // Comparing types of different classes which are in a sub-class relation is not handled by the
    // cast optimizer (below).
    if lhsTy.isClass && rhsTy.isClass && lhsTy.nominal != rhsTy.nominal {
      return false
    }
  }

  // If casting in either direction doesn't work, the types cannot be equal.
  if !(canDynamicallyCast(from: lhsTy, to: rhsTy, in: function, sourceTypeIsExact: typesAreExact) ?? true) ||
     !(canDynamicallyCast(from: rhsTy, to: lhsTy, in: function, sourceTypeIsExact: typesAreExact) ?? true) {
    return false
  }
  return nil
}