forked from tensorflow/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BitcodePrinter.swift
108 lines (103 loc) · 3.19 KB
/
BitcodePrinter.swift
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
// Copyright 2019 The TensorFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Output of this printer is heavily inspired by llvm-bcanalyzer -dump.
// It supports most of its syntax, except:
// 1. We don't try to reinterpret arrays as strings
// 2. We don't report abbreviation id used to encode a record
class BitcodePrinter: Printer {
func print(_ bits: Bits) {
if bits.count <= 32 {
print(bits.uint32)
} else {
print("...")
}
}
private func printBlockName(_ block: BitcodeBlock) {
if let name = block.info.name {
print(name)
} else {
print("blockid=")
print(block.info.id)
}
}
private func printOperand(_ op: BitcodeOperand, _ i: inout Int) {
switch (op) {
case let .bits(value):
print(" op")
print(i)
print("=")
print(value)
i += 1
case let .array(values):
for v in values {
printOperand(v, &i)
}
default:
break
}
}
func print(_ record: BitcodeRecord, in block: BitcodeBlock) {
print("<")
if let name = block.info.recordNames[record.code] {
print(name)
} else {
print("code=")
print(record.code)
}
var i: Int = 0
for op in record.ops {
printOperand(op, &i)
}
print("/>")
if case let .some(.blob(value)) = record.ops.last {
print(" blob data = ")
if let asString = String(bytes: value, encoding: .utf8) {
print("'")
print(asString)
print("'")
} else {
print("unprintable, ")
print((value.count + 7) / 8)
print(" bytes.")
}
}
print("\n")
}
func print(_ block: BitcodeBlock) {
// ID 0 is normally reserved for the info block, but we don't parse it
// as a block anyway, and we use the 0 ID for the main outer block instead
if block.info.id != 0 {
print("<")
printBlockName(block)
print(" NumWords=")
print(block.blockLen32)
print(" BlockCodeSize=")
print(block.abbrLen)
print(">\n")
indent()
}
for record in block.records {
print(record, in: block)
}
for subblock in block.subblocks {
print(subblock)
}
if block.info.id != 0 {
unindent()
print("</")
printBlockName(block)
print(">\n")
}
}
}