Multithreaded compilation: internal or external?

Status
Not open for further replies.

Bhelyer

Well-known member
2,231
I am writing a compiler for the D language. I also just got the CPU for my new machine; a quad-core.

These two facts got me thinking about multi-threaded builds. How are they done? I know I can multithread (well, multiprocess), say, building NetHack by using make(1)'s `-j` switch, which starts multiple jobs up and GCC has no involvement in the simultaneous compilation. How is this done in the Windows/Visual Studio world? Is it built into the compiler, or a tool external to the compiler, as with make(1)? Is there a compiler that does have this built in? Have you used it?

If you were me, what would you do? Build it in, or leave it out? Leaving it out would seem to me to duplicate work. If two modules have

Code:
import foo.bar;

then the package foo is searched for a module bar, which is then lexed, parsed, and all the public top-level declarations are pulled out for use. That only has to be done once, but if multicompilation is achieved by multiple instances of the compiler, it has to be done anew in each module.

I don't know much about concurrent programming really, or compiler writing, so I thought I'd start a discussion here -- what do you think?
 
When it comes to compilation there are tremendous amounts of parallelism possible at almost every level.

IMO, while you can achieve a ton of of parallelism by architecting things inside the compiler internally, the simplest and safest bet is to just achieve parallelism externally. Get a dependency graph of your projects, and compile those that are independent in parallel.

This approach allows you to architect your compiler incredibly simply. It can just run serially step by step all the way to the end with no trickyness.

If, on the other hand, you really want a fun challenge, definitley go for internal parallelism. There are opportunities *everywhere*. You can parse multiple files simultaneously. You can parse an individual file with multiple threads. You can build your symbol tables in parallel. You can do semantic analysis in parallel. You can emit code in parallel. You can load metadata in parallel.

The only trickyness here is ensuring that you don't introduce any race conditions or anything else that might cause problems.

While this probably isn't true for some languages, most that i'm aware of can get a near linear speedup in compilation (provided the code isn't pathological). For example, some compilers i've worked on get their parallelism by processing files in parallel. If they're given a codebase that just jams everything into one single file, then they're SOL. However, in practice, this sort of thing is pretty uncommon, so you can usually parallelize just fine.
 

Bhelyer

Well-known member
2,231
Thanks for your posts!

Wow Meta, that's... ambitious. I was just thinking of dealing which each file with a thread, and they could cooperate on public declarations. Multi-threaded parsing? My head tells me that me doing it is probably a bad idea. But it sounds fun. :)

My current parser passes around a TokenStream that was generated by lexing the module, and consumes the tokens as it parses, which would require some changes. It's tempting, but I think I'll just try thread-per-module first (well, first I'll get the damn thing working at all!), and see how it goes.
 
Bhelyer":3i21h4yc said:
Thanks for your posts!

Wow Meta, that's... ambitious. I was just thinking of dealing which each file with a thread, and they could cooperate on public declarations. Multi-threaded parsing? My head tells me that me doing it is probably a bad idea. But it sounds fun. :)
Parsing can be a rather expensive task. Here's a way you can make it multithreaded (for common code constructs). Employ a 'quick parser' and a 'full parser'. The full parser starts by doing a top down normal parse. When you get to certain types of constructs (like methods/functions/etc.) switch to the 'quick parser'. The quick parser just uses a counter to check the number of open/close braces it has seen. Increment on { and decrement on }. When you get back to 0 switch back to the full parser. You can then take that block and pass it to another instance of the 'full parser' to parse.

The idea here is that parsing a method for real is more expensive than just finding the start/end points of the method. So the top down parser finds all the method bodies and then has those bodies parsed on separate threads (since they can all be parsed independently). When these threads return, you can stitch their results back into the tree.
 
Here's some pseudo code to demonstrate what i was talking about:

Code:
TypeDeclaration ParseTypeDeclaration() {
    // initial type declaration parsing.

    var tasks = new List<Task<MemberDeclaration>>();
    while (IsMemberDeclaration()) {
       tasks.Add(StartParseMemberDeclarationTask());
    }

    // remainder of parsing task.

    return new TypeDeclaration(..., tasks.Select(t => t.Result), ...);
}

Task<MemberDeclaration> StartParseMemberDeclarationTask() {
    int startPosition = this.position;
    int endPosition = FindMemberEndPosition();

    this.position = endPosition;

    return Task.Factory.StartNew(() => ParseMemberDeclaration(startPosition, endPosition));
}

MemberDeclaration ParseMemberDeclaration(int start, int end) {
   // parse stuff.
}

This can basically happen at any level of parsing. If you autogenerate your parser you can make it spit out these constructs automatically. The important bit is that you need to be able to quickly determine where a construct ends. In C based languages, this is usually very easy to do as you can just count curlies until you reach the end (of the method, class whatever).

Some languages are even simpler than this. As long as scanning is much faster than parsing, then this approach will pay off.
 
Bhelyer":3jy6xyuv said:
Meta, you are a bad man. :p
Yes. Yes i am.
By posting psuedo-code, and describing it as 'simple', I'm going to have to try it now. ;)
Ideally, when processing all the files (and even processing large files), you should be able to saturate all cores and you should be near linear speedup over your cores. RayTracers are the ideal parallelizing task. But a close second are compilers :)
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
RayTracers are the ideal parallelizing task. But a close second are compilers :)

In your experience does the IO aspect of compilation cause serious issues or is the compilation phase normally soooo much slower than disk IO that it tends to not matter as much?

So for example does parallelising a file tend to get a close to linear speed up since you are avoiding additional concurrent IO verses the 'simple' do multiple projects at once where you start trying to bounce the read head around.

Also in your opinion should we care about the latter based on the increased use of SSD or aggressive in memory caching by the OS.

Purely from a nosy perspective, I've often wondered about those issues
 
ShuggyCoUk":112i7h93 said:
RayTracers are the ideal parallelizing task. But a close second are compilers :)

In your experience does the IO aspect of compilation cause serious issues or is the compilation phase normally soooo much slower than disk IO that it tends to not matter as much?
It causes issues, but they're not serious. The more important bit is to try to reduce contention as well as avoiding unnecessarily repetitive IO. As an obvious example. If you ahve the same DLL referenced by N projects you're compiling, you don't want to load that DLL N times.
So for example does parallelising a file tend to get a close to linear speed up since you are avoiding additional concurrent IO verses the 'simple' do multiple projects at once where you start trying to bounce the read head around.
There's almost always work to do while IO is going on. Parsing, declaration building, symbol binding, semantic analysis, emitting (which can be done to in memory buffers which flush when they get the chance), etc. etc.
Also in your opinion should we care about the latter based on the increased use of SSD or aggressive in memory caching by the OS.

Purely from a nosy perspective, I've often wondered about those issues
IO is not something you can ignore. But it's not something that kills you either.
 
Status
Not open for further replies.