228 points · by est31 · 5y ago · 100 comments
(defun ack (:match)
((0 @n) (+ n 1))
((@m 0) (ack (- m 1) 1))
((@m @n) (ack (- m 1) (ack m (- n 1)))))
I then added an "early peephole" pass which works on the input code before it has been divided into basic blocks:http://www.kylheku.com/cgit/txr/tree/share/txr/stdlib/optimi... (function at line 588)
There, I added recognition for a certain four-instruction kernel occurring out of pattern matching code, and rewrote it to three instructions.
Poof; I was left rubbing my eyes as out popped an instruction sequence identical to the one for this non-pattern-matching Ackermann, modulo some register names:
(defun ack (m n)
(cond
((eq m 0) (+ n 1))
((eq n 0) (ack (- m 1) 1))
(t (ack (- m 1) (ack m (- n 1))))))
That early reduction kind of removed a logjam, allowing other optimizations to proceed.The pattern matching code generates a flag which is set true upon matching, so that subsequent cases are skipped. This flag completely disappears.
The recognized instruction pattern spans (what would be) two basic blocks because it includes a jmp instruction. The rewritten instruction sequence eliminates one conditional branch, which gets rid of a basic block division, which is part of why it works.
Anyway, a big picture lesson here is that a big reason for the existence of pattern matching is so that so you have a tool that can be applied to optimize pattern matching.
The rewrite removes a conditional which tests a temporary flag; that test ends up in a basic block by itself:
(defun early-peephole (code)
(rewrite-case insns code
(((mov (t @t1) (d @d1))
(jmp @lab2)
@(symbolp @lab1)
(mov (t @t1) (t 0))
A label is matched (backreferencing the earlier (jmp @lab2), so we know this item must be a label) followed by an ifq: @lab2
(ifq (t @t1) (t 0) @lab3)
and so the above label and ifq form a basic block which does nothing more than tests a register to go somewhere else: the following code or some lab3 elsewhere.This is very reminiscent to the numerous temporary-testing basic blocks shown the messy "unoptimizable" flow graph in the submission.
. @rest)
^((mov (t ,t1) (d ,d1))
(jmp ,lab3)
,lab1
(mov (t ,t1) (t 0))
,lab2
,*rest))
In the rewritten pattern, that ifq is gone.If we look at the diagram in the submission: some things are striking. For instance, have a basic block 14:
bb14: fill temp5 with false
And another one: bb13: fill temp5 with true
Both of these jumps unconditionally to bb16: check temp5
The situation tested by my pattern above is exactly this sort of thing.E.g. if we look at the pattern matching ack without optimization, we can find them:
2> (disassemble (let ((*opt-level* 0)) (compile 'ack)))
data:
0: ack
1: 0
2: 1
3: t
Note 3: t means that in this VM description, register d3 holds t, the canonical Boolean true symbol: [ snip ]
31: 2C060403 movsr t6 d3
32: 34000022 jmp 34
33: 2C060000 movsr t6 nil
34: 10000006 end t6
35: 3C000036 ifq t6 nil 54
Here is an instance of the pattern. Except for the "end t6" has to do with closing a "frame ..." instruction earlier. We don't see this "end t6" in the pattern, and so it would cause a mismatch; but this instruction is removed by frame elimination, which is earlier in the compiler and happens at a lower optimization level.So then, what do we have here?
basic block A: "fill temp6 with true, jump to C"
31: 2C060403 movsr t6 d3
32: 34000022 jmp 34
basic block B: "fill temp6 with false, fall to C"
33: 2C060000 movsr t6 nil
basic block C: "check temp6"
34: 10000006 end t6
35: 3C000036 ifq t6 nil 54
That very similar that aforementioned situation in that basic block diagram!In my case, what breaks the logjam is that we get rid of the check, because the pattern knows that the check is only being reached from those two sources.
And then, register t6 succumbs to dead register removal. A subsequent data flow analysis, done after flow control optimizations (jump threading) discovers that these definitions of the t6 value have no next use.
I think that thanks to work done since then, that early-peephole thing could be moved into jump threading. There could be jump threading patterns which infer that the target of a jump is a conditional instruction which depends on the value of a register which is set to a true/false value prior to the jump, and then adjust the original jump. It's more general, but more annoying to code because of pattern matching across multiple discontinuous basic blocks.
http://www.kylheku.com/cgit/txr/tree/share/txr/stdlib/
Files compiler.tl, optimize.tl. asm.tl.
Main entry points into it are the functions compile and compile-file, as well as compile-toplevel which is public and used by those two.
Reminds me of a Zig stream I watched recently where Andy was updating the compiler backend to use an LLVM 12 release candidate. He ended up filling a couple bug reports with LLVM, using Zig compiler issues to generate reduced case LLVM IR examples that compiled differently with LLVM 11. He mentioned that he had to try this upgrade with the release candidate because right now they're LLVM regressions, but once 12 ships they become Zig regressions!
And Zig developers also do a very good job at reporting and fixing them. Which is why contributing to Zig also means contributing to LLVM.
If your compiler generates IR that's just awful enough that it's a coin toss whether the backend can optimize it, whereas it can optimize the "naive" IR you'd write by hand, it's a compiler problem, not a backend problem.
Curious: is there a Markdown exporter that supports some syntax for this?
The main contribution by Github's markdown renderer is that it doesn't remove that tag.
<detail>
<summary>...</summary>
Some `markdown`
</detail>
I would imagine this sort of behavior is in commonmark, but I am too lazy to check.This is obviously true in most cases -- if it takes me an hour to write task X in high-level language, it will probably take me a day or more to write it in assembly. After spending only one hour on assembly version the program will be nowhere close to completion, and likely completely non-functional. So whatever compiler produces will be much better -- it will at least work.
I can believe that at some moment hand-rolled assembly will "beat" generated code (I am pretty sure that if someone spends a month optimizing assembly listing it will beat the best Rust program written in a hour), but I am not sure what the ratio is. I am sure it is not 1:1, and I suspect the ratio gets worse as program grows and there are more parts that one needs to keep track of.
Yes, it's much weaker, but it's not useless. The vast majority of code in a program does not need to be as fast as it could possibly be [1], so there's no point in manually implementing everything in assembly. That doesn't mean that it never makes sense to manually implement something in assembly for performance reasons.
[1] And for many programs, all the code does not need to be as fast as it could possibly be.
Here is a fixed version (note I added "times 20" at the end):
"the compiler generates better assembly code than a human could within the time it takes to write high-level code times 20"
See -- now I can make predictions. Let's say you have a function that you want to make fast, and you want to optimize it in assembly. The function took 30 minutes to write and debug. Do you have 10 hours to spare? Try assembly. No time? Leave as-is.
Much more useful this way, no?
This seems incomplete. Which human? The average software developer? That doesn't say much. Few developers have the necessary expertise. Expert assembly programmers are often able to outperform compilers.
With high novelty? Probably not until machine learning and compilers are deeply entangled.
The argument of allowing a human programmer to spend vastly more time is hardly fair, one could also probably write a hyper-optimizing compiler that takes far longer to compile to level the playing field, and that compiler will still triumph over men in how optimized the end result is.
The only real advantage overal to human programmers here is the flexibility. A man can easily be told “spend four months on optimizing this”, a machine would have to be substantially rewritten to fully take advantage of being given extra time.
Rust + LLVM will already handily beat a naive bare bones C or C++ compiler that isn't loaded with sophisticated optimization tricks.
If the work is done I expect Rust to be faster than C and C++ for the same reason that C++ can sometimes be faster than C: a more advanced type system can allow better optimization in many cases.
In C++ for example you can do algorithms with templates, while in C you generally end up with function pointers all over the place. See qsort() vs. std::sort<> for one common case.
With Rust you can do all this generic stuff plus leverage better safety to do more strict aliasing optimizations, less unnecessary memory fencing, and so on.
Every now and then I check in on whether LLVM can deal with rustc spamming "noalias" on all references. You can find the latest change in [1]. While in theory this unlocks _a ton_ of optimizations, noalias is used very rarely in C/C++ code so these compiler passes are not exercised a lot by existing LLVM tests and/or not realized in full.
Rust was specifically designed so that one can ignore all the restrictions if one be confined and tell the compiler “I know better, and I know it is safe.”.
Of course, if one be wrong in such confidence, u.b. lurks around the corner.
I suppose one big problem with Rust is that it's less specified than in C what is and isn't safe, so it's harder to be so confident.
On the Rust side I think the language needs some way to annotate if's as likely/unlikely. This doesn't matter in most cases but can occasionally matter a lot in tight high performance code. It can allow the compiler to emit code that is structured so as to cause the branch predictor to usually be right, which can have a large impact.
Sadly, PGO does not work with cross-language LTO, because of conflict of LLVM module name ('Profile').
Get new friends—no, seriously. I used to think like them, and hung out with similar minds. It is gatekeeping[0] in a way that, if internalized, will blind you to opportunity.
A few things I missed because I scoffed at them for not being "pure enough":
1) The entire Javascript ecosystem
2) Bitcoin, circa 2009
3) Countless SV startup opportunities from 2001-2015
4) ML and data science (e.g. the terrible tooling)
The success I have found always came with an open mind to people's approaches, even if they were not the ones I settled on. It took me way too long to learn this, but I hope I can change a few younger people's paths.
[0] https://www.urbandictionary.com/define.php?term=Gatekeeping
I sometimes see programmers have very strange, irrational purity misgivings a particular case was someone who did not wish to fork off `grep` for some task, but actually wrote his own implementation which broke input into lines and used and manually searched for substrings; — he was initially convinced that this would be faster, or was at least “cleaner” than simply forking off `grep`, and piping to it.
The reality is that modern `grep` implementations are so optimized that writing something that was as efficient would probably exceed the complexity of his entire project.
I have never understood why many programmers seem to have an irrational dislike against forking off POSIX utilities when they target such platforms, and piping through them, which are often far more optimized than anything they've ever written.
Besides you can compile C++ to webAssembly and llvm ir. (don't know about cranelift).
Maybe that's not entirely true though, you can still generate C/C++ in the end I guess.
Well - sure. LLVM is loaded with sophisticated optimization tricks. If one compiler does sophisticated optimization tricks and the other compiler doesn't do sophisticated optimization tricks, the compiler with the sophisticated optimization tricks will be faster.
Tangent: Ten years ago or so, LLVM/Clang was touted as being head and shoulders better than GCC, the big new thing, the bees knees. Some of how it was better was obvious to everyone- readable error messages are pretty awesome. (GCC stole that idea pretty quickly) But the big thing that the LLVM/Clang people talked about was how blazingly fast compilation was compared to GCC. It was normal to take 1/10th as long to compile something. The code didn't run as fast as the code generated by GCC, maybe 50% of the performance, but that was a problem that they would eventually fix with more sophisticated optimizers. But compilation was fast!
Here we are ten years later, and LLVM/Clang generates code that runs almost as quickly as GCC. What did it cost, besides ten years of incrementally making the optimizer more and more sophisticated, a little bit better one little bit at a time? Well, it takes just as long to compile something with LLVM's sophisticated optimizer as it does to compile something with GCC's sophisticated optimizer.
The point is, there's a lot of yak shaving that will have to go into making Rust+LLVM work together better. And LLVM is already well acquainted with the barber. The low hanging fruit you're looking for has already been plucked.
In some places it's clear: LLVM's error messages were head and shoulders better than GCC's, and it was immediately obvious to everyone that GCC had to improve. And they're much better now.
But I don't believe GCC has made substantial improvements to its compilation speed since LLVM was introduced. In fact I believe it to be the opposite; as a Gentoo user I generally notice that compilation performance gets worse with every major GCC update. It's only due to hardware upgrades that compilation gets shorter.
LLVM is inherently much more modular than GCC is, which makes it a very attractive target for a language backend. It's a very large amount of work to shoehorn a language into GCC. The modular nature of LLVM is quite useful for lots of purposes, it is the back end for the syntax highlighting and error highlighting module I use in emacs. clang-format is a godsend for me, and unlike most other autoformatters, it formats based on semantics instead of syntax, which is a huge boon. The static analyzer and llvm-mca are also closely tied to the modularity of LLVM. It's not immediately obvious how one might implement these features based on GCC.
So yes, I 100% agree that LLVM is a hugely beneficial contribution to our digital society, even though it's not my first choice for a compiler.
On a PDP-11.