Skip to content

Instantly share code, notes, and snippets.

@soraros
Last active May 7, 2025 13:55
Show Gist options
  • Save soraros/44d56698cb20a6c5db3160f13ca81675 to your computer and use it in GitHub Desktop.
Save soraros/44d56698cb20a6c5db3160f13ca81675 to your computer and use it in GitHub Desktop.
# 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.
import compile
from builtin._location import __call_location
from collections.string import StaticString
from os import path
@export
fn f(x: Int) -> Int:
# print_val(x)
return x + 1
fn main():
dump_ir[f, "out"]()
@value
struct Setting:
var kind: StaticString
var ext: StaticString
alias settings = InlineArray[size=3](
Setting("llvm", "ll"),
Setting("llvm-opt", "opt.ll"),
Setting("asm", "s"),
)
@no_inline
fn dump_ir[Fn: AnyTrivialRegType, //, f: Fn, name: StaticString = "out"]():
"""Dump IR for a function to a file."""
print(compile.get_linkage_name[f]())
dir = path.dirname(__call_location[inline_count=0]().file_name)
@parameter
for i in range(len(settings)):
alias s = settings[i]
ir = compile.compile_info[f, emission_kind=s.kind]()
print("-", full_path := path.join(dir, String(name, ".", s.ext)))
try:
with open(full_path, "w") as f:
f.write(ir)
except e:
print("error:", e)
@export
@no_inline
fn print_val[T: Writable, //](x: T):
print(x)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment