1193 lines · plain
1====================================2Getting Started with the LLVM System3====================================4 5.. contents::6 :local:7 8Overview9========10 11Welcome to the LLVM project!12 13The LLVM project has multiple components. The core of the project is14itself called "LLVM". This contains all of the tools, libraries, and header15files needed to process intermediate representations and convert them into16object files. Tools include an assembler, disassembler, bitcode analyzer, and17bitcode optimizer. It also contains basic regression tests.18 19C-like languages use the `Clang <https://clang.llvm.org/>`_ front end. This20component compiles C, C++, Objective-C, and Objective-C++ code into LLVM bitcode21-- and from there into object files, using LLVM.22 23Other components include:24the `libc++ C++ standard library <https://libcxx.llvm.org>`_,25the `LLD linker <https://lld.llvm.org>`_, and more.26 27.. _sources:28 29Getting the Source Code and Building LLVM30=========================================31 32#. Check out LLVM (including subprojects like Clang):33 34 * ``git clone https://github.com/llvm/llvm-project.git``35 * Or, on Windows:36 37 ``git clone --config core.autocrlf=false38 https://github.com/llvm/llvm-project.git``39 * To save storage and speed up the checkout time, you may want to do a40 `shallow clone <https://git-scm.com/docs/git-clone#Documentation/git-clone.txt---depthltdepthgt>`_.41 For example, to get the latest revision of the LLVM project, use42 43 ``git clone --depth 1 https://github.com/llvm/llvm-project.git``44 45 * You are likely not interested in the user branches in the repo (used for46 stacked pull requests and reverts), you can filter them from your47 `git fetch` (or `git pull`) with this configuration:48 49 .. code-block:: console50 51 git config --add remote.origin.fetch '^refs/heads/users/*'52 git config --add remote.origin.fetch '^refs/heads/revert-*'53 54#. Configure and build LLVM and Clang:55 56 * ``cd llvm-project``57 * ``cmake -S llvm -B build -G <generator> [options]``58 59 Some common build system generators are:60 61 * ``Ninja`` --- for generating `Ninja <https://ninja-build.org>`_62 build files. Most llvm developers use Ninja.63 * ``Unix Makefiles`` --- for generating make-compatible parallel makefiles.64 * ``Visual Studio`` --- for generating Visual Studio projects and65 solutions.66 * ``Xcode`` --- for generating Xcode projects.67 68 * See the `CMake docs69 <https://cmake.org/cmake/help/latest/manual/cmake-generators.7.html>`_70 for a more comprehensive list.71 72 Some common options:73 74 * ``-DLLVM_ENABLE_PROJECTS='...'`` --- A semicolon-separated list of the LLVM75 subprojects you'd like to additionally build. Can include any of: clang,76 clang-tools-extra, lldb, lld, polly, or cross-project-tests.77 78 For example, to build LLVM, Clang, and LLD, use79 ``-DLLVM_ENABLE_PROJECTS="clang;lld"``.80 81 * ``-DCMAKE_INSTALL_PREFIX=directory`` --- Specify for *directory* the full82 pathname of where you want the LLVM tools and libraries to be installed83 (default ``/usr/local``).84 85 * ``-DCMAKE_BUILD_TYPE=type`` --- Controls the optimization level and debug86 information of the build. Valid options for *type* are ``Debug``,87 ``Release``, ``RelWithDebInfo``, and ``MinSizeRel``. For more detailed88 information, see :ref:`CMAKE_BUILD_TYPE <cmake_build_type>`.89 90 * ``-DLLVM_ENABLE_ASSERTIONS=ON`` --- Compile with assertion checks enabled91 (default is ON for Debug builds, OFF for all other build types).92 93 * ``-DLLVM_USE_LINKER=lld`` --- Link with the `lld linker`_, assuming it94 is installed on your system. This can dramatically speed up link times95 if the default linker is slow.96 97 * ``-DLLVM_PARALLEL_{COMPILE,LINK,TABLEGEN}_JOBS=N`` --- Limit the number of98 compile/link/tablegen jobs running in parallel at the same time. This is99 especially important for linking since linking can use lots of memory. If100 you run into memory issues building LLVM, try setting this to limit the101 maximum number of compile/link/tablegen jobs running at the same time.102 103 * ``cmake --build build [--target <target>]`` or the build system specified104 above directly.105 106 * The default target (i.e. ``cmake --build build`` or ``make -C build``)107 will build all of LLVM.108 109 * The ``check-all`` target (i.e. ``ninja check-all``) will run the110 regression tests to ensure everything is in working order.111 112 * CMake will generate build targets for each tool and library, and most113 LLVM sub-projects generate their own ``check-<project>`` target.114 115 * Running a serial build will be **slow**. To improve speed, try running a116 parallel build. That's done by default in Ninja; for ``make``, use the117 option ``-j NN``, where ``NN`` is the number of parallel jobs, e.g. the118 number of available CPUs.119 120 * A basic CMake and build/test invocation which only builds LLVM and no other121 subprojects:122 123 ``cmake -S llvm -B build -G Ninja -DCMAKE_BUILD_TYPE=Debug``124 125 ``ninja -C build check-llvm``126 127 This will set up an LLVM build with debugging info, then compile LLVM and128 run LLVM tests.129 130 * For more detailed information on CMake options, see `CMake <CMake.html>`__131 132 * If you get build or test failures, see `below`_.133 134Consult the `Getting Started with LLVM`_ section for detailed information on135configuring and compiling LLVM. Go to `Directory Layout`_ to learn about the136layout of the source code tree.137 138Stand-alone Builds139------------------140 141Stand-alone builds allow you to build a sub-project against a pre-built142version of the clang or llvm libraries that is already present on your143system.144 145You can use the source code from a standard checkout of the llvm-project146(as described above) to do stand-alone builds, but you may also build147from a :ref:`sparse checkout<workflow-multicheckout-nocommit>` or from the148tarballs available on the `releases <https://github.com/llvm/llvm-project/releases/>`_149page.150 151For stand-alone builds, you must have an llvm install that is configured152properly to be consumable by stand-alone builds of the other projects.153This could be a distro-provided LLVM install, or you can build it yourself,154like this:155 156.. code-block:: console157 158 cmake -G Ninja -S path/to/llvm-project/llvm -B $builddir \159 -DLLVM_INSTALL_UTILS=ON \160 -DCMAKE_INSTALL_PREFIX=/path/to/llvm/install/prefix \161 < other options >162 163 ninja -C $builddir install164 165Once llvm is installed, to configure a project for a stand-alone build, invoke CMake like this:166 167.. code-block:: console168 169 cmake -G Ninja -S path/to/llvm-project/$subproj \170 -B $buildir_subproj \171 -DLLVM_EXTERNAL_LIT=/path/to/lit \172 -DLLVM_ROOT=/path/to/llvm/install/prefix173 174Notice that:175 176* The stand-alone build needs to happen in a folder that is not the177 original folder where LLVMN was built178 (`$builddir!=$builddir_subproj`).179* ``LLVM_ROOT`` should point to the prefix of your llvm installation,180 so for example, if llvm is installed into ``/usr/bin`` and181 ``/usr/lib64``, then you should pass ``-DLLVM_ROOT=/usr/``.182* Both the ``LLVM_ROOT`` and ``LLVM_EXTERNAL_LIT`` options are183 required to do stand-alone builds for all sub-projects. Additional184 required options for each sub-project can be found in the table185 below.186 187The ``check-$subproj`` and ``install`` build targets are supported for the188sub-projects listed in the table below.189 190============ ======================== ======================191Sub-Project Required Sub-Directories Required CMake Options192============ ======================== ======================193llvm llvm, cmake, third-party LLVM_INSTALL_UTILS=ON194clang clang, cmake CLANG_INCLUDE_TESTS=ON (Required for check-clang only)195lld lld, cmake196============ ======================== ======================197 198Example of building stand-alone `clang`:199 200.. code-block:: console201 202 #!/bin/sh203 204 build_llvm=`pwd`/build-llvm205 build_clang=`pwd`/build-clang206 installprefix=`pwd`/install207 llvm=`pwd`/llvm-project208 mkdir -p $build_llvm209 mkdir -p $installprefix210 211 cmake -G Ninja -S $llvm/llvm -B $build_llvm \212 -DLLVM_INSTALL_UTILS=ON \213 -DCMAKE_INSTALL_PREFIX=$installprefix \214 -DCMAKE_BUILD_TYPE=Release215 216 ninja -C $build_llvm install217 218 cmake -G Ninja -S $llvm/clang -B $build_clang \219 -DLLVM_EXTERNAL_LIT=$build_llvm/utils/lit \220 -DLLVM_ROOT=$installprefix221 222 ninja -C $build_clang223 224Requirements225============226 227Before you begin to use the LLVM system, review the requirements below.228This may save you some trouble by knowing ahead of time what hardware and229software you will need.230 231Hardware232--------233 234LLVM is known to work on the following host platforms:235 236================== ===================== ==============================237OS Arch Compilers238================== ===================== ==============================239Linux x86\ :sup:`1` GCC, Clang240Linux amd64 GCC, Clang241Linux ARM GCC, Clang242Linux AArch64 GCC, Clang243Linux LoongArch GCC, Clang244Linux Mips GCC, Clang245Linux PowerPC GCC, Clang246Linux RISC-V GCC, Clang247Linux SystemZ GCC, Clang248Solaris V9 (Ultrasparc) GCC249DragonFlyBSD amd64 GCC, Clang250FreeBSD x86\ :sup:`1` GCC, Clang251FreeBSD amd64 GCC, Clang252FreeBSD AArch64 GCC, Clang253NetBSD x86\ :sup:`1` GCC, Clang254NetBSD amd64 GCC, Clang255OpenBSD x86\ :sup:`1` GCC, Clang256OpenBSD amd64 GCC, Clang257macOS\ :sup:`2` PowerPC GCC258macOS x86 GCC, Clang259macOS arm64 Clang260Cygwin/Win32 x86\ :sup:`1, 3` GCC261Windows x86\ :sup:`1` Visual Studio262Windows x64 x86-64 Visual Studio, Clang\ :sup:`4`263Windows on Arm ARM64 Visual Studio, Clang\ :sup:`4`264================== ===================== ==============================265 266.. note::267 268 #. Code generation supported for Pentium processors and up269 #. Code generation supported for 32-bit ABI only270 #. To use LLVM modules on a Win32-based system, you may configure LLVM271 with ``-DBUILD_SHARED_LIBS=On``.272 #. Visual Studio alone can compile LLVM. When using Clang, you273 must also have Visual Studio installed.274 275Note that Debug builds require a lot of time and disk space. An LLVM-only build276will need about 1-3 GB of space. A full build of LLVM and Clang will need around27715-20 GB of disk space. The exact space requirements will vary by system. (It278is so large because of all the debugging information and the fact that the279libraries are statically linked into multiple tools).280 281If you are space-constrained, you can build only selected tools or only282selected targets. The Release build requires considerably less space.283 284The LLVM suite *may* compile on other platforms, but it is not guaranteed to do285so. If compilation is successful, the LLVM utilities should be able to286assemble, disassemble, analyze, and optimize LLVM bitcode. Code generation287should work as well, although the generated native code may not work on your288platform.289 290Software291--------292 293Compiling LLVM requires that you have several software packages installed. The294table below lists those required packages. The Package column is the usual name295for the software package that LLVM depends on. The Version column provides296"known to work" versions of the package. The Notes column describes how LLVM297uses the package and provides other details.298 299=========================================================== ============ ==========================================300Package Version Notes301=========================================================== ============ ==========================================302`CMake <http://cmake.org/>`_ >=3.20.0 Makefile/workspace generator303`python <http://www.python.org/>`_ >=3.8 Automated test suite\ :sup:`1`304`zlib <http://zlib.net>`_ >=1.2.3.4 Compression library\ :sup:`2`305`GNU Make <http://savannah.gnu.org/projects/make>`_ 3.79, 3.79.1 Makefile/build processor\ :sup:`3`306`PyYAML <https://pypi.org/project/PyYAML/>`_ >=5.1 Header generator\ :sup:`4`307=========================================================== ============ ==========================================308 309.. note::310 311 #. Only needed if you want to run the automated test suite in the312 ``llvm/test`` directory, or if you plan to utilize any Python libraries,313 utilities, or bindings.314 #. Optional, adds compression/uncompression capabilities to selected LLVM315 tools.316 #. Optional, you can use any other build tool supported by CMake.317 #. Only needed when building libc with New Headergen. Mainly used by libc.318 319Additionally, your compilation host is expected to have the usual plethora of320Unix utilities. Specifically:321 322* **ar** --- archive library builder323* **bzip2** --- bzip2 command for distribution generation324* **bunzip2** --- bunzip2 command for distribution checking325* **chmod** --- change permissions on a file326* **cat** --- output concatenation utility327* **cp** --- copy files328* **date** --- print the current date/time329* **echo** --- print to standard output330* **egrep** --- extended regular expression search utility331* **find** --- find files/dirs in a file system332* **grep** --- regular expression search utility333* **gzip** --- gzip command for distribution generation334* **gunzip** --- gunzip command for distribution checking335* **install** --- install directories/files336* **mkdir** --- create a directory337* **mv** --- move (rename) files338* **ranlib** --- symbol table builder for archive libraries339* **rm** --- remove (delete) files and directories340* **sed** --- stream editor for transforming output341* **sh** --- Bourne shell for make build scripts342* **tar** --- tape archive for distribution generation343* **test** --- test things in file system344* **unzip** --- unzip command for distribution checking345* **zip** --- zip command for distribution generation346 347.. _below:348.. _check here:349 350.. _host_cpp_toolchain:351 352Host C++ Toolchain, both Compiler and Standard Library353------------------------------------------------------354 355LLVM is very demanding of the host C++ compiler, and as such tends to expose356bugs in the compiler. We also attempt to follow improvements and developments in357the C++ language and library reasonably closely. As such, we require a modern358host C++ toolchain, both compiler and standard library, in order to build LLVM.359 360LLVM is written using the subset of C++ documented in :doc:`coding361standards<CodingStandards>`. To enforce this language version, we check the most362popular host toolchains for specific minimum versions in our build systems:363 364* Clang 5.0365* Apple Clang 10.0366* GCC 7.4367* Visual Studio 2019 16.8368 369Anything older than these toolchains *may* work, but will require forcing the370build system with a special option and is not really a supported host platform.371Also note that older versions of these compilers have often crashed or372miscompiled LLVM.373 374For less widely used host toolchains such as ICC or xlC, be aware that a very375recent version may be required to support all of the C++ features used in LLVM.376 377We track certain versions of software that are *known* to fail when used as378part of the host toolchain. These even include linkers at times.379 380**GNU ld 2.16.X**. Some 2.16.X versions of the ld linker will produce very long381warning messages complaining that some "``.gnu.linkonce.t.*``" symbol was382defined in a discarded section. You can safely ignore these messages as they are383erroneous and the linkage is correct. These messages disappear using ld 2.17.384 385**GNU binutils 2.17**: Binutils 2.17 contains `a bug386<http://sourceware.org/bugzilla/show_bug.cgi?id=3111>`__ which causes huge link387times (minutes instead of seconds) when building LLVM. We recommend upgrading388to a newer version (2.17.50.0.4 or later).389 390**GNU Binutils 2.19.1 Gold**: This version of Gold contained `a bug391<http://sourceware.org/bugzilla/show_bug.cgi?id=9836>`__ which causes392intermittent failures when building LLVM with position independent code. The393symptom is an error about cyclic dependencies. We recommend upgrading to a394newer version of Gold.395 396Getting a Modern Host C++ Toolchain397^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^398 399This section mostly applies to Linux and older BSDs. On macOS, you should400have a sufficiently modern Xcode, or you will likely need to upgrade until you401do. Windows does not have a "system compiler", so you must install either Visual402Studio 2019 (or later), or a recent version of mingw64. FreeBSD 10.0 and newer403have a modern Clang as the system compiler.404 405However, some Linux distributions and some other or older BSDs sometimes have406extremely old versions of GCC. These steps attempt to help you upgrade your407compiler even on such a system. However, if at all possible, we encourage you408to use a recent version of a distribution with a modern system compiler that409meets these requirements. Note that it is tempting to install a prior410version of Clang and libc++ to be the host compiler; however, libc++ was not411well tested or set up to build on Linux until relatively recently. As412a consequence, this guide suggests just using libstdc++ and a modern GCC as the413initial host in a bootstrap, and then using Clang (and potentially libc++).414 415The first step is to get a recent GCC toolchain installed. The most common416distribution on which users have struggled with the version requirements is417Ubuntu Precise, 12.04 LTS. For this distribution, one easy option is to install418the `toolchain testing PPA`_ and use it to install a modern GCC. There is419a really nice discussion of this on the `ask ubuntu stack exchange`_ and a420`github gist`_ with updated commands. However, not all users can use PPAs and421there are many other distributions, so it may be necessary (or just useful, if422you're here you *are* doing compiler development after all) to build and install423GCC from source. It is also quite easy to do these days.424 425.. _toolchain testing PPA:426 https://launchpad.net/~ubuntu-toolchain-r/+archive/test427.. _ask ubuntu stack exchange:428 https://askubuntu.com/questions/466651/how-do-i-use-the-latest-gcc-on-ubuntu/581497#58149429.. _github gist:430 https://gist.github.com/application2000/73fd6f4bf1be6600a2cf9f56315a2d91431 432Easy steps for installing a specific version of GCC:433 434.. code-block:: console435 436 % gcc_version=7.4.0437 % wget https://ftp.gnu.org/gnu/gcc/gcc-${gcc_version}/gcc-${gcc_version}.tar.bz2438 % wget https://ftp.gnu.org/gnu/gcc/gcc-${gcc_version}/gcc-${gcc_version}.tar.bz2.sig439 % wget https://ftp.gnu.org/gnu/gnu-keyring.gpg440 % signature_invalid=`gpg --verify --no-default-keyring --keyring ./gnu-keyring.gpg gcc-${gcc_version}.tar.bz2.sig`441 % if [ $signature_invalid ]; then echo "Invalid signature" ; exit 1 ; fi442 % tar -xvjf gcc-${gcc_version}.tar.bz2443 % cd gcc-${gcc_version}444 % ./contrib/download_prerequisites445 % cd ..446 % mkdir gcc-${gcc_version}-build447 % cd gcc-${gcc_version}-build448 % $PWD/../gcc-${gcc_version}/configure --prefix=$HOME/toolchains --enable-languages=c,c++449 % make -j$(nproc)450 % make install451 452For more details, check out the excellent `GCC wiki entry`_, where I got most453of this information from.454 455.. _GCC wiki entry:456 https://gcc.gnu.org/wiki/InstallingGCC457 458Once you have a GCC toolchain, configure your build of LLVM to use the new459toolchain for your host compiler and C++ standard library. Because the new460version of libstdc++ is not on the system library search path, you need to pass461extra linker flags so that it can be found at link time (``-L``) and at runtime462(``-rpath``). If you are using CMake, this invocation should produce working463binaries:464 465.. code-block:: console466 467 % mkdir build468 % cd build469 % CC=$HOME/toolchains/bin/gcc CXX=$HOME/toolchains/bin/g++ \470 cmake .. -DCMAKE_CXX_LINK_FLAGS="-Wl,-rpath,$HOME/toolchains/lib64 -L$HOME/toolchains/lib64"471 472If you fail to set rpath, most LLVM binaries will fail on startup with a message473from the loader similar to ``libstdc++.so.6: version `GLIBCXX_3.4.20' not474found``. This means you need to tweak the ``-rpath`` linker flag.475 476This method will add an absolute path to the rpath of all executables. That's477fine for local development. If you want to distribute the binaries you build478so that they can run on older systems, copy ``libstdc++.so.6`` into the479``lib/`` directory. All of LLVM's shipping binaries have an rpath pointing at480``$ORIGIN/../lib``, so they will find ``libstdc++.so.6`` there. Non-distributed481binaries don't have an rpath set and won't find ``libstdc++.so.6``. Pass482``-DLLVM_LOCAL_RPATH="$HOME/toolchains/lib64"`` to CMake to add an absolute483path to ``libstdc++.so.6`` as above. Since these binaries are not distributed,484having an absolute local path is fine for them.485 486When you build Clang, you will need to give *it* access to a modern C++487standard library in order to use it as your new host in part of a bootstrap.488There are two easy ways to do this, either build (and install) libc++ along489with Clang and then use it with the ``-stdlib=libc++`` compile and link flag,490or install Clang into the same prefix (``$HOME/toolchains`` above) as GCC.491Clang will look within its own prefix for libstdc++ and use it if found. You492can also add an explicit prefix for Clang to look in for a GCC toolchain with493the ``--gcc-toolchain=/opt/my/gcc/prefix`` flag, passing it to both compile and494link commands when using your just-built-Clang to bootstrap.495 496.. _Getting Started with LLVM:497 498Getting Started with LLVM499=========================500 501The remainder of this guide is meant to get you up and running with LLVM and to502give you some basic information about the LLVM environment.503 504The later sections of this guide describe the `general layout`_ of the LLVM505source tree, a `simple example`_ using the LLVM toolchain, and `links`_ to find506more information about LLVM or to get help via e-mail.507 508Terminology and Notation509------------------------510 511Throughout this manual, the following names are used to denote paths specific to512the local system and working environment. *These are not environment variables513you need to set but just strings used in the rest of this document below*. In514any of the examples below, simply replace each of these names with the515appropriate pathname on your local system. All these paths are absolute:516 517``SRC_ROOT``518 519 This is the top-level directory of the LLVM source tree.520 521``OBJ_ROOT``522 523 This is the top-level directory of the LLVM object tree (i.e. the tree where524 object files and compiled programs will be placed. It can be the same as525 SRC_ROOT).526 527Sending patches528^^^^^^^^^^^^^^^529 530See :ref:`Contributing <submit_patch>`.531 532Bisecting commits533^^^^^^^^^^^^^^^^^534 535See `Bisecting LLVM code <GitBisecting.html>`_ for how to use ``git bisect``536on LLVM.537 538Reverting a change539^^^^^^^^^^^^^^^^^^540 541When reverting changes using git, the default message will say "This reverts542commit XYZ". Leave this at the end of the commit message, but add some details543before it as to why the commit is being reverted. A brief explanation and/or544links to bots that demonstrate the problem are sufficient.545 546Local LLVM Configuration547------------------------548 549Once checked out repository, the LLVM suite source code must be configured550before being built. This process uses CMake. Unlike the normal ``configure``551script, CMake generates the build files in whatever format you request as well552as various ``*.inc`` files, and ``llvm/include/llvm/Config/config.h.cmake``.553 554Variables are passed to ``cmake`` on the command line using the format555``-D<variable name>=<value>``. The following variables are some common options556used by people developing LLVM.557 558* ``CMAKE_C_COMPILER``559* ``CMAKE_CXX_COMPILER``560* ``CMAKE_BUILD_TYPE``561* ``CMAKE_INSTALL_PREFIX``562* ``Python3_EXECUTABLE``563* ``LLVM_TARGETS_TO_BUILD``564* ``LLVM_ENABLE_PROJECTS``565* ``LLVM_ENABLE_RUNTIMES``566* ``LLVM_ENABLE_DOXYGEN``567* ``LLVM_ENABLE_SPHINX``568* ``LLVM_BUILD_LLVM_DYLIB``569* ``LLVM_LINK_LLVM_DYLIB``570* ``LLVM_PARALLEL_LINK_JOBS``571* ``LLVM_OPTIMIZED_TABLEGEN``572 573See :ref:`the list of frequently-used CMake variables <cmake_frequently_used_variables>`574for more information.575 576To configure LLVM, follow these steps:577 578#. Change directory into the object root directory:579 580 .. code-block:: console581 582 % cd OBJ_ROOT583 584#. Run the ``cmake``:585 586 .. code-block:: console587 588 % cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=<type> -DCMAKE_INSTALL_PREFIX=/install/path589 [other options] SRC_ROOT590 591Compiling the LLVM Suite Source Code592------------------------------------593 594Unlike with autotools, with CMake your build type is defined at configuration.595If you want to change your build type, you can re-run CMake with the following596invocation:597 598 .. code-block:: console599 600 % cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=<type> SRC_ROOT601 602Between runs, CMake preserves the values set for all options. CMake has the603following build types defined:604 605Debug606 607 These builds are the default. The build system will compile the tools and608 libraries unoptimized, with debugging information, and asserts enabled.609 610Release611 612 For these builds, the build system will compile the tools and libraries613 with optimizations enabled and not generate debug info. CMakes default614 optimization level is -O3. This can be configured by setting the615 ``CMAKE_CXX_FLAGS_RELEASE`` variable on the CMake command line.616 617RelWithDebInfo618 619 These builds are useful when debugging. They generate optimized binaries with620 debug information. CMakes default optimization level is -O2. This can be621 configured by setting the ``CMAKE_CXX_FLAGS_RELWITHDEBINFO`` variable on the622 CMake command line.623 624Once you have LLVM configured, you can build it by entering the *OBJ_ROOT*625directory and issuing the following command:626 627.. code-block:: console628 629 % make630 631If the build fails, please `check here`_ to see if you are using a version of632GCC that is known not to compile LLVM.633 634If you have multiple processors in your machine, you may wish to use some of the635parallel build options provided by GNU Make. For example, you could use the636command:637 638.. code-block:: console639 640 % make -j2641 642There are several special targets which are useful when working with the LLVM643source code:644 645``make clean``646 647 Removes all files generated by the build. This includes object files,648 generated C/C++ files, libraries, and executables.649 650``make install``651 652 Installs LLVM header files, libraries, tools, and documentation in a hierarchy653 under ``$PREFIX``, specified with ``CMAKE_INSTALL_PREFIX``, which654 defaults to ``/usr/local``.655 656``make docs-llvm-html``657 658 If configured with ``-DLLVM_ENABLE_SPHINX=On``, this will generate a directory659 at ``OBJ_ROOT/docs/html`` which contains the HTML formatted documentation.660 661Cross-Compiling LLVM662--------------------663 664It is possible to cross-compile LLVM itself. That is, you can create LLVM665executables and libraries to be hosted on a platform different from the platform666where they are built (a Canadian Cross build). To generate build files for667cross-compiling CMake provides a variable ``CMAKE_TOOLCHAIN_FILE`` which can668define compiler flags and variables used during the CMake test operations.669 670The result of such a build is executables that are not runnable on the build671host but can be executed on the target. As an example, the following CMake672invocation can generate build files targeting iOS. This will work on macOS673with the latest Xcode:674 675.. code-block:: console676 677 % cmake -G "Ninja" -DCMAKE_OSX_ARCHITECTURES="armv7;armv7s;arm64"678 -DCMAKE_TOOLCHAIN_FILE=<PATH_TO_LLVM>/cmake/platforms/iOS.cmake679 -DCMAKE_BUILD_TYPE=Release -DLLVM_BUILD_RUNTIME=Off -DLLVM_INCLUDE_TESTS=Off680 -DLLVM_INCLUDE_EXAMPLES=Off -DLLVM_ENABLE_BACKTRACES=Off [options]681 <PATH_TO_LLVM>682 683Note: There are some additional flags that need to be passed when building for684iOS due to limitations in the iOS SDK.685 686Check :doc:`HowToCrossCompileLLVM` and `Clang docs on how to cross-compile in general687<https://clang.llvm.org/docs/CrossCompilation.html>`_ for more information688about cross-compiling.689 690The Location of LLVM Object Files691---------------------------------692 693The LLVM build system is capable of sharing a single LLVM source tree among694several LLVM builds. Hence, it is possible to build LLVM for several different695platforms or configurations using the same source tree.696 697* Change directory to where the LLVM object files should live:698 699 .. code-block:: console700 701 % cd OBJ_ROOT702 703* Run ``cmake``:704 705 .. code-block:: console706 707 % cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release SRC_ROOT708 709The LLVM build will create a structure underneath *OBJ_ROOT* that matches the710LLVM source tree. At each level where source files are present in the source711tree there will be a corresponding ``CMakeFiles`` directory in the *OBJ_ROOT*.712Underneath that directory there is another directory with a name ending in713``.dir`` under which you'll find object files for each source.714 715For example:716 717 .. code-block:: console718 719 % cd llvm_build_dir720 % find lib/Support/ -name APFloat*721 lib/Support/CMakeFiles/LLVMSupport.dir/APFloat.cpp.o722 723Optional Configuration Items724----------------------------725 726If you're running on a Linux system that supports the `binfmt_misc727<http://en.wikipedia.org/wiki/binfmt_misc>`_728module, and you have root access on the system, you can set your system up to729execute LLVM bitcode files directly. To do this, use commands like this (the730first command may not be required if you are already using the module):731 732.. code-block:: console733 734 % mount -t binfmt_misc none /proc/sys/fs/binfmt_misc735 % echo ':llvm:M::BC::/path/to/lli:' > /proc/sys/fs/binfmt_misc/register736 % chmod u+x hello.bc (if needed)737 % ./hello.bc738 739This allows you to execute LLVM bitcode files directly. On Debian, you can also740use this command instead of the 'echo' command above:741 742.. code-block:: console743 744 % sudo update-binfmts --install llvm /path/to/lli --magic 'BC'745 746.. _Program Layout:747.. _general layout:748 749Directory Layout750================751 752One useful source of information about the LLVM source base is the LLVM `doxygen753<http://www.doxygen.org/>`_ documentation available at754`<https://llvm.org/doxygen/>`_. The following is a brief introduction to code755layout:756 757``llvm/cmake``758--------------759Generates system build files.760 761``llvm/cmake/modules``762 Build configuration for llvm user defined options. Checks compiler version and763 linker flags.764 765``llvm/cmake/platforms``766 Toolchain configuration for Android NDK, iOS systems and non-Windows hosts to767 target MSVC.768 769``llvm/examples``770-----------------771 772- Some simple examples showing how to use LLVM as a compiler for a custom773 language - including lowering, optimization, and code generation.774 775- Kaleidoscope Tutorial: Kaleidoscope language tutorial runs through the776 implementation of a nice little compiler for a non-trivial language777 including a hand-written lexer, parser, AST, as well as code generation778 support using LLVM- both static (ahead of time) and various approaches to779 Just In Time (JIT) compilation.780 `Kaleidoscope Tutorial for complete beginner781 <https://llvm.org/docs/tutorial/MyFirstLanguageFrontend/index.html>`_.782 783- BuildingAJIT: Examples of the `BuildingAJIT tutorial784 <https://llvm.org/docs/tutorial/BuildingAJIT1.html>`_ that shows how LLVM’s785 ORC JIT APIs interact with other parts of LLVM. It also teaches how to786 recombine them to build a custom JIT that is suited to your use-case.787 788``llvm/include``789----------------790 791Public header files exported from the LLVM library. The three main subdirectories:792 793``llvm/include/llvm``794 795 All LLVM-specific header files, and subdirectories for different portions of796 LLVM: ``Analysis``, ``CodeGen``, ``Target``, ``Transforms``, etc...797 798``llvm/include/llvm/Support``799 800 Generic support libraries provided with LLVM but not necessarily specific to801 LLVM. For example, some C++ STL utilities and a Command Line option processing802 library store header files here.803 804``llvm/include/llvm/Config``805 806 Header files configured by ``cmake``. They wrap "standard" UNIX and807 C header files. Source code can include these header files which808 automatically take care of the conditional #includes that ``cmake``809 generates.810 811``llvm/lib``812------------813 814Most source files are here. By putting code in libraries, LLVM makes it easy to815share code among the `tools`_.816 817``llvm/lib/IR/``818 819 Core LLVM source files that implement core classes like Instruction and820 BasicBlock.821 822``llvm/lib/AsmParser/``823 824 Source code for the LLVM assembly language parser library.825 826``llvm/lib/Bitcode/``827 828 Code for reading and writing bitcode.829 830``llvm/lib/Analysis/``831 832 A variety of program analyses, such as Call Graphs, Induction Variables,833 Natural Loop Identification, etc.834 835``llvm/lib/Transforms/``836 837 IR-to-IR program transformations, such as Aggressive Dead Code Elimination,838 Sparse Conditional Constant Propagation, Inlining, Loop Invariant Code Motion,839 Dead Global Elimination, and many others.840 841``llvm/lib/Target/``842 843 Files describing target architectures for code generation. For example,844 ``llvm/lib/Target/X86`` holds the X86 machine description.845 846``llvm/lib/CodeGen/``847 848 The major parts of the code generator: Instruction Selector, Instruction849 Scheduling, and Register Allocation.850 851``llvm/lib/MC/``852 853 The libraries represent and process code at machine code level. Handles854 assembly and object-file emission.855 856``llvm/lib/ExecutionEngine/``857 858 Libraries for directly executing bitcode at runtime in interpreted and859 JIT-compiled scenarios.860 861``llvm/lib/Support/``862 863 Source code that corresponds to the header files in ``llvm/include/ADT/``864 and ``llvm/include/Support/``.865 866``llvm/bindings``867----------------------868 869Contains bindings for the LLVM compiler infrastructure to allow870programs written in languages other than C or C++ to take advantage of the LLVM871infrastructure.872The LLVM project provides language bindings for OCaml and Python.873 874``llvm/projects``875-----------------876 877Projects not strictly part of LLVM but shipped with LLVM. This is also the878directory for creating your own LLVM-based projects which leverage the LLVM879build system.880 881``llvm/test``882-------------883 884Feature and regression tests and other sanity checks on LLVM infrastructure. These885are intended to run quickly and cover a lot of territory without being exhaustive.886 887``test-suite``888--------------889 890A comprehensive correctness, performance, and benchmarking test suite891for LLVM. This comes in a ``separate git repository892<https://github.com/llvm/llvm-test-suite>``, because it contains a893large amount of third-party code under a variety of licenses. For894details see the :doc:`Testing Guide <TestingGuide>` document.895 896.. _tools:897 898``llvm/tools``899--------------900 901Executables built out of the libraries902above, which form the main part of the user interface. You can always get help903for a tool by typing ``tool_name -help``. The following is a brief introduction904to the most important tools. More detailed information is in905the `Command Guide <CommandGuide/index.html>`_.906 907``bugpoint``908 909 ``bugpoint`` is used to debug optimization passes or code generation backends910 by narrowing down the given test case to the minimum number of passes and/or911 instructions that still cause a problem, whether it is a crash or912 miscompilation. See `<HowToSubmitABug.html>`_ for more information on using913 ``bugpoint``.914 915``llvm-ar``916 917 The archiver produces an archive containing the given LLVM bitcode files,918 optionally with an index for faster lookup.919 920``llvm-as``921 922 The assembler transforms the human-readable LLVM assembly to LLVM bitcode.923 924``llvm-dis``925 926 The disassembler transforms the LLVM bitcode to human-readable LLVM assembly.927 928``llvm-link``929 930 ``llvm-link``, not surprisingly, links multiple LLVM modules into a single931 program.932 933``lli``934 935 ``lli`` is the LLVM interpreter, which can directly execute LLVM bitcode936 (although very slowly...). For architectures that support it (currently x86,937 Sparc, and PowerPC), by default, ``lli`` will function as a Just-In-Time938 compiler (if the functionality was compiled in), and will execute the code939 *much* faster than the interpreter.940 941``llc``942 943 ``llc`` is the LLVM backend compiler, which translates LLVM bitcode to a944 native code assembly file.945 946``opt``947 948 ``opt`` reads LLVM bitcode, applies a series of LLVM to LLVM transformations949 (which are specified on the command line), and outputs the resultant950 bitcode. '``opt -help``' is a good way to get a list of the951 program transformations available in LLVM.952 953 ``opt`` can also run a specific analysis on an input LLVM bitcode954 file and print the results. Primarily useful for debugging955 analyses, or familiarizing yourself with what an analysis does.956 957``llvm/utils``958--------------959 960Utilities for working with LLVM source code; some are part of the build process961because they are code generators for parts of the infrastructure.962 963 964``codegen-diff``965 966 ``codegen-diff`` finds differences between code that LLC967 generates and code that LLI generates. This is useful if you are968 debugging one of them, assuming that the other generates correct output. For969 the full user manual, run ```perldoc codegen-diff'``.970 971``emacs/``972 973 Emacs and XEmacs syntax highlighting for LLVM assembly files and TableGen974 description files. See the ``README`` for information on using them.975 976``getsrcs.sh``977 978 Finds and outputs all non-generated source files,979 useful if one wishes to do a lot of development across directories980 and does not want to find each file. One way to use it is to run,981 for example: ``xemacs `utils/getsources.sh``` from the top of the LLVM source982 tree.983 984``llvmgrep``985 986 Performs an ``egrep -H -n`` on each source file in LLVM and987 passes to it a regular expression provided on ``llvmgrep``'s command988 line. This is an efficient way of searching the source base for a989 particular regular expression.990 991``TableGen/``992 993 Contains the tool used to generate register994 descriptions, instruction set descriptions, and even assemblers from common995 TableGen description files.996 997``vim/``998 999 vim syntax-highlighting for LLVM assembly files1000 and TableGen description files. See the ``README`` for how to use them.1001 1002.. _simple example:1003 1004An Example Using the LLVM Tool Chain1005====================================1006 1007This section gives an example of using LLVM with the Clang front end.1008 1009Example with clang1010------------------1011 1012#. First, create a simple C file, name it 'hello.c':1013 1014 .. code-block:: c1015 1016 #include <stdio.h>1017 1018 int main() {1019 printf("hello world\n");1020 return 0;1021 }1022 1023#. Next, compile the C file into a native executable:1024 1025 .. code-block:: console1026 1027 % clang hello.c -o hello1028 1029 .. note::1030 1031 Clang works just like GCC by default. The standard ``-S`` and ``-c`` arguments1032 work as usual (producing a native ``.s`` or ``.o`` file, respectively).1033 1034#. Next, compile the C file into an LLVM bitcode file:1035 1036 .. code-block:: console1037 1038 % clang -O3 -emit-llvm hello.c -c -o hello.bc1039 1040 The ``-emit-llvm`` option can be used with the ``-S`` or ``-c`` options to emit an LLVM1041 ``.ll`` or ``.bc`` file (respectively) for the code. This allows you to use1042 the `standard LLVM tools <CommandGuide/index.html>`_ on the bitcode file.1043 1044#. Run the program in both forms. To run the program, use:1045 1046 .. code-block:: console1047 1048 % ./hello1049 1050 and1051 1052 .. code-block:: console1053 1054 % lli hello.bc1055 1056 The second example shows how to invoke the LLVM JIT, :doc:`lli1057 <CommandGuide/lli>`.1058 1059#. Use the ``llvm-dis`` utility to take a look at the LLVM assembly code:1060 1061 .. code-block:: console1062 1063 % llvm-dis < hello.bc | less1064 1065#. Compile the program to native assembly using the LLC code generator:1066 1067 .. code-block:: console1068 1069 % llc hello.bc -o hello.s1070 1071#. Assemble the native assembly language file into a program:1072 1073 .. code-block:: console1074 1075 % /opt/SUNWspro/bin/cc -xarch=v9 hello.s -o hello.native # On Solaris1076 1077 % gcc hello.s -o hello.native # On others1078 1079#. Execute the native code program:1080 1081 .. code-block:: console1082 1083 % ./hello.native1084 1085 Note that using clang to compile directly to native code (i.e. when the1086 ``-emit-llvm`` option is not present) does steps 6/7/8 for you.1087 1088Common Problems1089===============1090 1091If you are having problems building or using LLVM, or if you have any other1092general questions about LLVM, please consult the `Frequently Asked1093Questions <FAQ.html>`_ page.1094 1095If you are having problems with limited memory and build time, please try1096building with ``ninja`` instead of ``make``. Please consider configuring the1097following options with CMake:1098 1099 * ``-G Ninja``1100 1101 Setting this option will allow you to build with ninja instead of make.1102 Building with ninja significantly improves your build time, especially with1103 incremental builds, and improves your memory usage.1104 1105 * ``-DLLVM_USE_LINKER``1106 1107 Setting this option to ``lld`` will significantly reduce linking time for LLVM1108 executables, particularly on Linux and Windows. If you are building LLVM1109 for the first time and lld is not available to you as a binary package, then1110 you may want to use the gold linker as a faster alternative to GNU ld.1111 1112 * ``-DCMAKE_BUILD_TYPE``1113 1114 Controls optimization level and debug information of the build. This setting1115 can affect RAM and disk usage, see :ref:`CMAKE_BUILD_TYPE <cmake_build_type>`1116 for more information.1117 1118 * ``-DLLVM_ENABLE_ASSERTIONS``1119 1120 This option defaults to ``ON`` for Debug builds and defaults to ``OFF`` for Release1121 builds. As mentioned in the previous option, using the Release build type and1122 enabling assertions may be a good alternative to using the Debug build type.1123 1124 * ``-DLLVM_PARALLEL_LINK_JOBS``1125 1126 Set this equal to number of jobs you wish to run simultaneously. This is1127 similar to the ``-j`` option used with ``make``, but only for link jobs. This option1128 can only be used with ninja. You may wish to use a very low number of jobs,1129 as this will greatly reduce the amount of memory used during the build1130 process. If you have limited memory, you may wish to set this to ``1``.1131 1132 * ``-DLLVM_TARGETS_TO_BUILD``1133 1134 Set this equal to the target you wish to build. You may wish to set this to1135 only your host architecture. For example ``X86`` if you are using an Intel or1136 AMD machine. You will find a full list of targets within the1137 `llvm-project/llvm/lib/Target <https://github.com/llvm/llvm-project/tree/main/llvm/lib/Target>`_1138 directory.1139 1140 * ``-DLLVM_OPTIMIZED_TABLEGEN``1141 1142 Set this to ``ON`` to generate a fully optimized TableGen compiler during your1143 build, even if that build is a ``Debug`` build. This will significantly improve1144 your build time. You should not enable this if your intention is to debug the1145 TableGen compiler.1146 1147 * ``-DLLVM_ENABLE_PROJECTS``1148 1149 Set this equal to the projects you wish to compile (e.g. ``clang``, ``lld``, etc.) If1150 compiling more than one project, separate the items with a semicolon. Should1151 you run into issues with the semicolon, try surrounding it with single quotes.1152 1153 * ``-DLLVM_ENABLE_RUNTIMES``1154 1155 Set this equal to the runtimes you wish to compile (e.g. ``libcxx``, ``libcxxabi``, etc.)1156 If compiling more than one runtime, separate the items with a semicolon. Should1157 you run into issues with the semicolon, try surrounding it with single quotes.1158 1159 * ``-DCLANG_ENABLE_STATIC_ANALYZER``1160 1161 Set this option to ``OFF`` if you do not require the clang static analyzer. This1162 should improve your build time slightly.1163 1164 * ``-DLLVM_USE_SPLIT_DWARF``1165 1166 Consider setting this to ``ON`` if you require a debug build, as this will ease1167 memory pressure on the linker. This will make linking much faster, as the1168 binaries will not contain any of the debug information. Instead, the debug1169 information is in a separate DWARF object file (with the extension ``.dwo``).1170 This only applies to host platforms using ELF, such as Linux.1171 1172 * ``-DBUILD_SHARED_LIBS``1173 1174 Setting this to ``ON`` will build shared libraries instead of static1175 libraries. This will ease memory pressure on the linker. However, this should1176 only be used when developing llvm. See1177 :ref:`BUILD_SHARED_LIBS <LLVM-related variables BUILD_SHARED_LIBS>`1178 for more information.1179 1180.. _links:1181 1182Links1183=====1184 1185This document is just an **introduction** on how to use LLVM to do some simple1186things... there are many more interesting and complicated things that you can do1187that aren't documented here (but we'll gladly accept a patch if you want to1188write something up!). For more information about LLVM, check out:1189 1190* `LLVM Homepage <https://llvm.org/>`_1191* `LLVM Doxygen Tree <https://llvm.org/doxygen/>`_1192* `Starting a Project that Uses LLVM <https://llvm.org/docs/Projects.html>`_1193