clang, LLVM, IR

In this post I'll show you how to download, install and use clang on Windows. Ok but, what is clang in a first place? clang is compiler front-end for C, C++ and Objective-C languages. Front-end means that it takes source code and turns it into IR. IR stands for Intermediate Representation and it's sort of byte-code that will be optimized and converted into actual machine code (e.g. .exe file) for specific platform by LLVM - the compiler back-end. IR is also assembly-like language which's files have .ll extension. clang is also a name of terminal command that we'll use to compile examples.
 
So basically it goes like this: source code > clang > IR > LLVM > exe
 

Downloading and installing

In order to install anything you have to download it first. So do this:
 
1 Go to http://releases.llvm.org and click donwload link on the left at the top of the list. This will move you to donwload website for that version of clang.
 
2 Under Pre-Built Binaries, find Clang for Windows. In my case, I used Clang for Windows (64-bit). And click it. It's downloading LLVM-4.0.0-win64.exe file.
 
3 Run this file and remember to set select option Add LLVM to the system PATH for all users.
 
4 Restart computer. Sometimes terminal do not take new PATH variable.
 
5 After installation, open terminal and type clang. You should see clang.exe: error: no input files. It means that clang is installed and ready to work with.
 

Let's make some code

Next step is to prepare two files. A HelloWorld.cpp file and Build.bat file.
 
HelloWorld.cpp

 
Build.bat

 

Build it!

Now, let's run Build.bat from terminal. As an outcome you should get couple new files:
 
HelloWorld.exe - The compiled .cpp file in form of .exe file. Run it and you'll see Hello World!
HelloWorld.ll - C++ code translated to text file that contains It's assembly-like language IR.
HelloWorld.ast - Binary file that represents Abstract Syntax Tree of HelloWorld.cpp file.
 
The first line translates .cpp file to IR language text file. Next line translates .cpp file into .ast file. And the last one takes IR source code
(.ll file) and builds .exe file from it. One of the most interesting files here is .ll. Command: clang HelloWorld.ll -o HelloWorld.exe allows me to write my own IR code and build it into fully working .exe file. That is good starting point to learn IR. That's all for today, the Hello World looks like ... this:
 
HelloWorld.ll