-
Notifications
You must be signed in to change notification settings - Fork 60
Expand file tree
/
Copy pathreflection.jl
More file actions
400 lines (340 loc) · 12.8 KB
/
reflection.jl
File metadata and controls
400 lines (340 loc) · 12.8 KB
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
import InteractiveUtils
using UUIDs
const Cthulhu = Base.PkgId(UUID("f68482b8-f384-11e8-15f7-abe071a5a75f"), "Cthulhu")
#
# syntax highlighting
#
const _pygmentize = Ref{Union{String,Nothing}}()
function pygmentize()
if !isassigned(_pygmentize)
_pygmentize[] = Sys.which("pygmentize")
end
return _pygmentize[]
end
const _pygmentize_version = Ref{Union{VersionNumber, Nothing}}()
function pygmentize_version()
isassigned(_pygmentize_version) && return _pygmentize_version[]
pygmentize_cmd = pygmentize()
if isnothing(pygmentize_cmd)
return _pygmentize_version[] = nothing
end
cmd = `$pygmentize_cmd -V`
@static if Sys.iswindows()
# Avoid encoding issues with pipes on Windows by using cmd.exe to capture stdout for us
cmd = `cmd.exe /C $cmd`
cmd = addenv(cmd, "PYTHONUTF8" => 1)
end
version_str = readchomp(cmd)
pos = findfirst("Pygments version ", version_str)
if !isnothing(pos)
version_start = last(pos) + 1
version_end = findnext(',', version_str, version_start) - 1
version = tryparse(VersionNumber, version_str[version_start:version_end])
else
version = nothing
end
if isnothing(version)
@warn "Could not parse Pygments version:\n$version_str"
end
return _pygmentize_version[] = version
end
function pygmentize_support(lexer)
highlighter_ver = pygmentize_version()
if isnothing(highlighter_ver)
@warn "Syntax highlighting of $lexer code relies on Pygments.\n\
Use `pip install pygments` to install the lastest version" maxlog = 1
return false
elseif lexer == "ptx"
if highlighter_ver < v"2.16"
@warn "Pygments supports PTX highlighting starting from version 2.16\n\
Detected version $highlighter_ver\n\
Please update with `pip install pygments -U`" maxlog = 1
return false
end
return true
elseif lexer == "gcn"
if highlighter_ver < v"2.8"
@warn "Pygments supports GCN highlighting starting from version 2.8\n\
Detected version $highlighter_ver\n\
Please update with `pip install pygments -U`" maxlog = 1
return false
end
return true
else
return false
end
end
function highlight(io::IO, code, lexer)
have_color = get(io, :color, false)
if !have_color
print(io, code)
elseif lexer == "llvm"
InteractiveUtils.print_llvm(io, code)
elseif pygmentize_support(lexer)
lexer = lexer == "gcn" ? "amdgpu" : lexer
pygments_args = String[pygmentize(), "-f", "terminal", "-P", "bg=dark", "-l", lexer]
@static if Sys.iswindows()
# Avoid encoding issues with pipes on Windows by using a temporary file
mktemp() do tmp_path, tmp_io
println(tmp_io, code)
close(tmp_io)
push!(pygments_args, "-o", tmp_path, tmp_path)
cmd = Cmd(pygments_args)
wait(open(cmd)) # stdout and stderr go to devnull
print(io, read(tmp_path, String))
end
else
cmd = Cmd(pygments_args)
pipe = open(cmd, "r+")
print(pipe, code)
close(pipe.in)
print(io, read(pipe, String))
end
else
print(io, code)
end
return
end
#
# Compat shims
#
include("reflection_compat.jl")
#
# code_* replacements
#
function code_lowered(@nospecialize(job::CompilerJob); kwargs...)
sig = job.source.specTypes # XXX: can we just use the method instance?
code_lowered_by_type(sig; kwargs...)
end
function code_typed(@nospecialize(job::CompilerJob); interactive::Bool=false, kwargs...)
sig = job.source.specTypes # XXX: can we just use the method instance?
if interactive
# call Cthulhu without introducing a dependency on Cthulhu
mod = get(Base.loaded_modules, Cthulhu, nothing)
mod===nothing && error("Interactive code reflection requires Cthulhu; please install and load this package first.")
interp = get_interpreter(job)
descend_code_typed = getfield(mod, :descend_code_typed)
descend_code_typed(sig; interp, kwargs...)
else
interp = get_interpreter(job)
Base.code_typed_by_type(sig; interp, kwargs...)
end
end
function code_warntype(io::IO, @nospecialize(job::CompilerJob); interactive::Bool=false, kwargs...)
sig = job.source.specTypes # XXX: can we just use the method instance?
if interactive
@assert io == stdout
# call Cthulhu without introducing a dependency on Cthulhu
mod = get(Base.loaded_modules, Cthulhu, nothing)
mod===nothing && error("Interactive code reflection requires Cthulhu; please install and load this package first.")
interp = get_interpreter(job)
descend_code_warntype = getfield(mod, :descend_code_warntype)
descend_code_warntype(sig; interp, kwargs...)
else
interp = get_interpreter(job)
code_warntype_by_type(io, sig; interp, kwargs...)
end
end
code_warntype(@nospecialize(job::CompilerJob); kwargs...) = code_warntype(stdout, job; kwargs...)
InteractiveUtils.code_lowered(err::InvalidIRError; kwargs...) = code_lowered(err.job; kwargs...)
InteractiveUtils.code_typed(err::InvalidIRError; kwargs...) = code_typed(err.job; kwargs...)
InteractiveUtils.code_warntype(err::InvalidIRError; kwargs...) = code_warntype(err.job; kwargs...)
InteractiveUtils.code_lowered(err::KernelError; kwargs...) = code_lowered(err.job; kwargs...)
InteractiveUtils.code_typed(err::KernelError; kwargs...) = code_typed(err.job; kwargs...)
InteractiveUtils.code_warntype(err::KernelError; kwargs...) = code_warntype(err.job; kwargs...)
struct jl_llvmf_dump
TSM::LLVM.API.LLVMOrcThreadSafeModuleRef
F::LLVM.API.LLVMValueRef
@static if VERSION >= v"1.14.0-DEV.1823" # JuliaLang/julia#60698
dump::Ptr{Nothing}
jl_llvmf_dump(TSM::LLVM.API.LLVMOrcThreadSafeModuleRef, F::LLVM.API.LLVMValueRef) = new(TSM, F, C_NULL)
end
end
"""
code_llvm([io], job; optimize=job.config.optimize, raw=false, dump_module=false)
Prints the device LLVM IR generated for the given compiler job to `io` (default `stdout`).
The following keyword arguments are supported:
- `optimize`: determines if the code is optimized, which includes kernel-specific
optimizations if `kernel` is true
- `raw`: return the raw IR including all metadata
- `dump_module`: display the entire module instead of just the function
See also: [`@device_code_llvm`](@ref), `InteractiveUtils.code_llvm`
"""
function code_llvm(io::IO, @nospecialize(job::CompilerJob); optimize::Bool=job.config.optimize, raw::Bool=false,
debuginfo::Symbol=:default, dump_module::Bool=false, kwargs...)
# NOTE: jl_dump_function_ir supports stripping metadata, so don't do it in the driver
config = CompilerConfig(job.config; validate=false, strip=false, optimize)
str = JuliaContext() do ctx
ir, meta = compile(:llvm, CompilerJob(job; config))
ts_mod = ThreadSafeModule(ir)
entry_fn = meta.entry
GC.@preserve ts_mod entry_fn begin
value = Ref(jl_llvmf_dump(ts_mod.ref, entry_fn.ref))
ccall(:jl_dump_function_ir, Ref{String},
(Ptr{jl_llvmf_dump}, Bool, Bool, Ptr{UInt8}),
value, !raw, dump_module, debuginfo)
end
end
highlight(io, str, "llvm")
end
code_llvm(@nospecialize(job::CompilerJob); kwargs...) = code_llvm(stdout, job; kwargs...)
"""
code_native([io], f, types; cap::VersionNumber, kernel=false, raw=false)
Prints the native assembly generated for the given compiler job to `io` (default `stdout`).
The following keyword arguments are supported:
- `cap` which device to generate code for
- `kernel`: treat the function as an entry-point kernel
- `raw`: return the raw code including all metadata
See also: [`@device_code_native`](@ref), `InteractiveUtils.code_llvm`
"""
function code_native(io::IO, @nospecialize(job::CompilerJob);
raw::Bool=false, dump_module::Bool=false)
config = CompilerConfig(job.config; strip=!raw, only_entry=!dump_module, validate=false)
asm, meta = JuliaContext() do ctx
compile(:asm, CompilerJob(job; config))
end
highlight(io, asm, source_code(job.config.target))
end
code_native(@nospecialize(job::CompilerJob); kwargs...) =
code_native(stdout, job; kwargs...)
#
# @device_code_* functions
#
function emit_hooked_compilation(inner_hook, ex...)
user_code = ex[end]
user_kwargs = ex[1:end-1]
quote
# we only want to invoke the hook once for every compilation job
jobs = Set()
function outer_hook(job)
if !in(job, jobs)
# the user hook might invoke the compiler again, so disable the hook
old_hook = $compile_hook[]
try
$compile_hook[] = nothing
$inner_hook(job; $(map(esc, user_kwargs)...))
finally
$compile_hook[] = old_hook
end
push!(jobs, job)
end
end
# now invoke the user code with this hook in place
try
$compile_hook[] = outer_hook
$(esc(user_code))
finally
$compile_hook[] = nothing
end
if isempty(jobs)
error("no kernels executed while evaluating the given expression")
end
nothing
end
end
"""
@device_code_lowered ex
Evaluates the expression `ex` and returns the result of
`InteractiveUtils.code_lowered` for every compiled GPU kernel.
See also: `InteractiveUtils.@code_lowered`
"""
macro device_code_lowered(ex...)
quote
buf = Any[]
function hook(job::CompilerJob)
append!(buf, code_lowered(job))
end
$(emit_hooked_compilation(:hook, ex...))
buf
end
end
"""
@device_code_typed ex
Evaluates the expression `ex` and returns the result of
`InteractiveUtils.code_typed` for every compiled GPU kernel.
See also: `InteractiveUtils.@code_typed`
"""
macro device_code_typed(ex...)
quote
output = Dict{CompilerJob,Any}()
function hook(job::CompilerJob; kwargs...)
output[job] = code_typed(job; kwargs...)
end
$(emit_hooked_compilation(:hook, ex...))
output
end
end
"""
@device_code_warntype [io::IO=stdout] ex
Evaluates the expression `ex` and prints the result of
`InteractiveUtils.code_warntype` to `io` for every compiled GPU kernel.
See also: `InteractiveUtils.@code_warntype`
"""
macro device_code_warntype(ex...)
function hook(job::CompilerJob; io::IO=stdout, kwargs...)
println(io, "$job")
println(io)
code_warntype(io, job; kwargs...)
end
emit_hooked_compilation(hook, ex...)
end
"""
@device_code_llvm [io::IO=stdout, ...] ex
Evaluates the expression `ex` and prints the result of `InteractiveUtils.code_llvm`
to `io` for every compiled GPU kernel. For other supported keywords, see
[`GPUCompiler.code_llvm`](@ref).
See also: InteractiveUtils.@code_llvm
"""
macro device_code_llvm(ex...)
function hook(job::CompilerJob; io::IO=stdout, kwargs...)
println(io, "; $job")
code_llvm(io, job; kwargs...)
end
emit_hooked_compilation(hook, ex...)
end
"""
@device_code_native [io::IO=stdout, ...] ex
Evaluates the expression `ex` and prints the result of [`GPUCompiler.code_native`](@ref) to `io`
for every compiled GPU kernel. For other supported keywords, see
[`GPUCompiler.code_native`](@ref).
"""
macro device_code_native(ex...)
function hook(job::CompilerJob; io::IO=stdout, kwargs...)
println(io, "// $job")
println(io)
code_native(io, job; kwargs...)
end
emit_hooked_compilation(hook, ex...)
end
"""
@device_code dir::AbstractString=... [...] ex
Evaluates the expression `ex` and dumps all intermediate forms of code to the directory
`dir`.
"""
macro device_code(ex...)
localUnique = 1
function hook(job::CompilerJob; dir::AbstractString)
name = job.source.def.name
fn = "$(name)_$(localUnique)"
mkpath(dir)
open(joinpath(dir, "$fn.lowered.jl"), "w") do io
code = only(code_lowered(job))
println(io, code)
end
open(joinpath(dir, "$fn.typed.jl"), "w") do io
code = only(code_typed(job; debuginfo=:source))
println(io, code)
end
open(joinpath(dir, "$fn.unopt.ll"), "w") do io
code_llvm(io, job; dump_module=true, raw=true, optimize=false)
end
open(joinpath(dir, "$fn.opt.ll"), "w") do io
code_llvm(io, job; dump_module=true, raw=true, optimize=true)
end
open(joinpath(dir, "$fn.asm"), "w") do io
code_native(io, job; dump_module=true, raw=true)
end
localUnique += 1
end
emit_hooked_compilation(hook, ex...)
end