### Install LLVM/Clang with Ninja Source: https://releases.llvm.org/3.6.1/docs/HowToCrossCompileLLVM.html Installs the built LLVM/Clang into the install directory, creating a sysroot. ```shell $ ninja install ``` -------------------------------- ### YAML sequence example Source: https://releases.llvm.org/3.6.1/docs/YamlIO.html Shows the basic YAML sequence syntax where each item starts with a leading dash. ```yaml # a sequence - x86 - x86_64 - PowerPC ``` -------------------------------- ### resume instruction example Source: https://releases.llvm.org/3.6.1/docs/LangRef.html Example of the 'resume' instruction resuming exception propagation with a landingpad value. ```llvm resume { i8*, i32 } %exn ``` -------------------------------- ### add instruction example Source: https://releases.llvm.org/3.6.1/docs/LangRef.html Example of the 'add' instruction summing two i32 operands. ```llvm = add i32 4, %var ; yields i32:result = 4 + %var ``` -------------------------------- ### Shell session example Source: https://releases.llvm.org/3.6.1/docs/SphinxQuickstartTemplate.html A shell session example showing two commands. Use a `console` code block for shell sessions. ```console $ echo "Goodbye cruel world!" $ rm -rf / ``` -------------------------------- ### sext instruction examples Source: https://releases.llvm.org/3.6.1/docs/LangRef.html Examples of sign-extending integers and vectors, including from i1 where result is -1 or 0. ```llvm %X = sext i8 -1 to i16 ; yields i16 :65535 %Y = sext i1 true to i32 ; yields i32:-1 %Z = sext <2 x i16> to <2 x i32> ; yields ``` -------------------------------- ### Run example through mem2reg optimization pass Source: https://releases.llvm.org/3.6.1/docs/tutorial/OCamlLangImpl7.html Runs the previous example through the mem2reg optimization pass, which promotes allocas into SSA registers and inserts Phi nodes as appropriate. The output shows the optimized IR with the phi node. ```llvm $ llvm-as < example.ll | opt -mem2reg | llvm-dis @G = weak global i32 0 @H = weak global i32 0 define i32 @test(i1 %Condition) { entry: br i1 %Condition, label %cond_true, label %cond_false cond_true: %X.0 = load i32* @G br label %cond_next cond_false: %X.1 = load i32* @H br label %cond_next cond_next: %X.01 = phi i32 [ %X.1, %cond_false ], [ %X.0, %cond_true ] ret i32 %X.01 } ``` -------------------------------- ### sub instruction example Source: https://releases.llvm.org/3.6.1/docs/LangRef.html Examples of the 'sub' instruction computing differences and negation. ```llvm = sub i32 4, %var ; yields i32:result = 4 - %var = sub i32 0, %val ; yields i32:result = -%var ``` -------------------------------- ### Example statistics output from opt -stats Source: https://releases.llvm.org/3.6.1/docs/ProgrammersManual.html Example report from running opt on a C file from the SPEC benchmark suite, showing the unified format of statistics from various passes. ```text 7646 bitcodewriter - Number of normal instructions 725 bitcodewriter - Number of oversized instructions 129996 bitcodewriter - Number of bitcode bytes written 2817 raise - Number of insts DCEd or constprop'd 3213 raise - Number of cast-of-self removed 5046 raise - Number of expression trees converted 75 raise - Number of other getelementptr's formed 138 raise - Number of load/store peepholes 42 deadtypeelim - Number of unused typenames removed from symtab 392 funcresolve - Number of varargs functions resolved 27 globaldce - Number of global variables removed 2 adce - Number of basic blocks removed 134 cee - Number of branches revectored 49 cee - Number of setcc instruction eliminated 532 gcse - Number of loads removed 2919 gcse - Number of instructions removed 86 indvars - Number of canonical indvars added 87 indvars - Number of aux indvars removed 25 instcombine - Number of dead inst eliminate 434 instcombine - Number of insts combined 248 licm - Number of load insts hoisted 1298 licm - Number of insts hoisted to a loop pre-header 3 licm - Number of insts hoisted to multiple loop preds (bad, no loop pre-header) 75 mem2reg - Number of alloca's promoted 1444 cfgsimplify - Number of blocks simplified ``` -------------------------------- ### Create hello.c Source: https://releases.llvm.org/3.6.1/docs/GettingStartedVS.html Simple C program that prints 'hello world' to standard output. Used as the input for the LLVM tool chain example. ```c #include int main() { printf("hello world\n"); return 0; } ``` -------------------------------- ### zext instruction examples Source: https://releases.llvm.org/3.6.1/docs/LangRef.html Examples of zero-extending integers and vectors, including from i1 where result is 0 or 1. ```llvm %X = zext i32 257 to i64 ; yields i64:257 %Y = zext i1 true to i32 ; yields i32:1 %Z = zext <2 x i16> to <2 x i32> ; yields ``` -------------------------------- ### Example: addr.txt input file Source: https://releases.llvm.org/3.6.1/docs/CommandGuide/llvm-symbolizer.html Input file listing object file paths and addresses, one per line, that llvm-symbolizer reads from standard input. ```text $ cat addr.txt a.out 0x4004f4 /tmp/b.out 0x400528 /tmp/c.so 0x710 /tmp/mach_universal_binary:i386 0x1f84 /tmp/mach_universal_binary:x86_64 0x100000f24 ``` -------------------------------- ### llvm.convert.from.fp16 Usage Example Source: https://releases.llvm.org/3.6.1/docs/LangRef.html Example of loading a half precision value stored as i16 and converting it to float using llvm.convert.from.fp16. ```llvm %a = load i16* @x, align 2 %res = call float @llvm.convert.from.fp16(i16 %a) ``` -------------------------------- ### LTO example: a.h, a.c, and main.c source files Source: https://releases.llvm.org/3.6.1/docs/LinkTimeOptimization.html These three source files form the LTO example. a.h declares external functions, a.c defines foo1, foo2, and static foo3, and main.c defines foo4 and main. The example shows how the linker's symbol resolution enables the optimizer to remove unused functions. ```c --- a.h --- extern int foo1(void); extern void foo2(void); extern void foo4(void); --- a.c --- #include "a.h" static signed int i = 0; void foo2(void) { i = -1; } static int foo3() { foo4(); return 10; } int foo1(void) { int data = 0; if (i < 0) data = foo3(); data = data + 42; return data; } --- main.c --- #include #include "a.h" void foo4(void) { printf("Hi\n"); } int main() { return foo1(); } ``` -------------------------------- ### bitcast instruction examples Source: https://releases.llvm.org/3.6.1/docs/LangRef.html Examples of the bitcast instruction showing conversions between integers, pointers, and vectors of the same bit size. ```llvm %X = bitcast i8 255 to i8 ; yields i8 :-1 %Y = bitcast i32* %x to sint* ; yields sint*:%x %Z = bitcast <2 x int> %V to i64; ; yields i64: %V %Z = bitcast <2 x i32*> %V to <2 x i64*> ; yields <2 x i64*> ``` -------------------------------- ### switch instruction example Source: https://releases.llvm.org/3.6.1/docs/LangRef.html Examples of using switch to emulate conditional and unconditional br instructions, and to implement a jump table with multiple cases. ```llvm ; Emulate a conditional br instruction %Val = zext i1 %value to i32 switch i32 %Val, label %truedest [ i32 0, label %falsedest ] ; Emulate an unconditional br instruction switch i32 0, label %dest [ ] ; Implement a jump table: switch i32 %val, label %otherwise [ i32 0, label %onzero i32 1, label %onone i32 2, label %ontwo ] ``` -------------------------------- ### landingpad instruction examples Source: https://releases.llvm.org/3.6.1/docs/LangRef.html Three example landingpad instructions: one that catches an integer, one that is a cleanup, and one that catches an integer and filters to only throw a double. The personality function is @__gxx_personality_v0. ```llvm ;; A landing pad which can catch an integer. %res = landingpad { i8*, i32 } personality i32 (...)* @__gxx_personality_v0 catch i8** @_ZTIi ;; A landing pad that is a cleanup. %res = landingpad { i8*, i32 } personality i32 (...)* @__gxx_personality_v0 cleanup ;; A landing pad which can catch an integer and can only throw a double. %res = landingpad { i8*, i32 } personality i32 (...)* @__gxx_personality_v0 catch i8** @_ZTIi filter [1 x i8**] [@_ZTId] ``` -------------------------------- ### Build and run commands for toy.cpp Source: https://releases.llvm.org/3.6.1/docs/tutorial/LangImpl5.html Compile the toy.cpp file with clang++ and LLVM flags, then run the resulting executable. Use these commands to build and test the Kaleidoscope example. ```bash # Compile clang++ -g toy.cpp `llvm-config --cxxflags --ldflags --system-libs --libs core mcjit native` -O3 -o toy # Run ./toy ``` -------------------------------- ### Start GDB on the opt process Source: https://releases.llvm.org/3.6.1/docs/WritingAnLLVMPass.html Starts the GNU debugger on the opt executable to debug a dynamically loaded pass. The output shows the GDB banner and prompt, indicating the process is ready for commands. Note that opt contains extensive debugging information, so startup can take time. ```text $ gdb opt GNU gdb 5.0 Copyright 2000 Free Software Foundation, Inc. GDB is free software, covered by the GNU General Public License, and you are welcome to change it and/or distribute copies of it under certain conditions. Type "show copying" to see the conditions. There is absolutely no warranty for GDB. Type "show warranty" for details. This GDB was configured as "sparc-sun-solaris2.6"... (gdb) ``` -------------------------------- ### Kaleidoscope Mandelbrot set example Source: https://releases.llvm.org/3.6.1/docs/tutorial/LangImpl6.html Example Kaleidoscope application that renders the Mandelbrot set, mentioned at the end of the chapter. ```text At the end of this tutorial, we’ll run through an example Kaleidoscope application that renders the Mandelbrot set. ``` -------------------------------- ### trunc instruction examples Source: https://releases.llvm.org/3.6.1/docs/LangRef.html Examples of truncating integers and vectors, showing results for i8 and i1 destinations. ```llvm %X = trunc i32 257 to i8 ; yields i8:1 %Y = trunc i32 123 to i1 ; yields i1:true %Z = trunc i32 122 to i1 ; yields i1:false %W = trunc <2 x i16> to <2 x i8> ; yields ``` -------------------------------- ### AST construction example for parsing 'x+y' Source: https://releases.llvm.org/3.6.1/docs/tutorial/OCamlLangImpl2.html Shows how to build an AST for the expression 'x+y' using the Variable and Binary constructors. This is a conceptual example of the parser's output. ```ocaml let x = Variable "x" in let y = Variable "y" in let result = Binary ('+', x, y) in ... ``` -------------------------------- ### br instruction example Source: https://releases.llvm.org/3.6.1/docs/LangRef.html Example of a conditional branch using icmp to compare two integers and branching to different labels, with return instructions in each block. ```llvm Test: %cond = icmp eq i32 %a, %b br i1 %cond, label %IfEqual, label %IfUnequal IfEqual: ret i32 1 IfUnequal: ret i32 0 ``` -------------------------------- ### File ID Example in C Source: https://releases.llvm.org/3.6.1/docs/CoverageMappingFormat.html Shows how file IDs enable mapping information for code defined inside macros, with code and expansion regions annotated. ```c void func(const char *str) { // Code Region from 1:28 to 6:2 with file id 0 #define PUT printf("%s\n", str) // 2 Code Regions from 2:15 to 2:34 with file ids 1 and 2 if(*str) PUT; // Expansion Region from 4:5 to 4:8 with file id 0 that expands a macro with file id 1 PUT; // Expansion Region from 5:3 to 5:6 with file id 0 that expands a macro with file id 2 } ``` -------------------------------- ### uselistorder and uselistorder_bb examples Source: https://releases.llvm.org/3.6.1/docs/LangRef.html Shows the two use-list order directives at function and global scope. The first example reorders uses of an argument and a basic block label inside a function; the second reorders uses of a global and a constant at global scope. ```llvm define void @foo(i32 %arg1, i32 %arg2) { entry: ; ... instructions ... bb: ; ... instructions ... ; At function scope. uselistorder i32 %arg1, { 1, 0, 2 } uselistorder label %bb, { 1, 0 } } ; At global scope. uselistorder i32* @global, { 1, 2, 0 } uselistorder i32 7, { 1, 0 } ``` -------------------------------- ### C source file with two functions Source: https://releases.llvm.org/3.6.1/docs/CoverageMappingFormat.html Example C file with two functions, foo and bar, used to illustrate how coverage mapping is generated. ```c int foo() { return 42; } int bar() { return 13; } ``` -------------------------------- ### LTO example: compile and link commands Source: https://releases.llvm.org/3.6.1/docs/LinkTimeOptimization.html These commands compile a.c to LLVM bitcode, main.c to native object code, and link them with a standard link command. The example requires a system linker that supports LTO through the described interface. ```shell % clang -emit-llvm -c a.c -o a.o # <-- a.o is LLVM bitcode file % clang -c main.c -o main.o # <-- main.o is native object file % clang a.o main.o -o main # <-- standard link command without modifications ``` -------------------------------- ### LLVM IR for the C example with PHI node Source: https://releases.llvm.org/3.6.1/docs/tutorial/OCamlLangImpl7.html Shows the LLVM IR that the C example compiles to, including explicit loads and a PHI node to merge the two possible values of X. ```llvm @G = weak global i32 0 ; type of @G is i32* @H = weak global i32 0 ; type of @H is i32* define i32 @test(i1 %Condition) { entry: br i1 %Condition, label %cond_true, label %cond_false cond_true: %X.0 = load i32* @G br label %cond_next cond_false: %X.1 = load i32* @H br label %cond_next cond_next: %X.2 = phi i32 [ %X.1, %cond_false ], [ %X.0, %cond_true ] ret i32 %X.2 } ``` -------------------------------- ### C source code for factorial example (showdebug.c) Source: https://releases.llvm.org/3.6.1/docs/DebuggingJITedCode.html C code with line numbers added for the example. It defines compute_factorial and main, where main reads a digit from the first command-line argument and returns the factorial result clipped at 255. ```c 1 int compute_factorial(int n) 2 { 3 if (n <= 1) 4 return 1; 5 6 int f = n; 7 while (--n > 1) 8 f *= n; 9 return f; 10 } 11 12 13 int main(int argc, char** argv) 14 { 15 if (argc < 2) 16 return -1; 17 char firstletter = argv[1][0]; 18 int result = compute_factorial(firstletter - '0'); 19 20 // Returned result is clipped at 255... 21 return result; 22 } ``` -------------------------------- ### llvm.convert.to.fp16 Usage Example Source: https://releases.llvm.org/3.6.1/docs/LangRef.html Example of converting a float to half precision and storing the resulting i16 to memory. This is part of the storage-only half precision workflow. ```llvm %res = call i16 @llvm.convert.to.fp16.f32(float %a) store i16 %res, i16* @x, align 2 ``` -------------------------------- ### Run opt with -help to list registered passes Source: https://releases.llvm.org/3.6.1/docs/WritingAnLLVMPass.html Shows the help output for the opt tool after loading the Hello pass. Use this to verify the pass was registered and to see available options. ```bash $ opt -load ../../../Debug+Asserts/lib/Hello.so -help OVERVIEW: llvm .bc -> .bc modular optimizer USAGE: opt [options] ``` -------------------------------- ### Value::use_begin Source: https://releases.llvm.org/3.6.1/docs/ProgrammersManual.html Get an iterator to the start of the use-list. ```APIDOC ## Value::use_begin ### Description Get an iterator to the start of the use-list. ### Method use_begin ### Parameters None ### Returns - **use_iterator** - Iterator to the start of the use-list. ``` -------------------------------- ### uitofp instruction example Source: https://releases.llvm.org/3.6.1/docs/LangRef.html Example of the uitofp instruction converting unsigned integers to floating point values. If the value cannot fit in the floating point type, the results are undefined. ```llvm %X = uitofp i32 257 to float ; yields float:257.0 %Y = uitofp i8 -1 to double ; yields double:255.0 ``` -------------------------------- ### Compile and run commands for toy.cpp Source: https://releases.llvm.org/3.6.1/docs/tutorial/LangImpl4.html Build the toy example with clang++ using llvm-config flags, then run the resulting binary. On Linux, add the -rdynamic option so external functions resolve properly at runtime. ```bash # Compile clang++ -g toy.cpp `llvm-config --cxxflags --ldflags --system-libs --libs core mcjit native` -O3 -o toy # Run ./toy ``` -------------------------------- ### User::op_begin Source: https://releases.llvm.org/3.6.1/docs/ProgrammersManual.html Get an iterator to the start of the operand list. ```APIDOC ## User::op_begin ### Description Get an iterator to the start of the operand list. ### Method op_begin ### Parameters None ### Returns - **op_iterator** - Iterator to the start of the operand list. ``` -------------------------------- ### C preprocessor example showing target-specific code Source: https://releases.llvm.org/3.6.1/docs/tutorial/LangImpl9.html This example shows how the C preprocessor can introduce target-specific behavior, undermining portability. It uses #ifdef __i386__ to define X as 1 on 32-bit x86 systems and 42 otherwise. ```c #ifdef __i386__ int X = 1; #else int X = 42; #endif ``` -------------------------------- ### C code block example Source: https://releases.llvm.org/3.6.1/docs/SphinxQuickstartTemplate.html A minimal C program that returns 0. Use this as a starting point for code examples in Sphinx documentation. ```c int main() { return 0; } ``` -------------------------------- ### Complete toy.cpp LLVM JIT example Source: https://releases.llvm.org/3.6.1/docs/tutorial/LangImpl4.html Full C++ source for the toy language frontend with the LLVM JIT and optimizer. Includes the lexer, parser, AST, code generation, and main driver. Build with the clang++ command shown above; on Linux add -rdynamic so external functions resolve at runtime. ```cpp #include "llvm/Analysis/Passes.h" #include "llvm/ExecutionEngine/ExecutionEngine.h" #include "llvm/ExecutionEngine/MCJIT.h" #include "llvm/ExecutionEngine/SectionMemoryManager.h" #include "llvm/IR/DataLayout.h" #include "llvm/IR/DerivedTypes.h" #include "llvm/IR/IRBuilder.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/IR/Verifier.h" #include "llvm/PassManager.h" #include "llvm/Support/TargetSelect.h" #include ``` -------------------------------- ### Close anonymous namespace Source: https://releases.llvm.org/3.6.1/docs/WritingAnLLVMPass.html Closes the anonymous namespace started earlier in the example. ```cpp } // end of anonymous namespace ``` -------------------------------- ### New comdat syntax example Source: https://releases.llvm.org/3.6.1/docs/ReleaseNotes.html Shows the new comdat syntax introduced in this release. The version without parentheses is syntactic sugar for a comdat with the same name as the global. ```llvm $c = comdat any @g = global i32 0, comdat($c) @c = global i32 0, comdat ``` -------------------------------- ### Static variables example for .apple_names Source: https://releases.llvm.org/3.6.1/docs/SourceLevelDebugging.html Example used to illustrate which static and global variables are included in the .apple_names section. Both static variables named var are included, one at file scope and one inside function f. ```c static int var = 0; void f () { static int var = 0; } ``` -------------------------------- ### Kaleidoscope 'for' loop example with putchard Source: https://releases.llvm.org/3.6.1/docs/tutorial/LangImpl5.html Defines a 'for' loop expression in Kaleidoscope that iterates a variable from a starting value while a condition holds. The example prints 100 '*' characters by calling putchard(42) inside the loop body. ```kaleidoscope extern putchard(char) def printstar(n) for i = 1, i < n, 1.0 in putchard(42); # ascii 42 = '*' # print 100 '*' characters printstar(100); ``` -------------------------------- ### Compile sample.ll with llc -load=MyGC.so Source: https://releases.llvm.org/3.6.1/docs/GarbageCollection.html Compile a sample LLVM IR file that uses the "mygc" GC attribute, then run it through llvm-as and llc with the plugin loaded via -load=MyGC.so. The plugin may have a platform-specific extension. ```shell $ cat sample.ll define void @f() gc "mygc" { entry: ret void } $ llvm-as < sample.ll | llc -load=MyGC.so ``` -------------------------------- ### LLVM 'load' instruction example Source: https://releases.llvm.org/3.6.1/docs/LangRef.html Example of loading a value from memory in LLVM IR. It allocates an i32, stores the constant 3, then loads it back into %val, which yields i32 3. ```llvm %ptr = alloca i32 ; yields i32*:ptr store i32 3, i32* %ptr ; yields void %val = load i32* %ptr ; yields i32:val = i32 3 ``` -------------------------------- ### Build gold with plugin support Source: https://releases.llvm.org/3.6.1/docs/GoldPlugin.html Download, configure, and build gold with plugin support. Requires git, make, and a C toolchain. The resulting build/gold/ld-new supports the -plugin option, and running make additionally builds build/binutils/ar and nm. ```shell $ git clone --depth 1 git://sourceware.org/git/binutils-gdb.git binutils $ mkdir build $ cd build $ ../binutils/configure --enable-gold --enable-plugins --disable-werror $ make all-gold ``` -------------------------------- ### Basic Shape class hierarchy for LLVM-style RTTI Source: https://releases.llvm.org/3.6.1/docs/HowToSetUpLLVMStyleRTTI.html Defines the Shape class used as the base for setting up LLVM-style RTTI. This is the starting point for the basic setup described in the section. ```cpp class Shape { public: Shape() {} } ``` -------------------------------- ### Set up git-svn clone for LLVM Source: https://releases.llvm.org/3.6.1/docs/GettingStarted.html Commands to clone the LLVM repository and initialize git-svn for submitting code. Includes optional setup for clang. Requires a valid SVN username. ```shell % git clone http://llvm.org/git/llvm.git % cd llvm % git svn init https://llvm.org/svn/llvm-project/llvm/trunk --username= % git config svn-remote.svn.fetch :refs/remotes/origin/master % git svn rebase -l # -l avoids fetching ahead of the git mirror. # If you have clang too: % cd tools % git clone http://llvm.org/git/clang.git % cd clang % git svn init https://llvm.org/svn/llvm-project/cfe/trunk --username= % git config svn-remote.svn.fetch :refs/remotes/origin/master % git svn rebase -l ``` -------------------------------- ### LLVM 'call' instruction example Source: https://releases.llvm.org/3.6.1/docs/LangRef.html Example of the 'call' instruction in LLVM IR, showing various forms: direct calls, tail calls, fast calling convention, signext/zeroext attributes, noreturn, and returning aggregate types via extractvalue. ```llvm %retval = call i32 @test(i32 %argc) call i32 (i8*, ...)* @printf(i8* %msg, i32 12, i8 42) ; yields i32 %X = tail call i32 @foo() ; yields i32 %Y = tail call fastcc i32 @foo() ; yields i32 call void %foo(i8 97 signext) %struct.A = type { i32, i8 } %r = call %struct.A @foo() ; yields { i32, i8 } %gr = extractvalue %struct.A %r, 0 ; yields i32 %gr1 = extractvalue %struct.A %r, 1 ; yields i8 %Z = call void @foo() noreturn ; indicates that %foo never returns normally %ZZ = call zeroext i32 @bar() ; Return value is %zero extended ``` -------------------------------- ### fadd instruction example Source: https://releases.llvm.org/3.6.1/docs/LangRef.html Example of the 'fadd' instruction summing two float operands. ```llvm = fadd float 4.0, %var ; yields float:result = 4.0 + %var ``` -------------------------------- ### llvm.fmuladd.f32 Example Call Source: https://releases.llvm.org/3.6.1/docs/LangRef.html Example call to llvm.fmuladd.f32. It is equivalent to a * b + c, but rounding may be omitted between multiplication and addition if fused. Fusion is not guaranteed; use llvm.fma.* if a fused multiply-add is required. This never sets errno. ```llvm %0 = call float @llvm.fmuladd.f32(%a, %b, %c) ``` -------------------------------- ### Example of two-space indentation (LLVM style) Source: https://releases.llvm.org/3.6.1/docs/CodingStandards.html Shown in the context of the 'Use Spaces Instead of Tabs' rule. The example illustrates the preferred two-space indentation style that should be followed when modifying or extending existing code, per the Golden Rule. ```text if (true) { // two spaces of indentation } ``` -------------------------------- ### Additional assert examples Source: https://releases.llvm.org/3.6.1/docs/CodingStandards.html More examples of assert statements with descriptive error messages for various conditions. ```cpp assert(Ty->isPointerType() && "Can't allocate a non-pointer type!"); assert((Opcode == Shl || Opcode == Shr) && "ShiftInst Opcode invalid!"); assert(idx < getNumSuccessors() && "Successor # out of range!"); assert(V1.getType() == V2.getType() && "Constant types must be identical!"); assert(isa(Succ->front()) && "Only works on PHId BBs!"); ``` -------------------------------- ### Set up code generation context and builder Source: https://releases.llvm.org/3.6.1/docs/tutorial/OCamlLangImpl3.html Sets up the code generation environment: an error exception, an LLVM context, a module named "my cool jit", an IR builder, a symbol table for named values, and the double type. These static variables are used throughout code generation. ```ocaml exception Error of string let context = global_context () let the_module = create_module context "my cool jit" let builder = builder context let named_values:(string, llvalue) Hashtbl.t = Hashtbl.create 10 let double_type = double_type context ``` -------------------------------- ### Kaleidoscope Session: Evaluating 4+5 Source: https://releases.llvm.org/3.6.1/docs/tutorial/OCamlLangImpl4.html Example session showing evaluation of a simple arithmetic expression. The JIT compiles the anonymous function and prints the result 9.0. ```text ready> 4+5; define double @""() { entry: ret double 9.000000e+00 } Evaluated to 9.000000 ``` -------------------------------- ### Check out Test Suite Source Code (optional) Source: https://releases.llvm.org/3.6.1/docs/GettingStarted.html Clones the test-suite repository into the llvm/projects directory. This step is optional. ```bash % cd llvm/projects % git clone http://llvm.org/git/test-suite.git ``` -------------------------------- ### Optimized function output example Source: https://releases.llvm.org/3.6.1/docs/tutorial/OCamlLangImpl4.html Shows the optimized LLVM IR for a test function, demonstrating that the optimizer removed a redundant floating-point add instruction. ```llvm ready> def test(x) (1+2+x)*(x+(1+2)); ready> Read function definition: define double @test(double %x) { entry: %addtmp = fadd double %x, 3.000000e+00 %multmp = fmul double %addtmp, %addtmp ret double %multmp } ``` -------------------------------- ### getelementptr examples with structs and arrays Source: https://releases.llvm.org/3.6.1/docs/LangRef.html Shows getelementptr usage with structs, arrays, and vectors, including nested indexing and different index types (i64, i16). ```llvm ; yields [12 x i8]*:aptr %aptr = getelementptr {i32, [12 x i8]}* %saptr, i64 0, i32 1 ; yields i8*:vptr %vptr = getelementptr {i32, <2 x i8>}* %svptr, i64 0, i32 1, i32 1 ; yields i8*:eptr %eptr = getelementptr [12 x i8]* %aptr, i64 0, i32 1 ; yields i32*:iptr %iptr = getelementptr [10 x i32]* @arr, i16 0, i16 0 ``` -------------------------------- ### Compile and run toy.cpp Source: https://releases.llvm.org/3.6.1/docs/tutorial/LangImpl2.html Compile the toy.cpp file with clang++ using -g and -O3 flags, then run the resulting executable a.out. ```bash # Compile clang++ -g -O3 toy.cpp # Run ./a.out ``` -------------------------------- ### indirectbr instruction example Source: https://releases.llvm.org/3.6.1/docs/LangRef.html Example of an indirectbr instruction jumping to one of three labels based on the address in %Addr. ```llvm indirectbr i8* %Addr, [ label %bb1, label %bb2, label %bb3 ] ``` -------------------------------- ### YAML mapping example Source: https://releases.llvm.org/3.6.1/docs/YamlIO.html Shows the basic YAML mapping syntax where a key ends with a colon and is followed by a value. The pound/hash symbol (#) begins a comment line. ```yaml # a mapping name: Tom hat-size: 7 ``` -------------------------------- ### JIT Function Definition and Call Source: https://releases.llvm.org/3.6.1/docs/tutorial/LangImpl4.html Example session defining a function 'testfunc' and then calling it with arguments (4,10). Shows the LLVM IR for the function definition and the top-level call, with the final evaluated result 24.000000. ```text ready> def testfunc(x y) x + y*2; Read function definition: define double @testfunc(double %x, double %y) { entry: %multmp = fmul double %y, 2.000000e+00 %addtmp = fadd double %multmp, %x ret double %addtmp } ready> testfunc(4, 10); Read top-level expression: define double @1() { entry: %calltmp = call double @testfunc(double 4.000000e+00, double 1.000000e+01) ret double %calltmp } Evaluated to 24.000000 ``` -------------------------------- ### Load a plugin with opt -load Source: https://releases.llvm.org/3.6.1/docs/CommandGuide/opt.html Shows how to load a dynamic plugin object that registers new optimization or analysis passes. Use -help together with -load to see the complete list of optimizations after loading. ```bash opt -load=plugin.so -help ``` -------------------------------- ### Doxygen member group example Source: https://releases.llvm.org/3.6.1/docs/CodingStandards.html Example of using member groups to organize related functions within a class. ```cpp class Something { /// \name Functions that do Foo. /// @{ void fooBar(); void fooBaz(); /// @} ... }; ``` -------------------------------- ### llvm-symbolizer example: input and output Source: https://releases.llvm.org/3.6.1/docs/CommandGuide/llvm-symbolizer.html Shows the input format for llvm-symbolizer: each line contains an object file path and an address. The output prints the source location for each address, including inlined functions. ```text $ cat addr.txt a.out 0x4004f4 /tmp/b.out 0x400528 /tmp/c.so 0x710 /tmp/mach_universal_binary:i386 0x1f84 /tmp/mach_universal_binary:x86_64 0x100000f24 $ llvm-symbolizer < addr.txt main /tmp/a.cc:4 f(int, int) /tmp/b.cc:11 h_inlined_into_g /tmp/header.h:2 g_inlined_into_f /tmp/header.h:7 f_inlined_into_main /tmp/source.cc:3 main /tmp/source.cc:8 _main /tmp/source_i386.cc:8 _main /tmp/source_x86_64.cc:8 ``` -------------------------------- ### Expansion Region Example in C Source: https://releases.llvm.org/3.6.1/docs/CoverageMappingFormat.html Shows a C function with a macro expansion region, which has an expanded file id to locate the mapping regions created by the expansion. ```c int func(int x) { #define MAX(x,y) ((x) > (y)? (x) : (y)) return MAX(x, 42); // Expansion Region from 3:10 to 3:13 } ``` -------------------------------- ### llvm.fmuladd.f32 Usage Example Source: https://releases.llvm.org/3.6.1/docs/LangRef.html Example usage of llvm.fmuladd.f32 with explicit float arguments. The comment indicates the result is (a * b) + c. ```llvm %r2 = call float @llvm.fmuladd.f32(float %a, float %b, float %c) ; yields float:r2 = (a * b) + c ``` -------------------------------- ### OCamlbuild tags configuration (_tags) Source: https://releases.llvm.org/3.6.1/docs/tutorial/OCamlLangImpl6.html OCamlbuild tag rules for the toy example. Configures camlp4 preprocessing for lexer/parser and links LLVM bindings for byte and native builds. ```text <{lexer,parser}.ml>: use_camlp4, pp(camlp4of) <*.{byte,native}>: g++, use_llvm, use_llvm_analysis <*.{byte,native}>: use_llvm_executionengine, use_llvm_target <*.{byte,native}>: use_llvm_scalar_opts, use_bindings ``` -------------------------------- ### inttoptr instruction examples Source: https://releases.llvm.org/3.6.1/docs/LangRef.html Examples of the inttoptr instruction showing zero extension, no-op, truncation, and vector truncation behavior. ```llvm %X = inttoptr i32 255 to i32* ; yields zero extension on 64-bit architecture %Y = inttoptr i32 255 to i32* ; yields no-op on 32-bit architecture %Z = inttoptr i64 0 to i32* ; yields truncation on 32-bit architecture %Z = inttoptr <4 x i32> %G to <4 x i8*>; yields truncation of vector G to four pointers ``` -------------------------------- ### fptrunc instruction examples Source: https://releases.llvm.org/3.6.1/docs/LangRef.html Examples of truncating double to float, showing defined and undefined results when value doesn't fit. ```llvm %X = fptrunc double 123.0 to float ; yields float:123.0 %Y = fptrunc double 1.0E+300 to float ; yields undefined ``` -------------------------------- ### noalias and alias.scope metadata example Source: https://releases.llvm.org/3.6.1/docs/LangRef.html Shows how to define scope domains, scopes, and scope lists, and how to attach !alias.scope and !noalias metadata to load/store instructions to indicate non-aliasing. The comments explain the aliasing rules for each pair. ```llvm ; Two scope domains: !0 = !{!0} !1 = !{!1} ; Some scopes in these domains: !2 = !{!2, !0} !3 = !{!3, !0} !4 = !{!4, !1} ; Some scope lists: !5 = !{!4} ; A list containing only scope !4 !6 = !{!4, !3, !2} !7 = !{!3} ; These two instructions don't alias: %0 = load float* %c, align 4, !alias.scope !5 store float %0, float* %arrayidx.i, align 4, !noalias !5 ; These two instructions also don't alias (for domain !1, the set of scopes ; in the !alias.scope equals that in the !noalias list): %2 = load float* %c, align 4, !alias.scope !5 store float %2, float* %arrayidx.i2, align 4, !noalias !6 ; These two instructions don't alias (for domain !0, the set of scopes in ; the !noalias list is not a superset of, or equal to, the scopes in the ; !alias.scope list): %2 = load float* %c, align 4, !alias.scope !6 store float %0, float* %arrayidx.i, align 4, !noalias !7 ``` -------------------------------- ### ret instruction example Source: https://releases.llvm.org/3.6.1/docs/LangRef.html Example of the ret instruction returning an integer, returning from a void function, and returning a struct value. ```llvm ret i32 5 ; Return an integer value of 5 ret void ; Return from a void function ret { i32, i8 } { i32 4, i8 2 } ; Return a struct of values 4 and 2 ``` -------------------------------- ### ptrtoint instruction examples Source: https://releases.llvm.org/3.6.1/docs/LangRef.html Examples of the ptrtoint instruction showing truncation, zero extension, and vector zero extension on a 32-bit architecture. ```llvm %X = ptrtoint i32* %P to i8 ; yields truncation on 32-bit architecture %Y = ptrtoint i32* %P to i64 ; yields zero extension on 32-bit architecture %Z = ptrtoint <4 x i32*> %P to <4 x i64>; yields vector zero extension for a vector of addresses on 32-bit architecture ``` -------------------------------- ### Main driver code for toy.ml Source: https://releases.llvm.org/3.6.1/docs/tutorial/OCamlLangImpl7.html Initializes the native target, registers binary operator precedences, primes the first token, creates the JIT execution engine and function pass manager, and configures the optimizer pipeline with data layout and memory-to-register promotion. ```ocaml (*===----------------------------------------------------------------------=== * Main driver code. *===----------------------------------------------------------------------===*) open Llvm open Llvm_executionengine open Llvm_target open Llvm_scalar_opts let main () = ignore (initialize_native_target ()); (* Install standard binary operators. * 1 is the lowest precedence. *) Hashtbl.add Parser.binop_precedence '=' 2; Hashtbl.add Parser.binop_precedence '<' 10; Hashtbl.add Parser.binop_precedence '+' 20; Hashtbl.add Parser.binop_precedence '-' 20; Hashtbl.add Parser.binop_precedence '*' 40; (* highest. *) (* Prime the first token. *) print_string ``` -------------------------------- ### Main driver with JIT and optimizer setup (toy.ml) Source: https://releases.llvm.org/3.6.1/docs/tutorial/OCamlLangImpl4.html Main driver for the Kaleidoscope compiler. Initializes the native target, sets operator precedences, creates the JIT and function pass manager, adds optimization passes (instruction combination, reassociation, GVN, CFG simplification), then runs the top-level loop and dumps the module. ```ocaml (*===----------------------------------------------------------------------=== * Main driver code. *===----------------------------------------------------------------------===*) open Llvm open Llvm_executionengine open Llvm_target open Llvm_scalar_opts let main () = ignore (initialize_native_target ()); (* Install standard binary operators. * 1 is the lowest precedence. *) Hashtbl.add Parser.binop_precedence '<' 10; Hashtbl.add Parser.binop_precedence '+' 20; Hashtbl.add Parser.binop_precedence '-' 20; Hashtbl.add Parser.binop_precedence '*' 40; (* highest. *) (* Prime the first token. *) print_string "ready> "; flush stdout; let stream = Lexer.lex (Stream.of_channel stdin) in (* Create the JIT. *) let the_execution_engine = ExecutionEngine.create Codegen.the_module in let the_fpm = PassManager.create_function Codegen.the_module in (* Set up the optimizer pipeline. Start with registering info about how the * target lays out data structures. *) DataLayout.add (ExecutionEngine.target_data the_execution_engine) the_fpm; (* Do simple "peephole" optimizations and bit-twiddling optzn. *) add_instruction_combination the_fpm; (* reassociate expressions. *) add_reassociation the_fpm; (* Eliminate Common SubExpressions. *) add_gvn the_fpm; (* Simplify the control flow graph (deleting unreachable blocks, etc). *) add_cfg_simplification the_fpm; ignore (PassManager.initialize the_fpm); (* Run the main "interpreter loop" now. *) Toplevel.main_loop the_fpm the_execution_engine stream; (* Print out all the generated code. *) dump_module Codegen.the_module ;; main () ``` -------------------------------- ### Hello World LLVM Module Example Source: https://releases.llvm.org/3.6.1/docs/LangRef.html Shows the structure of an LLVM module: a global string constant, an external declaration of the puts function, a main function definition, and named metadata. Use it to see how global variables, function declarations, and metadata are represented in LLVM IR. ```llvm ; Declare the string constant as a global constant. @.str = private unnamed_addr constant [13 x i8] c"hello world\0A\00" ; External declaration of the puts function declare i32 @puts(i8* nocapture) nounwind ; Definition of main function define i32 @main() { ; i32()* ; Convert [13 x i8]* to i8 *... %cast210 = getelementptr [13 x i8]* @.str, i64 0, i64 0 ; Call puts function to write out the string to stdout. call i32 @puts(i8* %cast210) ret i32 0 } ; Named metadata !0 = !{i32 42, null, ! ``` -------------------------------- ### cmpxchg example: atomic square-and-update loop Source: https://releases.llvm.org/3.6.1/docs/LangRef.html An LLVM IR example showing a loop that atomically squares a value using cmpxchg. It loads the initial value, computes the square, attempts the compare-and-swap, and retries on failure. The example uses acq_rel success and monotonic failure ordering. ```llvm entry: %orig = atomic load i32* %ptr unordered ; yields i32 br label %loop loop: %cmp = phi i32 [ %orig, %entry ], [%old, %loop] %squared = mul i32 %cmp, %cmp %val_success = cmpxchg i32* %ptr, i32 %cmp, i32 %squared acq_rel monotonic ; yields { i32, i1 } %value_loaded = extractvalue { i32, i1 } %val_success, 0 %success = extractvalue { i32, i1 } %val_success, 1 br i1 %success, label %done, label %loop done: ... ``` -------------------------------- ### LLVMBuild library component example Source: https://releases.llvm.org/3.6.1/docs/LLVMBuild.html A typical LLVMBuild component description for a library component. It defines the required properties type, name, and parent, and lists required libraries. ```ini [component_0] type = Library name = Linker parent = Libraries required_libraries = Archive BitReader Core Support TransformUtils ``` -------------------------------- ### Correct Doxygen comment placement Source: https://releases.llvm.org/3.6.1/docs/CodingStandards.html Correct example: documentation comments for public APIs go in the header, implementation files can include additional non-Doxygen comments. ```cpp // In Something.h: /// \brief An abstraction for some complicated thing. class Something { public: /// \brief Does foo and bar. void fooBar(); }; // In Something.cpp: // Builds a B-tree in order to do foo. See paper by... void Something::fooBar() { ... } ``` -------------------------------- ### Check out the LLVM test-suite module with svn Source: https://releases.llvm.org/3.6.1/docs/TestSuiteMakefileGuide.html Use this command to fetch the test-suite module into llvm/projects/test-suite. Run it from the llvm/projects directory in the source tree before configuring and building LLVM. ```shell % svn co http://llvm.org/svn/llvm-project/test-suite/trunk test-suite ``` -------------------------------- ### Example of 'No rule to make target' error Source: https://releases.llvm.org/3.6.1/docs/FAQ.html Example error message when a Makefile dependency is missing after files are moved or removed in Subversion. ```makefile gmake[2]: *** No rule to make target `/path/to/somefile', needed by `/path/to/another/file.d'. Stop. ```