1===================== 2LLVM Coding Standards 3===================== 4 5.. contents:: 6 :local: 7 8Introduction 9============ 10 11This document describes coding standards that are used in the LLVM project. 12Although no coding standards should be regarded as absolute requirements to be 13followed in all instances, coding standards are 14particularly important for large-scale code bases that follow a library-based 15design (like LLVM). 16 17While this document may provide guidance for some mechanical formatting issues, 18whitespace, or other "microscopic details", these are not fixed standards. 19Always follow the golden rule: 20 21.. _Golden Rule: 22 23 **If you are extending, enhancing, or bug fixing already implemented code, 24 use the style that is already being used so that the source is uniform and 25 easy to follow.** 26 27Note that some code bases (e.g. ``libc++``) have special reasons to deviate 28from the coding standards. For example, in the case of ``libc++``, this is 29because the naming and other conventions are dictated by the C++ standard. 30 31There are some conventions that are not uniformly followed in the code base 32(e.g. the naming convention). This is because they are relatively new, and a 33lot of code was written before they were put in place. Our long term goal is 34for the entire codebase to follow the convention, but we explicitly *do not* 35want patches that do large-scale reformatting of existing code. On the other 36hand, it is reasonable to rename the methods of a class if you're about to 37change it in some other way. Please commit such changes separately to 38make code review easier. 39 40The ultimate goal of these guidelines is to increase the readability and 41maintainability of our common source base. 42 43Languages, Libraries, and Standards 44=================================== 45 46Most source code in LLVM and other LLVM projects using these coding standards 47is C++ code. There are some places where C code is used either due to 48environment restrictions, historical restrictions, or due to third-party source 49code imported into the tree. Generally, our preference is for standards 50conforming, modern, and portable C++ code as the implementation language of 51choice. 52 53For automation, build-systems and utility scripts Python is preferred and 54is widely used in the LLVM repository already. 55 56C++ Standard Versions 57--------------------- 58 59Unless otherwise documented, LLVM subprojects are written using standard C++17 60code and avoid unnecessary vendor-specific extensions. 61 62Nevertheless, we restrict ourselves to features which are available in the 63major toolchains supported as host compilers (see :doc:`GettingStarted` page, 64section `Software`). 65 66Each toolchain provides a good reference for what it accepts: 67 68* Clang: https://clang.llvm.org/cxx_status.html 69 70 * libc++: https://libcxx.llvm.org/Status/Cxx17.html 71 72* GCC: https://gcc.gnu.org/projects/cxx-status.html#cxx17 73 74 * libstdc++: https://gcc.gnu.org/onlinedocs/libstdc++/manual/status.html#status.iso.2017 75 76* MSVC: https://learn.microsoft.com/cpp/overview/visual-cpp-language-conformance 77 78Additionally, there are compiler comparison tables of supported C++ features on 79`cppreference.com <https://en.cppreference.com/w/cpp/compiler_support/17>`_. 80 81 82C++ Standard Library 83-------------------- 84 85Instead of implementing custom data structures, we encourage the use of C++ 86standard library facilities or LLVM support libraries whenever they are 87available for a particular task. LLVM and related projects emphasize and rely 88on the standard library facilities and the LLVM support libraries as much as 89possible. 90 91LLVM support libraries (for example, `ADT 92<https://github.com/llvm/llvm-project/tree/main/llvm/include/llvm/ADT>`_) 93implement specialized data structures or functionality missing in the standard 94library. Such libraries are usually implemented in the ``llvm`` namespace and 95follow the expected standard interface, when there is one. 96 97When both C++ and the LLVM support libraries provide similar functionality, and 98there isn't a specific reason to favor the C++ implementation, it is generally 99preferable to use the LLVM library. For example, ``llvm::DenseMap`` should 100almost always be used instead of ``std::map`` or ``std::unordered_map``, and 101``llvm::SmallVector`` should usually be used instead of ``std::vector``. 102 103We explicitly avoid some standard facilities, like the I/O streams, and instead 104use LLVM's streams library (raw_ostream_). More detailed information on these 105subjects is available in the :doc:`ProgrammersManual`. 106 107For more information about LLVM's data structures and the tradeoffs they make, 108please consult `that section of the programmer's manual 109<https://llvm.org/docs/ProgrammersManual.html#picking-the-right-data-structure-for-a-task>`_. 110 111Python version and Source Code Formatting 112----------------------------------------- 113 114The current minimum version of Python required is documented in the :doc:`GettingStarted` 115section. Python code in the LLVM repository should only use language features 116available in this version of Python. 117 118The Python code within the LLVM repository should adhere to the formatting guidelines 119outlined in `PEP 8 <https://peps.python.org/pep-0008/>`_. 120 121For consistency and to limit churn, code should be automatically formatted with 122the `black <https://github.com/psf/black>`_ utility, which is PEP 8 compliant. 123Use its default rules. For example, avoid specifying ``--line-length`` even 124though it does not default to 80. The default rules can change between major 125versions of black. In order to avoid unnecessary churn in the formatting rules, 126we currently use black version 23.x in LLVM. 127 128When contributing a patch unrelated to formatting, you should format only the 129Python code that the patch modifies. For this purpose, use the `darker 130<https://pypi.org/project/darker/>`_ utility, which runs default black rules 131over only the modified Python code. Doing so should ensure the patch will pass 132the Python format checks in LLVM's pre-commit CI, which also uses darker. When 133contributing a patch specifically for reformatting Python files, use black, 134which currently only supports formatting entire files. 135 136Here are some quick examples, but see the black and darker documentation for 137details: 138 139.. code-block:: bash 140 141 $ pip install black=='23.*' darker # install black 23.x and darker 142 $ darker test.py # format uncommitted changes 143 $ darker -r HEAD^ test.py # also format changes from last commit 144 $ black test.py # format entire file 145 146Instead of individual file names, you can specify directories to 147darker, and it will find the changed files. However, if a directory is 148large, like a clone of the LLVM repository, darker can be painfully 149slow. In that case, you might wish to use git to list changed files. 150For example: 151 152.. code-block:: bash 153 154 $ darker -r HEAD^ $(git diff --name-only --diff-filter=d HEAD^) 155 156Mechanical Source Issues 157======================== 158 159Source Code Formatting 160---------------------- 161 162Commenting 163^^^^^^^^^^ 164 165Comments are important for readability and maintainability. When writing comments, 166write them as English prose, using proper capitalization, punctuation, etc. 167Aim to describe what the code is trying to do and why, not *how* it does it at 168a micro level. Here are a few important things to document: 169 170.. _header file comment: 171 172File Headers 173"""""""""""" 174 175Every source file should have a header on it that describes the basic purpose of 176the file. The standard header looks like this: 177 178.. code-block:: c++ 179 180 //===----------------------------------------------------------------------===// 181 // 182 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 183 // See https://llvm.org/LICENSE.txt for license information. 184 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 185 // 186 //===----------------------------------------------------------------------===// 187 /// 188 /// \file 189 /// This file contains the declaration of the Instruction class, which is the 190 /// base class for all of the VM instructions. 191 /// 192 //===----------------------------------------------------------------------===// 193 194The first section in the file is a concise note that defines the license that the 195file is released under. This makes it perfectly clear what terms the source 196code can be distributed under and should not be modified in any way. 197 198The main body is a `Doxygen <http://www.doxygen.nl/>`_ comment (identified by 199the ``///`` comment marker instead of the usual ``//``) describing the purpose 200of the file. The first sentence (or a passage beginning with ``\brief``) is 201used as an abstract. Any additional information should be separated by a blank 202line. If an algorithm is based on a paper or is described in another source, 203provide a reference. 204 205Header Guard 206"""""""""""" 207 208The header file's guard should be the all-caps path that a user of this header 209would #include, using '_' instead of path separator and extension marker. 210For example, the header file 211``llvm/include/llvm/Analysis/Utils/Local.h`` would be ``#include``-ed as 212``#include "llvm/Analysis/Utils/Local.h"``, so its guard is 213``LLVM_ANALYSIS_UTILS_LOCAL_H``. 214 215Class overviews 216""""""""""""""" 217 218Classes are a fundamental part of an object-oriented design. As such, a 219class definition should have a comment block that explains what the class is 220used for and how it works. Every non-trivial class is expected to have a 221``doxygen`` comment block. 222 223Method information 224"""""""""""""""""" 225 226Methods and global functions should also be documented. A quick note about 227what it does and a description of the edge cases is all that is necessary here. 228The reader should be able to understand how to use interfaces without reading 229the code itself. 230 231Good things to talk about here are what happens when something unexpected 232happens, for instance, does the method return null? 233 234Comment Formatting 235^^^^^^^^^^^^^^^^^^ 236 237In general, prefer C++-style comments (``//`` for normal comments, ``///`` for 238``doxygen`` documentation comments). There are a few cases when it is 239useful to use C-style (``/* */``) comments however: 240 241#. When writing C code to be compatible with C89. 242 243#. When writing a header file that may be ``#include``\d by a C source file. 244 245#. When writing a source file that is used by a tool that only accepts C-style 246 comments. 247 248#. When documenting the significance of constants used as actual parameters in 249 a call. This is most helpful for ``bool`` parameters, or passing ``0`` or 250 ``nullptr``. The comment should contain the parameter name, which ought to be 251 meaningful. For example, it's not clear what the parameter means in this call: 252 253 .. code-block:: c++ 254 255 Object.emitName(nullptr); 256 257 An in-line C-style comment makes the intent obvious: 258 259 .. code-block:: c++ 260 261 Object.emitName(/*Prefix=*/nullptr); 262 263Commenting out large blocks of code is discouraged, but if you really have to do 264this (for documentation purposes or as a suggestion for debug printing), use 265``#if 0`` and ``#endif``. These nest properly and are better behaved in general 266than C style comments. 267 268Doxygen Use in Documentation Comments 269^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 270 271Use the ``\file`` command to turn the standard file header into a file-level 272comment. 273 274Include descriptive paragraphs for all public interfaces (public classes, 275member and non-member functions). Avoid restating the information that can 276be inferred from the API name. The first sentence (or a paragraph beginning 277with ``\brief``) is used as an abstract. Try to use a single sentence as the 278``\brief`` adds visual clutter. Put detailed discussion into separate 279paragraphs. 280 281To refer to parameter names inside a paragraph, use the ``\p name`` command. 282Don't use the ``\arg name`` command since it starts a new paragraph that 283contains documentation for the parameter. 284 285Wrap non-inline code examples in ``\code ... \endcode``. 286 287To document a function parameter, start a new paragraph with the 288``\param name`` command. If the parameter is used as an out or an in/out 289parameter, use the ``\param [out] name`` or ``\param [in,out] name`` command, 290respectively. 291 292To describe function return value, start a new paragraph with the ``\returns`` 293command. 294 295A minimal documentation comment: 296 297.. code-block:: c++ 298 299 /// Sets the xyzzy property to \p Baz. 300 void setXyzzy(bool Baz); 301 302A documentation comment that uses all Doxygen features in a preferred way: 303 304.. code-block:: c++ 305 306 /// Does foo and bar. 307 /// 308 /// Does not do foo the usual way if \p Baz is true. 309 /// 310 /// Typical usage: 311 /// \code 312 /// fooBar(false, "quux", Res); 313 /// \endcode 314 /// 315 /// \param Quux kind of foo to do. 316 /// \param [out] Result filled with bar sequence on foo success. 317 /// 318 /// \returns true on success. 319 bool fooBar(bool Baz, StringRef Quux, std::vector<int> &Result); 320 321Don't duplicate the documentation comment in the header file and in the 322implementation file. Put the documentation comments for public APIs into the 323header file. Documentation comments for private APIs can go to the 324implementation file. In any case, implementation files can include additional 325comments (not necessarily in Doxygen markup) to explain implementation details 326as needed. 327 328Don't duplicate function or class name at the beginning of the comment. 329For humans it is obvious which function or class is being documented; 330automatic documentation processing tools are smart enough to bind the comment 331to the correct declaration. 332 333Avoid: 334 335.. code-block:: c++ 336 337 // Example.h: 338 339 // example - Does something important. 340 void example(); 341 342 // Example.cpp: 343 344 // example - Does something important. 345 void example() { ... } 346 347Preferred: 348 349.. code-block:: c++ 350 351 // Example.h: 352 353 /// Does something important. 354 void example(); 355 356 // Example.cpp: 357 358 /// Builds a B-tree in order to do foo. See paper by... 359 void example() { ... } 360 361Error and Warning Messages 362^^^^^^^^^^^^^^^^^^^^^^^^^^ 363 364Clear diagnostic messages are important to help users identify and fix issues in 365their inputs. Use succinct but correct English prose that gives the user the 366context needed to understand what went wrong. Also, to match error message 367styles commonly produced by other tools, start the first sentence with a 368lower-case letter, and finish the last sentence without a period, if it would 369end in one otherwise. Sentences which end with different punctuation, such as 370"did you forget ';'?", should still do so. 371 372For example this is a good error message: 373 374.. code-block:: none 375 376 error: file.o: section header 3 is corrupt. Size is 10 when it should be 20 377 378This is a bad message, since it does not provide useful information and uses the 379wrong style: 380 381.. code-block:: none 382 383 error: file.o: Corrupt section header. 384 385As with other coding standards, individual projects, such as the Clang Static 386Analyzer, may have preexisting styles that do not conform to this. If a 387different formatting scheme is used consistently throughout the project, use 388that style instead. Otherwise, this standard applies to all LLVM tools, 389including clang, clang-tidy, and so on. 390 391If the tool or project does not have existing functions to emit warnings or 392errors, use the error and warning handlers provided in ``Support/WithColor.h`` 393to ensure they are printed in the appropriate style, rather than printing to 394stderr directly. 395 396When using ``report_fatal_error``, follow the same standards for the message as 397regular error messages. Assertion messages and ``llvm_unreachable`` calls do not 398necessarily need to follow these same styles as they are automatically 399formatted, and thus these guidelines may not be suitable. 400 401``#include`` Style 402^^^^^^^^^^^^^^^^^^ 403 404Immediately after the `header file comment`_ (and include guards if working on a 405header file), the `minimal list of #includes`_ required by the file should be 406listed. We prefer these ``#include``\s to be listed in this order: 407 408.. _Main Module Header: 409.. _Local/Private Headers: 410 411#. Main Module Header 412#. Local/Private Headers 413#. LLVM project/subproject headers (``clang/...``, ``lldb/...``, ``llvm/...``, etc) 414#. System ``#include``\s 415 416and each category should be sorted lexicographically by the full path. 417 418The `Main Module Header`_ file applies to ``.cpp`` files which implement an 419interface defined by a ``.h`` file. This ``#include`` should always be included 420**first** regardless of where it lives on the file system. By including a 421header file first in the ``.cpp`` files that implement the interfaces, we ensure 422that the header does not have any hidden dependencies which are not explicitly 423``#include``\d in the header, but should be. It is also a form of documentation 424in the ``.cpp`` file to indicate where the interfaces it implements are defined. 425 426LLVM project and subproject headers should be grouped from most specific to least 427specific, for the same reasons described above. For example, LLDB depends on 428both clang and LLVM, and clang depends on LLVM. So an LLDB source file should 429include ``lldb`` headers first, followed by ``clang`` headers, followed by 430``llvm`` headers, to reduce the possibility (for example) of an LLDB header 431accidentally picking up a missing include due to the previous inclusion of that 432header in the main source file or some earlier header file. clang should 433similarly include its own headers before including llvm headers. This rule 434applies to all LLVM subprojects. 435 436.. _fit into 80 columns: 437 438Source Code Width 439^^^^^^^^^^^^^^^^^ 440 441Write your code to fit within 80 columns. 442 443There must be some limit to the width of the code in 444order to allow developers to have multiple files side-by-side in 445windows on a modest display. If you are going to pick a width limit, it is 446somewhat arbitrary but you might as well pick something standard. Going with 90 447columns (for example) instead of 80 columns wouldn't add any significant value 448and would be detrimental to printing out code. Also many other projects have 449standardized on 80 columns, so some people have already configured their editors 450for it (vs something else, like 90 columns). 451 452Whitespace 453^^^^^^^^^^ 454 455In all cases, prefer spaces to tabs in source files. People have different 456preferred indentation levels, and different styles of indentation that they 457like; this is fine. What isn't fine is that different editors/viewers expand 458tabs out to different tab stops. This can cause your code to look completely 459unreadable, and it is not worth dealing with. 460 461As always, follow the `Golden Rule`_ above: follow the style of existing code 462if you are modifying and extending it. 463 464Do not add trailing whitespace. Some common editors will automatically remove 465trailing whitespace when saving a file which causes unrelated changes to appear 466in diffs and commits. 467 468Format Lambdas Like Blocks Of Code 469"""""""""""""""""""""""""""""""""" 470 471When formatting a multi-line lambda, format it like a block of code. If there 472is only one multi-line lambda in a statement, and there are no expressions 473lexically after it in the statement, drop the indent to the standard two space 474indent for a block of code, as if it were an if-block opened by the preceding 475part of the statement: 476 477.. code-block:: c++ 478 479 std::sort(foo.begin(), foo.end(), [&](Foo a, Foo b) -> bool { 480 if (a.blah < b.blah) 481 return true; 482 if (a.baz < b.baz) 483 return true; 484 return a.bam < b.bam; 485 }); 486 487To take best advantage of this formatting, if you are designing an API which 488accepts a continuation or single callable argument (be it a function object, or 489a ``std::function``), it should be the last argument if at all possible. 490 491If there are multiple multi-line lambdas in a statement, or additional 492parameters after the lambda, indent the block two spaces from the indent of the 493``[]``: 494 495.. code-block:: c++ 496 497 dyn_switch(V->stripPointerCasts(), 498 [] (PHINode *PN) { 499 // process phis... 500 }, 501 [] (SelectInst *SI) { 502 // process selects... 503 }, 504 [] (LoadInst *LI) { 505 // process loads... 506 }, 507 [] (AllocaInst *AI) { 508 // process allocas... 509 }); 510 511Braced Initializer Lists 512"""""""""""""""""""""""" 513 514Starting from C++11, there are significantly more uses of braced lists to 515perform initialization. For example, they can be used to construct aggregate 516temporaries in expressions. They now have a natural way of ending up nested 517within each other and within function calls in order to build up aggregates 518(such as option structs) from local variables. 519 520The historically common formatting of braced initialization of aggregate 521variables does not mix cleanly with deep nesting, general expression contexts, 522function arguments, and lambdas. We suggest new code use a simple rule for 523formatting braced initialization lists: act as-if the braces were parentheses 524in a function call. The formatting rules exactly match those already well 525understood for formatting nested function calls. Examples: 526 527.. code-block:: c++ 528 529 foo({a, b, c}, {1, 2, 3}); 530 531 llvm::Constant *Mask[] = { 532 llvm::ConstantInt::get(llvm::Type::getInt32Ty(getLLVMContext()), 0), 533 llvm::ConstantInt::get(llvm::Type::getInt32Ty(getLLVMContext()), 1), 534 llvm::ConstantInt::get(llvm::Type::getInt32Ty(getLLVMContext()), 2)}; 535 536This formatting scheme also makes it particularly easy to get predictable, 537consistent, and automatic formatting with tools like `Clang Format`_. 538 539.. _Clang Format: https://clang.llvm.org/docs/ClangFormat.html 540 541Language and Compiler Issues 542---------------------------- 543 544Treat Compiler Warnings Like Errors 545^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 546 547Compiler warnings are often useful and help improve the code. Those that are 548not useful, can be often suppressed with a small code change. For example, an 549assignment in the ``if`` condition is often a typo: 550 551.. code-block:: c++ 552 553 if (V = getValue()) { 554 ... 555 } 556 557Several compilers will print a warning for the code above. It can be suppressed 558by adding parentheses: 559 560.. code-block:: c++ 561 562 if ((V = getValue())) { 563 ... 564 } 565 566Write Portable Code 567^^^^^^^^^^^^^^^^^^^ 568 569In almost all cases, it is possible to write completely portable code. When 570you need to rely on non-portable code, put it behind a well-defined and 571well-documented interface. 572 573Do not use RTTI or Exceptions 574^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 575 576In an effort to reduce code and executable size, LLVM does not use exceptions 577or RTTI (`runtime type information 578<https://en.wikipedia.org/wiki/Run-time_type_information>`_, for example, 579``dynamic_cast<>``). 580 581That said, LLVM does make extensive use of a hand-rolled form of RTTI that use 582templates like :ref:`isa\<>, cast\<>, and dyn_cast\<> <isa>`. 583This form of RTTI is opt-in and can be 584:doc:`added to any class <HowToSetUpLLVMStyleRTTI>`. 585 586Prefer C++-style casts 587^^^^^^^^^^^^^^^^^^^^^^ 588 589When casting, use ``static_cast``, ``reinterpret_cast``, and ``const_cast``, 590rather than C-style casts. There are two exceptions to this: 591 592* When casting to ``void`` to suppress warnings about unused variables (as an 593 alternative to ``[[maybe_unused]]``). Prefer C-style casts in this instance. 594 595* When casting between integral types (including enums that are not strongly- 596 typed), functional-style casts are permitted as an alternative to 597 ``static_cast``. 598 599.. _static constructor: 600 601Do not use Static Constructors 602^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 603 604Static constructors and destructors (e.g., global variables whose types have a 605constructor or destructor) should not be added to the code base, and should be 606removed wherever possible. 607 608Globals in different source files are initialized in `arbitrary order 609<https://yosefk.com/c++fqa/ctors.html#fqa-10.12>`_, making the code more 610difficult to reason about. 611 612Static constructors have negative impact on launch time of programs that use 613LLVM as a library. We would really like for there to be zero cost for linking 614in an additional LLVM target or other library into an application, but static 615constructors undermine this goal. 616 617Use of ``class`` and ``struct`` Keywords 618^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 619 620In C++, the ``class`` and ``struct`` keywords can be used almost 621interchangeably. The only difference is when they are used to declare a class: 622``class`` makes all members private by default while ``struct`` makes all 623members public by default. 624 625* All declarations and definitions of a given ``class`` or ``struct`` must use 626 the same keyword. For example: 627 628.. code-block:: c++ 629 630 // Avoid if `Example` is defined as a struct. 631 class Example; 632 633 // OK. 634 struct Example; 635 636 struct Example { ... }; 637 638* ``struct`` should be used when *all* members are declared public. 639 640.. code-block:: c++ 641 642 // Avoid using `struct` here, use `class` instead. 643 struct Foo { 644 private: 645 int Data; 646 public: 647 Foo() : Data(0) { } 648 int getData() const { return Data; } 649 void setData(int D) { Data = D; } 650 }; 651 652 // OK to use `struct`: all members are public. 653 struct Bar { 654 int Data; 655 Bar() : Data(0) { } 656 }; 657 658Do not use Braced Initializer Lists to Call a Constructor 659^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 660 661Starting from C++11 there is a "generalized initialization syntax" which allows 662calling constructors using braced initializer lists. Do not use these to call 663constructors with non-trivial logic or if you care that you're calling some 664*particular* constructor. Those should look like function calls using 665parentheses rather than like aggregate initialization. Similarly, if you need 666to explicitly name the type and call its constructor to create a temporary, 667don't use a braced initializer list. Instead, use a braced initializer list 668(without any type for temporaries) when doing aggregate initialization or 669something notionally equivalent. Examples: 670 671.. code-block:: c++ 672 673 class Foo { 674 public: 675 // Construct a Foo by reading data from the disk in the whizbang format, ... 676 Foo(std::string filename); 677 678 // Construct a Foo by looking up the Nth element of some global data ... 679 Foo(int N); 680 681 // ... 682 }; 683 684 // The Foo constructor call is reading a file, don't use braces to call it. 685 std::fill(foo.begin(), foo.end(), Foo("name")); 686 687 // The pair is being constructed like an aggregate, use braces. 688 bar_map.insert({my_key, my_value}); 689 690If you use a braced initializer list when initializing a variable, use an equals before the open curly brace: 691 692.. code-block:: c++ 693 694 int data[] = {0, 1, 2, 3}; 695 696Use ``auto`` Type Deduction to Make Code More Readable 697^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 698 699Some are advocating a policy of "almost always ``auto``" in C++11, however LLVM 700uses a more moderate stance. Use ``auto`` if and only if it makes the code more 701readable or easier to maintain. Don't "almost always" use ``auto``, but do use 702``auto`` with initializers like ``cast<Foo>(...)`` or other places where the 703type is already obvious from the context. Another time when ``auto`` works well 704for these purposes is when the type would have been abstracted away anyways, 705often behind a container's typedef such as ``std::vector<T>::iterator``. 706 707Similarly, C++14 adds generic lambda expressions where parameter types can be 708``auto``. Use these where you would have used a template. 709 710Beware unnecessary copies with ``auto`` 711^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 712 713The convenience of ``auto`` makes it easy to forget that its default behavior 714is a copy. Particularly in range-based ``for`` loops, careless copies are 715expensive. 716 717Use ``auto &`` for values and ``auto *`` for pointers unless you need to make a 718copy. 719 720.. code-block:: c++ 721 722 // Typically there's no reason to copy. 723 for (const auto &Val : Container) observe(Val); 724 for (auto &Val : Container) Val.change(); 725 726 // Remove the reference if you really want a new copy. 727 for (auto Val : Container) { Val.change(); saveSomewhere(Val); } 728 729 // Copy pointers, but make it clear that they're pointers. 730 for (const auto *Ptr : Container) observe(*Ptr); 731 for (auto *Ptr : Container) Ptr->change(); 732 733Beware of non-determinism due to ordering of pointers 734^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 735 736In general, there is no relative ordering among pointers. As a result, 737when unordered containers like sets and maps are used with pointer keys 738the iteration order is undefined. Hence, iterating such containers may 739result in non-deterministic code generation. While the generated code 740might work correctly, non-determinism can make it harder to reproduce bugs and 741debug the compiler. 742 743In case an ordered result is expected, remember to 744sort an unordered container before iteration. Or use ordered containers 745like ``vector``/``MapVector``/``SetVector`` if you want to iterate pointer 746keys. 747 748Beware of non-deterministic sorting order of equal elements 749^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 750 751``std::sort`` uses a non-stable sorting algorithm in which the order of equal 752elements is not guaranteed to be preserved. Thus using ``std::sort`` for a 753container having equal elements may result in non-deterministic behavior. 754To uncover such instances of non-determinism, LLVM has introduced a new 755llvm::sort wrapper function. For an EXPENSIVE_CHECKS build this will randomly 756shuffle the container before sorting. Default to using ``llvm::sort`` instead 757of ``std::sort``. 758 759Style Issues 760============ 761 762The High-Level Issues 763--------------------- 764 765Self-contained Headers 766^^^^^^^^^^^^^^^^^^^^^^ 767 768Header files should be self-contained (compile on their own) and end in ``.h``. 769Non-header files that are meant for inclusion should end in ``.inc`` and be 770used sparingly. 771 772All header files should be self-contained. Users and refactoring tools should 773not have to adhere to special conditions to include the header. Specifically, a 774header should have header guards and include all other headers it needs. 775 776There are rare cases where a file designed to be included is not 777self-contained. These are typically intended to be included at unusual 778locations, such as the middle of another file. They might not use header 779guards, and might not include their prerequisites. Name such files with the 780.inc extension. Use sparingly, and prefer self-contained headers when possible. 781 782In general, a header should be implemented by one or more ``.cpp`` files. Each 783of these ``.cpp`` files should include the header that defines their interface 784first. This ensures that all of the dependences of the header have been 785properly added to the header itself, and are not implicit. System headers 786should be included after user headers for a translation unit. 787 788Library Layering 789^^^^^^^^^^^^^^^^ 790 791A directory of header files (for example ``include/llvm/Foo``) defines a 792library (``Foo``). One library (both 793its headers and implementation) should only use things from the libraries 794listed in its dependencies. 795 796Some of this constraint can be enforced by classic Unix linkers (Mac & Windows 797linkers, as well as lld, do not enforce this constraint). A Unix linker 798searches left to right through the libraries specified on its command line and 799never revisits a library. In this way, no circular dependencies between 800libraries can exist. 801 802This doesn't fully enforce all inter-library dependencies, and importantly 803doesn't enforce header file circular dependencies created by inline functions. 804A good way to answer the "is this layered correctly" would be to consider 805whether a Unix linker would succeed at linking the program if all inline 806functions were defined out-of-line. (& for all valid orderings of dependencies 807- since linking resolution is linear, it's possible that some implicit 808dependencies can sneak through: A depends on B and C, so valid orderings are 809"C B A" or "B C A", in both cases the explicit dependencies come before their 810use. But in the first case, B could still link successfully if it implicitly 811depended on C, or the opposite in the second case) 812 813.. _minimal list of #includes: 814 815``#include`` as Little as Possible 816^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 817 818``#include`` hurts compile time performance. Don't do it unless you have to, 819especially in header files. 820 821But wait! Sometimes you need to have the definition of a class to use it, or to 822inherit from it. In these cases go ahead and ``#include`` that header file. Be 823aware however that there are many cases where you don't need to have the full 824definition of a class. If you are using a pointer or reference to a class, you 825don't need the header file. If you are simply returning a class instance from a 826prototyped function or method, you don't need it. In fact, for most cases, you 827simply don't need the definition of a class. And not ``#include``\ing speeds up 828compilation. 829 830It is easy to try to go too overboard on this recommendation, however. You 831**must** include all of the header files that you are using --- you can include 832them either directly or indirectly through another header file. To make sure 833that you don't accidentally forget to include a header file in your module 834header, make sure to include your module header **first** in the implementation 835file (as mentioned above). This way there won't be any hidden dependencies that 836you'll find out about later. 837 838Keep "Internal" Headers Private 839^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 840 841Many modules have a complex implementation that causes them to use more than one 842implementation (``.cpp``) file. It is often tempting to put the internal 843communication interface (helper classes, extra functions, etc) in the public 844module header file. Don't do this! 845 846If you really need to do something like this, put a private header file in the 847same directory as the source files, and include it locally. This ensures that 848your private interface remains private and undisturbed by outsiders. 849 850.. note:: 851 852 It's okay to put extra implementation methods in a public class itself. Just 853 make them private (or protected) and all is well. 854 855Use Namespace Qualifiers to Implement Previously Declared Functions 856^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 857 858When providing an out of line implementation of a function in a source file, do 859not open namespace blocks in the source file. Instead, use namespace qualifiers 860to help ensure that your definition matches an existing declaration. Do this: 861 862.. code-block:: c++ 863 864 // Foo.h 865 namespace llvm { 866 int foo(const char *s); 867 } 868 869 // Foo.cpp 870 #include "Foo.h" 871 using namespace llvm; 872 int llvm::foo(const char *s) { 873 // ... 874 } 875 876Doing this helps to avoid bugs where the definition does not match the 877declaration from the header. For example, the following C++ code defines a new 878overload of ``llvm::foo`` instead of providing a definition for the existing 879function declared in the header: 880 881.. code-block:: c++ 882 883 // Foo.cpp 884 #include "Foo.h" 885 namespace llvm { 886 int foo(char *s) { // Mismatch between "const char *" and "char *" 887 } 888 } // namespace llvm 889 890This error will not be caught until the build is nearly complete, when the 891linker fails to find a definition for any uses of the original function. If the 892function were instead defined with a namespace qualifier, the error would have 893been caught immediately when the definition was compiled. 894 895Class method implementations must already name the class and new overloads 896cannot be introduced out of line, so this recommendation does not apply to them. 897 898.. _early exits: 899 900Use Early Exits and ``continue`` to Simplify Code 901^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 902 903When reading code, keep in mind how much state and how many previous decisions 904have to be remembered by the reader to understand a block of code. Aim to 905reduce indentation where possible when it doesn't make it more difficult to 906understand the code. One great way to do this is by making use of early exits 907and the ``continue`` keyword in long loops. Consider this code that does not 908use an early exit: 909 910.. code-block:: c++ 911 912 Value *doSomething(Instruction *I) { 913 if (!I->isTerminator() && 914 I->hasOneUse() && doOtherThing(I)) { 915 ... some long code .... 916 } 917 918 return 0; 919 } 920 921This code has several problems if the body of the ``'if'`` is large. When 922you're looking at the top of the function, it isn't immediately clear that this 923*only* does interesting things with non-terminator instructions, and only 924applies to things with the other predicates. Second, it is relatively difficult 925to describe (in comments) why these predicates are important because the ``if`` 926statement makes it difficult to lay out the comments. Third, when you're deep 927within the body of the code, it is indented an extra level. Finally, when 928reading the top of the function, it isn't clear what the result is if the 929predicate isn't true; you have to read to the end of the function to know that 930it returns null. 931 932It is much preferred to format the code like this: 933 934.. code-block:: c++ 935 936 Value *doSomething(Instruction *I) { 937 // Terminators never need 'something' done to them because ... 938 if (I->isTerminator()) 939 return 0; 940 941 // We conservatively avoid transforming instructions with multiple uses 942 // because goats like cheese. 943 if (!I->hasOneUse()) 944 return 0; 945 946 // This is really just here for example. 947 if (!doOtherThing(I)) 948 return 0; 949 950 ... some long code .... 951 } 952 953This fixes these problems. A similar problem frequently happens in ``for`` 954loops. A silly example is something like this: 955 956.. code-block:: c++ 957 958 for (Instruction &I : BB) { 959 if (auto *BO = dyn_cast<BinaryOperator>(&I)) { 960 Value *LHS = BO->getOperand(0); 961 Value *RHS = BO->getOperand(1); 962 if (LHS != RHS) { 963 ... 964 } 965 } 966 } 967 968When you have very, very small loops, this sort of structure is fine. But if it 969exceeds more than 10-15 lines, it becomes difficult for people to read and 970understand at a glance. The problem with this sort of code is that it gets very 971nested very quickly. Meaning that the reader of the code has to keep a lot of 972context in their brain to remember what is going immediately on in the loop, 973because they don't know if/when the ``if`` conditions will have ``else``\s etc. 974It is strongly preferred to structure the loop like this: 975 976.. code-block:: c++ 977 978 for (Instruction &I : BB) { 979 auto *BO = dyn_cast<BinaryOperator>(&I); 980 if (!BO) continue; 981 982 Value *LHS = BO->getOperand(0); 983 Value *RHS = BO->getOperand(1); 984 if (LHS == RHS) continue; 985 986 ... 987 } 988 989This has all the benefits of using early exits for functions: it reduces nesting 990of the loop, it makes it easier to describe why the conditions are true, and it 991makes it obvious to the reader that there is no ``else`` coming up that they 992have to push context into their brain for. If a loop is large, this can be a 993big understandability win. 994 995Don't use ``else`` after a ``return`` 996^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 997 998For similar reasons as above (reduction of indentation and easier reading), please 999do not use ``'else'`` or ``'else if'`` after something that interrupts control 1000flow --- like ``return``, ``break``, ``continue``, ``goto``, etc. For example: 1001 1002.. code-block:: c++ 1003 1004 case 'J': { 1005 if (Signed) { 1006 Type = Context.getsigjmp_bufType(); 1007 if (Type.isNull()) { 1008 Error = ASTContext::GE_Missing_sigjmp_buf; 1009 return QualType(); 1010 } else { 1011 break; // Unnecessary. 1012 } 1013 } else { 1014 Type = Context.getjmp_bufType(); 1015 if (Type.isNull()) { 1016 Error = ASTContext::GE_Missing_jmp_buf; 1017 return QualType(); 1018 } else { 1019 break; // Unnecessary. 1020 } 1021 } 1022 } 1023 1024It is better to write it like this: 1025 1026.. code-block:: c++ 1027 1028 case 'J': 1029 if (Signed) { 1030 Type = Context.getsigjmp_bufType(); 1031 if (Type.isNull()) { 1032 Error = ASTContext::GE_Missing_sigjmp_buf; 1033 return QualType(); 1034 } 1035 } else { 1036 Type = Context.getjmp_bufType(); 1037 if (Type.isNull()) { 1038 Error = ASTContext::GE_Missing_jmp_buf; 1039 return QualType(); 1040 } 1041 } 1042 break; 1043 1044Or better yet (in this case) as: 1045 1046.. code-block:: c++ 1047 1048 case 'J': 1049 if (Signed) 1050 Type = Context.getsigjmp_bufType(); 1051 else 1052 Type = Context.getjmp_bufType(); 1053 1054 if (Type.isNull()) { 1055 Error = Signed ? ASTContext::GE_Missing_sigjmp_buf : 1056 ASTContext::GE_Missing_jmp_buf; 1057 return QualType(); 1058 } 1059 break; 1060 1061The idea is to reduce indentation and the amount of code you have to keep track 1062of when reading the code. 1063 1064Note: this advice does not apply to a ``constexpr if`` statement. The 1065substatement of the ``else`` clause may be a discarded statement, so removing 1066the ``else`` can cause unexpected template instantiations. Thus, the following 1067example is correct: 1068 1069.. code-block:: c++ 1070 1071 template<typename T> 1072 static constexpr bool VarTempl = true; 1073 1074 template<typename T> 1075 int func() { 1076 if constexpr (VarTempl<T>) 1077 return 1; 1078 else 1079 static_assert(!VarTempl<T>); 1080 } 1081 1082Turn Predicate Loops into Predicate Functions 1083^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1084 1085It is very common to write small loops that just compute a boolean value. There 1086are a number of ways that people commonly write these, but an example of this 1087sort of thing is: 1088 1089.. code-block:: c++ 1090 1091 bool FoundFoo = false; 1092 for (unsigned I = 0, E = BarList.size(); I != E; ++I) 1093 if (BarList[I]->isFoo()) { 1094 FoundFoo = true; 1095 break; 1096 } 1097 1098 if (FoundFoo) { 1099 ... 1100 } 1101 1102Instead of this sort of loop, we prefer to use a predicate function (which may 1103be `static`_) that uses `early exits`_: 1104 1105.. code-block:: c++ 1106 1107 /// \returns true if the specified list has an element that is a foo. 1108 static bool containsFoo(const std::vector<Bar*> &List) { 1109 for (unsigned I = 0, E = List.size(); I != E; ++I) 1110 if (List[I]->isFoo()) 1111 return true; 1112 return false; 1113 } 1114 ... 1115 1116 if (containsFoo(BarList)) { 1117 ... 1118 } 1119 1120There are many reasons for doing this: it reduces indentation and factors out 1121code which can often be shared by other code that checks for the same predicate. 1122More importantly, it *forces you to pick a name* for the function, and forces 1123you to write a comment for it. In this silly example, this doesn't add much 1124value. However, if the condition is complex, this can make it a lot easier for 1125the reader to understand the code that queries for this predicate. Instead of 1126being faced with the in-line details of how we check to see if the BarList 1127contains a foo, we can trust the function name and continue reading with better 1128locality. 1129 1130The Low-Level Issues 1131-------------------- 1132 1133Name Types, Functions, Variables, and Enumerators Properly 1134^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1135 1136Poorly-chosen names can mislead the reader and cause bugs. We cannot stress 1137enough how important it is to use *descriptive* names. Pick names that match 1138the semantics and role of the underlying entities, within reason. Avoid 1139abbreviations unless they are well known. After picking a good name, make sure 1140to use consistent capitalization for the name, as inconsistency requires clients 1141to either memorize the APIs or to look it up to find the exact spelling. 1142 1143In general, names should be in camel case (e.g. ``TextFileReader`` and 1144``isLValue()``). Different kinds of declarations have different rules: 1145 1146* **Type names** (including classes, structs, enums, typedefs, etc) should be 1147 nouns and start with an upper-case letter (e.g. ``TextFileReader``). 1148 1149* **Variable names** should be nouns (as they represent state). The name should 1150 be camel case, and start with an upper case letter (e.g. ``Leader`` or 1151 ``Boats``). 1152 1153* **Function names** should be verb phrases (as they represent actions), and 1154 command-like function should be imperative. The name should be camel case, 1155 and start with a lower case letter (e.g. ``openFile()`` or ``isFoo()``). 1156 1157* **Enum declarations** (e.g. ``enum Foo {...}``) are types, so they should 1158 follow the naming conventions for types. A common use for enums is as a 1159 discriminator for a union, or an indicator of a subclass. When an enum is 1160 used for something like this, it should have a ``Kind`` suffix 1161 (e.g. ``ValueKind``). 1162 1163* **Enumerators** (e.g. ``enum { Foo, Bar }``) and **public member variables** 1164 should start with an upper-case letter, just like types. Unless the 1165 enumerators are defined in their own small namespace or inside a class, 1166 enumerators should have a prefix corresponding to the enum declaration name. 1167 For example, ``enum ValueKind { ... };`` may contain enumerators like 1168 ``VK_Argument``, ``VK_BasicBlock``, etc. Enumerators that are just 1169 convenience constants are exempt from the requirement for a prefix. For 1170 instance: 1171 1172 .. code-block:: c++ 1173 1174 enum { 1175 MaxSize = 42, 1176 Density = 12 1177 }; 1178 1179As an exception, classes that mimic STL classes can have member names in STL's 1180style of lower-case words separated by underscores (e.g. ``begin()``, 1181``push_back()``, and ``empty()``). Classes that provide multiple 1182iterators should add a singular prefix to ``begin()`` and ``end()`` 1183(e.g. ``global_begin()`` and ``use_begin()``). 1184 1185Here are some examples: 1186 1187.. code-block:: c++ 1188 1189 class VehicleMaker { 1190 ... 1191 Factory<Tire> F; // Avoid: a non-descriptive abbreviation. 1192 Factory<Tire> Factory; // Better: more descriptive. 1193 Factory<Tire> TireFactory; // Even better: if VehicleMaker has more than one 1194 // kind of factories. 1195 }; 1196 1197 Vehicle makeVehicle(VehicleType Type) { 1198 VehicleMaker M; // Might be OK if scope is small. 1199 Tire Tmp1 = M.makeTire(); // Avoid: 'Tmp1' provides no information. 1200 Light Headlight = M.makeLight("head"); // Good: descriptive. 1201 ... 1202 } 1203 1204Assert Liberally 1205^^^^^^^^^^^^^^^^ 1206 1207Use the "``assert``" macro to its fullest. Check all of your preconditions and 1208assumptions, you never know when a bug (not necessarily even yours) might be 1209caught early by an assertion, which reduces debugging time dramatically. The 1210"``<cassert>``" header file is probably already included by the header files you 1211are using, so it doesn't cost anything to use it. 1212 1213To further assist with debugging, make sure to put some kind of error message in 1214the assertion statement, which is printed if the assertion is tripped. This 1215helps the poor debugger make sense of why an assertion is being made and 1216enforced, and hopefully what to do about it. Here is one complete example: 1217 1218.. code-block:: c++ 1219 1220 inline Value *getOperand(unsigned I) { 1221 assert(I < Operands.size() && "getOperand() out of range!"); 1222 return Operands[I]; 1223 } 1224 1225Here are more examples: 1226 1227.. code-block:: c++ 1228 1229 assert(Ty->isPointerType() && "Can't allocate a non-pointer type!"); 1230 1231 assert((Opcode == Shl || Opcode == Shr) && "ShiftInst Opcode invalid!"); 1232 1233 assert(idx < getNumSuccessors() && "Successor # out of range!"); 1234 1235 assert(V1.getType() == V2.getType() && "Constant types must be identical!"); 1236 1237 assert(isa<PHINode>(Succ->front()) && "Only works on PHId BBs!"); 1238 1239You get the idea. 1240 1241In the past, asserts were used to indicate a piece of code that should not be 1242reached. These were typically of the form: 1243 1244.. code-block:: c++ 1245 1246 assert(0 && "Invalid radix for integer literal"); 1247 1248This has a few issues, the main one being that some compilers might not 1249understand the assertion, or warn about a missing return in builds where 1250assertions are compiled out. 1251 1252Today, we have something much better: ``llvm_unreachable``: 1253 1254.. code-block:: c++ 1255 1256 llvm_unreachable("Invalid radix for integer literal"); 1257 1258When assertions are enabled, this will print the message if it's ever reached 1259and then exit the program. When assertions are disabled (i.e. in release 1260builds), ``llvm_unreachable`` becomes a hint to compilers to skip generating 1261code for this branch. If the compiler does not support this, it will fall back 1262to the "abort" implementation. 1263 1264Use ``llvm_unreachable`` to mark a specific point in code that should never be 1265reached. This is especially desirable for addressing warnings about unreachable 1266branches, etc., but can be used whenever reaching a particular code path is 1267unconditionally a bug (not originating from user input; see below) of some kind. 1268Use of ``assert`` should always include a testable predicate (as opposed to 1269``assert(false)``). 1270 1271If the error condition can be triggered by user input then the 1272recoverable error mechanism described in :doc:`ProgrammersManual` should be 1273used instead. In cases where this is not practical, ``report_fatal_error`` may 1274be used. 1275 1276Another issue is that values used only by assertions will produce an "unused 1277value" warning when assertions are disabled. For example, this code will warn: 1278 1279.. code-block:: c++ 1280 1281 unsigned Size = V.size(); 1282 assert(Size > 42 && "Vector smaller than it should be"); 1283 1284 bool NewToSet = Myset.insert(Value); 1285 assert(NewToSet && "The value shouldn't be in the set yet"); 1286 1287These are two interesting different cases. In the first case, the call to 1288``V.size()`` is only useful for the assert, and we don't want it executed when 1289assertions are disabled. Code like this should move the call into the assert 1290itself. In the second case, the side effects of the call must happen whether 1291the assert is enabled or not. In this case, the value should be cast to void to 1292disable the warning. To be specific, it is preferred to write the code like 1293this: 1294 1295.. code-block:: c++ 1296 1297 assert(V.size() > 42 && "Vector smaller than it should be"); 1298 1299 bool NewToSet = Myset.insert(Value); (void)NewToSet; 1300 assert(NewToSet && "The value shouldn't be in the set yet"); 1301 1302Do Not Use ``using namespace std`` 1303^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1304 1305In LLVM, we prefer to explicitly prefix all identifiers from the standard 1306namespace with an "``std::``" prefix, rather than rely on "``using namespace 1307std;``". 1308 1309In header files, adding a ``'using namespace XXX'`` directive pollutes the 1310namespace of any source file that ``#include``\s the header, creating 1311maintenance issues. 1312 1313In implementation files (e.g. ``.cpp`` files), the rule is more of a stylistic 1314rule, but is still important. Basically, using explicit namespace prefixes 1315makes the code **clearer**, because it is immediately obvious what facilities 1316are being used and where they are coming from. And **more portable**, because 1317namespace clashes cannot occur between LLVM code and other namespaces. The 1318portability rule is important because different standard library implementations 1319expose different symbols (potentially ones they shouldn't), and future revisions 1320to the C++ standard will add more symbols to the ``std`` namespace. As such, we 1321never use ``'using namespace std;'`` in LLVM. 1322 1323The exception to the general rule (i.e. it's not an exception for the ``std`` 1324namespace) is for implementation files. For example, all of the code in the 1325LLVM project implements code that lives in the 'llvm' namespace. As such, it is 1326ok, and actually clearer, for the ``.cpp`` files to have a ``'using namespace 1327llvm;'`` directive at the top, after the ``#include``\s. This reduces 1328indentation in the body of the file for source editors that indent based on 1329braces, and keeps the conceptual context cleaner. The general form of this rule 1330is that any ``.cpp`` file that implements code in any namespace may use that 1331namespace (and its parents'), but should not use any others. 1332 1333Provide a Virtual Method Anchor for Classes in Headers 1334^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1335 1336If a class is defined in a header file and has a vtable (either it has virtual 1337methods or it derives from classes with virtual methods), it must always have at 1338least one out-of-line virtual method in the class. Without this, the compiler 1339will copy the vtable and RTTI into every ``.o`` file that ``#include``\s the 1340header, bloating ``.o`` file sizes and increasing link times. 1341 1342Don't use default labels in fully covered switches over enumerations 1343^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1344 1345``-Wswitch`` warns if a switch, without a default label, over an enumeration 1346does not cover every enumeration value. If you write a default label on a fully 1347covered switch over an enumeration then the ``-Wswitch`` warning won't fire 1348when new elements are added to that enumeration. To help avoid adding these 1349kinds of defaults, Clang has the warning ``-Wcovered-switch-default`` which is 1350off by default but turned on when building LLVM with a version of Clang that 1351supports the warning. 1352 1353A knock-on effect of this stylistic requirement is that when building LLVM with 1354GCC you may get warnings related to "control may reach end of non-void function" 1355if you return from each case of a covered switch-over-enum because GCC assumes 1356that the enum expression may take any representable value, not just those of 1357individual enumerators. To suppress this warning, use ``llvm_unreachable`` after 1358the switch. 1359 1360Use range-based ``for`` loops wherever possible 1361^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1362 1363The introduction of range-based ``for`` loops in C++11 means that explicit 1364manipulation of iterators is rarely necessary. We use range-based ``for`` 1365loops wherever possible for all newly added code. For example: 1366 1367.. code-block:: c++ 1368 1369 BasicBlock *BB = ... 1370 for (Instruction &I : *BB) 1371 ... use I ... 1372 1373Usage of ``std::for_each()``/``llvm::for_each()`` functions is discouraged, 1374unless the callable object already exists. 1375 1376Don't evaluate ``end()`` every time through a loop 1377^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1378 1379In cases where range-based ``for`` loops can't be used and it is necessary 1380to write an explicit iterator-based loop, pay close attention to whether 1381``end()`` is re-evaluated on each loop iteration. One common mistake is to 1382write a loop in this style: 1383 1384.. code-block:: c++ 1385 1386 BasicBlock *BB = ... 1387 for (auto I = BB->begin(); I != BB->end(); ++I) 1388 ... use I ... 1389 1390The problem with this construct is that it evaluates "``BB->end()``" every time 1391through the loop. Instead of writing the loop like this, we strongly prefer 1392loops to be written so that they evaluate it once before the loop starts. A 1393convenient way to do this is like so: 1394 1395.. code-block:: c++ 1396 1397 BasicBlock *BB = ... 1398 for (auto I = BB->begin(), E = BB->end(); I != E; ++I) 1399 ... use I ... 1400 1401The observant may quickly point out that these two loops may have different 1402semantics: if the container (a basic block in this case) is being mutated, then 1403"``BB->end()``" may change its value every time through the loop and the second 1404loop may not in fact be correct. If you actually do depend on this behavior, 1405please write the loop in the first form and add a comment indicating that you 1406did it intentionally. 1407 1408Why do we prefer the second form (when correct)? Writing the loop in the first 1409form has two problems. First it may be less efficient than evaluating it at the 1410start of the loop. In this case, the cost is probably minor --- a few extra 1411loads every time through the loop. However, if the base expression is more 1412complex, then the cost can rise quickly. I've seen loops where the end 1413expression was actually something like: "``SomeMap[X]->end()``" and map lookups 1414really aren't cheap. By writing it in the second form consistently, you 1415eliminate the issue entirely and don't even have to think about it. 1416 1417The second (even bigger) issue is that writing the loop in the first form hints 1418to the reader that the loop is mutating the container (a fact that a comment 1419would handily confirm!). If you write the loop in the second form, it is 1420immediately obvious without even looking at the body of the loop that the 1421container isn't being modified, which makes it easier to read the code and 1422understand what it does. 1423 1424While the second form of the loop is a few extra keystrokes, we do strongly 1425prefer it. 1426 1427``#include <iostream>`` is Forbidden 1428^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1429 1430The use of ``#include <iostream>`` in library files is hereby **forbidden**, 1431because many common implementations transparently inject a `static constructor`_ 1432into every translation unit that includes it. 1433 1434Note that using the other stream headers (``<sstream>`` for example) is not 1435problematic in this regard --- just ``<iostream>``. However, ``raw_ostream`` 1436provides various APIs that are better performing for almost every use than 1437``std::ostream`` style APIs. 1438 1439.. note:: 1440 1441 New code should always use `raw_ostream`_ for writing, or the 1442 ``llvm::MemoryBuffer`` API for reading files. 1443 1444.. _raw_ostream: 1445 1446Use ``raw_ostream`` 1447^^^^^^^^^^^^^^^^^^^ 1448 1449LLVM includes a lightweight, simple, and efficient stream implementation in 1450``llvm/Support/raw_ostream.h``, which provides all of the common features of 1451``std::ostream``. All new code should use ``raw_ostream`` instead of 1452``ostream``. 1453 1454Unlike ``std::ostream``, ``raw_ostream`` is not a template and can be forward 1455declared as ``class raw_ostream``. Public headers should generally not include 1456the ``raw_ostream`` header, but use forward declarations and constant references 1457to ``raw_ostream`` instances. 1458 1459Avoid ``std::endl`` 1460^^^^^^^^^^^^^^^^^^^ 1461 1462The ``std::endl`` modifier, when used with ``iostreams`` outputs a newline to 1463the output stream specified. In addition to doing this, however, it also 1464flushes the output stream. In other words, these are equivalent: 1465 1466.. code-block:: c++ 1467 1468 std::cout << std::endl; 1469 std::cout << '\n' << std::flush; 1470 1471Most of the time, you probably have no reason to flush the output stream, so 1472it's better to use a literal ``'\n'``. 1473 1474Don't use ``inline`` when defining a function in a class definition 1475^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1476 1477A member function defined in a class definition is implicitly inline, so don't 1478put the ``inline`` keyword in this case. 1479 1480Don't: 1481 1482.. code-block:: c++ 1483 1484 class Foo { 1485 public: 1486 inline void bar() { 1487 // ... 1488 } 1489 }; 1490 1491Do: 1492 1493.. code-block:: c++ 1494 1495 class Foo { 1496 public: 1497 void bar() { 1498 // ... 1499 } 1500 }; 1501 1502Microscopic Details 1503------------------- 1504 1505This section describes preferred low-level formatting guidelines along with 1506reasoning on why we prefer them. 1507 1508Spaces Before Parentheses 1509^^^^^^^^^^^^^^^^^^^^^^^^^ 1510 1511Put a space before an open parenthesis only in control flow statements, but not 1512in normal function call expressions and function-like macros. For example: 1513 1514.. code-block:: c++ 1515 1516 if (X) ... 1517 for (I = 0; I != 100; ++I) ... 1518 while (LLVMRocks) ... 1519 1520 somefunc(42); 1521 assert(3 != 4 && "laws of math are failing me"); 1522 1523 A = foo(42, 92) + bar(X); 1524 1525The reason for doing this is not completely arbitrary. This style makes control 1526flow operators stand out more, and makes expressions flow better. 1527 1528Prefer Preincrement 1529^^^^^^^^^^^^^^^^^^^ 1530 1531Hard fast rule: Preincrement (``++X``) may be no slower than postincrement 1532(``X++``) and could very well be a lot faster than it. Use preincrementation 1533whenever possible. 1534 1535The semantics of postincrement include making a copy of the value being 1536incremented, returning it, and then preincrementing the "work value". For 1537primitive types, this isn't a big deal. But for iterators, it can be a huge 1538issue (for example, some iterators contains stack and set objects in them... 1539copying an iterator could invoke the copy ctor's of these as well). In general, 1540get in the habit of always using preincrement, and you won't have a problem. 1541 1542 1543Namespace Indentation 1544^^^^^^^^^^^^^^^^^^^^^ 1545 1546In general, we strive to reduce indentation wherever possible. This is useful 1547because we want code to `fit into 80 columns`_ without excessive wrapping, but 1548also because it makes it easier to understand the code. To facilitate this and 1549avoid some insanely deep nesting on occasion, don't indent namespaces. If it 1550helps readability, feel free to add a comment indicating what namespace is 1551being closed by a ``}``. For example: 1552 1553.. code-block:: c++ 1554 1555 namespace llvm { 1556 namespace knowledge { 1557 1558 /// This class represents things that Smith can have an intimate 1559 /// understanding of and contains the data associated with it. 1560 class Grokable { 1561 ... 1562 public: 1563 explicit Grokable() { ... } 1564 virtual ~Grokable() = 0; 1565 1566 ... 1567 1568 }; 1569 1570 } // namespace knowledge 1571 } // namespace llvm 1572 1573 1574Feel free to skip the closing comment when the namespace being closed is 1575obvious for any reason. For example, the outer-most namespace in a header file 1576is rarely a source of confusion. But namespaces both anonymous and named in 1577source files that are being closed half way through the file probably could use 1578clarification. 1579 1580.. _static: 1581 1582Anonymous Namespaces 1583^^^^^^^^^^^^^^^^^^^^ 1584 1585After talking about namespaces in general, you may be wondering about anonymous 1586namespaces in particular. Anonymous namespaces are a great language feature 1587that tells the C++ compiler that the contents of the namespace are only visible 1588within the current translation unit, allowing more aggressive optimization and 1589eliminating the possibility of symbol name collisions. Anonymous namespaces are 1590to C++ as "static" is to C functions and global variables. While "``static``" 1591is available in C++, anonymous namespaces are more general: they can make entire 1592classes private to a file. 1593 1594The problem with anonymous namespaces is that they naturally want to encourage 1595indentation of their body, and they reduce locality of reference: if you see a 1596random function definition in a C++ file, it is easy to see if it is marked 1597static, but seeing if it is in an anonymous namespace requires scanning a big 1598chunk of the file. 1599 1600Because of this, we have a simple guideline: make anonymous namespaces as small 1601as possible, and only use them for class declarations. For example: 1602 1603.. code-block:: c++ 1604 1605 namespace { 1606 class StringSort { 1607 ... 1608 public: 1609 StringSort(...) 1610 bool operator<(const char *RHS) const; 1611 }; 1612 } // namespace 1613 1614 static void runHelper() { 1615 ... 1616 } 1617 1618 bool StringSort::operator<(const char *RHS) const { 1619 ... 1620 } 1621 1622Avoid putting declarations other than classes into anonymous namespaces: 1623 1624.. code-block:: c++ 1625 1626 namespace { 1627 1628 // ... many declarations ... 1629 1630 void runHelper() { 1631 ... 1632 } 1633 1634 // ... many declarations ... 1635 1636 } // namespace 1637 1638When you are looking at "``runHelper``" in the middle of a large C++ file, 1639you have no immediate way to tell if this function is local to the file. In 1640contrast, when the function is marked static, you don't need to cross-reference 1641faraway places in the file to tell that the function is local. 1642 1643Don't Use Braces on Simple Single-Statement Bodies of if/else/loop Statements 1644^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1645 1646When writing the body of an ``if``, ``else``, or for/while loop statement, we 1647prefer to omit the braces to avoid unnecessary line noise. However, braces 1648should be used in cases where the omission of braces harm the readability and 1649maintainability of the code. 1650 1651We consider that readability is harmed when omitting the brace in the presence 1652of a single statement that is accompanied by a comment (assuming the comment 1653can't be hoisted above the ``if`` or loop statement, see below). 1654 1655Similarly, braces should be used when a single-statement body is complex enough 1656that it becomes difficult to see where the block containing the following 1657statement began. An ``if``/``else`` chain or a loop is considered a single 1658statement for this rule, and this rule applies recursively. 1659 1660This list is not exhaustive. For example, readability is also harmed if an 1661``if``/``else`` chain does not use braced bodies for either all or none of its 1662members, or has complex conditionals, deep nesting, etc. The examples below 1663intend to provide some guidelines. 1664 1665Maintainability is harmed if the body of an ``if`` ends with a (directly or 1666indirectly) nested ``if`` statement with no ``else``. Braces on the outer ``if`` 1667would help to avoid running into a "dangling else" situation. 1668 1669 1670.. code-block:: c++ 1671 1672 // Omit the braces since the body is simple and clearly associated with the 1673 // `if`. 1674 if (isa<FunctionDecl>(D)) 1675 handleFunctionDecl(D); 1676 else if (isa<VarDecl>(D)) 1677 handleVarDecl(D); 1678 1679 // Here we document the condition itself and not the body. 1680 if (isa<VarDecl>(D)) { 1681 // It is necessary that we explain the situation with this surprisingly long 1682 // comment, so it would be unclear without the braces whether the following 1683 // statement is in the scope of the `if`. 1684 // Because the condition is documented, we can't really hoist this 1685 // comment that applies to the body above the `if`. 1686 handleOtherDecl(D); 1687 } 1688 1689 // Use braces on the outer `if` to avoid a potential dangling `else` 1690 // situation. 1691 if (isa<VarDecl>(D)) { 1692 if (shouldProcessAttr(A)) 1693 handleAttr(A); 1694 } 1695 1696 // Use braces for the `if` block to keep it uniform with the `else` block. 1697 if (isa<FunctionDecl>(D)) { 1698 handleFunctionDecl(D); 1699 } else { 1700 // In this `else` case, it is necessary that we explain the situation with 1701 // this surprisingly long comment, so it would be unclear without the braces 1702 // whether the following statement is in the scope of the `if`. 1703 handleOtherDecl(D); 1704 } 1705 1706 // Use braces for the `else if` and `else` block to keep it uniform with the 1707 // `if` block. 1708 if (isa<FunctionDecl>(D)) { 1709 verifyFunctionDecl(D); 1710 handleFunctionDecl(D); 1711 } else if (isa<GlobalVarDecl>(D)) { 1712 handleGlobalVarDecl(D); 1713 } else { 1714 handleOtherDecl(D); 1715 } 1716 1717 // This should also omit braces. The `for` loop contains only a single 1718 // statement, so it shouldn't have braces. The `if` also only contains a 1719 // single simple statement (the `for` loop), so it also should omit braces. 1720 if (isa<FunctionDecl>(D)) 1721 for (auto *A : D.attrs()) 1722 handleAttr(A); 1723 1724 // Use braces for a `do-while` loop and its enclosing statement. 1725 if (Tok->is(tok::l_brace)) { 1726 do { 1727 Tok = Tok->Next; 1728 } while (Tok); 1729 } 1730 1731 // Use braces for the outer `if` since the nested `for` is braced. 1732 if (isa<FunctionDecl>(D)) { 1733 for (auto *A : D.attrs()) { 1734 // In this `for` loop body, it is necessary that we explain the situation 1735 // with this surprisingly long comment, forcing braces on the `for` block. 1736 handleAttr(A); 1737 } 1738 } 1739 1740 // Use braces on the outer block because there are more than two levels of 1741 // nesting. 1742 if (isa<FunctionDecl>(D)) { 1743 for (auto *A : D.attrs()) 1744 for (ssize_t i : llvm::seq<ssize_t>(count)) 1745 handleAttrOnDecl(D, A, i); 1746 } 1747 1748 // Use braces on the outer block because of a nested `if`; otherwise the 1749 // compiler would warn: `add explicit braces to avoid dangling else` 1750 if (auto *D = dyn_cast<FunctionDecl>(D)) { 1751 if (shouldProcess(D)) 1752 handleVarDecl(D); 1753 else 1754 markAsIgnored(D); 1755 } 1756 1757 1758See Also 1759======== 1760 1761A lot of these comments and recommendations have been culled from other sources. 1762Two particularly important books for our work are: 1763 1764#. `Effective C++ 1765 <https://www.amazon.com/Effective-Specific-Addison-Wesley-Professional-Computing/dp/0321334876>`_ 1766 by Scott Meyers. Also interesting and useful are "More Effective C++" and 1767 "Effective STL" by the same author. 1768 1769#. `Large-Scale C++ Software Design 1770 <https://www.amazon.com/Large-Scale-Software-Design-John-Lakos/dp/0201633620>`_ 1771 by John Lakos 1772 1773If you get some free time, and you haven't read them: do so, you might learn 1774something. 1775