11 This document describes coding standards that are used in the LLVM project.
12 Although no coding standards should be regarded as absolute requirements to be
13 followed in all instances, coding standards are
14 particularly important for large-scale code bases that follow a library-based
17 While this document may provide guidance for some mechanical formatting issues,
18 whitespace, or other "microscopic details", these are not fixed standards.
19 Always follow the golden rule:
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
27 Note that some code bases (e.g. ``libc++``) have special reasons to deviate
28 from the coding standards. For example, in the case of ``libc++``, this is
29 because the naming and other conventions are dictated by the C++ standard.
31 There 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
33 lot of code was written before they were put in place. Our long term goal is
34 for the entire codebase to follow the convention, but we explicitly *do not*
35 want patches that do large-scale reformatting of existing code. On the other
36 hand, it is reasonable to rename the methods of a class if you're about to
37 change it in some other way. Please commit such changes separately to
38 make code review easier.
40 The ultimate goal of these guidelines is to increase the readability and
41 maintainability of our common source base.
43 Languages, Libraries, and Standards
44 ===================================
46 Most source code in LLVM and other LLVM projects using these coding standards
47 is C++ code. There are some places where C code is used either due to
48 environment restrictions, historical restrictions, or due to third-party source
49 code imported into the tree. Generally, our preference is for standards
50 conforming, modern, and portable C++ code as the implementation language of
53 For automation, build-systems and utility scripts Python is preferred and
54 is widely used in the LLVM repository already.
59 Unless otherwise documented, LLVM subprojects are written using standard C++17
60 code and avoid unnecessary vendor-specific extensions.
62 Nevertheless, we restrict ourselves to features which are available in the
63 major toolchains supported as host compilers (see :doc:`GettingStarted` page,
66 Each toolchain provides a good reference for what it accepts:
68 * Clang: https://clang.llvm.org/cxx_status.html
70 * libc++: https://libcxx.llvm.org/Status/Cxx17.html
72 * GCC: https://gcc.gnu.org/projects/cxx-status.html#cxx17
74 * libstdc++: https://gcc.gnu.org/onlinedocs/libstdc++/manual/status.html#status.iso.2017
76 * MSVC: https://msdn.microsoft.com/en-us/library/hh567368.aspx
82 Instead of implementing custom data structures, we encourage the use of C++
83 standard library facilities or LLVM support libraries whenever they are
84 available for a particular task. LLVM and related projects emphasize and rely
85 on the standard library facilities and the LLVM support libraries as much as
88 LLVM support libraries (for example, `ADT
89 <https://github.com/llvm/llvm-project/tree/main/llvm/include/llvm/ADT>`_)
90 implement specialized data structures or functionality missing in the standard
91 library. Such libraries are usually implemented in the ``llvm`` namespace and
92 follow the expected standard interface, when there is one.
94 When both C++ and the LLVM support libraries provide similar functionality, and
95 there isn't a specific reason to favor the C++ implementation, it is generally
96 preferable to use the LLVM library. For example, ``llvm::DenseMap`` should
97 almost always be used instead of ``std::map`` or ``std::unordered_map``, and
98 ``llvm::SmallVector`` should usually be used instead of ``std::vector``.
100 We explicitly avoid some standard facilities, like the I/O streams, and instead
101 use LLVM's streams library (raw_ostream_). More detailed information on these
102 subjects is available in the :doc:`ProgrammersManual`.
104 For more information about LLVM's data structures and the tradeoffs they make,
105 please consult `that section of the programmer's manual
106 <https://llvm.org/docs/ProgrammersManual.html#picking-the-right-data-structure-for-a-task>`_.
108 Python version and Source Code Formatting
109 -----------------------------------------
111 The current minimum version of Python required is documented in the :doc:`GettingStarted`
112 section. Python code in the LLVM repository should only use language features
113 available in this version of Python.
115 The Python code within the LLVM repository should adhere to the formatting guidelines
116 outlined in `PEP 8 <https://peps.python.org/pep-0008/>`_.
118 For consistency and to limit churn, code should be automatically formatted with
119 the `black <https://github.com/psf/black>`_ utility, which is PEP 8 compliant.
120 Use its default rules. For example, avoid specifying ``--line-length`` even
121 though it does not default to 80. The default rules can change between major
122 versions of black. In order to avoid unnecessary churn in the formatting rules,
123 we currently use black version 23.x in LLVM.
125 When contributing a patch unrelated to formatting, you should format only the
126 Python code that the patch modifies. For this purpose, use the `darker
127 <https://pypi.org/project/darker/>`_ utility, which runs default black rules
128 over only the modified Python code. Doing so should ensure the patch will pass
129 the Python format checks in LLVM's pre-commit CI, which also uses darker. When
130 contributing a patch specifically for reformatting Python files, use black,
131 which currently only supports formatting entire files.
133 Here are some quick examples, but see the black and darker documentation for
138 $ pip install black=='23.*' darker # install black 23.x and darker
139 $ darker test.py # format uncommitted changes
140 $ darker -r HEAD^ test.py # also format changes from last commit
141 $ black test.py # format entire file
143 Instead of individual file names, you can specify directories to
144 darker, and it will find the changed files. However, if a directory is
145 large, like a clone of the LLVM repository, darker can be painfully
146 slow. In that case, you might wish to use git to list changed files.
151 $ darker -r HEAD^ $(git diff --name-only --diff-filter=d HEAD^)
153 Mechanical Source Issues
154 ========================
156 Source Code Formatting
157 ----------------------
162 Comments are important for readability and maintainability. When writing comments,
163 write them as English prose, using proper capitalization, punctuation, etc.
164 Aim to describe what the code is trying to do and why, not *how* it does it at
165 a micro level. Here are a few important things to document:
167 .. _header file comment:
172 Every source file should have a header on it that describes the basic purpose of
173 the file. The standard header looks like this:
177 //===-- llvm/Instruction.h - Instruction class definition -------*- C++ -*-===//
179 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
180 // See https://llvm.org/LICENSE.txt for license information.
181 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
183 //===----------------------------------------------------------------------===//
186 /// This file contains the declaration of the Instruction class, which is the
187 /// base class for all of the VM instructions.
189 //===----------------------------------------------------------------------===//
191 A few things to note about this particular format: The "``-*- C++ -*-``" string
192 on the first line is there to tell Emacs that the source file is a C++ file, not
193 a C file (Emacs assumes ``.h`` files are C files by default).
197 This tag is not necessary in ``.cpp`` files. The name of the file is also
198 on the first line, along with a very short description of the purpose of the
201 The next section in the file is a concise note that defines the license that the
202 file is released under. This makes it perfectly clear what terms the source
203 code can be distributed under and should not be modified in any way.
205 The main body is a `Doxygen <http://www.doxygen.nl/>`_ comment (identified by
206 the ``///`` comment marker instead of the usual ``//``) describing the purpose
207 of the file. The first sentence (or a passage beginning with ``\brief``) is
208 used as an abstract. Any additional information should be separated by a blank
209 line. If an algorithm is based on a paper or is described in another source,
215 The header file's guard should be the all-caps path that a user of this header
216 would #include, using '_' instead of path separator and extension marker.
217 For example, the header file
218 ``llvm/include/llvm/Analysis/Utils/Local.h`` would be ``#include``-ed as
219 ``#include "llvm/Analysis/Utils/Local.h"``, so its guard is
220 ``LLVM_ANALYSIS_UTILS_LOCAL_H``.
225 Classes are a fundamental part of an object-oriented design. As such, a
226 class definition should have a comment block that explains what the class is
227 used for and how it works. Every non-trivial class is expected to have a
228 ``doxygen`` comment block.
233 Methods and global functions should also be documented. A quick note about
234 what it does and a description of the edge cases is all that is necessary here.
235 The reader should be able to understand how to use interfaces without reading
238 Good things to talk about here are what happens when something unexpected
239 happens, for instance, does the method return null?
244 In general, prefer C++-style comments (``//`` for normal comments, ``///`` for
245 ``doxygen`` documentation comments). There are a few cases when it is
246 useful to use C-style (``/* */``) comments however:
248 #. When writing C code to be compatible with C89.
250 #. When writing a header file that may be ``#include``\d by a C source file.
252 #. When writing a source file that is used by a tool that only accepts C-style
255 #. When documenting the significance of constants used as actual parameters in
256 a call. This is most helpful for ``bool`` parameters, or passing ``0`` or
257 ``nullptr``. The comment should contain the parameter name, which ought to be
258 meaningful. For example, it's not clear what the parameter means in this call:
262 Object.emitName(nullptr);
264 An in-line C-style comment makes the intent obvious:
268 Object.emitName(/*Prefix=*/nullptr);
270 Commenting out large blocks of code is discouraged, but if you really have to do
271 this (for documentation purposes or as a suggestion for debug printing), use
272 ``#if 0`` and ``#endif``. These nest properly and are better behaved in general
273 than C style comments.
275 Doxygen Use in Documentation Comments
276 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
278 Use the ``\file`` command to turn the standard file header into a file-level
281 Include descriptive paragraphs for all public interfaces (public classes,
282 member and non-member functions). Avoid restating the information that can
283 be inferred from the API name. The first sentence (or a paragraph beginning
284 with ``\brief``) is used as an abstract. Try to use a single sentence as the
285 ``\brief`` adds visual clutter. Put detailed discussion into separate
288 To refer to parameter names inside a paragraph, use the ``\p name`` command.
289 Don't use the ``\arg name`` command since it starts a new paragraph that
290 contains documentation for the parameter.
292 Wrap non-inline code examples in ``\code ... \endcode``.
294 To document a function parameter, start a new paragraph with the
295 ``\param name`` command. If the parameter is used as an out or an in/out
296 parameter, use the ``\param [out] name`` or ``\param [in,out] name`` command,
299 To describe function return value, start a new paragraph with the ``\returns``
302 A minimal documentation comment:
306 /// Sets the xyzzy property to \p Baz.
307 void setXyzzy(bool Baz);
309 A documentation comment that uses all Doxygen features in a preferred way:
313 /// Does foo and bar.
315 /// Does not do foo the usual way if \p Baz is true.
319 /// fooBar(false, "quux", Res);
322 /// \param Quux kind of foo to do.
323 /// \param [out] Result filled with bar sequence on foo success.
325 /// \returns true on success.
326 bool fooBar(bool Baz, StringRef Quux, std::vector<int> &Result);
328 Don't duplicate the documentation comment in the header file and in the
329 implementation file. Put the documentation comments for public APIs into the
330 header file. Documentation comments for private APIs can go to the
331 implementation file. In any case, implementation files can include additional
332 comments (not necessarily in Doxygen markup) to explain implementation details
335 Don't duplicate function or class name at the beginning of the comment.
336 For humans it is obvious which function or class is being documented;
337 automatic documentation processing tools are smart enough to bind the comment
338 to the correct declaration.
346 // example - Does something important.
351 // example - Does something important.
352 void example() { ... }
360 /// Does something important.
365 /// Builds a B-tree in order to do foo. See paper by...
366 void example() { ... }
368 Error and Warning Messages
369 ^^^^^^^^^^^^^^^^^^^^^^^^^^
371 Clear diagnostic messages are important to help users identify and fix issues in
372 their inputs. Use succinct but correct English prose that gives the user the
373 context needed to understand what went wrong. Also, to match error message
374 styles commonly produced by other tools, start the first sentence with a
375 lower-case letter, and finish the last sentence without a period, if it would
376 end in one otherwise. Sentences which end with different punctuation, such as
377 "did you forget ';'?", should still do so.
379 For example this is a good error message:
383 error: file.o: section header 3 is corrupt. Size is 10 when it should be 20
385 This is a bad message, since it does not provide useful information and uses the
390 error: file.o: Corrupt section header.
392 As with other coding standards, individual projects, such as the Clang Static
393 Analyzer, may have preexisting styles that do not conform to this. If a
394 different formatting scheme is used consistently throughout the project, use
395 that style instead. Otherwise, this standard applies to all LLVM tools,
396 including clang, clang-tidy, and so on.
398 If the tool or project does not have existing functions to emit warnings or
399 errors, use the error and warning handlers provided in ``Support/WithColor.h``
400 to ensure they are printed in the appropriate style, rather than printing to
403 When using ``report_fatal_error``, follow the same standards for the message as
404 regular error messages. Assertion messages and ``llvm_unreachable`` calls do not
405 necessarily need to follow these same styles as they are automatically
406 formatted, and thus these guidelines may not be suitable.
411 Immediately after the `header file comment`_ (and include guards if working on a
412 header file), the `minimal list of #includes`_ required by the file should be
413 listed. We prefer these ``#include``\s to be listed in this order:
415 .. _Main Module Header:
416 .. _Local/Private Headers:
418 #. Main Module Header
419 #. Local/Private Headers
420 #. LLVM project/subproject headers (``clang/...``, ``lldb/...``, ``llvm/...``, etc)
421 #. System ``#include``\s
423 and each category should be sorted lexicographically by the full path.
425 The `Main Module Header`_ file applies to ``.cpp`` files which implement an
426 interface defined by a ``.h`` file. This ``#include`` should always be included
427 **first** regardless of where it lives on the file system. By including a
428 header file first in the ``.cpp`` files that implement the interfaces, we ensure
429 that the header does not have any hidden dependencies which are not explicitly
430 ``#include``\d in the header, but should be. It is also a form of documentation
431 in the ``.cpp`` file to indicate where the interfaces it implements are defined.
433 LLVM project and subproject headers should be grouped from most specific to least
434 specific, for the same reasons described above. For example, LLDB depends on
435 both clang and LLVM, and clang depends on LLVM. So an LLDB source file should
436 include ``lldb`` headers first, followed by ``clang`` headers, followed by
437 ``llvm`` headers, to reduce the possibility (for example) of an LLDB header
438 accidentally picking up a missing include due to the previous inclusion of that
439 header in the main source file or some earlier header file. clang should
440 similarly include its own headers before including llvm headers. This rule
441 applies to all LLVM subprojects.
443 .. _fit into 80 columns:
448 Write your code to fit within 80 columns.
450 There must be some limit to the width of the code in
451 order to allow developers to have multiple files side-by-side in
452 windows on a modest display. If you are going to pick a width limit, it is
453 somewhat arbitrary but you might as well pick something standard. Going with 90
454 columns (for example) instead of 80 columns wouldn't add any significant value
455 and would be detrimental to printing out code. Also many other projects have
456 standardized on 80 columns, so some people have already configured their editors
457 for it (vs something else, like 90 columns).
462 In all cases, prefer spaces to tabs in source files. People have different
463 preferred indentation levels, and different styles of indentation that they
464 like; this is fine. What isn't fine is that different editors/viewers expand
465 tabs out to different tab stops. This can cause your code to look completely
466 unreadable, and it is not worth dealing with.
468 As always, follow the `Golden Rule`_ above: follow the style of existing code
469 if you are modifying and extending it.
471 Do not add trailing whitespace. Some common editors will automatically remove
472 trailing whitespace when saving a file which causes unrelated changes to appear
473 in diffs and commits.
475 Format Lambdas Like Blocks Of Code
476 """"""""""""""""""""""""""""""""""
478 When formatting a multi-line lambda, format it like a block of code. If there
479 is only one multi-line lambda in a statement, and there are no expressions
480 lexically after it in the statement, drop the indent to the standard two space
481 indent for a block of code, as if it were an if-block opened by the preceding
482 part of the statement:
486 std::sort(foo.begin(), foo.end(), [&](Foo a, Foo b) -> bool {
491 return a.bam < b.bam;
494 To take best advantage of this formatting, if you are designing an API which
495 accepts a continuation or single callable argument (be it a function object, or
496 a ``std::function``), it should be the last argument if at all possible.
498 If there are multiple multi-line lambdas in a statement, or additional
499 parameters after the lambda, indent the block two spaces from the indent of the
504 dyn_switch(V->stripPointerCasts(),
508 [] (SelectInst *SI) {
509 // process selects...
514 [] (AllocaInst *AI) {
515 // process allocas...
518 Braced Initializer Lists
519 """"""""""""""""""""""""
521 Starting from C++11, there are significantly more uses of braced lists to
522 perform initialization. For example, they can be used to construct aggregate
523 temporaries in expressions. They now have a natural way of ending up nested
524 within each other and within function calls in order to build up aggregates
525 (such as option structs) from local variables.
527 The historically common formatting of braced initialization of aggregate
528 variables does not mix cleanly with deep nesting, general expression contexts,
529 function arguments, and lambdas. We suggest new code use a simple rule for
530 formatting braced initialization lists: act as-if the braces were parentheses
531 in a function call. The formatting rules exactly match those already well
532 understood for formatting nested function calls. Examples:
536 foo({a, b, c}, {1, 2, 3});
538 llvm::Constant *Mask[] = {
539 llvm::ConstantInt::get(llvm::Type::getInt32Ty(getLLVMContext()), 0),
540 llvm::ConstantInt::get(llvm::Type::getInt32Ty(getLLVMContext()), 1),
541 llvm::ConstantInt::get(llvm::Type::getInt32Ty(getLLVMContext()), 2)};
543 This formatting scheme also makes it particularly easy to get predictable,
544 consistent, and automatic formatting with tools like `Clang Format`_.
546 .. _Clang Format: https://clang.llvm.org/docs/ClangFormat.html
548 Language and Compiler Issues
549 ----------------------------
551 Treat Compiler Warnings Like Errors
552 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
554 Compiler warnings are often useful and help improve the code. Those that are
555 not useful, can be often suppressed with a small code change. For example, an
556 assignment in the ``if`` condition is often a typo:
560 if (V = getValue()) {
564 Several compilers will print a warning for the code above. It can be suppressed
565 by adding parentheses:
569 if ((V = getValue())) {
576 In almost all cases, it is possible to write completely portable code. When
577 you need to rely on non-portable code, put it behind a well-defined and
578 well-documented interface.
580 Do not use RTTI or Exceptions
581 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
583 In an effort to reduce code and executable size, LLVM does not use exceptions
584 or RTTI (`runtime type information
585 <https://en.wikipedia.org/wiki/Run-time_type_information>`_, for example,
588 That said, LLVM does make extensive use of a hand-rolled form of RTTI that use
589 templates like :ref:`isa\<>, cast\<>, and dyn_cast\<> <isa>`.
590 This form of RTTI is opt-in and can be
591 :doc:`added to any class <HowToSetUpLLVMStyleRTTI>`.
593 .. _static constructor:
595 Do not use Static Constructors
596 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
598 Static constructors and destructors (e.g., global variables whose types have a
599 constructor or destructor) should not be added to the code base, and should be
600 removed wherever possible.
602 Globals in different source files are initialized in `arbitrary order
603 <https://yosefk.com/c++fqa/ctors.html#fqa-10.12>`_, making the code more
604 difficult to reason about.
606 Static constructors have negative impact on launch time of programs that use
607 LLVM as a library. We would really like for there to be zero cost for linking
608 in an additional LLVM target or other library into an application, but static
609 constructors undermine this goal.
611 Use of ``class`` and ``struct`` Keywords
612 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
614 In C++, the ``class`` and ``struct`` keywords can be used almost
615 interchangeably. The only difference is when they are used to declare a class:
616 ``class`` makes all members private by default while ``struct`` makes all
617 members public by default.
619 * All declarations and definitions of a given ``class`` or ``struct`` must use
620 the same keyword. For example:
624 // Avoid if `Example` is defined as a struct.
630 struct Example { ... };
632 * ``struct`` should be used when *all* members are declared public.
636 // Avoid using `struct` here, use `class` instead.
642 int getData() const { return Data; }
643 void setData(int D) { Data = D; }
646 // OK to use `struct`: all members are public.
652 Do not use Braced Initializer Lists to Call a Constructor
653 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
655 Starting from C++11 there is a "generalized initialization syntax" which allows
656 calling constructors using braced initializer lists. Do not use these to call
657 constructors with non-trivial logic or if you care that you're calling some
658 *particular* constructor. Those should look like function calls using
659 parentheses rather than like aggregate initialization. Similarly, if you need
660 to explicitly name the type and call its constructor to create a temporary,
661 don't use a braced initializer list. Instead, use a braced initializer list
662 (without any type for temporaries) when doing aggregate initialization or
663 something notionally equivalent. Examples:
669 // Construct a Foo by reading data from the disk in the whizbang format, ...
670 Foo(std::string filename);
672 // Construct a Foo by looking up the Nth element of some global data ...
678 // The Foo constructor call is reading a file, don't use braces to call it.
679 std::fill(foo.begin(), foo.end(), Foo("name"));
681 // The pair is being constructed like an aggregate, use braces.
682 bar_map.insert({my_key, my_value});
684 If you use a braced initializer list when initializing a variable, use an equals before the open curly brace:
688 int data[] = {0, 1, 2, 3};
690 Use ``auto`` Type Deduction to Make Code More Readable
691 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
693 Some are advocating a policy of "almost always ``auto``" in C++11, however LLVM
694 uses a more moderate stance. Use ``auto`` if and only if it makes the code more
695 readable or easier to maintain. Don't "almost always" use ``auto``, but do use
696 ``auto`` with initializers like ``cast<Foo>(...)`` or other places where the
697 type is already obvious from the context. Another time when ``auto`` works well
698 for these purposes is when the type would have been abstracted away anyways,
699 often behind a container's typedef such as ``std::vector<T>::iterator``.
701 Similarly, C++14 adds generic lambda expressions where parameter types can be
702 ``auto``. Use these where you would have used a template.
704 Beware unnecessary copies with ``auto``
705 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
707 The convenience of ``auto`` makes it easy to forget that its default behavior
708 is a copy. Particularly in range-based ``for`` loops, careless copies are
711 Use ``auto &`` for values and ``auto *`` for pointers unless you need to make a
716 // Typically there's no reason to copy.
717 for (const auto &Val : Container) observe(Val);
718 for (auto &Val : Container) Val.change();
720 // Remove the reference if you really want a new copy.
721 for (auto Val : Container) { Val.change(); saveSomewhere(Val); }
723 // Copy pointers, but make it clear that they're pointers.
724 for (const auto *Ptr : Container) observe(*Ptr);
725 for (auto *Ptr : Container) Ptr->change();
727 Beware of non-determinism due to ordering of pointers
728 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
730 In general, there is no relative ordering among pointers. As a result,
731 when unordered containers like sets and maps are used with pointer keys
732 the iteration order is undefined. Hence, iterating such containers may
733 result in non-deterministic code generation. While the generated code
734 might work correctly, non-determinism can make it harder to reproduce bugs and
737 In case an ordered result is expected, remember to
738 sort an unordered container before iteration. Or use ordered containers
739 like ``vector``/``MapVector``/``SetVector`` if you want to iterate pointer
742 Beware of non-deterministic sorting order of equal elements
743 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
745 ``std::sort`` uses a non-stable sorting algorithm in which the order of equal
746 elements is not guaranteed to be preserved. Thus using ``std::sort`` for a
747 container having equal elements may result in non-deterministic behavior.
748 To uncover such instances of non-determinism, LLVM has introduced a new
749 llvm::sort wrapper function. For an EXPENSIVE_CHECKS build this will randomly
750 shuffle the container before sorting. Default to using ``llvm::sort`` instead
756 The High-Level Issues
757 ---------------------
759 Self-contained Headers
760 ^^^^^^^^^^^^^^^^^^^^^^
762 Header files should be self-contained (compile on their own) and end in ``.h``.
763 Non-header files that are meant for inclusion should end in ``.inc`` and be
766 All header files should be self-contained. Users and refactoring tools should
767 not have to adhere to special conditions to include the header. Specifically, a
768 header should have header guards and include all other headers it needs.
770 There are rare cases where a file designed to be included is not
771 self-contained. These are typically intended to be included at unusual
772 locations, such as the middle of another file. They might not use header
773 guards, and might not include their prerequisites. Name such files with the
774 .inc extension. Use sparingly, and prefer self-contained headers when possible.
776 In general, a header should be implemented by one or more ``.cpp`` files. Each
777 of these ``.cpp`` files should include the header that defines their interface
778 first. This ensures that all of the dependences of the header have been
779 properly added to the header itself, and are not implicit. System headers
780 should be included after user headers for a translation unit.
785 A directory of header files (for example ``include/llvm/Foo``) defines a
786 library (``Foo``). One library (both
787 its headers and implementation) should only use things from the libraries
788 listed in its dependencies.
790 Some of this constraint can be enforced by classic Unix linkers (Mac & Windows
791 linkers, as well as lld, do not enforce this constraint). A Unix linker
792 searches left to right through the libraries specified on its command line and
793 never revisits a library. In this way, no circular dependencies between
796 This doesn't fully enforce all inter-library dependencies, and importantly
797 doesn't enforce header file circular dependencies created by inline functions.
798 A good way to answer the "is this layered correctly" would be to consider
799 whether a Unix linker would succeed at linking the program if all inline
800 functions were defined out-of-line. (& for all valid orderings of dependencies
801 - since linking resolution is linear, it's possible that some implicit
802 dependencies can sneak through: A depends on B and C, so valid orderings are
803 "C B A" or "B C A", in both cases the explicit dependencies come before their
804 use. But in the first case, B could still link successfully if it implicitly
805 depended on C, or the opposite in the second case)
807 .. _minimal list of #includes:
809 ``#include`` as Little as Possible
810 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
812 ``#include`` hurts compile time performance. Don't do it unless you have to,
813 especially in header files.
815 But wait! Sometimes you need to have the definition of a class to use it, or to
816 inherit from it. In these cases go ahead and ``#include`` that header file. Be
817 aware however that there are many cases where you don't need to have the full
818 definition of a class. If you are using a pointer or reference to a class, you
819 don't need the header file. If you are simply returning a class instance from a
820 prototyped function or method, you don't need it. In fact, for most cases, you
821 simply don't need the definition of a class. And not ``#include``\ing speeds up
824 It is easy to try to go too overboard on this recommendation, however. You
825 **must** include all of the header files that you are using --- you can include
826 them either directly or indirectly through another header file. To make sure
827 that you don't accidentally forget to include a header file in your module
828 header, make sure to include your module header **first** in the implementation
829 file (as mentioned above). This way there won't be any hidden dependencies that
830 you'll find out about later.
832 Keep "Internal" Headers Private
833 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
835 Many modules have a complex implementation that causes them to use more than one
836 implementation (``.cpp``) file. It is often tempting to put the internal
837 communication interface (helper classes, extra functions, etc) in the public
838 module header file. Don't do this!
840 If you really need to do something like this, put a private header file in the
841 same directory as the source files, and include it locally. This ensures that
842 your private interface remains private and undisturbed by outsiders.
846 It's okay to put extra implementation methods in a public class itself. Just
847 make them private (or protected) and all is well.
849 Use Namespace Qualifiers to Implement Previously Declared Functions
850 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
852 When providing an out of line implementation of a function in a source file, do
853 not open namespace blocks in the source file. Instead, use namespace qualifiers
854 to help ensure that your definition matches an existing declaration. Do this:
860 int foo(const char *s);
865 using namespace llvm;
866 int llvm::foo(const char *s) {
870 Doing this helps to avoid bugs where the definition does not match the
871 declaration from the header. For example, the following C++ code defines a new
872 overload of ``llvm::foo`` instead of providing a definition for the existing
873 function declared in the header:
880 int foo(char *s) { // Mismatch between "const char *" and "char *"
884 This error will not be caught until the build is nearly complete, when the
885 linker fails to find a definition for any uses of the original function. If the
886 function were instead defined with a namespace qualifier, the error would have
887 been caught immediately when the definition was compiled.
889 Class method implementations must already name the class and new overloads
890 cannot be introduced out of line, so this recommendation does not apply to them.
894 Use Early Exits and ``continue`` to Simplify Code
895 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
897 When reading code, keep in mind how much state and how many previous decisions
898 have to be remembered by the reader to understand a block of code. Aim to
899 reduce indentation where possible when it doesn't make it more difficult to
900 understand the code. One great way to do this is by making use of early exits
901 and the ``continue`` keyword in long loops. Consider this code that does not
906 Value *doSomething(Instruction *I) {
907 if (!I->isTerminator() &&
908 I->hasOneUse() && doOtherThing(I)) {
909 ... some long code ....
915 This code has several problems if the body of the ``'if'`` is large. When
916 you're looking at the top of the function, it isn't immediately clear that this
917 *only* does interesting things with non-terminator instructions, and only
918 applies to things with the other predicates. Second, it is relatively difficult
919 to describe (in comments) why these predicates are important because the ``if``
920 statement makes it difficult to lay out the comments. Third, when you're deep
921 within the body of the code, it is indented an extra level. Finally, when
922 reading the top of the function, it isn't clear what the result is if the
923 predicate isn't true; you have to read to the end of the function to know that
926 It is much preferred to format the code like this:
930 Value *doSomething(Instruction *I) {
931 // Terminators never need 'something' done to them because ...
932 if (I->isTerminator())
935 // We conservatively avoid transforming instructions with multiple uses
936 // because goats like cheese.
940 // This is really just here for example.
941 if (!doOtherThing(I))
944 ... some long code ....
947 This fixes these problems. A similar problem frequently happens in ``for``
948 loops. A silly example is something like this:
952 for (Instruction &I : BB) {
953 if (auto *BO = dyn_cast<BinaryOperator>(&I)) {
954 Value *LHS = BO->getOperand(0);
955 Value *RHS = BO->getOperand(1);
962 When you have very, very small loops, this sort of structure is fine. But if it
963 exceeds more than 10-15 lines, it becomes difficult for people to read and
964 understand at a glance. The problem with this sort of code is that it gets very
965 nested very quickly. Meaning that the reader of the code has to keep a lot of
966 context in their brain to remember what is going immediately on in the loop,
967 because they don't know if/when the ``if`` conditions will have ``else``\s etc.
968 It is strongly preferred to structure the loop like this:
972 for (Instruction &I : BB) {
973 auto *BO = dyn_cast<BinaryOperator>(&I);
976 Value *LHS = BO->getOperand(0);
977 Value *RHS = BO->getOperand(1);
978 if (LHS == RHS) continue;
983 This has all the benefits of using early exits for functions: it reduces nesting
984 of the loop, it makes it easier to describe why the conditions are true, and it
985 makes it obvious to the reader that there is no ``else`` coming up that they
986 have to push context into their brain for. If a loop is large, this can be a
987 big understandability win.
989 Don't use ``else`` after a ``return``
990 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
992 For similar reasons as above (reduction of indentation and easier reading), please
993 do not use ``'else'`` or ``'else if'`` after something that interrupts control
994 flow --- like ``return``, ``break``, ``continue``, ``goto``, etc. For example:
1000 Type = Context.getsigjmp_bufType();
1001 if (Type.isNull()) {
1002 Error = ASTContext::GE_Missing_sigjmp_buf;
1005 break; // Unnecessary.
1008 Type = Context.getjmp_bufType();
1009 if (Type.isNull()) {
1010 Error = ASTContext::GE_Missing_jmp_buf;
1013 break; // Unnecessary.
1018 It is better to write it like this:
1024 Type = Context.getsigjmp_bufType();
1025 if (Type.isNull()) {
1026 Error = ASTContext::GE_Missing_sigjmp_buf;
1030 Type = Context.getjmp_bufType();
1031 if (Type.isNull()) {
1032 Error = ASTContext::GE_Missing_jmp_buf;
1038 Or better yet (in this case) as:
1044 Type = Context.getsigjmp_bufType();
1046 Type = Context.getjmp_bufType();
1048 if (Type.isNull()) {
1049 Error = Signed ? ASTContext::GE_Missing_sigjmp_buf :
1050 ASTContext::GE_Missing_jmp_buf;
1055 The idea is to reduce indentation and the amount of code you have to keep track
1056 of when reading the code.
1058 Note: this advice does not apply to a ``constexpr if`` statement. The
1059 substatement of the ``else`` clause may be a discarded statement, so removing
1060 the ``else`` can cause unexpected template instantiations. Thus, the following
1065 template<typename T>
1066 static constexpr bool VarTempl = true;
1068 template<typename T>
1070 if constexpr (VarTempl<T>)
1073 static_assert(!VarTempl<T>);
1076 Turn Predicate Loops into Predicate Functions
1077 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1079 It is very common to write small loops that just compute a boolean value. There
1080 are a number of ways that people commonly write these, but an example of this
1085 bool FoundFoo = false;
1086 for (unsigned I = 0, E = BarList.size(); I != E; ++I)
1087 if (BarList[I]->isFoo()) {
1096 Instead of this sort of loop, we prefer to use a predicate function (which may
1097 be `static`_) that uses `early exits`_:
1101 /// \returns true if the specified list has an element that is a foo.
1102 static bool containsFoo(const std::vector<Bar*> &List) {
1103 for (unsigned I = 0, E = List.size(); I != E; ++I)
1104 if (List[I]->isFoo())
1110 if (containsFoo(BarList)) {
1114 There are many reasons for doing this: it reduces indentation and factors out
1115 code which can often be shared by other code that checks for the same predicate.
1116 More importantly, it *forces you to pick a name* for the function, and forces
1117 you to write a comment for it. In this silly example, this doesn't add much
1118 value. However, if the condition is complex, this can make it a lot easier for
1119 the reader to understand the code that queries for this predicate. Instead of
1120 being faced with the in-line details of how we check to see if the BarList
1121 contains a foo, we can trust the function name and continue reading with better
1124 The Low-Level Issues
1125 --------------------
1127 Name Types, Functions, Variables, and Enumerators Properly
1128 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1130 Poorly-chosen names can mislead the reader and cause bugs. We cannot stress
1131 enough how important it is to use *descriptive* names. Pick names that match
1132 the semantics and role of the underlying entities, within reason. Avoid
1133 abbreviations unless they are well known. After picking a good name, make sure
1134 to use consistent capitalization for the name, as inconsistency requires clients
1135 to either memorize the APIs or to look it up to find the exact spelling.
1137 In general, names should be in camel case (e.g. ``TextFileReader`` and
1138 ``isLValue()``). Different kinds of declarations have different rules:
1140 * **Type names** (including classes, structs, enums, typedefs, etc) should be
1141 nouns and start with an upper-case letter (e.g. ``TextFileReader``).
1143 * **Variable names** should be nouns (as they represent state). The name should
1144 be camel case, and start with an upper case letter (e.g. ``Leader`` or
1147 * **Function names** should be verb phrases (as they represent actions), and
1148 command-like function should be imperative. The name should be camel case,
1149 and start with a lower case letter (e.g. ``openFile()`` or ``isFoo()``).
1151 * **Enum declarations** (e.g. ``enum Foo {...}``) are types, so they should
1152 follow the naming conventions for types. A common use for enums is as a
1153 discriminator for a union, or an indicator of a subclass. When an enum is
1154 used for something like this, it should have a ``Kind`` suffix
1155 (e.g. ``ValueKind``).
1157 * **Enumerators** (e.g. ``enum { Foo, Bar }``) and **public member variables**
1158 should start with an upper-case letter, just like types. Unless the
1159 enumerators are defined in their own small namespace or inside a class,
1160 enumerators should have a prefix corresponding to the enum declaration name.
1161 For example, ``enum ValueKind { ... };`` may contain enumerators like
1162 ``VK_Argument``, ``VK_BasicBlock``, etc. Enumerators that are just
1163 convenience constants are exempt from the requirement for a prefix. For
1173 As an exception, classes that mimic STL classes can have member names in STL's
1174 style of lower-case words separated by underscores (e.g. ``begin()``,
1175 ``push_back()``, and ``empty()``). Classes that provide multiple
1176 iterators should add a singular prefix to ``begin()`` and ``end()``
1177 (e.g. ``global_begin()`` and ``use_begin()``).
1179 Here are some examples:
1183 class VehicleMaker {
1185 Factory<Tire> F; // Avoid: a non-descriptive abbreviation.
1186 Factory<Tire> Factory; // Better: more descriptive.
1187 Factory<Tire> TireFactory; // Even better: if VehicleMaker has more than one
1188 // kind of factories.
1191 Vehicle makeVehicle(VehicleType Type) {
1192 VehicleMaker M; // Might be OK if scope is small.
1193 Tire Tmp1 = M.makeTire(); // Avoid: 'Tmp1' provides no information.
1194 Light Headlight = M.makeLight("head"); // Good: descriptive.
1201 Use the "``assert``" macro to its fullest. Check all of your preconditions and
1202 assumptions, you never know when a bug (not necessarily even yours) might be
1203 caught early by an assertion, which reduces debugging time dramatically. The
1204 "``<cassert>``" header file is probably already included by the header files you
1205 are using, so it doesn't cost anything to use it.
1207 To further assist with debugging, make sure to put some kind of error message in
1208 the assertion statement, which is printed if the assertion is tripped. This
1209 helps the poor debugger make sense of why an assertion is being made and
1210 enforced, and hopefully what to do about it. Here is one complete example:
1214 inline Value *getOperand(unsigned I) {
1215 assert(I < Operands.size() && "getOperand() out of range!");
1219 Here are more examples:
1223 assert(Ty->isPointerType() && "Can't allocate a non-pointer type!");
1225 assert((Opcode == Shl || Opcode == Shr) && "ShiftInst Opcode invalid!");
1227 assert(idx < getNumSuccessors() && "Successor # out of range!");
1229 assert(V1.getType() == V2.getType() && "Constant types must be identical!");
1231 assert(isa<PHINode>(Succ->front()) && "Only works on PHId BBs!");
1235 In the past, asserts were used to indicate a piece of code that should not be
1236 reached. These were typically of the form:
1240 assert(0 && "Invalid radix for integer literal");
1242 This has a few issues, the main one being that some compilers might not
1243 understand the assertion, or warn about a missing return in builds where
1244 assertions are compiled out.
1246 Today, we have something much better: ``llvm_unreachable``:
1250 llvm_unreachable("Invalid radix for integer literal");
1252 When assertions are enabled, this will print the message if it's ever reached
1253 and then exit the program. When assertions are disabled (i.e. in release
1254 builds), ``llvm_unreachable`` becomes a hint to compilers to skip generating
1255 code for this branch. If the compiler does not support this, it will fall back
1256 to the "abort" implementation.
1258 Use ``llvm_unreachable`` to mark a specific point in code that should never be
1259 reached. This is especially desirable for addressing warnings about unreachable
1260 branches, etc., but can be used whenever reaching a particular code path is
1261 unconditionally a bug (not originating from user input; see below) of some kind.
1262 Use of ``assert`` should always include a testable predicate (as opposed to
1265 If the error condition can be triggered by user input then the
1266 recoverable error mechanism described in :doc:`ProgrammersManual` should be
1267 used instead. In cases where this is not practical, ``report_fatal_error`` may
1270 Another issue is that values used only by assertions will produce an "unused
1271 value" warning when assertions are disabled. For example, this code will warn:
1275 unsigned Size = V.size();
1276 assert(Size > 42 && "Vector smaller than it should be");
1278 bool NewToSet = Myset.insert(Value);
1279 assert(NewToSet && "The value shouldn't be in the set yet");
1281 These are two interesting different cases. In the first case, the call to
1282 ``V.size()`` is only useful for the assert, and we don't want it executed when
1283 assertions are disabled. Code like this should move the call into the assert
1284 itself. In the second case, the side effects of the call must happen whether
1285 the assert is enabled or not. In this case, the value should be cast to void to
1286 disable the warning. To be specific, it is preferred to write the code like
1291 assert(V.size() > 42 && "Vector smaller than it should be");
1293 bool NewToSet = Myset.insert(Value); (void)NewToSet;
1294 assert(NewToSet && "The value shouldn't be in the set yet");
1296 Do Not Use ``using namespace std``
1297 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1299 In LLVM, we prefer to explicitly prefix all identifiers from the standard
1300 namespace with an "``std::``" prefix, rather than rely on "``using namespace
1303 In header files, adding a ``'using namespace XXX'`` directive pollutes the
1304 namespace of any source file that ``#include``\s the header, creating
1307 In implementation files (e.g. ``.cpp`` files), the rule is more of a stylistic
1308 rule, but is still important. Basically, using explicit namespace prefixes
1309 makes the code **clearer**, because it is immediately obvious what facilities
1310 are being used and where they are coming from. And **more portable**, because
1311 namespace clashes cannot occur between LLVM code and other namespaces. The
1312 portability rule is important because different standard library implementations
1313 expose different symbols (potentially ones they shouldn't), and future revisions
1314 to the C++ standard will add more symbols to the ``std`` namespace. As such, we
1315 never use ``'using namespace std;'`` in LLVM.
1317 The exception to the general rule (i.e. it's not an exception for the ``std``
1318 namespace) is for implementation files. For example, all of the code in the
1319 LLVM project implements code that lives in the 'llvm' namespace. As such, it is
1320 ok, and actually clearer, for the ``.cpp`` files to have a ``'using namespace
1321 llvm;'`` directive at the top, after the ``#include``\s. This reduces
1322 indentation in the body of the file for source editors that indent based on
1323 braces, and keeps the conceptual context cleaner. The general form of this rule
1324 is that any ``.cpp`` file that implements code in any namespace may use that
1325 namespace (and its parents'), but should not use any others.
1327 Provide a Virtual Method Anchor for Classes in Headers
1328 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1330 If a class is defined in a header file and has a vtable (either it has virtual
1331 methods or it derives from classes with virtual methods), it must always have at
1332 least one out-of-line virtual method in the class. Without this, the compiler
1333 will copy the vtable and RTTI into every ``.o`` file that ``#include``\s the
1334 header, bloating ``.o`` file sizes and increasing link times.
1336 Don't use default labels in fully covered switches over enumerations
1337 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1339 ``-Wswitch`` warns if a switch, without a default label, over an enumeration
1340 does not cover every enumeration value. If you write a default label on a fully
1341 covered switch over an enumeration then the ``-Wswitch`` warning won't fire
1342 when new elements are added to that enumeration. To help avoid adding these
1343 kinds of defaults, Clang has the warning ``-Wcovered-switch-default`` which is
1344 off by default but turned on when building LLVM with a version of Clang that
1345 supports the warning.
1347 A knock-on effect of this stylistic requirement is that when building LLVM with
1348 GCC you may get warnings related to "control may reach end of non-void function"
1349 if you return from each case of a covered switch-over-enum because GCC assumes
1350 that the enum expression may take any representable value, not just those of
1351 individual enumerators. To suppress this warning, use ``llvm_unreachable`` after
1354 Use range-based ``for`` loops wherever possible
1355 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1357 The introduction of range-based ``for`` loops in C++11 means that explicit
1358 manipulation of iterators is rarely necessary. We use range-based ``for``
1359 loops wherever possible for all newly added code. For example:
1363 BasicBlock *BB = ...
1364 for (Instruction &I : *BB)
1367 Usage of ``std::for_each()``/``llvm::for_each()`` functions is discouraged,
1368 unless the callable object already exists.
1370 Don't evaluate ``end()`` every time through a loop
1371 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1373 In cases where range-based ``for`` loops can't be used and it is necessary
1374 to write an explicit iterator-based loop, pay close attention to whether
1375 ``end()`` is re-evaluated on each loop iteration. One common mistake is to
1376 write a loop in this style:
1380 BasicBlock *BB = ...
1381 for (auto I = BB->begin(); I != BB->end(); ++I)
1384 The problem with this construct is that it evaluates "``BB->end()``" every time
1385 through the loop. Instead of writing the loop like this, we strongly prefer
1386 loops to be written so that they evaluate it once before the loop starts. A
1387 convenient way to do this is like so:
1391 BasicBlock *BB = ...
1392 for (auto I = BB->begin(), E = BB->end(); I != E; ++I)
1395 The observant may quickly point out that these two loops may have different
1396 semantics: if the container (a basic block in this case) is being mutated, then
1397 "``BB->end()``" may change its value every time through the loop and the second
1398 loop may not in fact be correct. If you actually do depend on this behavior,
1399 please write the loop in the first form and add a comment indicating that you
1400 did it intentionally.
1402 Why do we prefer the second form (when correct)? Writing the loop in the first
1403 form has two problems. First it may be less efficient than evaluating it at the
1404 start of the loop. In this case, the cost is probably minor --- a few extra
1405 loads every time through the loop. However, if the base expression is more
1406 complex, then the cost can rise quickly. I've seen loops where the end
1407 expression was actually something like: "``SomeMap[X]->end()``" and map lookups
1408 really aren't cheap. By writing it in the second form consistently, you
1409 eliminate the issue entirely and don't even have to think about it.
1411 The second (even bigger) issue is that writing the loop in the first form hints
1412 to the reader that the loop is mutating the container (a fact that a comment
1413 would handily confirm!). If you write the loop in the second form, it is
1414 immediately obvious without even looking at the body of the loop that the
1415 container isn't being modified, which makes it easier to read the code and
1416 understand what it does.
1418 While the second form of the loop is a few extra keystrokes, we do strongly
1421 ``#include <iostream>`` is Forbidden
1422 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1424 The use of ``#include <iostream>`` in library files is hereby **forbidden**,
1425 because many common implementations transparently inject a `static constructor`_
1426 into every translation unit that includes it.
1428 Note that using the other stream headers (``<sstream>`` for example) is not
1429 problematic in this regard --- just ``<iostream>``. However, ``raw_ostream``
1430 provides various APIs that are better performing for almost every use than
1431 ``std::ostream`` style APIs.
1435 New code should always use `raw_ostream`_ for writing, or the
1436 ``llvm::MemoryBuffer`` API for reading files.
1443 LLVM includes a lightweight, simple, and efficient stream implementation in
1444 ``llvm/Support/raw_ostream.h``, which provides all of the common features of
1445 ``std::ostream``. All new code should use ``raw_ostream`` instead of
1448 Unlike ``std::ostream``, ``raw_ostream`` is not a template and can be forward
1449 declared as ``class raw_ostream``. Public headers should generally not include
1450 the ``raw_ostream`` header, but use forward declarations and constant references
1451 to ``raw_ostream`` instances.
1456 The ``std::endl`` modifier, when used with ``iostreams`` outputs a newline to
1457 the output stream specified. In addition to doing this, however, it also
1458 flushes the output stream. In other words, these are equivalent:
1462 std::cout << std::endl;
1463 std::cout << '\n' << std::flush;
1465 Most of the time, you probably have no reason to flush the output stream, so
1466 it's better to use a literal ``'\n'``.
1468 Don't use ``inline`` when defining a function in a class definition
1469 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1471 A member function defined in a class definition is implicitly inline, so don't
1472 put the ``inline`` keyword in this case.
1499 This section describes preferred low-level formatting guidelines along with
1500 reasoning on why we prefer them.
1502 Spaces Before Parentheses
1503 ^^^^^^^^^^^^^^^^^^^^^^^^^
1505 Put a space before an open parenthesis only in control flow statements, but not
1506 in normal function call expressions and function-like macros. For example:
1511 for (I = 0; I != 100; ++I) ...
1512 while (LLVMRocks) ...
1515 assert(3 != 4 && "laws of math are failing me");
1517 A = foo(42, 92) + bar(X);
1519 The reason for doing this is not completely arbitrary. This style makes control
1520 flow operators stand out more, and makes expressions flow better.
1525 Hard fast rule: Preincrement (``++X``) may be no slower than postincrement
1526 (``X++``) and could very well be a lot faster than it. Use preincrementation
1529 The semantics of postincrement include making a copy of the value being
1530 incremented, returning it, and then preincrementing the "work value". For
1531 primitive types, this isn't a big deal. But for iterators, it can be a huge
1532 issue (for example, some iterators contains stack and set objects in them...
1533 copying an iterator could invoke the copy ctor's of these as well). In general,
1534 get in the habit of always using preincrement, and you won't have a problem.
1537 Namespace Indentation
1538 ^^^^^^^^^^^^^^^^^^^^^
1540 In general, we strive to reduce indentation wherever possible. This is useful
1541 because we want code to `fit into 80 columns`_ without excessive wrapping, but
1542 also because it makes it easier to understand the code. To facilitate this and
1543 avoid some insanely deep nesting on occasion, don't indent namespaces. If it
1544 helps readability, feel free to add a comment indicating what namespace is
1545 being closed by a ``}``. For example:
1550 namespace knowledge {
1552 /// This class represents things that Smith can have an intimate
1553 /// understanding of and contains the data associated with it.
1557 explicit Grokable() { ... }
1558 virtual ~Grokable() = 0;
1564 } // namespace knowledge
1568 Feel free to skip the closing comment when the namespace being closed is
1569 obvious for any reason. For example, the outer-most namespace in a header file
1570 is rarely a source of confusion. But namespaces both anonymous and named in
1571 source files that are being closed half way through the file probably could use
1576 Anonymous Namespaces
1577 ^^^^^^^^^^^^^^^^^^^^
1579 After talking about namespaces in general, you may be wondering about anonymous
1580 namespaces in particular. Anonymous namespaces are a great language feature
1581 that tells the C++ compiler that the contents of the namespace are only visible
1582 within the current translation unit, allowing more aggressive optimization and
1583 eliminating the possibility of symbol name collisions. Anonymous namespaces are
1584 to C++ as "static" is to C functions and global variables. While "``static``"
1585 is available in C++, anonymous namespaces are more general: they can make entire
1586 classes private to a file.
1588 The problem with anonymous namespaces is that they naturally want to encourage
1589 indentation of their body, and they reduce locality of reference: if you see a
1590 random function definition in a C++ file, it is easy to see if it is marked
1591 static, but seeing if it is in an anonymous namespace requires scanning a big
1594 Because of this, we have a simple guideline: make anonymous namespaces as small
1595 as possible, and only use them for class declarations. For example:
1604 bool operator<(const char *RHS) const;
1608 static void runHelper() {
1612 bool StringSort::operator<(const char *RHS) const {
1616 Avoid putting declarations other than classes into anonymous namespaces:
1622 // ... many declarations ...
1628 // ... many declarations ...
1632 When you are looking at "``runHelper``" in the middle of a large C++ file,
1633 you have no immediate way to tell if this function is local to the file. In
1634 contrast, when the function is marked static, you don't need to cross-reference
1635 faraway places in the file to tell that the function is local.
1637 Don't Use Braces on Simple Single-Statement Bodies of if/else/loop Statements
1638 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1640 When writing the body of an ``if``, ``else``, or for/while loop statement, we
1641 prefer to omit the braces to avoid unnecessary line noise. However, braces
1642 should be used in cases where the omission of braces harm the readability and
1643 maintainability of the code.
1645 We consider that readability is harmed when omitting the brace in the presence
1646 of a single statement that is accompanied by a comment (assuming the comment
1647 can't be hoisted above the ``if`` or loop statement, see below).
1649 Similarly, braces should be used when a single-statement body is complex enough
1650 that it becomes difficult to see where the block containing the following
1651 statement began. An ``if``/``else`` chain or a loop is considered a single
1652 statement for this rule, and this rule applies recursively.
1654 This list is not exhaustive. For example, readability is also harmed if an
1655 ``if``/``else`` chain does not use braced bodies for either all or none of its
1656 members, or has complex conditionals, deep nesting, etc. The examples below
1657 intend to provide some guidelines.
1659 Maintainability is harmed if the body of an ``if`` ends with a (directly or
1660 indirectly) nested ``if`` statement with no ``else``. Braces on the outer ``if``
1661 would help to avoid running into a "dangling else" situation.
1666 // Omit the braces since the body is simple and clearly associated with the
1668 if (isa<FunctionDecl>(D))
1669 handleFunctionDecl(D);
1670 else if (isa<VarDecl>(D))
1673 // Here we document the condition itself and not the body.
1674 if (isa<VarDecl>(D)) {
1675 // It is necessary that we explain the situation with this surprisingly long
1676 // comment, so it would be unclear without the braces whether the following
1677 // statement is in the scope of the `if`.
1678 // Because the condition is documented, we can't really hoist this
1679 // comment that applies to the body above the `if`.
1683 // Use braces on the outer `if` to avoid a potential dangling `else`
1685 if (isa<VarDecl>(D)) {
1686 if (shouldProcessAttr(A))
1690 // Use braces for the `if` block to keep it uniform with the `else` block.
1691 if (isa<FunctionDecl>(D)) {
1692 handleFunctionDecl(D);
1694 // In this `else` case, it is necessary that we explain the situation with
1695 // this surprisingly long comment, so it would be unclear without the braces
1696 // whether the following statement is in the scope of the `if`.
1700 // This should also omit braces. The `for` loop contains only a single
1701 // statement, so it shouldn't have braces. The `if` also only contains a
1702 // single simple statement (the `for` loop), so it also should omit braces.
1703 if (isa<FunctionDecl>(D))
1704 for (auto *A : D.attrs())
1707 // Use braces for a `do-while` loop and its enclosing statement.
1708 if (Tok->is(tok::l_brace)) {
1714 // Use braces for the outer `if` since the nested `for` is braced.
1715 if (isa<FunctionDecl>(D)) {
1716 for (auto *A : D.attrs()) {
1717 // In this `for` loop body, it is necessary that we explain the situation
1718 // with this surprisingly long comment, forcing braces on the `for` block.
1723 // Use braces on the outer block because there are more than two levels of
1725 if (isa<FunctionDecl>(D)) {
1726 for (auto *A : D.attrs())
1727 for (ssize_t i : llvm::seq<ssize_t>(count))
1728 handleAttrOnDecl(D, A, i);
1731 // Use braces on the outer block because of a nested `if`; otherwise the
1732 // compiler would warn: `add explicit braces to avoid dangling else`
1733 if (auto *D = dyn_cast<FunctionDecl>(D)) {
1734 if (shouldProcess(D))
1744 A lot of these comments and recommendations have been culled from other sources.
1745 Two particularly important books for our work are:
1748 <https://www.amazon.com/Effective-Specific-Addison-Wesley-Professional-Computing/dp/0321334876>`_
1749 by Scott Meyers. Also interesting and useful are "More Effective C++" and
1750 "Effective STL" by the same author.
1752 #. `Large-Scale C++ Software Design
1753 <https://www.amazon.com/Large-Scale-Software-Design-John-Lakos/dp/0201633620>`_
1756 If you get some free time, and you haven't read them: do so, you might learn