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 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641
|
//===--- Context.swift - defines the context types ------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2022 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
import OptimizerBridging
/// The base type of all contexts.
protocol Context {
var _bridged: BridgedPassContext { get }
}
extension Context {
var options: Options { Options(_bridged: _bridged) }
var diagnosticEngine: DiagnosticEngine {
return DiagnosticEngine(bridged: _bridged.getDiagnosticEngine())
}
// The calleeAnalysis is not specific to a function and therefore can be provided in
// all contexts.
var calleeAnalysis: CalleeAnalysis {
let bridgeCA = _bridged.getCalleeAnalysis()
return CalleeAnalysis(bridged: bridgeCA)
}
var hadError: Bool { _bridged.hadError() }
var silStage: SILStage {
switch _bridged.getSILStage() {
case .Raw: return .raw
case .Canonical: return .canonical
case .Lowered: return .lowered
default: fatalError("unhandled SILStage case")
}
}
var moduleIsSerialized: Bool { _bridged.moduleIsSerialized() }
func lookupDeinit(ofNominal: NominalTypeDecl) -> Function? {
_bridged.lookUpNominalDeinitFunction(ofNominal.bridged).function
}
func getBuiltinIntegerType(bitWidth: Int) -> Type { _bridged.getBuiltinIntegerType(bitWidth).type }
func lookupFunction(name: String) -> Function? {
name._withBridgedStringRef {
_bridged.lookupFunction($0).function
}
}
}
/// A context which allows mutation of a function's SIL.
protocol MutatingContext : Context {
// Called by all instruction mutations, including inserted new instructions.
var notifyInstructionChanged: (Instruction) -> () { get }
}
extension MutatingContext {
func notifyInvalidatedStackNesting() { _bridged.notifyInvalidatedStackNesting() }
var needFixStackNesting: Bool { _bridged.getNeedFixStackNesting() }
func verifyIsTransforming(function: Function) {
precondition(_bridged.isTransforming(function.bridged), "pass modifies wrong function")
}
/// Splits the basic block, which contains `inst`, before `inst` and returns the
/// new block.
///
/// `inst` and all subsequent instructions are moved to the new block, while all
/// instructions _before_ `inst` remain in the original block.
func splitBlock(before inst: Instruction) -> BasicBlock {
notifyBranchesChanged()
return _bridged.splitBlockBefore(inst.bridged).block
}
/// Splits the basic block, which contains `inst`, after `inst` and returns the
/// new block.
///
/// All subsequent instructions after `inst` are moved to the new block, while `inst` and all
/// instructions _before_ `inst` remain in the original block.
func splitBlock(after inst: Instruction) -> BasicBlock {
notifyBranchesChanged()
return _bridged.splitBlockAfter(inst.bridged).block
}
func createBlock(after block: BasicBlock) -> BasicBlock {
notifyBranchesChanged()
return _bridged.createBlockAfter(block.bridged).block
}
func erase(instruction: Instruction) {
if !instruction.isInStaticInitializer {
verifyIsTransforming(function: instruction.parentFunction)
}
if instruction is FullApplySite {
notifyCallsChanged()
}
if instruction is TermInst {
notifyBranchesChanged()
}
notifyInstructionsChanged()
_bridged.eraseInstruction(instruction.bridged)
}
func erase(instructionIncludingAllUsers inst: Instruction) {
if inst.isDeleted {
return
}
for result in inst.results {
for use in result.uses {
erase(instructionIncludingAllUsers: use.instruction)
}
}
erase(instruction: inst)
}
func erase(instructionIncludingDebugUses inst: Instruction) {
precondition(inst.results.allSatisfy { $0.uses.ignoreDebugUses.isEmpty })
erase(instructionIncludingAllUsers: inst)
}
func erase(block: BasicBlock) {
_bridged.eraseBlock(block.bridged)
}
func tryOptimizeApplyOfPartialApply(closure: PartialApplyInst) -> Bool {
if _bridged.tryOptimizeApplyOfPartialApply(closure.bridged) {
notifyInstructionsChanged()
notifyCallsChanged()
for use in closure.callee.uses {
if use.instruction is FullApplySite {
notifyInstructionChanged(use.instruction)
}
}
return true
}
return false
}
func tryDeleteDeadClosure(closure: SingleValueInstruction, needKeepArgsAlive: Bool = true) -> Bool {
if _bridged.tryDeleteDeadClosure(closure.bridged, needKeepArgsAlive) {
notifyInstructionsChanged()
return true
}
return false
}
func tryDevirtualize(apply: FullApplySite, isMandatory: Bool) -> ApplySite? {
let result = _bridged.tryDevirtualizeApply(apply.bridged, isMandatory)
if let newApply = result.newApply.instruction {
erase(instruction: apply)
notifyInstructionsChanged()
notifyCallsChanged()
if result.cfgChanged {
notifyBranchesChanged()
}
notifyInstructionChanged(newApply)
return newApply as! FullApplySite
}
return nil
}
func tryOptimizeKeypath(apply: FullApplySite) -> Bool {
return _bridged.tryOptimizeKeypath(apply.bridged)
}
func inlineFunction(apply: FullApplySite, mandatoryInline: Bool) {
// This is only a best-effort attempt to notity the new cloned instructions as changed.
// TODO: get a list of cloned instructions from the `inlineFunction`
let instAfterInling: Instruction?
switch apply {
case is ApplyInst:
instAfterInling = apply.next
case let beginApply as BeginApplyInst:
let next = beginApply.next!
instAfterInling = (next is EndApplyInst ? nil : next)
case is TryApplyInst:
instAfterInling = apply.parentBlock.next?.instructions.first
default:
instAfterInling = nil
}
_bridged.inlineFunction(apply.bridged, mandatoryInline)
if let instAfterInling = instAfterInling {
notifyNewInstructions(from: apply, to: instAfterInling)
}
}
private func notifyNewInstructions(from: Instruction, to: Instruction) {
var inst = from
while inst != to {
if !inst.isDeleted {
notifyInstructionChanged(inst)
}
if let next = inst.next {
inst = next
} else {
inst = inst.parentBlock.next!.instructions.first!
}
}
}
func getContextSubstitutionMap(for type: Type) -> SubstitutionMap {
SubstitutionMap(_bridged.getContextSubstitutionMap(type.bridged))
}
func notifyInstructionsChanged() {
_bridged.asNotificationHandler().notifyChanges(.instructionsChanged)
}
func notifyCallsChanged() {
_bridged.asNotificationHandler().notifyChanges(.callsChanged)
}
func notifyBranchesChanged() {
_bridged.asNotificationHandler().notifyChanges(.branchesChanged)
}
/// Notifies the pass manager that the optimization result of the current pass depends
/// on the body (i.e. SIL instructions) of another function than the currently optimized one.
func notifyDependency(onBodyOf otherFunction: Function) {
_bridged.notifyDependencyOnBodyOf(otherFunction.bridged)
}
}
/// The context which is passed to the run-function of a FunctionPass.
struct FunctionPassContext : MutatingContext {
let _bridged: BridgedPassContext
// A no-op.
var notifyInstructionChanged: (Instruction) -> () { return { inst in } }
func continueWithNextSubpassRun(for inst: Instruction? = nil) -> Bool {
return _bridged.continueWithNextSubpassRun(inst.bridged)
}
func createSimplifyContext(preserveDebugInfo: Bool, notifyInstructionChanged: @escaping (Instruction) -> ()) -> SimplifyContext {
SimplifyContext(_bridged: _bridged, notifyInstructionChanged: notifyInstructionChanged, preserveDebugInfo: preserveDebugInfo)
}
var aliasAnalysis: AliasAnalysis {
let bridgedAA = _bridged.getAliasAnalysis()
return AliasAnalysis(bridged: bridgedAA)
}
var deadEndBlocks: DeadEndBlocksAnalysis {
let bridgeDEA = _bridged.getDeadEndBlocksAnalysis()
return DeadEndBlocksAnalysis(bridged: bridgeDEA)
}
var dominatorTree: DominatorTree {
let bridgedDT = _bridged.getDomTree()
return DominatorTree(bridged: bridgedDT)
}
var postDominatorTree: PostDominatorTree {
let bridgedPDT = _bridged.getPostDomTree()
return PostDominatorTree(bridged: bridgedPDT)
}
var swiftArrayDecl: NominalTypeDecl {
NominalTypeDecl(_bridged: _bridged.getSwiftArrayDecl())
}
func loadFunction(name: StaticString, loadCalleesRecursively: Bool) -> Function? {
return name.withUTF8Buffer { (nameBuffer: UnsafeBufferPointer<UInt8>) in
let nameStr = BridgedStringRef(data: nameBuffer.baseAddress, count: nameBuffer.count)
return _bridged.loadFunction(nameStr, loadCalleesRecursively).function
}
}
func loadFunction(function: Function, loadCalleesRecursively: Bool) -> Bool {
if function.isDefinition {
return true
}
_bridged.loadFunction(function.bridged, loadCalleesRecursively)
return function.isDefinition
}
/// Looks up a function in the `Swift` module.
/// The `name` is the source name of the function and not the mangled name.
/// Returns nil if no such function or multiple matching functions are found.
func lookupStdlibFunction(name: StaticString) -> Function? {
return name.withUTF8Buffer { (nameBuffer: UnsafeBufferPointer<UInt8>) in
let nameStr = BridgedStringRef(data: nameBuffer.baseAddress, count: nameBuffer.count)
return _bridged.lookupStdlibFunction(nameStr).function
}
}
func modifyEffects(in function: Function, _ body: (inout FunctionEffects) -> ()) {
notifyEffectsChanged()
function._modifyEffects(body)
}
fileprivate func notifyEffectsChanged() {
_bridged.asNotificationHandler().notifyChanges(.effectsChanged)
}
func optimizeMemoryAccesses(in function: Function) -> Bool {
if _bridged.optimizeMemoryAccesses(function.bridged) {
notifyInstructionsChanged()
return true
}
return false
}
func eliminateDeadAllocations(in function: Function) -> Bool {
if _bridged.eliminateDeadAllocations(function.bridged) {
notifyInstructionsChanged()
return true
}
return false
}
func specializeVTable(for type: Type, in function: Function) -> VTable? {
guard let vtablePtr = _bridged.specializeVTableForType(type.bridged, function.bridged) else {
return nil
}
return VTable(bridged: BridgedVTable(vTable: vtablePtr))
}
func specializeClassMethodInst(_ cm: ClassMethodInst) -> Bool {
if _bridged.specializeClassMethodInst(cm.bridged) {
notifyInstructionsChanged()
notifyCallsChanged()
return true
}
return false
}
func specializeApplies(in function: Function, isMandatory: Bool) -> Bool {
if _bridged.specializeAppliesInFunction(function.bridged, isMandatory) {
notifyInstructionsChanged()
notifyCallsChanged()
return true
}
return false
}
func mangleOutlinedVariable(from function: Function) -> String {
return String(taking: _bridged.mangleOutlinedVariable(function.bridged))
}
func createGlobalVariable(name: String, type: Type, isPrivate: Bool) -> GlobalVariable {
let gv = name._withBridgedStringRef {
_bridged.createGlobalVariable($0, type.bridged, isPrivate)
}
return gv.globalVar
}
}
struct SimplifyContext : MutatingContext {
let _bridged: BridgedPassContext
let notifyInstructionChanged: (Instruction) -> ()
let preserveDebugInfo: Bool
}
extension Type {
func getStaticSize(context: SimplifyContext) -> Int? {
let v = context._bridged.getStaticSize(self.bridged)
return v == -1 ? nil : v
}
func getStaticAlignment(context: SimplifyContext) -> Int? {
let v = context._bridged.getStaticAlignment(self.bridged)
return v == -1 ? nil : v
}
func getStaticStride(context: SimplifyContext) -> Int? {
let v = context._bridged.getStaticStride(self.bridged)
return v == -1 ? nil : v
}
}
//===----------------------------------------------------------------------===//
// Builder initialization
//===----------------------------------------------------------------------===//
extension Builder {
/// Creates a builder which inserts _before_ `insPnt`, using a custom `location`.
init(before insPnt: Instruction, location: Location, _ context: some MutatingContext) {
context.verifyIsTransforming(function: insPnt.parentFunction)
self.init(insertAt: .before(insPnt), location: location,
context.notifyInstructionChanged, context._bridged.asNotificationHandler())
}
/// Creates a builder which inserts _before_ `insPnt`, using the location of `insPnt`.
init(before insPnt: Instruction, _ context: some MutatingContext) {
context.verifyIsTransforming(function: insPnt.parentFunction)
self.init(insertAt: .before(insPnt), location: insPnt.location,
context.notifyInstructionChanged, context._bridged.asNotificationHandler())
}
/// Creates a builder which inserts _after_ `insPnt`, using a custom `location`.
init(after insPnt: Instruction, location: Location, _ context: some MutatingContext) {
context.verifyIsTransforming(function: insPnt.parentFunction)
if let nextInst = insPnt.next {
self.init(insertAt: .before(nextInst), location: location,
context.notifyInstructionChanged, context._bridged.asNotificationHandler())
} else {
self.init(insertAt: .atEndOf(insPnt.parentBlock), location: location,
context.notifyInstructionChanged, context._bridged.asNotificationHandler())
}
}
/// Creates a builder which inserts _after_ `insPnt`, using the location of `insPnt`.
init(after insPnt: Instruction, _ context: some MutatingContext) {
context.verifyIsTransforming(function: insPnt.parentFunction)
self.init(after: insPnt, location: insPnt.location, context)
}
/// Creates a builder which inserts at the end of `block`, using a custom `location`.
init(atEndOf block: BasicBlock, location: Location, _ context: some MutatingContext) {
context.verifyIsTransforming(function: block.parentFunction)
self.init(insertAt: .atEndOf(block), location: location,
context.notifyInstructionChanged, context._bridged.asNotificationHandler())
}
/// Creates a builder which inserts at the begin of `block`, using a custom `location`.
init(atBeginOf block: BasicBlock, location: Location, _ context: some MutatingContext) {
context.verifyIsTransforming(function: block.parentFunction)
let firstInst = block.instructions.first!
self.init(insertAt: .before(firstInst), location: location,
context.notifyInstructionChanged, context._bridged.asNotificationHandler())
}
/// Creates a builder which inserts at the begin of `block`, using the location of the first
/// instruction of `block`.
init(atBeginOf block: BasicBlock, _ context: some MutatingContext) {
context.verifyIsTransforming(function: block.parentFunction)
let firstInst = block.instructions.first!
self.init(insertAt: .before(firstInst), location: firstInst.location,
context.notifyInstructionChanged, context._bridged.asNotificationHandler())
}
init(staticInitializerOf global: GlobalVariable, _ context: some MutatingContext) {
self.init(insertAt: .staticInitializer(global),
location: Location.artificialUnreachableLocation,
{ _ in }, context._bridged.asNotificationHandler())
}
}
//===----------------------------------------------------------------------===//
// Modifying the SIL
//===----------------------------------------------------------------------===//
extension Undef {
static func get(type: Type, _ context: some MutatingContext) -> Undef {
context._bridged.getSILUndef(type.bridged).value as! Undef
}
}
extension BasicBlock {
func addArgument(type: Type, ownership: Ownership, _ context: some MutatingContext) -> Argument {
context.notifyInstructionsChanged()
return bridged.addBlockArgument(type.bridged, ownership._bridged).argument
}
func addFunctionArgument(type: Type, _ context: some MutatingContext) -> FunctionArgument {
context.notifyInstructionsChanged()
return bridged.addFunctionArgument(type.bridged).argument as! FunctionArgument
}
func eraseArgument(at index: Int, _ context: some MutatingContext) {
context.notifyInstructionsChanged()
bridged.eraseArgument(index)
}
func moveAllInstructions(toBeginOf otherBlock: BasicBlock, _ context: some MutatingContext) {
context.notifyInstructionsChanged()
context.notifyBranchesChanged()
bridged.moveAllInstructionsToBegin(otherBlock.bridged)
}
func moveAllInstructions(toEndOf otherBlock: BasicBlock, _ context: some MutatingContext) {
context.notifyInstructionsChanged()
context.notifyBranchesChanged()
bridged.moveAllInstructionsToEnd(otherBlock.bridged)
}
func eraseAllArguments(_ context: some MutatingContext) {
// Arguments are stored in an array. We need to erase in reverse order to avoid quadratic complexity.
for argIdx in (0 ..< arguments.count).reversed() {
eraseArgument(at: argIdx, context)
}
}
func moveAllArguments(to otherBlock: BasicBlock, _ context: some MutatingContext) {
bridged.moveArgumentsTo(otherBlock.bridged)
}
}
extension AllocRefInstBase {
func setIsStackAllocatable(_ context: some MutatingContext) {
context.notifyInstructionsChanged()
bridged.AllocRefInstBase_setIsStackAllocatable()
context.notifyInstructionChanged(self)
}
}
extension Sequence where Element == Operand {
func replaceAll(with replacement: Value, _ context: some MutatingContext) {
for use in self {
use.set(to: replacement, context)
}
}
}
extension Operand {
func set(to value: Value, _ context: some MutatingContext) {
instruction.setOperand(at: index, to: value, context)
}
}
extension Instruction {
func setOperand(at index : Int, to value: Value, _ context: some MutatingContext) {
if let apply = self as? FullApplySite, apply.isCallee(operand: operands[index]) {
context.notifyCallsChanged()
}
context.notifyInstructionsChanged()
bridged.setOperand(index, value.bridged)
context.notifyInstructionChanged(self)
}
func move(before otherInstruction: Instruction, _ context: some MutatingContext) {
BridgedPassContext.moveInstructionBefore(bridged, otherInstruction.bridged)
context.notifyInstructionsChanged()
}
}
extension BuiltinInst {
func constantFold(_ context: some MutatingContext) -> Value? {
context._bridged.constantFoldBuiltin(bridged).value
}
}
extension RefCountingInst {
func setAtomicity(isAtomic: Bool, _ context: some MutatingContext) {
context.notifyInstructionsChanged()
bridged.RefCountingInst_setIsAtomic(isAtomic)
context.notifyInstructionChanged(self)
}
}
extension AllocRefInst {
func setIsBare(_ context: some MutatingContext) {
context.notifyInstructionsChanged()
bridged.AllocRefInst_setIsBare()
context.notifyInstructionChanged(self)
}
}
extension RefElementAddrInst {
func set(isImmutable: Bool, _ context: some MutatingContext) {
context.notifyInstructionsChanged()
bridged.RefElementAddrInst_setImmutable(isImmutable)
context.notifyInstructionChanged(self)
}
}
extension GlobalAddrInst {
func clearToken(_ context: some MutatingContext) {
context.notifyInstructionsChanged()
bridged.GlobalAddrInst_clearToken()
context.notifyInstructionChanged(self)
}
}
extension GlobalValueInst {
func setIsBare(_ context: some MutatingContext) {
context.notifyInstructionsChanged()
bridged.GlobalValueInst_setIsBare()
context.notifyInstructionChanged(self)
}
}
extension LoadInst {
func set(ownership: LoadInst.LoadOwnership, _ context: some MutatingContext) {
context.notifyInstructionsChanged()
bridged.LoadInst_setOwnership(ownership.rawValue)
context.notifyInstructionChanged(self)
}
}
extension TermInst {
func replaceBranchTarget(from fromBlock: BasicBlock, to toBlock: BasicBlock, _ context: some MutatingContext) {
context.notifyBranchesChanged()
bridged.TermInst_replaceBranchTarget(fromBlock.bridged, toBlock.bridged)
}
}
extension ForwardingInstruction {
func setForwardingOwnership(to ownership: Ownership, _ context: some MutatingContext) {
context.notifyInstructionsChanged()
bridged.ForwardingInst_setForwardingOwnership(ownership._bridged)
}
}
extension Function {
func set(needStackProtection: Bool, _ context: FunctionPassContext) {
context.notifyEffectsChanged()
bridged.setNeedStackProtection(needStackProtection)
}
func set(thunkKind: ThunkKind, _ context: FunctionPassContext) {
context.notifyEffectsChanged()
switch thunkKind {
case .noThunk: bridged.setThunk(.IsNotThunk)
case .thunk: bridged.setThunk(.IsThunk)
case .reabstractionThunk: bridged.setThunk(.IsReabstractionThunk)
case .signatureOptimizedThunk: bridged.setThunk(.IsSignatureOptimizedThunk)
}
}
func set(isPerformanceConstraint: Bool, _ context: FunctionPassContext) {
context.notifyEffectsChanged()
bridged.setIsPerformanceConstraint(isPerformanceConstraint)
}
func fixStackNesting(_ context: FunctionPassContext) {
context._bridged.fixStackNesting(bridged)
}
func appendNewBlock(_ context: FunctionPassContext) -> BasicBlock {
context.notifyBranchesChanged()
return context._bridged.appendBlock(bridged).block
}
}
|