xref: /aosp_15_r20/external/llvm/docs/CodingStandards.rst (revision 9880d6810fe72a1726cb53787c6711e909410d58)
1*9880d681SAndroid Build Coastguard Worker=====================
2*9880d681SAndroid Build Coastguard WorkerLLVM Coding Standards
3*9880d681SAndroid Build Coastguard Worker=====================
4*9880d681SAndroid Build Coastguard Worker
5*9880d681SAndroid Build Coastguard Worker.. contents::
6*9880d681SAndroid Build Coastguard Worker   :local:
7*9880d681SAndroid Build Coastguard Worker
8*9880d681SAndroid Build Coastguard WorkerIntroduction
9*9880d681SAndroid Build Coastguard Worker============
10*9880d681SAndroid Build Coastguard Worker
11*9880d681SAndroid Build Coastguard WorkerThis document attempts to describe a few coding standards that are being used in
12*9880d681SAndroid Build Coastguard Workerthe LLVM source tree.  Although no coding standards should be regarded as
13*9880d681SAndroid Build Coastguard Workerabsolute requirements to be followed in all instances, coding standards are
14*9880d681SAndroid Build Coastguard Workerparticularly important for large-scale code bases that follow a library-based
15*9880d681SAndroid Build Coastguard Workerdesign (like LLVM).
16*9880d681SAndroid Build Coastguard Worker
17*9880d681SAndroid Build Coastguard WorkerWhile this document may provide guidance for some mechanical formatting issues,
18*9880d681SAndroid Build Coastguard Workerwhitespace, or other "microscopic details", these are not fixed standards.
19*9880d681SAndroid Build Coastguard WorkerAlways follow the golden rule:
20*9880d681SAndroid Build Coastguard Worker
21*9880d681SAndroid Build Coastguard Worker.. _Golden Rule:
22*9880d681SAndroid Build Coastguard Worker
23*9880d681SAndroid Build Coastguard Worker    **If you are extending, enhancing, or bug fixing already implemented code,
24*9880d681SAndroid Build Coastguard Worker    use the style that is already being used so that the source is uniform and
25*9880d681SAndroid Build Coastguard Worker    easy to follow.**
26*9880d681SAndroid Build Coastguard Worker
27*9880d681SAndroid Build Coastguard WorkerNote that some code bases (e.g. ``libc++``) have really good reasons to deviate
28*9880d681SAndroid Build Coastguard Workerfrom the coding standards.  In the case of ``libc++``, this is because the
29*9880d681SAndroid Build Coastguard Workernaming and other conventions are dictated by the C++ standard.  If you think
30*9880d681SAndroid Build Coastguard Workerthere is a specific good reason to deviate from the standards here, please bring
31*9880d681SAndroid Build Coastguard Workerit up on the LLVM-dev mailing list.
32*9880d681SAndroid Build Coastguard Worker
33*9880d681SAndroid Build Coastguard WorkerThere are some conventions that are not uniformly followed in the code base
34*9880d681SAndroid Build Coastguard Worker(e.g. the naming convention).  This is because they are relatively new, and a
35*9880d681SAndroid Build Coastguard Workerlot of code was written before they were put in place.  Our long term goal is
36*9880d681SAndroid Build Coastguard Workerfor the entire codebase to follow the convention, but we explicitly *do not*
37*9880d681SAndroid Build Coastguard Workerwant patches that do large-scale reformating of existing code.  On the other
38*9880d681SAndroid Build Coastguard Workerhand, it is reasonable to rename the methods of a class if you're about to
39*9880d681SAndroid Build Coastguard Workerchange it in some other way.  Just do the reformating as a separate commit from
40*9880d681SAndroid Build Coastguard Workerthe functionality change.
41*9880d681SAndroid Build Coastguard Worker
42*9880d681SAndroid Build Coastguard WorkerThe ultimate goal of these guidelines is to increase the readability and
43*9880d681SAndroid Build Coastguard Workermaintainability of our common source base. If you have suggestions for topics to
44*9880d681SAndroid Build Coastguard Workerbe included, please mail them to `Chris <mailto:[email protected]>`_.
45*9880d681SAndroid Build Coastguard Worker
46*9880d681SAndroid Build Coastguard WorkerLanguages, Libraries, and Standards
47*9880d681SAndroid Build Coastguard Worker===================================
48*9880d681SAndroid Build Coastguard Worker
49*9880d681SAndroid Build Coastguard WorkerMost source code in LLVM and other LLVM projects using these coding standards
50*9880d681SAndroid Build Coastguard Workeris C++ code. There are some places where C code is used either due to
51*9880d681SAndroid Build Coastguard Workerenvironment restrictions, historical restrictions, or due to third-party source
52*9880d681SAndroid Build Coastguard Workercode imported into the tree. Generally, our preference is for standards
53*9880d681SAndroid Build Coastguard Workerconforming, modern, and portable C++ code as the implementation language of
54*9880d681SAndroid Build Coastguard Workerchoice.
55*9880d681SAndroid Build Coastguard Worker
56*9880d681SAndroid Build Coastguard WorkerC++ Standard Versions
57*9880d681SAndroid Build Coastguard Worker---------------------
58*9880d681SAndroid Build Coastguard Worker
59*9880d681SAndroid Build Coastguard WorkerLLVM, Clang, and LLD are currently written using C++11 conforming code,
60*9880d681SAndroid Build Coastguard Workeralthough we restrict ourselves to features which are available in the major
61*9880d681SAndroid Build Coastguard Workertoolchains supported as host compilers. The LLDB project is even more
62*9880d681SAndroid Build Coastguard Workeraggressive in the set of host compilers supported and thus uses still more
63*9880d681SAndroid Build Coastguard Workerfeatures. Regardless of the supported features, code is expected to (when
64*9880d681SAndroid Build Coastguard Workerreasonable) be standard, portable, and modern C++11 code. We avoid unnecessary
65*9880d681SAndroid Build Coastguard Workervendor-specific extensions, etc.
66*9880d681SAndroid Build Coastguard Worker
67*9880d681SAndroid Build Coastguard WorkerC++ Standard Library
68*9880d681SAndroid Build Coastguard Worker--------------------
69*9880d681SAndroid Build Coastguard Worker
70*9880d681SAndroid Build Coastguard WorkerUse the C++ standard library facilities whenever they are available for
71*9880d681SAndroid Build Coastguard Workera particular task. LLVM and related projects emphasize and rely on the standard
72*9880d681SAndroid Build Coastguard Workerlibrary facilities for as much as possible. Common support libraries providing
73*9880d681SAndroid Build Coastguard Workerfunctionality missing from the standard library for which there are standard
74*9880d681SAndroid Build Coastguard Workerinterfaces or active work on adding standard interfaces will often be
75*9880d681SAndroid Build Coastguard Workerimplemented in the LLVM namespace following the expected standard interface.
76*9880d681SAndroid Build Coastguard Worker
77*9880d681SAndroid Build Coastguard WorkerThere are some exceptions such as the standard I/O streams library which are
78*9880d681SAndroid Build Coastguard Workeravoided. Also, there is much more detailed information on these subjects in the
79*9880d681SAndroid Build Coastguard Worker:doc:`ProgrammersManual`.
80*9880d681SAndroid Build Coastguard Worker
81*9880d681SAndroid Build Coastguard WorkerSupported C++11 Language and Library Features
82*9880d681SAndroid Build Coastguard Worker---------------------------------------------
83*9880d681SAndroid Build Coastguard Worker
84*9880d681SAndroid Build Coastguard WorkerWhile LLVM, Clang, and LLD use C++11, not all features are available in all of
85*9880d681SAndroid Build Coastguard Workerthe toolchains which we support. The set of features supported for use in LLVM
86*9880d681SAndroid Build Coastguard Workeris the intersection of those supported in MSVC 2013, GCC 4.7, and Clang 3.1.
87*9880d681SAndroid Build Coastguard WorkerThe ultimate definition of this set is what build bots with those respective
88*9880d681SAndroid Build Coastguard Workertoolchains accept. Don't argue with the build bots. However, we have some
89*9880d681SAndroid Build Coastguard Workerguidance below to help you know what to expect.
90*9880d681SAndroid Build Coastguard Worker
91*9880d681SAndroid Build Coastguard WorkerEach toolchain provides a good reference for what it accepts:
92*9880d681SAndroid Build Coastguard Worker
93*9880d681SAndroid Build Coastguard Worker* Clang: http://clang.llvm.org/cxx_status.html
94*9880d681SAndroid Build Coastguard Worker* GCC: http://gcc.gnu.org/projects/cxx0x.html
95*9880d681SAndroid Build Coastguard Worker* MSVC: http://msdn.microsoft.com/en-us/library/hh567368.aspx
96*9880d681SAndroid Build Coastguard Worker
97*9880d681SAndroid Build Coastguard WorkerIn most cases, the MSVC list will be the dominating factor. Here is a summary
98*9880d681SAndroid Build Coastguard Workerof the features that are expected to work. Features not on this list are
99*9880d681SAndroid Build Coastguard Workerunlikely to be supported by our host compilers.
100*9880d681SAndroid Build Coastguard Worker
101*9880d681SAndroid Build Coastguard Worker* Rvalue references: N2118_
102*9880d681SAndroid Build Coastguard Worker
103*9880d681SAndroid Build Coastguard Worker  * But *not* Rvalue references for ``*this`` or member qualifiers (N2439_)
104*9880d681SAndroid Build Coastguard Worker
105*9880d681SAndroid Build Coastguard Worker* Static assert: N1720_
106*9880d681SAndroid Build Coastguard Worker* ``auto`` type deduction: N1984_, N1737_
107*9880d681SAndroid Build Coastguard Worker* Trailing return types: N2541_
108*9880d681SAndroid Build Coastguard Worker* Lambdas: N2927_
109*9880d681SAndroid Build Coastguard Worker
110*9880d681SAndroid Build Coastguard Worker  * But *not* lambdas with default arguments.
111*9880d681SAndroid Build Coastguard Worker
112*9880d681SAndroid Build Coastguard Worker* ``decltype``: N2343_
113*9880d681SAndroid Build Coastguard Worker* Nested closing right angle brackets: N1757_
114*9880d681SAndroid Build Coastguard Worker* Extern templates: N1987_
115*9880d681SAndroid Build Coastguard Worker* ``nullptr``: N2431_
116*9880d681SAndroid Build Coastguard Worker* Strongly-typed and forward declarable enums: N2347_, N2764_
117*9880d681SAndroid Build Coastguard Worker* Local and unnamed types as template arguments: N2657_
118*9880d681SAndroid Build Coastguard Worker* Range-based for-loop: N2930_
119*9880d681SAndroid Build Coastguard Worker
120*9880d681SAndroid Build Coastguard Worker  * But ``{}`` are required around inner ``do {} while()`` loops.  As a result,
121*9880d681SAndroid Build Coastguard Worker    ``{}`` are required around function-like macros inside range-based for
122*9880d681SAndroid Build Coastguard Worker    loops.
123*9880d681SAndroid Build Coastguard Worker
124*9880d681SAndroid Build Coastguard Worker* ``override`` and ``final``: N2928_, N3206_, N3272_
125*9880d681SAndroid Build Coastguard Worker* Atomic operations and the C++11 memory model: N2429_
126*9880d681SAndroid Build Coastguard Worker* Variadic templates: N2242_
127*9880d681SAndroid Build Coastguard Worker* Explicit conversion operators: N2437_
128*9880d681SAndroid Build Coastguard Worker* Defaulted and deleted functions: N2346_
129*9880d681SAndroid Build Coastguard Worker
130*9880d681SAndroid Build Coastguard Worker  * But not defaulted move constructors or move assignment operators, MSVC 2013
131*9880d681SAndroid Build Coastguard Worker    cannot synthesize them.
132*9880d681SAndroid Build Coastguard Worker* Initializer lists: N2627_
133*9880d681SAndroid Build Coastguard Worker* Delegating constructors: N1986_
134*9880d681SAndroid Build Coastguard Worker* Default member initializers (non-static data member initializers): N2756_
135*9880d681SAndroid Build Coastguard Worker
136*9880d681SAndroid Build Coastguard Worker  * Only use these for scalar members that would otherwise be left
137*9880d681SAndroid Build Coastguard Worker    uninitialized. Non-scalar members generally have appropriate default
138*9880d681SAndroid Build Coastguard Worker    constructors, and MSVC 2013 has problems when braced initializer lists are
139*9880d681SAndroid Build Coastguard Worker    involved.
140*9880d681SAndroid Build Coastguard Worker
141*9880d681SAndroid Build Coastguard Worker.. _N2118: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n2118.html
142*9880d681SAndroid Build Coastguard Worker.. _N2439: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2439.htm
143*9880d681SAndroid Build Coastguard Worker.. _N1720: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2004/n1720.html
144*9880d681SAndroid Build Coastguard Worker.. _N1984: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1984.pdf
145*9880d681SAndroid Build Coastguard Worker.. _N1737: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2004/n1737.pdf
146*9880d681SAndroid Build Coastguard Worker.. _N2541: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2541.htm
147*9880d681SAndroid Build Coastguard Worker.. _N2927: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2009/n2927.pdf
148*9880d681SAndroid Build Coastguard Worker.. _N2343: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2343.pdf
149*9880d681SAndroid Build Coastguard Worker.. _N1757: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1757.html
150*9880d681SAndroid Build Coastguard Worker.. _N1987: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1987.htm
151*9880d681SAndroid Build Coastguard Worker.. _N2431: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2431.pdf
152*9880d681SAndroid Build Coastguard Worker.. _N2347: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2347.pdf
153*9880d681SAndroid Build Coastguard Worker.. _N2764: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2764.pdf
154*9880d681SAndroid Build Coastguard Worker.. _N2657: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2657.htm
155*9880d681SAndroid Build Coastguard Worker.. _N2930: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2009/n2930.html
156*9880d681SAndroid Build Coastguard Worker.. _N2928: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2009/n2928.htm
157*9880d681SAndroid Build Coastguard Worker.. _N3206: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2010/n3206.htm
158*9880d681SAndroid Build Coastguard Worker.. _N3272: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2011/n3272.htm
159*9880d681SAndroid Build Coastguard Worker.. _N2429: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2429.htm
160*9880d681SAndroid Build Coastguard Worker.. _N2242: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2242.pdf
161*9880d681SAndroid Build Coastguard Worker.. _N2437: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2437.pdf
162*9880d681SAndroid Build Coastguard Worker.. _N2346: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2346.htm
163*9880d681SAndroid Build Coastguard Worker.. _N2627: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2672.htm
164*9880d681SAndroid Build Coastguard Worker.. _N1986: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1986.pdf
165*9880d681SAndroid Build Coastguard Worker.. _N2756: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2756.htm
166*9880d681SAndroid Build Coastguard Worker
167*9880d681SAndroid Build Coastguard WorkerThe supported features in the C++11 standard libraries are less well tracked,
168*9880d681SAndroid Build Coastguard Workerbut also much greater. Most of the standard libraries implement most of C++11's
169*9880d681SAndroid Build Coastguard Workerlibrary. The most likely lowest common denominator is Linux support. For
170*9880d681SAndroid Build Coastguard Workerlibc++, the support is just poorly tested and undocumented but expected to be
171*9880d681SAndroid Build Coastguard Workerlargely complete. YMMV. For libstdc++, the support is documented in detail in
172*9880d681SAndroid Build Coastguard Worker`the libstdc++ manual`_. There are some very minor missing facilities that are
173*9880d681SAndroid Build Coastguard Workerunlikely to be common problems, and there are a few larger gaps that are worth
174*9880d681SAndroid Build Coastguard Workerbeing aware of:
175*9880d681SAndroid Build Coastguard Worker
176*9880d681SAndroid Build Coastguard Worker* Not all of the type traits are implemented
177*9880d681SAndroid Build Coastguard Worker* No regular expression library.
178*9880d681SAndroid Build Coastguard Worker* While most of the atomics library is well implemented, the fences are
179*9880d681SAndroid Build Coastguard Worker  missing. Fortunately, they are rarely needed.
180*9880d681SAndroid Build Coastguard Worker* The locale support is incomplete.
181*9880d681SAndroid Build Coastguard Worker
182*9880d681SAndroid Build Coastguard WorkerOther than these areas you should assume the standard library is available and
183*9880d681SAndroid Build Coastguard Workerworking as expected until some build bot tells you otherwise. If you're in an
184*9880d681SAndroid Build Coastguard Workeruncertain area of one of the above points, but you cannot test on a Linux
185*9880d681SAndroid Build Coastguard Workersystem, your best approach is to minimize your use of these features, and watch
186*9880d681SAndroid Build Coastguard Workerthe Linux build bots to find out if your usage triggered a bug. For example, if
187*9880d681SAndroid Build Coastguard Workeryou hit a type trait which doesn't work we can then add support to LLVM's
188*9880d681SAndroid Build Coastguard Workertraits header to emulate it.
189*9880d681SAndroid Build Coastguard Worker
190*9880d681SAndroid Build Coastguard Worker.. _the libstdc++ manual:
191*9880d681SAndroid Build Coastguard Worker  http://gcc.gnu.org/onlinedocs/gcc-4.7.3/libstdc++/manual/manual/status.html#status.iso.2011
192*9880d681SAndroid Build Coastguard Worker
193*9880d681SAndroid Build Coastguard WorkerOther Languages
194*9880d681SAndroid Build Coastguard Worker---------------
195*9880d681SAndroid Build Coastguard Worker
196*9880d681SAndroid Build Coastguard WorkerAny code written in the Go programming language is not subject to the
197*9880d681SAndroid Build Coastguard Workerformatting rules below. Instead, we adopt the formatting rules enforced by
198*9880d681SAndroid Build Coastguard Workerthe `gofmt`_ tool.
199*9880d681SAndroid Build Coastguard Worker
200*9880d681SAndroid Build Coastguard WorkerGo code should strive to be idiomatic. Two good sets of guidelines for what
201*9880d681SAndroid Build Coastguard Workerthis means are `Effective Go`_ and `Go Code Review Comments`_.
202*9880d681SAndroid Build Coastguard Worker
203*9880d681SAndroid Build Coastguard Worker.. _gofmt:
204*9880d681SAndroid Build Coastguard Worker  https://golang.org/cmd/gofmt/
205*9880d681SAndroid Build Coastguard Worker
206*9880d681SAndroid Build Coastguard Worker.. _Effective Go:
207*9880d681SAndroid Build Coastguard Worker  https://golang.org/doc/effective_go.html
208*9880d681SAndroid Build Coastguard Worker
209*9880d681SAndroid Build Coastguard Worker.. _Go Code Review Comments:
210*9880d681SAndroid Build Coastguard Worker  https://code.google.com/p/go-wiki/wiki/CodeReviewComments
211*9880d681SAndroid Build Coastguard Worker
212*9880d681SAndroid Build Coastguard WorkerMechanical Source Issues
213*9880d681SAndroid Build Coastguard Worker========================
214*9880d681SAndroid Build Coastguard Worker
215*9880d681SAndroid Build Coastguard WorkerSource Code Formatting
216*9880d681SAndroid Build Coastguard Worker----------------------
217*9880d681SAndroid Build Coastguard Worker
218*9880d681SAndroid Build Coastguard WorkerCommenting
219*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^
220*9880d681SAndroid Build Coastguard Worker
221*9880d681SAndroid Build Coastguard WorkerComments are one critical part of readability and maintainability.  Everyone
222*9880d681SAndroid Build Coastguard Workerknows they should comment their code, and so should you.  When writing comments,
223*9880d681SAndroid Build Coastguard Workerwrite them as English prose, which means they should use proper capitalization,
224*9880d681SAndroid Build Coastguard Workerpunctuation, etc.  Aim to describe what the code is trying to do and why, not
225*9880d681SAndroid Build Coastguard Worker*how* it does it at a micro level. Here are a few critical things to document:
226*9880d681SAndroid Build Coastguard Worker
227*9880d681SAndroid Build Coastguard Worker.. _header file comment:
228*9880d681SAndroid Build Coastguard Worker
229*9880d681SAndroid Build Coastguard WorkerFile Headers
230*9880d681SAndroid Build Coastguard Worker""""""""""""
231*9880d681SAndroid Build Coastguard Worker
232*9880d681SAndroid Build Coastguard WorkerEvery source file should have a header on it that describes the basic purpose of
233*9880d681SAndroid Build Coastguard Workerthe file.  If a file does not have a header, it should not be checked into the
234*9880d681SAndroid Build Coastguard Workertree.  The standard header looks like this:
235*9880d681SAndroid Build Coastguard Worker
236*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
237*9880d681SAndroid Build Coastguard Worker
238*9880d681SAndroid Build Coastguard Worker  //===-- llvm/Instruction.h - Instruction class definition -------*- C++ -*-===//
239*9880d681SAndroid Build Coastguard Worker  //
240*9880d681SAndroid Build Coastguard Worker  //                     The LLVM Compiler Infrastructure
241*9880d681SAndroid Build Coastguard Worker  //
242*9880d681SAndroid Build Coastguard Worker  // This file is distributed under the University of Illinois Open Source
243*9880d681SAndroid Build Coastguard Worker  // License. See LICENSE.TXT for details.
244*9880d681SAndroid Build Coastguard Worker  //
245*9880d681SAndroid Build Coastguard Worker  //===----------------------------------------------------------------------===//
246*9880d681SAndroid Build Coastguard Worker  ///
247*9880d681SAndroid Build Coastguard Worker  /// \file
248*9880d681SAndroid Build Coastguard Worker  /// This file contains the declaration of the Instruction class, which is the
249*9880d681SAndroid Build Coastguard Worker  /// base class for all of the VM instructions.
250*9880d681SAndroid Build Coastguard Worker  ///
251*9880d681SAndroid Build Coastguard Worker  //===----------------------------------------------------------------------===//
252*9880d681SAndroid Build Coastguard Worker
253*9880d681SAndroid Build Coastguard WorkerA few things to note about this particular format: The "``-*- C++ -*-``" string
254*9880d681SAndroid Build Coastguard Workeron the first line is there to tell Emacs that the source file is a C++ file, not
255*9880d681SAndroid Build Coastguard Workera C file (Emacs assumes ``.h`` files are C files by default).
256*9880d681SAndroid Build Coastguard Worker
257*9880d681SAndroid Build Coastguard Worker.. note::
258*9880d681SAndroid Build Coastguard Worker
259*9880d681SAndroid Build Coastguard Worker    This tag is not necessary in ``.cpp`` files.  The name of the file is also
260*9880d681SAndroid Build Coastguard Worker    on the first line, along with a very short description of the purpose of the
261*9880d681SAndroid Build Coastguard Worker    file.  This is important when printing out code and flipping though lots of
262*9880d681SAndroid Build Coastguard Worker    pages.
263*9880d681SAndroid Build Coastguard Worker
264*9880d681SAndroid Build Coastguard WorkerThe next section in the file is a concise note that defines the license that the
265*9880d681SAndroid Build Coastguard Workerfile is released under.  This makes it perfectly clear what terms the source
266*9880d681SAndroid Build Coastguard Workercode can be distributed under and should not be modified in any way.
267*9880d681SAndroid Build Coastguard Worker
268*9880d681SAndroid Build Coastguard WorkerThe main body is a ``doxygen`` comment (identified by the ``///`` comment
269*9880d681SAndroid Build Coastguard Workermarker instead of the usual ``//``) describing the purpose of the file.  The
270*9880d681SAndroid Build Coastguard Workerfirst sentence or a passage beginning with ``\brief`` is used as an abstract.
271*9880d681SAndroid Build Coastguard WorkerAny additional information should be separated by a blank line.  If an
272*9880d681SAndroid Build Coastguard Workeralgorithm is being implemented or something tricky is going on, a reference
273*9880d681SAndroid Build Coastguard Workerto the paper where it is published should be included, as well as any notes or
274*9880d681SAndroid Build Coastguard Worker*gotchas* in the code to watch out for.
275*9880d681SAndroid Build Coastguard Worker
276*9880d681SAndroid Build Coastguard WorkerClass overviews
277*9880d681SAndroid Build Coastguard Worker"""""""""""""""
278*9880d681SAndroid Build Coastguard Worker
279*9880d681SAndroid Build Coastguard WorkerClasses are one fundamental part of a good object oriented design.  As such, a
280*9880d681SAndroid Build Coastguard Workerclass definition should have a comment block that explains what the class is
281*9880d681SAndroid Build Coastguard Workerused for and how it works.  Every non-trivial class is expected to have a
282*9880d681SAndroid Build Coastguard Worker``doxygen`` comment block.
283*9880d681SAndroid Build Coastguard Worker
284*9880d681SAndroid Build Coastguard WorkerMethod information
285*9880d681SAndroid Build Coastguard Worker""""""""""""""""""
286*9880d681SAndroid Build Coastguard Worker
287*9880d681SAndroid Build Coastguard WorkerMethods defined in a class (as well as any global functions) should also be
288*9880d681SAndroid Build Coastguard Workerdocumented properly.  A quick note about what it does and a description of the
289*9880d681SAndroid Build Coastguard Workerborderline behaviour is all that is necessary here (unless something
290*9880d681SAndroid Build Coastguard Workerparticularly tricky or insidious is going on).  The hope is that people can
291*9880d681SAndroid Build Coastguard Workerfigure out how to use your interfaces without reading the code itself.
292*9880d681SAndroid Build Coastguard Worker
293*9880d681SAndroid Build Coastguard WorkerGood things to talk about here are what happens when something unexpected
294*9880d681SAndroid Build Coastguard Workerhappens: does the method return null?  Abort?  Format your hard disk?
295*9880d681SAndroid Build Coastguard Worker
296*9880d681SAndroid Build Coastguard WorkerComment Formatting
297*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^
298*9880d681SAndroid Build Coastguard Worker
299*9880d681SAndroid Build Coastguard WorkerIn general, prefer C++ style comments (``//`` for normal comments, ``///`` for
300*9880d681SAndroid Build Coastguard Worker``doxygen`` documentation comments).  They take less space, require
301*9880d681SAndroid Build Coastguard Workerless typing, don't have nesting problems, etc.  There are a few cases when it is
302*9880d681SAndroid Build Coastguard Workeruseful to use C style (``/* */``) comments however:
303*9880d681SAndroid Build Coastguard Worker
304*9880d681SAndroid Build Coastguard Worker#. When writing C code: Obviously if you are writing C code, use C style
305*9880d681SAndroid Build Coastguard Worker   comments.
306*9880d681SAndroid Build Coastguard Worker
307*9880d681SAndroid Build Coastguard Worker#. When writing a header file that may be ``#include``\d by a C source file.
308*9880d681SAndroid Build Coastguard Worker
309*9880d681SAndroid Build Coastguard Worker#. When writing a source file that is used by a tool that only accepts C style
310*9880d681SAndroid Build Coastguard Worker   comments.
311*9880d681SAndroid Build Coastguard Worker
312*9880d681SAndroid Build Coastguard WorkerTo comment out a large block of code, use ``#if 0`` and ``#endif``. These nest
313*9880d681SAndroid Build Coastguard Workerproperly and are better behaved in general than C style comments.
314*9880d681SAndroid Build Coastguard Worker
315*9880d681SAndroid Build Coastguard WorkerDoxygen Use in Documentation Comments
316*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
317*9880d681SAndroid Build Coastguard Worker
318*9880d681SAndroid Build Coastguard WorkerUse the ``\file`` command to turn the standard file header into a file-level
319*9880d681SAndroid Build Coastguard Workercomment.
320*9880d681SAndroid Build Coastguard Worker
321*9880d681SAndroid Build Coastguard WorkerInclude descriptive paragraphs for all public interfaces (public classes,
322*9880d681SAndroid Build Coastguard Workermember and non-member functions).  Don't just restate the information that can
323*9880d681SAndroid Build Coastguard Workerbe inferred from the API name.  The first sentence or a paragraph beginning
324*9880d681SAndroid Build Coastguard Workerwith ``\brief`` is used as an abstract. Put detailed discussion into separate
325*9880d681SAndroid Build Coastguard Workerparagraphs.
326*9880d681SAndroid Build Coastguard Worker
327*9880d681SAndroid Build Coastguard WorkerTo refer to parameter names inside a paragraph, use the ``\p name`` command.
328*9880d681SAndroid Build Coastguard WorkerDon't use the ``\arg name`` command since it starts a new paragraph that
329*9880d681SAndroid Build Coastguard Workercontains documentation for the parameter.
330*9880d681SAndroid Build Coastguard Worker
331*9880d681SAndroid Build Coastguard WorkerWrap non-inline code examples in ``\code ... \endcode``.
332*9880d681SAndroid Build Coastguard Worker
333*9880d681SAndroid Build Coastguard WorkerTo document a function parameter, start a new paragraph with the
334*9880d681SAndroid Build Coastguard Worker``\param name`` command.  If the parameter is used as an out or an in/out
335*9880d681SAndroid Build Coastguard Workerparameter, use the ``\param [out] name`` or ``\param [in,out] name`` command,
336*9880d681SAndroid Build Coastguard Workerrespectively.
337*9880d681SAndroid Build Coastguard Worker
338*9880d681SAndroid Build Coastguard WorkerTo describe function return value, start a new paragraph with the ``\returns``
339*9880d681SAndroid Build Coastguard Workercommand.
340*9880d681SAndroid Build Coastguard Worker
341*9880d681SAndroid Build Coastguard WorkerA minimal documentation comment:
342*9880d681SAndroid Build Coastguard Worker
343*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
344*9880d681SAndroid Build Coastguard Worker
345*9880d681SAndroid Build Coastguard Worker  /// Sets the xyzzy property to \p Baz.
346*9880d681SAndroid Build Coastguard Worker  void setXyzzy(bool Baz);
347*9880d681SAndroid Build Coastguard Worker
348*9880d681SAndroid Build Coastguard WorkerA documentation comment that uses all Doxygen features in a preferred way:
349*9880d681SAndroid Build Coastguard Worker
350*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
351*9880d681SAndroid Build Coastguard Worker
352*9880d681SAndroid Build Coastguard Worker  /// \brief Does foo and bar.
353*9880d681SAndroid Build Coastguard Worker  ///
354*9880d681SAndroid Build Coastguard Worker  /// Does not do foo the usual way if \p Baz is true.
355*9880d681SAndroid Build Coastguard Worker  ///
356*9880d681SAndroid Build Coastguard Worker  /// Typical usage:
357*9880d681SAndroid Build Coastguard Worker  /// \code
358*9880d681SAndroid Build Coastguard Worker  ///   fooBar(false, "quux", Res);
359*9880d681SAndroid Build Coastguard Worker  /// \endcode
360*9880d681SAndroid Build Coastguard Worker  ///
361*9880d681SAndroid Build Coastguard Worker  /// \param Quux kind of foo to do.
362*9880d681SAndroid Build Coastguard Worker  /// \param [out] Result filled with bar sequence on foo success.
363*9880d681SAndroid Build Coastguard Worker  ///
364*9880d681SAndroid Build Coastguard Worker  /// \returns true on success.
365*9880d681SAndroid Build Coastguard Worker  bool fooBar(bool Baz, StringRef Quux, std::vector<int> &Result);
366*9880d681SAndroid Build Coastguard Worker
367*9880d681SAndroid Build Coastguard WorkerDon't duplicate the documentation comment in the header file and in the
368*9880d681SAndroid Build Coastguard Workerimplementation file.  Put the documentation comments for public APIs into the
369*9880d681SAndroid Build Coastguard Workerheader file.  Documentation comments for private APIs can go to the
370*9880d681SAndroid Build Coastguard Workerimplementation file.  In any case, implementation files can include additional
371*9880d681SAndroid Build Coastguard Workercomments (not necessarily in Doxygen markup) to explain implementation details
372*9880d681SAndroid Build Coastguard Workeras needed.
373*9880d681SAndroid Build Coastguard Worker
374*9880d681SAndroid Build Coastguard WorkerDon't duplicate function or class name at the beginning of the comment.
375*9880d681SAndroid Build Coastguard WorkerFor humans it is obvious which function or class is being documented;
376*9880d681SAndroid Build Coastguard Workerautomatic documentation processing tools are smart enough to bind the comment
377*9880d681SAndroid Build Coastguard Workerto the correct declaration.
378*9880d681SAndroid Build Coastguard Worker
379*9880d681SAndroid Build Coastguard WorkerWrong:
380*9880d681SAndroid Build Coastguard Worker
381*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
382*9880d681SAndroid Build Coastguard Worker
383*9880d681SAndroid Build Coastguard Worker  // In Something.h:
384*9880d681SAndroid Build Coastguard Worker
385*9880d681SAndroid Build Coastguard Worker  /// Something - An abstraction for some complicated thing.
386*9880d681SAndroid Build Coastguard Worker  class Something {
387*9880d681SAndroid Build Coastguard Worker  public:
388*9880d681SAndroid Build Coastguard Worker    /// fooBar - Does foo and bar.
389*9880d681SAndroid Build Coastguard Worker    void fooBar();
390*9880d681SAndroid Build Coastguard Worker  };
391*9880d681SAndroid Build Coastguard Worker
392*9880d681SAndroid Build Coastguard Worker  // In Something.cpp:
393*9880d681SAndroid Build Coastguard Worker
394*9880d681SAndroid Build Coastguard Worker  /// fooBar - Does foo and bar.
395*9880d681SAndroid Build Coastguard Worker  void Something::fooBar() { ... }
396*9880d681SAndroid Build Coastguard Worker
397*9880d681SAndroid Build Coastguard WorkerCorrect:
398*9880d681SAndroid Build Coastguard Worker
399*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
400*9880d681SAndroid Build Coastguard Worker
401*9880d681SAndroid Build Coastguard Worker  // In Something.h:
402*9880d681SAndroid Build Coastguard Worker
403*9880d681SAndroid Build Coastguard Worker  /// An abstraction for some complicated thing.
404*9880d681SAndroid Build Coastguard Worker  class Something {
405*9880d681SAndroid Build Coastguard Worker  public:
406*9880d681SAndroid Build Coastguard Worker    /// Does foo and bar.
407*9880d681SAndroid Build Coastguard Worker    void fooBar();
408*9880d681SAndroid Build Coastguard Worker  };
409*9880d681SAndroid Build Coastguard Worker
410*9880d681SAndroid Build Coastguard Worker  // In Something.cpp:
411*9880d681SAndroid Build Coastguard Worker
412*9880d681SAndroid Build Coastguard Worker  // Builds a B-tree in order to do foo.  See paper by...
413*9880d681SAndroid Build Coastguard Worker  void Something::fooBar() { ... }
414*9880d681SAndroid Build Coastguard Worker
415*9880d681SAndroid Build Coastguard WorkerIt is not required to use additional Doxygen features, but sometimes it might
416*9880d681SAndroid Build Coastguard Workerbe a good idea to do so.
417*9880d681SAndroid Build Coastguard Worker
418*9880d681SAndroid Build Coastguard WorkerConsider:
419*9880d681SAndroid Build Coastguard Worker
420*9880d681SAndroid Build Coastguard Worker* adding comments to any narrow namespace containing a collection of
421*9880d681SAndroid Build Coastguard Worker  related functions or types;
422*9880d681SAndroid Build Coastguard Worker
423*9880d681SAndroid Build Coastguard Worker* using top-level groups to organize a collection of related functions at
424*9880d681SAndroid Build Coastguard Worker  namespace scope where the grouping is smaller than the namespace;
425*9880d681SAndroid Build Coastguard Worker
426*9880d681SAndroid Build Coastguard Worker* using member groups and additional comments attached to member
427*9880d681SAndroid Build Coastguard Worker  groups to organize within a class.
428*9880d681SAndroid Build Coastguard Worker
429*9880d681SAndroid Build Coastguard WorkerFor example:
430*9880d681SAndroid Build Coastguard Worker
431*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
432*9880d681SAndroid Build Coastguard Worker
433*9880d681SAndroid Build Coastguard Worker  class Something {
434*9880d681SAndroid Build Coastguard Worker    /// \name Functions that do Foo.
435*9880d681SAndroid Build Coastguard Worker    /// @{
436*9880d681SAndroid Build Coastguard Worker    void fooBar();
437*9880d681SAndroid Build Coastguard Worker    void fooBaz();
438*9880d681SAndroid Build Coastguard Worker    /// @}
439*9880d681SAndroid Build Coastguard Worker    ...
440*9880d681SAndroid Build Coastguard Worker  };
441*9880d681SAndroid Build Coastguard Worker
442*9880d681SAndroid Build Coastguard Worker``#include`` Style
443*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^
444*9880d681SAndroid Build Coastguard Worker
445*9880d681SAndroid Build Coastguard WorkerImmediately after the `header file comment`_ (and include guards if working on a
446*9880d681SAndroid Build Coastguard Workerheader file), the `minimal list of #includes`_ required by the file should be
447*9880d681SAndroid Build Coastguard Workerlisted.  We prefer these ``#include``\s to be listed in this order:
448*9880d681SAndroid Build Coastguard Worker
449*9880d681SAndroid Build Coastguard Worker.. _Main Module Header:
450*9880d681SAndroid Build Coastguard Worker.. _Local/Private Headers:
451*9880d681SAndroid Build Coastguard Worker
452*9880d681SAndroid Build Coastguard Worker#. Main Module Header
453*9880d681SAndroid Build Coastguard Worker#. Local/Private Headers
454*9880d681SAndroid Build Coastguard Worker#. ``llvm/...``
455*9880d681SAndroid Build Coastguard Worker#. System ``#include``\s
456*9880d681SAndroid Build Coastguard Worker
457*9880d681SAndroid Build Coastguard Workerand each category should be sorted lexicographically by the full path.
458*9880d681SAndroid Build Coastguard Worker
459*9880d681SAndroid Build Coastguard WorkerThe `Main Module Header`_ file applies to ``.cpp`` files which implement an
460*9880d681SAndroid Build Coastguard Workerinterface defined by a ``.h`` file.  This ``#include`` should always be included
461*9880d681SAndroid Build Coastguard Worker**first** regardless of where it lives on the file system.  By including a
462*9880d681SAndroid Build Coastguard Workerheader file first in the ``.cpp`` files that implement the interfaces, we ensure
463*9880d681SAndroid Build Coastguard Workerthat the header does not have any hidden dependencies which are not explicitly
464*9880d681SAndroid Build Coastguard Worker``#include``\d in the header, but should be. It is also a form of documentation
465*9880d681SAndroid Build Coastguard Workerin the ``.cpp`` file to indicate where the interfaces it implements are defined.
466*9880d681SAndroid Build Coastguard Worker
467*9880d681SAndroid Build Coastguard Worker.. _fit into 80 columns:
468*9880d681SAndroid Build Coastguard Worker
469*9880d681SAndroid Build Coastguard WorkerSource Code Width
470*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^
471*9880d681SAndroid Build Coastguard Worker
472*9880d681SAndroid Build Coastguard WorkerWrite your code to fit within 80 columns of text.  This helps those of us who
473*9880d681SAndroid Build Coastguard Workerlike to print out code and look at your code in an ``xterm`` without resizing
474*9880d681SAndroid Build Coastguard Workerit.
475*9880d681SAndroid Build Coastguard Worker
476*9880d681SAndroid Build Coastguard WorkerThe longer answer is that there must be some limit to the width of the code in
477*9880d681SAndroid Build Coastguard Workerorder to reasonably allow developers to have multiple files side-by-side in
478*9880d681SAndroid Build Coastguard Workerwindows on a modest display.  If you are going to pick a width limit, it is
479*9880d681SAndroid Build Coastguard Workersomewhat arbitrary but you might as well pick something standard.  Going with 90
480*9880d681SAndroid Build Coastguard Workercolumns (for example) instead of 80 columns wouldn't add any significant value
481*9880d681SAndroid Build Coastguard Workerand would be detrimental to printing out code.  Also many other projects have
482*9880d681SAndroid Build Coastguard Workerstandardized on 80 columns, so some people have already configured their editors
483*9880d681SAndroid Build Coastguard Workerfor it (vs something else, like 90 columns).
484*9880d681SAndroid Build Coastguard Worker
485*9880d681SAndroid Build Coastguard WorkerThis is one of many contentious issues in coding standards, but it is not up for
486*9880d681SAndroid Build Coastguard Workerdebate.
487*9880d681SAndroid Build Coastguard Worker
488*9880d681SAndroid Build Coastguard WorkerUse Spaces Instead of Tabs
489*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^^^^^^^^^
490*9880d681SAndroid Build Coastguard Worker
491*9880d681SAndroid Build Coastguard WorkerIn all cases, prefer spaces to tabs in source files.  People have different
492*9880d681SAndroid Build Coastguard Workerpreferred indentation levels, and different styles of indentation that they
493*9880d681SAndroid Build Coastguard Workerlike; this is fine.  What isn't fine is that different editors/viewers expand
494*9880d681SAndroid Build Coastguard Workertabs out to different tab stops.  This can cause your code to look completely
495*9880d681SAndroid Build Coastguard Workerunreadable, and it is not worth dealing with.
496*9880d681SAndroid Build Coastguard Worker
497*9880d681SAndroid Build Coastguard WorkerAs always, follow the `Golden Rule`_ above: follow the style of
498*9880d681SAndroid Build Coastguard Workerexisting code if you are modifying and extending it.  If you like four spaces of
499*9880d681SAndroid Build Coastguard Workerindentation, **DO NOT** do that in the middle of a chunk of code with two spaces
500*9880d681SAndroid Build Coastguard Workerof indentation.  Also, do not reindent a whole source file: it makes for
501*9880d681SAndroid Build Coastguard Workerincredible diffs that are absolutely worthless.
502*9880d681SAndroid Build Coastguard Worker
503*9880d681SAndroid Build Coastguard WorkerIndent Code Consistently
504*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^^^^^^^
505*9880d681SAndroid Build Coastguard Worker
506*9880d681SAndroid Build Coastguard WorkerOkay, in your first year of programming you were told that indentation is
507*9880d681SAndroid Build Coastguard Workerimportant. If you didn't believe and internalize this then, now is the time.
508*9880d681SAndroid Build Coastguard WorkerJust do it. With the introduction of C++11, there are some new formatting
509*9880d681SAndroid Build Coastguard Workerchallenges that merit some suggestions to help have consistent, maintainable,
510*9880d681SAndroid Build Coastguard Workerand tool-friendly formatting and indentation.
511*9880d681SAndroid Build Coastguard Worker
512*9880d681SAndroid Build Coastguard WorkerFormat Lambdas Like Blocks Of Code
513*9880d681SAndroid Build Coastguard Worker""""""""""""""""""""""""""""""""""
514*9880d681SAndroid Build Coastguard Worker
515*9880d681SAndroid Build Coastguard WorkerWhen formatting a multi-line lambda, format it like a block of code, that's
516*9880d681SAndroid Build Coastguard Workerwhat it is. If there is only one multi-line lambda in a statement, and there
517*9880d681SAndroid Build Coastguard Workerare no expressions lexically after it in the statement, drop the indent to the
518*9880d681SAndroid Build Coastguard Workerstandard two space indent for a block of code, as if it were an if-block opened
519*9880d681SAndroid Build Coastguard Workerby the preceding part of the statement:
520*9880d681SAndroid Build Coastguard Worker
521*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
522*9880d681SAndroid Build Coastguard Worker
523*9880d681SAndroid Build Coastguard Worker  std::sort(foo.begin(), foo.end(), [&](Foo a, Foo b) -> bool {
524*9880d681SAndroid Build Coastguard Worker    if (a.blah < b.blah)
525*9880d681SAndroid Build Coastguard Worker      return true;
526*9880d681SAndroid Build Coastguard Worker    if (a.baz < b.baz)
527*9880d681SAndroid Build Coastguard Worker      return true;
528*9880d681SAndroid Build Coastguard Worker    return a.bam < b.bam;
529*9880d681SAndroid Build Coastguard Worker  });
530*9880d681SAndroid Build Coastguard Worker
531*9880d681SAndroid Build Coastguard WorkerTo take best advantage of this formatting, if you are designing an API which
532*9880d681SAndroid Build Coastguard Workeraccepts a continuation or single callable argument (be it a functor, or
533*9880d681SAndroid Build Coastguard Workera ``std::function``), it should be the last argument if at all possible.
534*9880d681SAndroid Build Coastguard Worker
535*9880d681SAndroid Build Coastguard WorkerIf there are multiple multi-line lambdas in a statement, or there is anything
536*9880d681SAndroid Build Coastguard Workerinteresting after the lambda in the statement, indent the block two spaces from
537*9880d681SAndroid Build Coastguard Workerthe indent of the ``[]``:
538*9880d681SAndroid Build Coastguard Worker
539*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
540*9880d681SAndroid Build Coastguard Worker
541*9880d681SAndroid Build Coastguard Worker  dyn_switch(V->stripPointerCasts(),
542*9880d681SAndroid Build Coastguard Worker             [] (PHINode *PN) {
543*9880d681SAndroid Build Coastguard Worker               // process phis...
544*9880d681SAndroid Build Coastguard Worker             },
545*9880d681SAndroid Build Coastguard Worker             [] (SelectInst *SI) {
546*9880d681SAndroid Build Coastguard Worker               // process selects...
547*9880d681SAndroid Build Coastguard Worker             },
548*9880d681SAndroid Build Coastguard Worker             [] (LoadInst *LI) {
549*9880d681SAndroid Build Coastguard Worker               // process loads...
550*9880d681SAndroid Build Coastguard Worker             },
551*9880d681SAndroid Build Coastguard Worker             [] (AllocaInst *AI) {
552*9880d681SAndroid Build Coastguard Worker               // process allocas...
553*9880d681SAndroid Build Coastguard Worker             });
554*9880d681SAndroid Build Coastguard Worker
555*9880d681SAndroid Build Coastguard WorkerBraced Initializer Lists
556*9880d681SAndroid Build Coastguard Worker""""""""""""""""""""""""
557*9880d681SAndroid Build Coastguard Worker
558*9880d681SAndroid Build Coastguard WorkerWith C++11, there are significantly more uses of braced lists to perform
559*9880d681SAndroid Build Coastguard Workerinitialization. These allow you to easily construct aggregate temporaries in
560*9880d681SAndroid Build Coastguard Workerexpressions among other niceness. They now have a natural way of ending up
561*9880d681SAndroid Build Coastguard Workernested within each other and within function calls in order to build up
562*9880d681SAndroid Build Coastguard Workeraggregates (such as option structs) from local variables. To make matters
563*9880d681SAndroid Build Coastguard Workerworse, we also have many more uses of braces in an expression context that are
564*9880d681SAndroid Build Coastguard Worker*not* performing initialization.
565*9880d681SAndroid Build Coastguard Worker
566*9880d681SAndroid Build Coastguard WorkerThe historically common formatting of braced initialization of aggregate
567*9880d681SAndroid Build Coastguard Workervariables does not mix cleanly with deep nesting, general expression contexts,
568*9880d681SAndroid Build Coastguard Workerfunction arguments, and lambdas. We suggest new code use a simple rule for
569*9880d681SAndroid Build Coastguard Workerformatting braced initialization lists: act as-if the braces were parentheses
570*9880d681SAndroid Build Coastguard Workerin a function call. The formatting rules exactly match those already well
571*9880d681SAndroid Build Coastguard Workerunderstood for formatting nested function calls. Examples:
572*9880d681SAndroid Build Coastguard Worker
573*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
574*9880d681SAndroid Build Coastguard Worker
575*9880d681SAndroid Build Coastguard Worker  foo({a, b, c}, {1, 2, 3});
576*9880d681SAndroid Build Coastguard Worker
577*9880d681SAndroid Build Coastguard Worker  llvm::Constant *Mask[] = {
578*9880d681SAndroid Build Coastguard Worker      llvm::ConstantInt::get(llvm::Type::getInt32Ty(getLLVMContext()), 0),
579*9880d681SAndroid Build Coastguard Worker      llvm::ConstantInt::get(llvm::Type::getInt32Ty(getLLVMContext()), 1),
580*9880d681SAndroid Build Coastguard Worker      llvm::ConstantInt::get(llvm::Type::getInt32Ty(getLLVMContext()), 2)};
581*9880d681SAndroid Build Coastguard Worker
582*9880d681SAndroid Build Coastguard WorkerThis formatting scheme also makes it particularly easy to get predictable,
583*9880d681SAndroid Build Coastguard Workerconsistent, and automatic formatting with tools like `Clang Format`_.
584*9880d681SAndroid Build Coastguard Worker
585*9880d681SAndroid Build Coastguard Worker.. _Clang Format: http://clang.llvm.org/docs/ClangFormat.html
586*9880d681SAndroid Build Coastguard Worker
587*9880d681SAndroid Build Coastguard WorkerLanguage and Compiler Issues
588*9880d681SAndroid Build Coastguard Worker----------------------------
589*9880d681SAndroid Build Coastguard Worker
590*9880d681SAndroid Build Coastguard WorkerTreat Compiler Warnings Like Errors
591*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
592*9880d681SAndroid Build Coastguard Worker
593*9880d681SAndroid Build Coastguard WorkerIf your code has compiler warnings in it, something is wrong --- you aren't
594*9880d681SAndroid Build Coastguard Workercasting values correctly, you have "questionable" constructs in your code, or
595*9880d681SAndroid Build Coastguard Workeryou are doing something legitimately wrong.  Compiler warnings can cover up
596*9880d681SAndroid Build Coastguard Workerlegitimate errors in output and make dealing with a translation unit difficult.
597*9880d681SAndroid Build Coastguard Worker
598*9880d681SAndroid Build Coastguard WorkerIt is not possible to prevent all warnings from all compilers, nor is it
599*9880d681SAndroid Build Coastguard Workerdesirable.  Instead, pick a standard compiler (like ``gcc``) that provides a
600*9880d681SAndroid Build Coastguard Workergood thorough set of warnings, and stick to it.  At least in the case of
601*9880d681SAndroid Build Coastguard Worker``gcc``, it is possible to work around any spurious errors by changing the
602*9880d681SAndroid Build Coastguard Workersyntax of the code slightly.  For example, a warning that annoys me occurs when
603*9880d681SAndroid Build Coastguard WorkerI write code like this:
604*9880d681SAndroid Build Coastguard Worker
605*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
606*9880d681SAndroid Build Coastguard Worker
607*9880d681SAndroid Build Coastguard Worker  if (V = getValue()) {
608*9880d681SAndroid Build Coastguard Worker    ...
609*9880d681SAndroid Build Coastguard Worker  }
610*9880d681SAndroid Build Coastguard Worker
611*9880d681SAndroid Build Coastguard Worker``gcc`` will warn me that I probably want to use the ``==`` operator, and that I
612*9880d681SAndroid Build Coastguard Workerprobably mistyped it.  In most cases, I haven't, and I really don't want the
613*9880d681SAndroid Build Coastguard Workerspurious errors.  To fix this particular problem, I rewrite the code like
614*9880d681SAndroid Build Coastguard Workerthis:
615*9880d681SAndroid Build Coastguard Worker
616*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
617*9880d681SAndroid Build Coastguard Worker
618*9880d681SAndroid Build Coastguard Worker  if ((V = getValue())) {
619*9880d681SAndroid Build Coastguard Worker    ...
620*9880d681SAndroid Build Coastguard Worker  }
621*9880d681SAndroid Build Coastguard Worker
622*9880d681SAndroid Build Coastguard Workerwhich shuts ``gcc`` up.  Any ``gcc`` warning that annoys you can be fixed by
623*9880d681SAndroid Build Coastguard Workermassaging the code appropriately.
624*9880d681SAndroid Build Coastguard Worker
625*9880d681SAndroid Build Coastguard WorkerWrite Portable Code
626*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^^
627*9880d681SAndroid Build Coastguard Worker
628*9880d681SAndroid Build Coastguard WorkerIn almost all cases, it is possible and within reason to write completely
629*9880d681SAndroid Build Coastguard Workerportable code.  If there are cases where it isn't possible to write portable
630*9880d681SAndroid Build Coastguard Workercode, isolate it behind a well defined (and well documented) interface.
631*9880d681SAndroid Build Coastguard Worker
632*9880d681SAndroid Build Coastguard WorkerIn practice, this means that you shouldn't assume much about the host compiler
633*9880d681SAndroid Build Coastguard Worker(and Visual Studio tends to be the lowest common denominator).  If advanced
634*9880d681SAndroid Build Coastguard Workerfeatures are used, they should only be an implementation detail of a library
635*9880d681SAndroid Build Coastguard Workerwhich has a simple exposed API, and preferably be buried in ``libSystem``.
636*9880d681SAndroid Build Coastguard Worker
637*9880d681SAndroid Build Coastguard WorkerDo not use RTTI or Exceptions
638*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
639*9880d681SAndroid Build Coastguard Worker
640*9880d681SAndroid Build Coastguard WorkerIn an effort to reduce code and executable size, LLVM does not use RTTI
641*9880d681SAndroid Build Coastguard Worker(e.g. ``dynamic_cast<>;``) or exceptions.  These two language features violate
642*9880d681SAndroid Build Coastguard Workerthe general C++ principle of *"you only pay for what you use"*, causing
643*9880d681SAndroid Build Coastguard Workerexecutable bloat even if exceptions are never used in the code base, or if RTTI
644*9880d681SAndroid Build Coastguard Workeris never used for a class.  Because of this, we turn them off globally in the
645*9880d681SAndroid Build Coastguard Workercode.
646*9880d681SAndroid Build Coastguard Worker
647*9880d681SAndroid Build Coastguard WorkerThat said, LLVM does make extensive use of a hand-rolled form of RTTI that use
648*9880d681SAndroid Build Coastguard Workertemplates like :ref:`isa\<>, cast\<>, and dyn_cast\<> <isa>`.
649*9880d681SAndroid Build Coastguard WorkerThis form of RTTI is opt-in and can be
650*9880d681SAndroid Build Coastguard Worker:doc:`added to any class <HowToSetUpLLVMStyleRTTI>`. It is also
651*9880d681SAndroid Build Coastguard Workersubstantially more efficient than ``dynamic_cast<>``.
652*9880d681SAndroid Build Coastguard Worker
653*9880d681SAndroid Build Coastguard Worker.. _static constructor:
654*9880d681SAndroid Build Coastguard Worker
655*9880d681SAndroid Build Coastguard WorkerDo not use Static Constructors
656*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
657*9880d681SAndroid Build Coastguard Worker
658*9880d681SAndroid Build Coastguard WorkerStatic constructors and destructors (e.g. global variables whose types have a
659*9880d681SAndroid Build Coastguard Workerconstructor or destructor) should not be added to the code base, and should be
660*9880d681SAndroid Build Coastguard Workerremoved wherever possible.  Besides `well known problems
661*9880d681SAndroid Build Coastguard Worker<http://yosefk.com/c++fqa/ctors.html#fqa-10.12>`_ where the order of
662*9880d681SAndroid Build Coastguard Workerinitialization is undefined between globals in different source files, the
663*9880d681SAndroid Build Coastguard Workerentire concept of static constructors is at odds with the common use case of
664*9880d681SAndroid Build Coastguard WorkerLLVM as a library linked into a larger application.
665*9880d681SAndroid Build Coastguard Worker
666*9880d681SAndroid Build Coastguard WorkerConsider the use of LLVM as a JIT linked into another application (perhaps for
667*9880d681SAndroid Build Coastguard Worker`OpenGL, custom languages <http://llvm.org/Users.html>`_, `shaders in movies
668*9880d681SAndroid Build Coastguard Worker<http://llvm.org/devmtg/2010-11/Gritz-OpenShadingLang.pdf>`_, etc). Due to the
669*9880d681SAndroid Build Coastguard Workerdesign of static constructors, they must be executed at startup time of the
670*9880d681SAndroid Build Coastguard Workerentire application, regardless of whether or how LLVM is used in that larger
671*9880d681SAndroid Build Coastguard Workerapplication.  There are two problems with this:
672*9880d681SAndroid Build Coastguard Worker
673*9880d681SAndroid Build Coastguard Worker* The time to run the static constructors impacts startup time of applications
674*9880d681SAndroid Build Coastguard Worker  --- a critical time for GUI apps, among others.
675*9880d681SAndroid Build Coastguard Worker
676*9880d681SAndroid Build Coastguard Worker* The static constructors cause the app to pull many extra pages of memory off
677*9880d681SAndroid Build Coastguard Worker  the disk: both the code for the constructor in each ``.o`` file and the small
678*9880d681SAndroid Build Coastguard Worker  amount of data that gets touched. In addition, touched/dirty pages put more
679*9880d681SAndroid Build Coastguard Worker  pressure on the VM system on low-memory machines.
680*9880d681SAndroid Build Coastguard Worker
681*9880d681SAndroid Build Coastguard WorkerWe would really like for there to be zero cost for linking in an additional LLVM
682*9880d681SAndroid Build Coastguard Workertarget or other library into an application, but static constructors violate
683*9880d681SAndroid Build Coastguard Workerthis goal.
684*9880d681SAndroid Build Coastguard Worker
685*9880d681SAndroid Build Coastguard WorkerThat said, LLVM unfortunately does contain static constructors.  It would be a
686*9880d681SAndroid Build Coastguard Worker`great project <http://llvm.org/PR11944>`_ for someone to purge all static
687*9880d681SAndroid Build Coastguard Workerconstructors from LLVM, and then enable the ``-Wglobal-constructors`` warning
688*9880d681SAndroid Build Coastguard Workerflag (when building with Clang) to ensure we do not regress in the future.
689*9880d681SAndroid Build Coastguard Worker
690*9880d681SAndroid Build Coastguard WorkerUse of ``class`` and ``struct`` Keywords
691*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
692*9880d681SAndroid Build Coastguard Worker
693*9880d681SAndroid Build Coastguard WorkerIn C++, the ``class`` and ``struct`` keywords can be used almost
694*9880d681SAndroid Build Coastguard Workerinterchangeably. The only difference is when they are used to declare a class:
695*9880d681SAndroid Build Coastguard Worker``class`` makes all members private by default while ``struct`` makes all
696*9880d681SAndroid Build Coastguard Workermembers public by default.
697*9880d681SAndroid Build Coastguard Worker
698*9880d681SAndroid Build Coastguard WorkerUnfortunately, not all compilers follow the rules and some will generate
699*9880d681SAndroid Build Coastguard Workerdifferent symbols based on whether ``class`` or ``struct`` was used to declare
700*9880d681SAndroid Build Coastguard Workerthe symbol (e.g., MSVC).  This can lead to problems at link time.
701*9880d681SAndroid Build Coastguard Worker
702*9880d681SAndroid Build Coastguard Worker* All declarations and definitions of a given ``class`` or ``struct`` must use
703*9880d681SAndroid Build Coastguard Worker  the same keyword.  For example:
704*9880d681SAndroid Build Coastguard Worker
705*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
706*9880d681SAndroid Build Coastguard Worker
707*9880d681SAndroid Build Coastguard Worker  class Foo;
708*9880d681SAndroid Build Coastguard Worker
709*9880d681SAndroid Build Coastguard Worker  // Breaks mangling in MSVC.
710*9880d681SAndroid Build Coastguard Worker  struct Foo { int Data; };
711*9880d681SAndroid Build Coastguard Worker
712*9880d681SAndroid Build Coastguard Worker* As a rule of thumb, ``struct`` should be kept to structures where *all*
713*9880d681SAndroid Build Coastguard Worker  members are declared public.
714*9880d681SAndroid Build Coastguard Worker
715*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
716*9880d681SAndroid Build Coastguard Worker
717*9880d681SAndroid Build Coastguard Worker  // Foo feels like a class... this is strange.
718*9880d681SAndroid Build Coastguard Worker  struct Foo {
719*9880d681SAndroid Build Coastguard Worker  private:
720*9880d681SAndroid Build Coastguard Worker    int Data;
721*9880d681SAndroid Build Coastguard Worker  public:
722*9880d681SAndroid Build Coastguard Worker    Foo() : Data(0) { }
723*9880d681SAndroid Build Coastguard Worker    int getData() const { return Data; }
724*9880d681SAndroid Build Coastguard Worker    void setData(int D) { Data = D; }
725*9880d681SAndroid Build Coastguard Worker  };
726*9880d681SAndroid Build Coastguard Worker
727*9880d681SAndroid Build Coastguard Worker  // Bar isn't POD, but it does look like a struct.
728*9880d681SAndroid Build Coastguard Worker  struct Bar {
729*9880d681SAndroid Build Coastguard Worker    int Data;
730*9880d681SAndroid Build Coastguard Worker    Bar() : Data(0) { }
731*9880d681SAndroid Build Coastguard Worker  };
732*9880d681SAndroid Build Coastguard Worker
733*9880d681SAndroid Build Coastguard WorkerDo not use Braced Initializer Lists to Call a Constructor
734*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
735*9880d681SAndroid Build Coastguard Worker
736*9880d681SAndroid Build Coastguard WorkerIn C++11 there is a "generalized initialization syntax" which allows calling
737*9880d681SAndroid Build Coastguard Workerconstructors using braced initializer lists. Do not use these to call
738*9880d681SAndroid Build Coastguard Workerconstructors with any interesting logic or if you care that you're calling some
739*9880d681SAndroid Build Coastguard Worker*particular* constructor. Those should look like function calls using
740*9880d681SAndroid Build Coastguard Workerparentheses rather than like aggregate initialization. Similarly, if you need
741*9880d681SAndroid Build Coastguard Workerto explicitly name the type and call its constructor to create a temporary,
742*9880d681SAndroid Build Coastguard Workerdon't use a braced initializer list. Instead, use a braced initializer list
743*9880d681SAndroid Build Coastguard Worker(without any type for temporaries) when doing aggregate initialization or
744*9880d681SAndroid Build Coastguard Workersomething notionally equivalent. Examples:
745*9880d681SAndroid Build Coastguard Worker
746*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
747*9880d681SAndroid Build Coastguard Worker
748*9880d681SAndroid Build Coastguard Worker  class Foo {
749*9880d681SAndroid Build Coastguard Worker  public:
750*9880d681SAndroid Build Coastguard Worker    // Construct a Foo by reading data from the disk in the whizbang format, ...
751*9880d681SAndroid Build Coastguard Worker    Foo(std::string filename);
752*9880d681SAndroid Build Coastguard Worker
753*9880d681SAndroid Build Coastguard Worker    // Construct a Foo by looking up the Nth element of some global data ...
754*9880d681SAndroid Build Coastguard Worker    Foo(int N);
755*9880d681SAndroid Build Coastguard Worker
756*9880d681SAndroid Build Coastguard Worker    // ...
757*9880d681SAndroid Build Coastguard Worker  };
758*9880d681SAndroid Build Coastguard Worker
759*9880d681SAndroid Build Coastguard Worker  // The Foo constructor call is very deliberate, no braces.
760*9880d681SAndroid Build Coastguard Worker  std::fill(foo.begin(), foo.end(), Foo("name"));
761*9880d681SAndroid Build Coastguard Worker
762*9880d681SAndroid Build Coastguard Worker  // The pair is just being constructed like an aggregate, use braces.
763*9880d681SAndroid Build Coastguard Worker  bar_map.insert({my_key, my_value});
764*9880d681SAndroid Build Coastguard Worker
765*9880d681SAndroid Build Coastguard WorkerIf you use a braced initializer list when initializing a variable, use an equals before the open curly brace:
766*9880d681SAndroid Build Coastguard Worker
767*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
768*9880d681SAndroid Build Coastguard Worker
769*9880d681SAndroid Build Coastguard Worker  int data[] = {0, 1, 2, 3};
770*9880d681SAndroid Build Coastguard Worker
771*9880d681SAndroid Build Coastguard WorkerUse ``auto`` Type Deduction to Make Code More Readable
772*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
773*9880d681SAndroid Build Coastguard Worker
774*9880d681SAndroid Build Coastguard WorkerSome are advocating a policy of "almost always ``auto``" in C++11, however LLVM
775*9880d681SAndroid Build Coastguard Workeruses a more moderate stance. Use ``auto`` if and only if it makes the code more
776*9880d681SAndroid Build Coastguard Workerreadable or easier to maintain. Don't "almost always" use ``auto``, but do use
777*9880d681SAndroid Build Coastguard Worker``auto`` with initializers like ``cast<Foo>(...)`` or other places where the
778*9880d681SAndroid Build Coastguard Workertype is already obvious from the context. Another time when ``auto`` works well
779*9880d681SAndroid Build Coastguard Workerfor these purposes is when the type would have been abstracted away anyways,
780*9880d681SAndroid Build Coastguard Workeroften behind a container's typedef such as ``std::vector<T>::iterator``.
781*9880d681SAndroid Build Coastguard Worker
782*9880d681SAndroid Build Coastguard WorkerBeware unnecessary copies with ``auto``
783*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
784*9880d681SAndroid Build Coastguard Worker
785*9880d681SAndroid Build Coastguard WorkerThe convenience of ``auto`` makes it easy to forget that its default behavior
786*9880d681SAndroid Build Coastguard Workeris a copy.  Particularly in range-based ``for`` loops, careless copies are
787*9880d681SAndroid Build Coastguard Workerexpensive.
788*9880d681SAndroid Build Coastguard Worker
789*9880d681SAndroid Build Coastguard WorkerAs a rule of thumb, use ``auto &`` unless you need to copy the result, and use
790*9880d681SAndroid Build Coastguard Worker``auto *`` when copying pointers.
791*9880d681SAndroid Build Coastguard Worker
792*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
793*9880d681SAndroid Build Coastguard Worker
794*9880d681SAndroid Build Coastguard Worker  // Typically there's no reason to copy.
795*9880d681SAndroid Build Coastguard Worker  for (const auto &Val : Container) { observe(Val); }
796*9880d681SAndroid Build Coastguard Worker  for (auto &Val : Container) { Val.change(); }
797*9880d681SAndroid Build Coastguard Worker
798*9880d681SAndroid Build Coastguard Worker  // Remove the reference if you really want a new copy.
799*9880d681SAndroid Build Coastguard Worker  for (auto Val : Container) { Val.change(); saveSomewhere(Val); }
800*9880d681SAndroid Build Coastguard Worker
801*9880d681SAndroid Build Coastguard Worker  // Copy pointers, but make it clear that they're pointers.
802*9880d681SAndroid Build Coastguard Worker  for (const auto *Ptr : Container) { observe(*Ptr); }
803*9880d681SAndroid Build Coastguard Worker  for (auto *Ptr : Container) { Ptr->change(); }
804*9880d681SAndroid Build Coastguard Worker
805*9880d681SAndroid Build Coastguard WorkerStyle Issues
806*9880d681SAndroid Build Coastguard Worker============
807*9880d681SAndroid Build Coastguard Worker
808*9880d681SAndroid Build Coastguard WorkerThe High-Level Issues
809*9880d681SAndroid Build Coastguard Worker---------------------
810*9880d681SAndroid Build Coastguard Worker
811*9880d681SAndroid Build Coastguard WorkerA Public Header File **is** a Module
812*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
813*9880d681SAndroid Build Coastguard Worker
814*9880d681SAndroid Build Coastguard WorkerC++ doesn't do too well in the modularity department.  There is no real
815*9880d681SAndroid Build Coastguard Workerencapsulation or data hiding (unless you use expensive protocol classes), but it
816*9880d681SAndroid Build Coastguard Workeris what we have to work with.  When you write a public header file (in the LLVM
817*9880d681SAndroid Build Coastguard Workersource tree, they live in the top level "``include``" directory), you are
818*9880d681SAndroid Build Coastguard Workerdefining a module of functionality.
819*9880d681SAndroid Build Coastguard Worker
820*9880d681SAndroid Build Coastguard WorkerIdeally, modules should be completely independent of each other, and their
821*9880d681SAndroid Build Coastguard Workerheader files should only ``#include`` the absolute minimum number of headers
822*9880d681SAndroid Build Coastguard Workerpossible. A module is not just a class, a function, or a namespace: it's a
823*9880d681SAndroid Build Coastguard Workercollection of these that defines an interface.  This interface may be several
824*9880d681SAndroid Build Coastguard Workerfunctions, classes, or data structures, but the important issue is how they work
825*9880d681SAndroid Build Coastguard Workertogether.
826*9880d681SAndroid Build Coastguard Worker
827*9880d681SAndroid Build Coastguard WorkerIn general, a module should be implemented by one or more ``.cpp`` files.  Each
828*9880d681SAndroid Build Coastguard Workerof these ``.cpp`` files should include the header that defines their interface
829*9880d681SAndroid Build Coastguard Workerfirst.  This ensures that all of the dependences of the module header have been
830*9880d681SAndroid Build Coastguard Workerproperly added to the module header itself, and are not implicit.  System
831*9880d681SAndroid Build Coastguard Workerheaders should be included after user headers for a translation unit.
832*9880d681SAndroid Build Coastguard Worker
833*9880d681SAndroid Build Coastguard Worker.. _minimal list of #includes:
834*9880d681SAndroid Build Coastguard Worker
835*9880d681SAndroid Build Coastguard Worker``#include`` as Little as Possible
836*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
837*9880d681SAndroid Build Coastguard Worker
838*9880d681SAndroid Build Coastguard Worker``#include`` hurts compile time performance.  Don't do it unless you have to,
839*9880d681SAndroid Build Coastguard Workerespecially in header files.
840*9880d681SAndroid Build Coastguard Worker
841*9880d681SAndroid Build Coastguard WorkerBut wait! Sometimes you need to have the definition of a class to use it, or to
842*9880d681SAndroid Build Coastguard Workerinherit from it.  In these cases go ahead and ``#include`` that header file.  Be
843*9880d681SAndroid Build Coastguard Workeraware however that there are many cases where you don't need to have the full
844*9880d681SAndroid Build Coastguard Workerdefinition of a class.  If you are using a pointer or reference to a class, you
845*9880d681SAndroid Build Coastguard Workerdon't need the header file.  If you are simply returning a class instance from a
846*9880d681SAndroid Build Coastguard Workerprototyped function or method, you don't need it.  In fact, for most cases, you
847*9880d681SAndroid Build Coastguard Workersimply don't need the definition of a class. And not ``#include``\ing speeds up
848*9880d681SAndroid Build Coastguard Workercompilation.
849*9880d681SAndroid Build Coastguard Worker
850*9880d681SAndroid Build Coastguard WorkerIt is easy to try to go too overboard on this recommendation, however.  You
851*9880d681SAndroid Build Coastguard Worker**must** include all of the header files that you are using --- you can include
852*9880d681SAndroid Build Coastguard Workerthem either directly or indirectly through another header file.  To make sure
853*9880d681SAndroid Build Coastguard Workerthat you don't accidentally forget to include a header file in your module
854*9880d681SAndroid Build Coastguard Workerheader, make sure to include your module header **first** in the implementation
855*9880d681SAndroid Build Coastguard Workerfile (as mentioned above).  This way there won't be any hidden dependencies that
856*9880d681SAndroid Build Coastguard Workeryou'll find out about later.
857*9880d681SAndroid Build Coastguard Worker
858*9880d681SAndroid Build Coastguard WorkerKeep "Internal" Headers Private
859*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
860*9880d681SAndroid Build Coastguard Worker
861*9880d681SAndroid Build Coastguard WorkerMany modules have a complex implementation that causes them to use more than one
862*9880d681SAndroid Build Coastguard Workerimplementation (``.cpp``) file.  It is often tempting to put the internal
863*9880d681SAndroid Build Coastguard Workercommunication interface (helper classes, extra functions, etc) in the public
864*9880d681SAndroid Build Coastguard Workermodule header file.  Don't do this!
865*9880d681SAndroid Build Coastguard Worker
866*9880d681SAndroid Build Coastguard WorkerIf you really need to do something like this, put a private header file in the
867*9880d681SAndroid Build Coastguard Workersame directory as the source files, and include it locally.  This ensures that
868*9880d681SAndroid Build Coastguard Workeryour private interface remains private and undisturbed by outsiders.
869*9880d681SAndroid Build Coastguard Worker
870*9880d681SAndroid Build Coastguard Worker.. note::
871*9880d681SAndroid Build Coastguard Worker
872*9880d681SAndroid Build Coastguard Worker    It's okay to put extra implementation methods in a public class itself. Just
873*9880d681SAndroid Build Coastguard Worker    make them private (or protected) and all is well.
874*9880d681SAndroid Build Coastguard Worker
875*9880d681SAndroid Build Coastguard Worker.. _early exits:
876*9880d681SAndroid Build Coastguard Worker
877*9880d681SAndroid Build Coastguard WorkerUse Early Exits and ``continue`` to Simplify Code
878*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
879*9880d681SAndroid Build Coastguard Worker
880*9880d681SAndroid Build Coastguard WorkerWhen reading code, keep in mind how much state and how many previous decisions
881*9880d681SAndroid Build Coastguard Workerhave to be remembered by the reader to understand a block of code.  Aim to
882*9880d681SAndroid Build Coastguard Workerreduce indentation where possible when it doesn't make it more difficult to
883*9880d681SAndroid Build Coastguard Workerunderstand the code.  One great way to do this is by making use of early exits
884*9880d681SAndroid Build Coastguard Workerand the ``continue`` keyword in long loops.  As an example of using an early
885*9880d681SAndroid Build Coastguard Workerexit from a function, consider this "bad" code:
886*9880d681SAndroid Build Coastguard Worker
887*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
888*9880d681SAndroid Build Coastguard Worker
889*9880d681SAndroid Build Coastguard Worker  Value *doSomething(Instruction *I) {
890*9880d681SAndroid Build Coastguard Worker    if (!isa<TerminatorInst>(I) &&
891*9880d681SAndroid Build Coastguard Worker        I->hasOneUse() && doOtherThing(I)) {
892*9880d681SAndroid Build Coastguard Worker      ... some long code ....
893*9880d681SAndroid Build Coastguard Worker    }
894*9880d681SAndroid Build Coastguard Worker
895*9880d681SAndroid Build Coastguard Worker    return 0;
896*9880d681SAndroid Build Coastguard Worker  }
897*9880d681SAndroid Build Coastguard Worker
898*9880d681SAndroid Build Coastguard WorkerThis code has several problems if the body of the ``'if'`` is large.  When
899*9880d681SAndroid Build Coastguard Workeryou're looking at the top of the function, it isn't immediately clear that this
900*9880d681SAndroid Build Coastguard Worker*only* does interesting things with non-terminator instructions, and only
901*9880d681SAndroid Build Coastguard Workerapplies to things with the other predicates.  Second, it is relatively difficult
902*9880d681SAndroid Build Coastguard Workerto describe (in comments) why these predicates are important because the ``if``
903*9880d681SAndroid Build Coastguard Workerstatement makes it difficult to lay out the comments.  Third, when you're deep
904*9880d681SAndroid Build Coastguard Workerwithin the body of the code, it is indented an extra level.  Finally, when
905*9880d681SAndroid Build Coastguard Workerreading the top of the function, it isn't clear what the result is if the
906*9880d681SAndroid Build Coastguard Workerpredicate isn't true; you have to read to the end of the function to know that
907*9880d681SAndroid Build Coastguard Workerit returns null.
908*9880d681SAndroid Build Coastguard Worker
909*9880d681SAndroid Build Coastguard WorkerIt is much preferred to format the code like this:
910*9880d681SAndroid Build Coastguard Worker
911*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
912*9880d681SAndroid Build Coastguard Worker
913*9880d681SAndroid Build Coastguard Worker  Value *doSomething(Instruction *I) {
914*9880d681SAndroid Build Coastguard Worker    // Terminators never need 'something' done to them because ...
915*9880d681SAndroid Build Coastguard Worker    if (isa<TerminatorInst>(I))
916*9880d681SAndroid Build Coastguard Worker      return 0;
917*9880d681SAndroid Build Coastguard Worker
918*9880d681SAndroid Build Coastguard Worker    // We conservatively avoid transforming instructions with multiple uses
919*9880d681SAndroid Build Coastguard Worker    // because goats like cheese.
920*9880d681SAndroid Build Coastguard Worker    if (!I->hasOneUse())
921*9880d681SAndroid Build Coastguard Worker      return 0;
922*9880d681SAndroid Build Coastguard Worker
923*9880d681SAndroid Build Coastguard Worker    // This is really just here for example.
924*9880d681SAndroid Build Coastguard Worker    if (!doOtherThing(I))
925*9880d681SAndroid Build Coastguard Worker      return 0;
926*9880d681SAndroid Build Coastguard Worker
927*9880d681SAndroid Build Coastguard Worker    ... some long code ....
928*9880d681SAndroid Build Coastguard Worker  }
929*9880d681SAndroid Build Coastguard Worker
930*9880d681SAndroid Build Coastguard WorkerThis fixes these problems.  A similar problem frequently happens in ``for``
931*9880d681SAndroid Build Coastguard Workerloops.  A silly example is something like this:
932*9880d681SAndroid Build Coastguard Worker
933*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
934*9880d681SAndroid Build Coastguard Worker
935*9880d681SAndroid Build Coastguard Worker  for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
936*9880d681SAndroid Build Coastguard Worker    if (BinaryOperator *BO = dyn_cast<BinaryOperator>(II)) {
937*9880d681SAndroid Build Coastguard Worker      Value *LHS = BO->getOperand(0);
938*9880d681SAndroid Build Coastguard Worker      Value *RHS = BO->getOperand(1);
939*9880d681SAndroid Build Coastguard Worker      if (LHS != RHS) {
940*9880d681SAndroid Build Coastguard Worker        ...
941*9880d681SAndroid Build Coastguard Worker      }
942*9880d681SAndroid Build Coastguard Worker    }
943*9880d681SAndroid Build Coastguard Worker  }
944*9880d681SAndroid Build Coastguard Worker
945*9880d681SAndroid Build Coastguard WorkerWhen you have very, very small loops, this sort of structure is fine. But if it
946*9880d681SAndroid Build Coastguard Workerexceeds more than 10-15 lines, it becomes difficult for people to read and
947*9880d681SAndroid Build Coastguard Workerunderstand at a glance. The problem with this sort of code is that it gets very
948*9880d681SAndroid Build Coastguard Workernested very quickly. Meaning that the reader of the code has to keep a lot of
949*9880d681SAndroid Build Coastguard Workercontext in their brain to remember what is going immediately on in the loop,
950*9880d681SAndroid Build Coastguard Workerbecause they don't know if/when the ``if`` conditions will have ``else``\s etc.
951*9880d681SAndroid Build Coastguard WorkerIt is strongly preferred to structure the loop like this:
952*9880d681SAndroid Build Coastguard Worker
953*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
954*9880d681SAndroid Build Coastguard Worker
955*9880d681SAndroid Build Coastguard Worker  for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
956*9880d681SAndroid Build Coastguard Worker    BinaryOperator *BO = dyn_cast<BinaryOperator>(II);
957*9880d681SAndroid Build Coastguard Worker    if (!BO) continue;
958*9880d681SAndroid Build Coastguard Worker
959*9880d681SAndroid Build Coastguard Worker    Value *LHS = BO->getOperand(0);
960*9880d681SAndroid Build Coastguard Worker    Value *RHS = BO->getOperand(1);
961*9880d681SAndroid Build Coastguard Worker    if (LHS == RHS) continue;
962*9880d681SAndroid Build Coastguard Worker
963*9880d681SAndroid Build Coastguard Worker    ...
964*9880d681SAndroid Build Coastguard Worker  }
965*9880d681SAndroid Build Coastguard Worker
966*9880d681SAndroid Build Coastguard WorkerThis has all the benefits of using early exits for functions: it reduces nesting
967*9880d681SAndroid Build Coastguard Workerof the loop, it makes it easier to describe why the conditions are true, and it
968*9880d681SAndroid Build Coastguard Workermakes it obvious to the reader that there is no ``else`` coming up that they
969*9880d681SAndroid Build Coastguard Workerhave to push context into their brain for.  If a loop is large, this can be a
970*9880d681SAndroid Build Coastguard Workerbig understandability win.
971*9880d681SAndroid Build Coastguard Worker
972*9880d681SAndroid Build Coastguard WorkerDon't use ``else`` after a ``return``
973*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
974*9880d681SAndroid Build Coastguard Worker
975*9880d681SAndroid Build Coastguard WorkerFor similar reasons above (reduction of indentation and easier reading), please
976*9880d681SAndroid Build Coastguard Workerdo not use ``'else'`` or ``'else if'`` after something that interrupts control
977*9880d681SAndroid Build Coastguard Workerflow --- like ``return``, ``break``, ``continue``, ``goto``, etc. For
978*9880d681SAndroid Build Coastguard Workerexample, this is *bad*:
979*9880d681SAndroid Build Coastguard Worker
980*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
981*9880d681SAndroid Build Coastguard Worker
982*9880d681SAndroid Build Coastguard Worker  case 'J': {
983*9880d681SAndroid Build Coastguard Worker    if (Signed) {
984*9880d681SAndroid Build Coastguard Worker      Type = Context.getsigjmp_bufType();
985*9880d681SAndroid Build Coastguard Worker      if (Type.isNull()) {
986*9880d681SAndroid Build Coastguard Worker        Error = ASTContext::GE_Missing_sigjmp_buf;
987*9880d681SAndroid Build Coastguard Worker        return QualType();
988*9880d681SAndroid Build Coastguard Worker      } else {
989*9880d681SAndroid Build Coastguard Worker        break;
990*9880d681SAndroid Build Coastguard Worker      }
991*9880d681SAndroid Build Coastguard Worker    } else {
992*9880d681SAndroid Build Coastguard Worker      Type = Context.getjmp_bufType();
993*9880d681SAndroid Build Coastguard Worker      if (Type.isNull()) {
994*9880d681SAndroid Build Coastguard Worker        Error = ASTContext::GE_Missing_jmp_buf;
995*9880d681SAndroid Build Coastguard Worker        return QualType();
996*9880d681SAndroid Build Coastguard Worker      } else {
997*9880d681SAndroid Build Coastguard Worker        break;
998*9880d681SAndroid Build Coastguard Worker      }
999*9880d681SAndroid Build Coastguard Worker    }
1000*9880d681SAndroid Build Coastguard Worker  }
1001*9880d681SAndroid Build Coastguard Worker
1002*9880d681SAndroid Build Coastguard WorkerIt is better to write it like this:
1003*9880d681SAndroid Build Coastguard Worker
1004*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
1005*9880d681SAndroid Build Coastguard Worker
1006*9880d681SAndroid Build Coastguard Worker  case 'J':
1007*9880d681SAndroid Build Coastguard Worker    if (Signed) {
1008*9880d681SAndroid Build Coastguard Worker      Type = Context.getsigjmp_bufType();
1009*9880d681SAndroid Build Coastguard Worker      if (Type.isNull()) {
1010*9880d681SAndroid Build Coastguard Worker        Error = ASTContext::GE_Missing_sigjmp_buf;
1011*9880d681SAndroid Build Coastguard Worker        return QualType();
1012*9880d681SAndroid Build Coastguard Worker      }
1013*9880d681SAndroid Build Coastguard Worker    } else {
1014*9880d681SAndroid Build Coastguard Worker      Type = Context.getjmp_bufType();
1015*9880d681SAndroid Build Coastguard Worker      if (Type.isNull()) {
1016*9880d681SAndroid Build Coastguard Worker        Error = ASTContext::GE_Missing_jmp_buf;
1017*9880d681SAndroid Build Coastguard Worker        return QualType();
1018*9880d681SAndroid Build Coastguard Worker      }
1019*9880d681SAndroid Build Coastguard Worker    }
1020*9880d681SAndroid Build Coastguard Worker    break;
1021*9880d681SAndroid Build Coastguard Worker
1022*9880d681SAndroid Build Coastguard WorkerOr better yet (in this case) as:
1023*9880d681SAndroid Build Coastguard Worker
1024*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
1025*9880d681SAndroid Build Coastguard Worker
1026*9880d681SAndroid Build Coastguard Worker  case 'J':
1027*9880d681SAndroid Build Coastguard Worker    if (Signed)
1028*9880d681SAndroid Build Coastguard Worker      Type = Context.getsigjmp_bufType();
1029*9880d681SAndroid Build Coastguard Worker    else
1030*9880d681SAndroid Build Coastguard Worker      Type = Context.getjmp_bufType();
1031*9880d681SAndroid Build Coastguard Worker
1032*9880d681SAndroid Build Coastguard Worker    if (Type.isNull()) {
1033*9880d681SAndroid Build Coastguard Worker      Error = Signed ? ASTContext::GE_Missing_sigjmp_buf :
1034*9880d681SAndroid Build Coastguard Worker                       ASTContext::GE_Missing_jmp_buf;
1035*9880d681SAndroid Build Coastguard Worker      return QualType();
1036*9880d681SAndroid Build Coastguard Worker    }
1037*9880d681SAndroid Build Coastguard Worker    break;
1038*9880d681SAndroid Build Coastguard Worker
1039*9880d681SAndroid Build Coastguard WorkerThe idea is to reduce indentation and the amount of code you have to keep track
1040*9880d681SAndroid Build Coastguard Workerof when reading the code.
1041*9880d681SAndroid Build Coastguard Worker
1042*9880d681SAndroid Build Coastguard WorkerTurn Predicate Loops into Predicate Functions
1043*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1044*9880d681SAndroid Build Coastguard Worker
1045*9880d681SAndroid Build Coastguard WorkerIt is very common to write small loops that just compute a boolean value.  There
1046*9880d681SAndroid Build Coastguard Workerare a number of ways that people commonly write these, but an example of this
1047*9880d681SAndroid Build Coastguard Workersort of thing is:
1048*9880d681SAndroid Build Coastguard Worker
1049*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
1050*9880d681SAndroid Build Coastguard Worker
1051*9880d681SAndroid Build Coastguard Worker  bool FoundFoo = false;
1052*9880d681SAndroid Build Coastguard Worker  for (unsigned I = 0, E = BarList.size(); I != E; ++I)
1053*9880d681SAndroid Build Coastguard Worker    if (BarList[I]->isFoo()) {
1054*9880d681SAndroid Build Coastguard Worker      FoundFoo = true;
1055*9880d681SAndroid Build Coastguard Worker      break;
1056*9880d681SAndroid Build Coastguard Worker    }
1057*9880d681SAndroid Build Coastguard Worker
1058*9880d681SAndroid Build Coastguard Worker  if (FoundFoo) {
1059*9880d681SAndroid Build Coastguard Worker    ...
1060*9880d681SAndroid Build Coastguard Worker  }
1061*9880d681SAndroid Build Coastguard Worker
1062*9880d681SAndroid Build Coastguard WorkerThis sort of code is awkward to write, and is almost always a bad sign.  Instead
1063*9880d681SAndroid Build Coastguard Workerof this sort of loop, we strongly prefer to use a predicate function (which may
1064*9880d681SAndroid Build Coastguard Workerbe `static`_) that uses `early exits`_ to compute the predicate.  We prefer the
1065*9880d681SAndroid Build Coastguard Workercode to be structured like this:
1066*9880d681SAndroid Build Coastguard Worker
1067*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
1068*9880d681SAndroid Build Coastguard Worker
1069*9880d681SAndroid Build Coastguard Worker  /// \returns true if the specified list has an element that is a foo.
1070*9880d681SAndroid Build Coastguard Worker  static bool containsFoo(const std::vector<Bar*> &List) {
1071*9880d681SAndroid Build Coastguard Worker    for (unsigned I = 0, E = List.size(); I != E; ++I)
1072*9880d681SAndroid Build Coastguard Worker      if (List[I]->isFoo())
1073*9880d681SAndroid Build Coastguard Worker        return true;
1074*9880d681SAndroid Build Coastguard Worker    return false;
1075*9880d681SAndroid Build Coastguard Worker  }
1076*9880d681SAndroid Build Coastguard Worker  ...
1077*9880d681SAndroid Build Coastguard Worker
1078*9880d681SAndroid Build Coastguard Worker  if (containsFoo(BarList)) {
1079*9880d681SAndroid Build Coastguard Worker    ...
1080*9880d681SAndroid Build Coastguard Worker  }
1081*9880d681SAndroid Build Coastguard Worker
1082*9880d681SAndroid Build Coastguard WorkerThere are many reasons for doing this: it reduces indentation and factors out
1083*9880d681SAndroid Build Coastguard Workercode which can often be shared by other code that checks for the same predicate.
1084*9880d681SAndroid Build Coastguard WorkerMore importantly, it *forces you to pick a name* for the function, and forces
1085*9880d681SAndroid Build Coastguard Workeryou to write a comment for it.  In this silly example, this doesn't add much
1086*9880d681SAndroid Build Coastguard Workervalue.  However, if the condition is complex, this can make it a lot easier for
1087*9880d681SAndroid Build Coastguard Workerthe reader to understand the code that queries for this predicate.  Instead of
1088*9880d681SAndroid Build Coastguard Workerbeing faced with the in-line details of how we check to see if the BarList
1089*9880d681SAndroid Build Coastguard Workercontains a foo, we can trust the function name and continue reading with better
1090*9880d681SAndroid Build Coastguard Workerlocality.
1091*9880d681SAndroid Build Coastguard Worker
1092*9880d681SAndroid Build Coastguard WorkerThe Low-Level Issues
1093*9880d681SAndroid Build Coastguard Worker--------------------
1094*9880d681SAndroid Build Coastguard Worker
1095*9880d681SAndroid Build Coastguard WorkerName Types, Functions, Variables, and Enumerators Properly
1096*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1097*9880d681SAndroid Build Coastguard Worker
1098*9880d681SAndroid Build Coastguard WorkerPoorly-chosen names can mislead the reader and cause bugs. We cannot stress
1099*9880d681SAndroid Build Coastguard Workerenough how important it is to use *descriptive* names.  Pick names that match
1100*9880d681SAndroid Build Coastguard Workerthe semantics and role of the underlying entities, within reason.  Avoid
1101*9880d681SAndroid Build Coastguard Workerabbreviations unless they are well known.  After picking a good name, make sure
1102*9880d681SAndroid Build Coastguard Workerto use consistent capitalization for the name, as inconsistency requires clients
1103*9880d681SAndroid Build Coastguard Workerto either memorize the APIs or to look it up to find the exact spelling.
1104*9880d681SAndroid Build Coastguard Worker
1105*9880d681SAndroid Build Coastguard WorkerIn general, names should be in camel case (e.g. ``TextFileReader`` and
1106*9880d681SAndroid Build Coastguard Worker``isLValue()``).  Different kinds of declarations have different rules:
1107*9880d681SAndroid Build Coastguard Worker
1108*9880d681SAndroid Build Coastguard Worker* **Type names** (including classes, structs, enums, typedefs, etc) should be
1109*9880d681SAndroid Build Coastguard Worker  nouns and start with an upper-case letter (e.g. ``TextFileReader``).
1110*9880d681SAndroid Build Coastguard Worker
1111*9880d681SAndroid Build Coastguard Worker* **Variable names** should be nouns (as they represent state).  The name should
1112*9880d681SAndroid Build Coastguard Worker  be camel case, and start with an upper case letter (e.g. ``Leader`` or
1113*9880d681SAndroid Build Coastguard Worker  ``Boats``).
1114*9880d681SAndroid Build Coastguard Worker
1115*9880d681SAndroid Build Coastguard Worker* **Function names** should be verb phrases (as they represent actions), and
1116*9880d681SAndroid Build Coastguard Worker  command-like function should be imperative.  The name should be camel case,
1117*9880d681SAndroid Build Coastguard Worker  and start with a lower case letter (e.g. ``openFile()`` or ``isFoo()``).
1118*9880d681SAndroid Build Coastguard Worker
1119*9880d681SAndroid Build Coastguard Worker* **Enum declarations** (e.g. ``enum Foo {...}``) are types, so they should
1120*9880d681SAndroid Build Coastguard Worker  follow the naming conventions for types.  A common use for enums is as a
1121*9880d681SAndroid Build Coastguard Worker  discriminator for a union, or an indicator of a subclass.  When an enum is
1122*9880d681SAndroid Build Coastguard Worker  used for something like this, it should have a ``Kind`` suffix
1123*9880d681SAndroid Build Coastguard Worker  (e.g. ``ValueKind``).
1124*9880d681SAndroid Build Coastguard Worker
1125*9880d681SAndroid Build Coastguard Worker* **Enumerators** (e.g. ``enum { Foo, Bar }``) and **public member variables**
1126*9880d681SAndroid Build Coastguard Worker  should start with an upper-case letter, just like types.  Unless the
1127*9880d681SAndroid Build Coastguard Worker  enumerators are defined in their own small namespace or inside a class,
1128*9880d681SAndroid Build Coastguard Worker  enumerators should have a prefix corresponding to the enum declaration name.
1129*9880d681SAndroid Build Coastguard Worker  For example, ``enum ValueKind { ... };`` may contain enumerators like
1130*9880d681SAndroid Build Coastguard Worker  ``VK_Argument``, ``VK_BasicBlock``, etc.  Enumerators that are just
1131*9880d681SAndroid Build Coastguard Worker  convenience constants are exempt from the requirement for a prefix.  For
1132*9880d681SAndroid Build Coastguard Worker  instance:
1133*9880d681SAndroid Build Coastguard Worker
1134*9880d681SAndroid Build Coastguard Worker  .. code-block:: c++
1135*9880d681SAndroid Build Coastguard Worker
1136*9880d681SAndroid Build Coastguard Worker      enum {
1137*9880d681SAndroid Build Coastguard Worker        MaxSize = 42,
1138*9880d681SAndroid Build Coastguard Worker        Density = 12
1139*9880d681SAndroid Build Coastguard Worker      };
1140*9880d681SAndroid Build Coastguard Worker
1141*9880d681SAndroid Build Coastguard WorkerAs an exception, classes that mimic STL classes can have member names in STL's
1142*9880d681SAndroid Build Coastguard Workerstyle of lower-case words separated by underscores (e.g. ``begin()``,
1143*9880d681SAndroid Build Coastguard Worker``push_back()``, and ``empty()``). Classes that provide multiple
1144*9880d681SAndroid Build Coastguard Workeriterators should add a singular prefix to ``begin()`` and ``end()``
1145*9880d681SAndroid Build Coastguard Worker(e.g. ``global_begin()`` and ``use_begin()``).
1146*9880d681SAndroid Build Coastguard Worker
1147*9880d681SAndroid Build Coastguard WorkerHere are some examples of good and bad names:
1148*9880d681SAndroid Build Coastguard Worker
1149*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
1150*9880d681SAndroid Build Coastguard Worker
1151*9880d681SAndroid Build Coastguard Worker  class VehicleMaker {
1152*9880d681SAndroid Build Coastguard Worker    ...
1153*9880d681SAndroid Build Coastguard Worker    Factory<Tire> F;            // Bad -- abbreviation and non-descriptive.
1154*9880d681SAndroid Build Coastguard Worker    Factory<Tire> Factory;      // Better.
1155*9880d681SAndroid Build Coastguard Worker    Factory<Tire> TireFactory;  // Even better -- if VehicleMaker has more than one
1156*9880d681SAndroid Build Coastguard Worker                                // kind of factories.
1157*9880d681SAndroid Build Coastguard Worker  };
1158*9880d681SAndroid Build Coastguard Worker
1159*9880d681SAndroid Build Coastguard Worker  Vehicle MakeVehicle(VehicleType Type) {
1160*9880d681SAndroid Build Coastguard Worker    VehicleMaker M;                         // Might be OK if having a short life-span.
1161*9880d681SAndroid Build Coastguard Worker    Tire Tmp1 = M.makeTire();               // Bad -- 'Tmp1' provides no information.
1162*9880d681SAndroid Build Coastguard Worker    Light Headlight = M.makeLight("head");  // Good -- descriptive.
1163*9880d681SAndroid Build Coastguard Worker    ...
1164*9880d681SAndroid Build Coastguard Worker  }
1165*9880d681SAndroid Build Coastguard Worker
1166*9880d681SAndroid Build Coastguard WorkerAssert Liberally
1167*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^
1168*9880d681SAndroid Build Coastguard Worker
1169*9880d681SAndroid Build Coastguard WorkerUse the "``assert``" macro to its fullest.  Check all of your preconditions and
1170*9880d681SAndroid Build Coastguard Workerassumptions, you never know when a bug (not necessarily even yours) might be
1171*9880d681SAndroid Build Coastguard Workercaught early by an assertion, which reduces debugging time dramatically.  The
1172*9880d681SAndroid Build Coastguard Worker"``<cassert>``" header file is probably already included by the header files you
1173*9880d681SAndroid Build Coastguard Workerare using, so it doesn't cost anything to use it.
1174*9880d681SAndroid Build Coastguard Worker
1175*9880d681SAndroid Build Coastguard WorkerTo further assist with debugging, make sure to put some kind of error message in
1176*9880d681SAndroid Build Coastguard Workerthe assertion statement, which is printed if the assertion is tripped. This
1177*9880d681SAndroid Build Coastguard Workerhelps the poor debugger make sense of why an assertion is being made and
1178*9880d681SAndroid Build Coastguard Workerenforced, and hopefully what to do about it.  Here is one complete example:
1179*9880d681SAndroid Build Coastguard Worker
1180*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
1181*9880d681SAndroid Build Coastguard Worker
1182*9880d681SAndroid Build Coastguard Worker  inline Value *getOperand(unsigned I) {
1183*9880d681SAndroid Build Coastguard Worker    assert(I < Operands.size() && "getOperand() out of range!");
1184*9880d681SAndroid Build Coastguard Worker    return Operands[I];
1185*9880d681SAndroid Build Coastguard Worker  }
1186*9880d681SAndroid Build Coastguard Worker
1187*9880d681SAndroid Build Coastguard WorkerHere are more examples:
1188*9880d681SAndroid Build Coastguard Worker
1189*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
1190*9880d681SAndroid Build Coastguard Worker
1191*9880d681SAndroid Build Coastguard Worker  assert(Ty->isPointerType() && "Can't allocate a non-pointer type!");
1192*9880d681SAndroid Build Coastguard Worker
1193*9880d681SAndroid Build Coastguard Worker  assert((Opcode == Shl || Opcode == Shr) && "ShiftInst Opcode invalid!");
1194*9880d681SAndroid Build Coastguard Worker
1195*9880d681SAndroid Build Coastguard Worker  assert(idx < getNumSuccessors() && "Successor # out of range!");
1196*9880d681SAndroid Build Coastguard Worker
1197*9880d681SAndroid Build Coastguard Worker  assert(V1.getType() == V2.getType() && "Constant types must be identical!");
1198*9880d681SAndroid Build Coastguard Worker
1199*9880d681SAndroid Build Coastguard Worker  assert(isa<PHINode>(Succ->front()) && "Only works on PHId BBs!");
1200*9880d681SAndroid Build Coastguard Worker
1201*9880d681SAndroid Build Coastguard WorkerYou get the idea.
1202*9880d681SAndroid Build Coastguard Worker
1203*9880d681SAndroid Build Coastguard WorkerIn the past, asserts were used to indicate a piece of code that should not be
1204*9880d681SAndroid Build Coastguard Workerreached.  These were typically of the form:
1205*9880d681SAndroid Build Coastguard Worker
1206*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
1207*9880d681SAndroid Build Coastguard Worker
1208*9880d681SAndroid Build Coastguard Worker  assert(0 && "Invalid radix for integer literal");
1209*9880d681SAndroid Build Coastguard Worker
1210*9880d681SAndroid Build Coastguard WorkerThis has a few issues, the main one being that some compilers might not
1211*9880d681SAndroid Build Coastguard Workerunderstand the assertion, or warn about a missing return in builds where
1212*9880d681SAndroid Build Coastguard Workerassertions are compiled out.
1213*9880d681SAndroid Build Coastguard Worker
1214*9880d681SAndroid Build Coastguard WorkerToday, we have something much better: ``llvm_unreachable``:
1215*9880d681SAndroid Build Coastguard Worker
1216*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
1217*9880d681SAndroid Build Coastguard Worker
1218*9880d681SAndroid Build Coastguard Worker  llvm_unreachable("Invalid radix for integer literal");
1219*9880d681SAndroid Build Coastguard Worker
1220*9880d681SAndroid Build Coastguard WorkerWhen assertions are enabled, this will print the message if it's ever reached
1221*9880d681SAndroid Build Coastguard Workerand then exit the program. When assertions are disabled (i.e. in release
1222*9880d681SAndroid Build Coastguard Workerbuilds), ``llvm_unreachable`` becomes a hint to compilers to skip generating
1223*9880d681SAndroid Build Coastguard Workercode for this branch. If the compiler does not support this, it will fall back
1224*9880d681SAndroid Build Coastguard Workerto the "abort" implementation.
1225*9880d681SAndroid Build Coastguard Worker
1226*9880d681SAndroid Build Coastguard WorkerAnother issue is that values used only by assertions will produce an "unused
1227*9880d681SAndroid Build Coastguard Workervalue" warning when assertions are disabled.  For example, this code will warn:
1228*9880d681SAndroid Build Coastguard Worker
1229*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
1230*9880d681SAndroid Build Coastguard Worker
1231*9880d681SAndroid Build Coastguard Worker  unsigned Size = V.size();
1232*9880d681SAndroid Build Coastguard Worker  assert(Size > 42 && "Vector smaller than it should be");
1233*9880d681SAndroid Build Coastguard Worker
1234*9880d681SAndroid Build Coastguard Worker  bool NewToSet = Myset.insert(Value);
1235*9880d681SAndroid Build Coastguard Worker  assert(NewToSet && "The value shouldn't be in the set yet");
1236*9880d681SAndroid Build Coastguard Worker
1237*9880d681SAndroid Build Coastguard WorkerThese are two interesting different cases. In the first case, the call to
1238*9880d681SAndroid Build Coastguard Worker``V.size()`` is only useful for the assert, and we don't want it executed when
1239*9880d681SAndroid Build Coastguard Workerassertions are disabled.  Code like this should move the call into the assert
1240*9880d681SAndroid Build Coastguard Workeritself.  In the second case, the side effects of the call must happen whether
1241*9880d681SAndroid Build Coastguard Workerthe assert is enabled or not.  In this case, the value should be cast to void to
1242*9880d681SAndroid Build Coastguard Workerdisable the warning.  To be specific, it is preferred to write the code like
1243*9880d681SAndroid Build Coastguard Workerthis:
1244*9880d681SAndroid Build Coastguard Worker
1245*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
1246*9880d681SAndroid Build Coastguard Worker
1247*9880d681SAndroid Build Coastguard Worker  assert(V.size() > 42 && "Vector smaller than it should be");
1248*9880d681SAndroid Build Coastguard Worker
1249*9880d681SAndroid Build Coastguard Worker  bool NewToSet = Myset.insert(Value); (void)NewToSet;
1250*9880d681SAndroid Build Coastguard Worker  assert(NewToSet && "The value shouldn't be in the set yet");
1251*9880d681SAndroid Build Coastguard Worker
1252*9880d681SAndroid Build Coastguard WorkerDo Not Use ``using namespace std``
1253*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1254*9880d681SAndroid Build Coastguard Worker
1255*9880d681SAndroid Build Coastguard WorkerIn LLVM, we prefer to explicitly prefix all identifiers from the standard
1256*9880d681SAndroid Build Coastguard Workernamespace with an "``std::``" prefix, rather than rely on "``using namespace
1257*9880d681SAndroid Build Coastguard Workerstd;``".
1258*9880d681SAndroid Build Coastguard Worker
1259*9880d681SAndroid Build Coastguard WorkerIn header files, adding a ``'using namespace XXX'`` directive pollutes the
1260*9880d681SAndroid Build Coastguard Workernamespace of any source file that ``#include``\s the header.  This is clearly a
1261*9880d681SAndroid Build Coastguard Workerbad thing.
1262*9880d681SAndroid Build Coastguard Worker
1263*9880d681SAndroid Build Coastguard WorkerIn implementation files (e.g. ``.cpp`` files), the rule is more of a stylistic
1264*9880d681SAndroid Build Coastguard Workerrule, but is still important.  Basically, using explicit namespace prefixes
1265*9880d681SAndroid Build Coastguard Workermakes the code **clearer**, because it is immediately obvious what facilities
1266*9880d681SAndroid Build Coastguard Workerare being used and where they are coming from. And **more portable**, because
1267*9880d681SAndroid Build Coastguard Workernamespace clashes cannot occur between LLVM code and other namespaces.  The
1268*9880d681SAndroid Build Coastguard Workerportability rule is important because different standard library implementations
1269*9880d681SAndroid Build Coastguard Workerexpose different symbols (potentially ones they shouldn't), and future revisions
1270*9880d681SAndroid Build Coastguard Workerto the C++ standard will add more symbols to the ``std`` namespace.  As such, we
1271*9880d681SAndroid Build Coastguard Workernever use ``'using namespace std;'`` in LLVM.
1272*9880d681SAndroid Build Coastguard Worker
1273*9880d681SAndroid Build Coastguard WorkerThe exception to the general rule (i.e. it's not an exception for the ``std``
1274*9880d681SAndroid Build Coastguard Workernamespace) is for implementation files.  For example, all of the code in the
1275*9880d681SAndroid Build Coastguard WorkerLLVM project implements code that lives in the 'llvm' namespace.  As such, it is
1276*9880d681SAndroid Build Coastguard Workerok, and actually clearer, for the ``.cpp`` files to have a ``'using namespace
1277*9880d681SAndroid Build Coastguard Workerllvm;'`` directive at the top, after the ``#include``\s.  This reduces
1278*9880d681SAndroid Build Coastguard Workerindentation in the body of the file for source editors that indent based on
1279*9880d681SAndroid Build Coastguard Workerbraces, and keeps the conceptual context cleaner.  The general form of this rule
1280*9880d681SAndroid Build Coastguard Workeris that any ``.cpp`` file that implements code in any namespace may use that
1281*9880d681SAndroid Build Coastguard Workernamespace (and its parents'), but should not use any others.
1282*9880d681SAndroid Build Coastguard Worker
1283*9880d681SAndroid Build Coastguard WorkerProvide a Virtual Method Anchor for Classes in Headers
1284*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1285*9880d681SAndroid Build Coastguard Worker
1286*9880d681SAndroid Build Coastguard WorkerIf a class is defined in a header file and has a vtable (either it has virtual
1287*9880d681SAndroid Build Coastguard Workermethods or it derives from classes with virtual methods), it must always have at
1288*9880d681SAndroid Build Coastguard Workerleast one out-of-line virtual method in the class.  Without this, the compiler
1289*9880d681SAndroid Build Coastguard Workerwill copy the vtable and RTTI into every ``.o`` file that ``#include``\s the
1290*9880d681SAndroid Build Coastguard Workerheader, bloating ``.o`` file sizes and increasing link times.
1291*9880d681SAndroid Build Coastguard Worker
1292*9880d681SAndroid Build Coastguard WorkerDon't use default labels in fully covered switches over enumerations
1293*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1294*9880d681SAndroid Build Coastguard Worker
1295*9880d681SAndroid Build Coastguard Worker``-Wswitch`` warns if a switch, without a default label, over an enumeration
1296*9880d681SAndroid Build Coastguard Workerdoes not cover every enumeration value. If you write a default label on a fully
1297*9880d681SAndroid Build Coastguard Workercovered switch over an enumeration then the ``-Wswitch`` warning won't fire
1298*9880d681SAndroid Build Coastguard Workerwhen new elements are added to that enumeration. To help avoid adding these
1299*9880d681SAndroid Build Coastguard Workerkinds of defaults, Clang has the warning ``-Wcovered-switch-default`` which is
1300*9880d681SAndroid Build Coastguard Workeroff by default but turned on when building LLVM with a version of Clang that
1301*9880d681SAndroid Build Coastguard Workersupports the warning.
1302*9880d681SAndroid Build Coastguard Worker
1303*9880d681SAndroid Build Coastguard WorkerA knock-on effect of this stylistic requirement is that when building LLVM with
1304*9880d681SAndroid Build Coastguard WorkerGCC you may get warnings related to "control may reach end of non-void function"
1305*9880d681SAndroid Build Coastguard Workerif you return from each case of a covered switch-over-enum because GCC assumes
1306*9880d681SAndroid Build Coastguard Workerthat the enum expression may take any representable value, not just those of
1307*9880d681SAndroid Build Coastguard Workerindividual enumerators. To suppress this warning, use ``llvm_unreachable`` after
1308*9880d681SAndroid Build Coastguard Workerthe switch.
1309*9880d681SAndroid Build Coastguard Worker
1310*9880d681SAndroid Build Coastguard WorkerDon't evaluate ``end()`` every time through a loop
1311*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1312*9880d681SAndroid Build Coastguard Worker
1313*9880d681SAndroid Build Coastguard WorkerBecause C++ doesn't have a standard "``foreach``" loop (though it can be
1314*9880d681SAndroid Build Coastguard Workeremulated with macros and may be coming in C++'0x) we end up writing a lot of
1315*9880d681SAndroid Build Coastguard Workerloops that manually iterate from begin to end on a variety of containers or
1316*9880d681SAndroid Build Coastguard Workerthrough other data structures.  One common mistake is to write a loop in this
1317*9880d681SAndroid Build Coastguard Workerstyle:
1318*9880d681SAndroid Build Coastguard Worker
1319*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
1320*9880d681SAndroid Build Coastguard Worker
1321*9880d681SAndroid Build Coastguard Worker  BasicBlock *BB = ...
1322*9880d681SAndroid Build Coastguard Worker  for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
1323*9880d681SAndroid Build Coastguard Worker    ... use I ...
1324*9880d681SAndroid Build Coastguard Worker
1325*9880d681SAndroid Build Coastguard WorkerThe problem with this construct is that it evaluates "``BB->end()``" every time
1326*9880d681SAndroid Build Coastguard Workerthrough the loop.  Instead of writing the loop like this, we strongly prefer
1327*9880d681SAndroid Build Coastguard Workerloops to be written so that they evaluate it once before the loop starts.  A
1328*9880d681SAndroid Build Coastguard Workerconvenient way to do this is like so:
1329*9880d681SAndroid Build Coastguard Worker
1330*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
1331*9880d681SAndroid Build Coastguard Worker
1332*9880d681SAndroid Build Coastguard Worker  BasicBlock *BB = ...
1333*9880d681SAndroid Build Coastguard Worker  for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1334*9880d681SAndroid Build Coastguard Worker    ... use I ...
1335*9880d681SAndroid Build Coastguard Worker
1336*9880d681SAndroid Build Coastguard WorkerThe observant may quickly point out that these two loops may have different
1337*9880d681SAndroid Build Coastguard Workersemantics: if the container (a basic block in this case) is being mutated, then
1338*9880d681SAndroid Build Coastguard Worker"``BB->end()``" may change its value every time through the loop and the second
1339*9880d681SAndroid Build Coastguard Workerloop may not in fact be correct.  If you actually do depend on this behavior,
1340*9880d681SAndroid Build Coastguard Workerplease write the loop in the first form and add a comment indicating that you
1341*9880d681SAndroid Build Coastguard Workerdid it intentionally.
1342*9880d681SAndroid Build Coastguard Worker
1343*9880d681SAndroid Build Coastguard WorkerWhy do we prefer the second form (when correct)?  Writing the loop in the first
1344*9880d681SAndroid Build Coastguard Workerform has two problems. First it may be less efficient than evaluating it at the
1345*9880d681SAndroid Build Coastguard Workerstart of the loop.  In this case, the cost is probably minor --- a few extra
1346*9880d681SAndroid Build Coastguard Workerloads every time through the loop.  However, if the base expression is more
1347*9880d681SAndroid Build Coastguard Workercomplex, then the cost can rise quickly.  I've seen loops where the end
1348*9880d681SAndroid Build Coastguard Workerexpression was actually something like: "``SomeMap[X]->end()``" and map lookups
1349*9880d681SAndroid Build Coastguard Workerreally aren't cheap.  By writing it in the second form consistently, you
1350*9880d681SAndroid Build Coastguard Workereliminate the issue entirely and don't even have to think about it.
1351*9880d681SAndroid Build Coastguard Worker
1352*9880d681SAndroid Build Coastguard WorkerThe second (even bigger) issue is that writing the loop in the first form hints
1353*9880d681SAndroid Build Coastguard Workerto the reader that the loop is mutating the container (a fact that a comment
1354*9880d681SAndroid Build Coastguard Workerwould handily confirm!).  If you write the loop in the second form, it is
1355*9880d681SAndroid Build Coastguard Workerimmediately obvious without even looking at the body of the loop that the
1356*9880d681SAndroid Build Coastguard Workercontainer isn't being modified, which makes it easier to read the code and
1357*9880d681SAndroid Build Coastguard Workerunderstand what it does.
1358*9880d681SAndroid Build Coastguard Worker
1359*9880d681SAndroid Build Coastguard WorkerWhile the second form of the loop is a few extra keystrokes, we do strongly
1360*9880d681SAndroid Build Coastguard Workerprefer it.
1361*9880d681SAndroid Build Coastguard Worker
1362*9880d681SAndroid Build Coastguard Worker``#include <iostream>`` is Forbidden
1363*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1364*9880d681SAndroid Build Coastguard Worker
1365*9880d681SAndroid Build Coastguard WorkerThe use of ``#include <iostream>`` in library files is hereby **forbidden**,
1366*9880d681SAndroid Build Coastguard Workerbecause many common implementations transparently inject a `static constructor`_
1367*9880d681SAndroid Build Coastguard Workerinto every translation unit that includes it.
1368*9880d681SAndroid Build Coastguard Worker
1369*9880d681SAndroid Build Coastguard WorkerNote that using the other stream headers (``<sstream>`` for example) is not
1370*9880d681SAndroid Build Coastguard Workerproblematic in this regard --- just ``<iostream>``. However, ``raw_ostream``
1371*9880d681SAndroid Build Coastguard Workerprovides various APIs that are better performing for almost every use than
1372*9880d681SAndroid Build Coastguard Worker``std::ostream`` style APIs.
1373*9880d681SAndroid Build Coastguard Worker
1374*9880d681SAndroid Build Coastguard Worker.. note::
1375*9880d681SAndroid Build Coastguard Worker
1376*9880d681SAndroid Build Coastguard Worker  New code should always use `raw_ostream`_ for writing, or the
1377*9880d681SAndroid Build Coastguard Worker  ``llvm::MemoryBuffer`` API for reading files.
1378*9880d681SAndroid Build Coastguard Worker
1379*9880d681SAndroid Build Coastguard Worker.. _raw_ostream:
1380*9880d681SAndroid Build Coastguard Worker
1381*9880d681SAndroid Build Coastguard WorkerUse ``raw_ostream``
1382*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^^
1383*9880d681SAndroid Build Coastguard Worker
1384*9880d681SAndroid Build Coastguard WorkerLLVM includes a lightweight, simple, and efficient stream implementation in
1385*9880d681SAndroid Build Coastguard Worker``llvm/Support/raw_ostream.h``, which provides all of the common features of
1386*9880d681SAndroid Build Coastguard Worker``std::ostream``.  All new code should use ``raw_ostream`` instead of
1387*9880d681SAndroid Build Coastguard Worker``ostream``.
1388*9880d681SAndroid Build Coastguard Worker
1389*9880d681SAndroid Build Coastguard WorkerUnlike ``std::ostream``, ``raw_ostream`` is not a template and can be forward
1390*9880d681SAndroid Build Coastguard Workerdeclared as ``class raw_ostream``.  Public headers should generally not include
1391*9880d681SAndroid Build Coastguard Workerthe ``raw_ostream`` header, but use forward declarations and constant references
1392*9880d681SAndroid Build Coastguard Workerto ``raw_ostream`` instances.
1393*9880d681SAndroid Build Coastguard Worker
1394*9880d681SAndroid Build Coastguard WorkerAvoid ``std::endl``
1395*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^^
1396*9880d681SAndroid Build Coastguard Worker
1397*9880d681SAndroid Build Coastguard WorkerThe ``std::endl`` modifier, when used with ``iostreams`` outputs a newline to
1398*9880d681SAndroid Build Coastguard Workerthe output stream specified.  In addition to doing this, however, it also
1399*9880d681SAndroid Build Coastguard Workerflushes the output stream.  In other words, these are equivalent:
1400*9880d681SAndroid Build Coastguard Worker
1401*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
1402*9880d681SAndroid Build Coastguard Worker
1403*9880d681SAndroid Build Coastguard Worker  std::cout << std::endl;
1404*9880d681SAndroid Build Coastguard Worker  std::cout << '\n' << std::flush;
1405*9880d681SAndroid Build Coastguard Worker
1406*9880d681SAndroid Build Coastguard WorkerMost of the time, you probably have no reason to flush the output stream, so
1407*9880d681SAndroid Build Coastguard Workerit's better to use a literal ``'\n'``.
1408*9880d681SAndroid Build Coastguard Worker
1409*9880d681SAndroid Build Coastguard WorkerDon't use ``inline`` when defining a function in a class definition
1410*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1411*9880d681SAndroid Build Coastguard Worker
1412*9880d681SAndroid Build Coastguard WorkerA member function defined in a class definition is implicitly inline, so don't
1413*9880d681SAndroid Build Coastguard Workerput the ``inline`` keyword in this case.
1414*9880d681SAndroid Build Coastguard Worker
1415*9880d681SAndroid Build Coastguard WorkerDon't:
1416*9880d681SAndroid Build Coastguard Worker
1417*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
1418*9880d681SAndroid Build Coastguard Worker
1419*9880d681SAndroid Build Coastguard Worker  class Foo {
1420*9880d681SAndroid Build Coastguard Worker  public:
1421*9880d681SAndroid Build Coastguard Worker    inline void bar() {
1422*9880d681SAndroid Build Coastguard Worker      // ...
1423*9880d681SAndroid Build Coastguard Worker    }
1424*9880d681SAndroid Build Coastguard Worker  };
1425*9880d681SAndroid Build Coastguard Worker
1426*9880d681SAndroid Build Coastguard WorkerDo:
1427*9880d681SAndroid Build Coastguard Worker
1428*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
1429*9880d681SAndroid Build Coastguard Worker
1430*9880d681SAndroid Build Coastguard Worker  class Foo {
1431*9880d681SAndroid Build Coastguard Worker  public:
1432*9880d681SAndroid Build Coastguard Worker    void bar() {
1433*9880d681SAndroid Build Coastguard Worker      // ...
1434*9880d681SAndroid Build Coastguard Worker    }
1435*9880d681SAndroid Build Coastguard Worker  };
1436*9880d681SAndroid Build Coastguard Worker
1437*9880d681SAndroid Build Coastguard WorkerMicroscopic Details
1438*9880d681SAndroid Build Coastguard Worker-------------------
1439*9880d681SAndroid Build Coastguard Worker
1440*9880d681SAndroid Build Coastguard WorkerThis section describes preferred low-level formatting guidelines along with
1441*9880d681SAndroid Build Coastguard Workerreasoning on why we prefer them.
1442*9880d681SAndroid Build Coastguard Worker
1443*9880d681SAndroid Build Coastguard WorkerSpaces Before Parentheses
1444*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^^^^^^^^
1445*9880d681SAndroid Build Coastguard Worker
1446*9880d681SAndroid Build Coastguard WorkerWe prefer to put a space before an open parenthesis only in control flow
1447*9880d681SAndroid Build Coastguard Workerstatements, but not in normal function call expressions and function-like
1448*9880d681SAndroid Build Coastguard Workermacros.  For example, this is good:
1449*9880d681SAndroid Build Coastguard Worker
1450*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
1451*9880d681SAndroid Build Coastguard Worker
1452*9880d681SAndroid Build Coastguard Worker  if (X) ...
1453*9880d681SAndroid Build Coastguard Worker  for (I = 0; I != 100; ++I) ...
1454*9880d681SAndroid Build Coastguard Worker  while (LLVMRocks) ...
1455*9880d681SAndroid Build Coastguard Worker
1456*9880d681SAndroid Build Coastguard Worker  somefunc(42);
1457*9880d681SAndroid Build Coastguard Worker  assert(3 != 4 && "laws of math are failing me");
1458*9880d681SAndroid Build Coastguard Worker
1459*9880d681SAndroid Build Coastguard Worker  A = foo(42, 92) + bar(X);
1460*9880d681SAndroid Build Coastguard Worker
1461*9880d681SAndroid Build Coastguard Workerand this is bad:
1462*9880d681SAndroid Build Coastguard Worker
1463*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
1464*9880d681SAndroid Build Coastguard Worker
1465*9880d681SAndroid Build Coastguard Worker  if(X) ...
1466*9880d681SAndroid Build Coastguard Worker  for(I = 0; I != 100; ++I) ...
1467*9880d681SAndroid Build Coastguard Worker  while(LLVMRocks) ...
1468*9880d681SAndroid Build Coastguard Worker
1469*9880d681SAndroid Build Coastguard Worker  somefunc (42);
1470*9880d681SAndroid Build Coastguard Worker  assert (3 != 4 && "laws of math are failing me");
1471*9880d681SAndroid Build Coastguard Worker
1472*9880d681SAndroid Build Coastguard Worker  A = foo (42, 92) + bar (X);
1473*9880d681SAndroid Build Coastguard Worker
1474*9880d681SAndroid Build Coastguard WorkerThe reason for doing this is not completely arbitrary.  This style makes control
1475*9880d681SAndroid Build Coastguard Workerflow operators stand out more, and makes expressions flow better. The function
1476*9880d681SAndroid Build Coastguard Workercall operator binds very tightly as a postfix operator.  Putting a space after a
1477*9880d681SAndroid Build Coastguard Workerfunction name (as in the last example) makes it appear that the code might bind
1478*9880d681SAndroid Build Coastguard Workerthe arguments of the left-hand-side of a binary operator with the argument list
1479*9880d681SAndroid Build Coastguard Workerof a function and the name of the right side.  More specifically, it is easy to
1480*9880d681SAndroid Build Coastguard Workermisread the "``A``" example as:
1481*9880d681SAndroid Build Coastguard Worker
1482*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
1483*9880d681SAndroid Build Coastguard Worker
1484*9880d681SAndroid Build Coastguard Worker  A = foo ((42, 92) + bar) (X);
1485*9880d681SAndroid Build Coastguard Worker
1486*9880d681SAndroid Build Coastguard Workerwhen skimming through the code.  By avoiding a space in a function, we avoid
1487*9880d681SAndroid Build Coastguard Workerthis misinterpretation.
1488*9880d681SAndroid Build Coastguard Worker
1489*9880d681SAndroid Build Coastguard WorkerPrefer Preincrement
1490*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^^
1491*9880d681SAndroid Build Coastguard Worker
1492*9880d681SAndroid Build Coastguard WorkerHard fast rule: Preincrement (``++X``) may be no slower than postincrement
1493*9880d681SAndroid Build Coastguard Worker(``X++``) and could very well be a lot faster than it.  Use preincrementation
1494*9880d681SAndroid Build Coastguard Workerwhenever possible.
1495*9880d681SAndroid Build Coastguard Worker
1496*9880d681SAndroid Build Coastguard WorkerThe semantics of postincrement include making a copy of the value being
1497*9880d681SAndroid Build Coastguard Workerincremented, returning it, and then preincrementing the "work value".  For
1498*9880d681SAndroid Build Coastguard Workerprimitive types, this isn't a big deal. But for iterators, it can be a huge
1499*9880d681SAndroid Build Coastguard Workerissue (for example, some iterators contains stack and set objects in them...
1500*9880d681SAndroid Build Coastguard Workercopying an iterator could invoke the copy ctor's of these as well).  In general,
1501*9880d681SAndroid Build Coastguard Workerget in the habit of always using preincrement, and you won't have a problem.
1502*9880d681SAndroid Build Coastguard Worker
1503*9880d681SAndroid Build Coastguard Worker
1504*9880d681SAndroid Build Coastguard WorkerNamespace Indentation
1505*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^^^^
1506*9880d681SAndroid Build Coastguard Worker
1507*9880d681SAndroid Build Coastguard WorkerIn general, we strive to reduce indentation wherever possible.  This is useful
1508*9880d681SAndroid Build Coastguard Workerbecause we want code to `fit into 80 columns`_ without wrapping horribly, but
1509*9880d681SAndroid Build Coastguard Workeralso because it makes it easier to understand the code. To facilitate this and
1510*9880d681SAndroid Build Coastguard Workeravoid some insanely deep nesting on occasion, don't indent namespaces. If it
1511*9880d681SAndroid Build Coastguard Workerhelps readability, feel free to add a comment indicating what namespace is
1512*9880d681SAndroid Build Coastguard Workerbeing closed by a ``}``.  For example:
1513*9880d681SAndroid Build Coastguard Worker
1514*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
1515*9880d681SAndroid Build Coastguard Worker
1516*9880d681SAndroid Build Coastguard Worker  namespace llvm {
1517*9880d681SAndroid Build Coastguard Worker  namespace knowledge {
1518*9880d681SAndroid Build Coastguard Worker
1519*9880d681SAndroid Build Coastguard Worker  /// This class represents things that Smith can have an intimate
1520*9880d681SAndroid Build Coastguard Worker  /// understanding of and contains the data associated with it.
1521*9880d681SAndroid Build Coastguard Worker  class Grokable {
1522*9880d681SAndroid Build Coastguard Worker  ...
1523*9880d681SAndroid Build Coastguard Worker  public:
1524*9880d681SAndroid Build Coastguard Worker    explicit Grokable() { ... }
1525*9880d681SAndroid Build Coastguard Worker    virtual ~Grokable() = 0;
1526*9880d681SAndroid Build Coastguard Worker
1527*9880d681SAndroid Build Coastguard Worker    ...
1528*9880d681SAndroid Build Coastguard Worker
1529*9880d681SAndroid Build Coastguard Worker  };
1530*9880d681SAndroid Build Coastguard Worker
1531*9880d681SAndroid Build Coastguard Worker  } // end namespace knowledge
1532*9880d681SAndroid Build Coastguard Worker  } // end namespace llvm
1533*9880d681SAndroid Build Coastguard Worker
1534*9880d681SAndroid Build Coastguard Worker
1535*9880d681SAndroid Build Coastguard WorkerFeel free to skip the closing comment when the namespace being closed is
1536*9880d681SAndroid Build Coastguard Workerobvious for any reason. For example, the outer-most namespace in a header file
1537*9880d681SAndroid Build Coastguard Workeris rarely a source of confusion. But namespaces both anonymous and named in
1538*9880d681SAndroid Build Coastguard Workersource files that are being closed half way through the file probably could use
1539*9880d681SAndroid Build Coastguard Workerclarification.
1540*9880d681SAndroid Build Coastguard Worker
1541*9880d681SAndroid Build Coastguard Worker.. _static:
1542*9880d681SAndroid Build Coastguard Worker
1543*9880d681SAndroid Build Coastguard WorkerAnonymous Namespaces
1544*9880d681SAndroid Build Coastguard Worker^^^^^^^^^^^^^^^^^^^^
1545*9880d681SAndroid Build Coastguard Worker
1546*9880d681SAndroid Build Coastguard WorkerAfter talking about namespaces in general, you may be wondering about anonymous
1547*9880d681SAndroid Build Coastguard Workernamespaces in particular.  Anonymous namespaces are a great language feature
1548*9880d681SAndroid Build Coastguard Workerthat tells the C++ compiler that the contents of the namespace are only visible
1549*9880d681SAndroid Build Coastguard Workerwithin the current translation unit, allowing more aggressive optimization and
1550*9880d681SAndroid Build Coastguard Workereliminating the possibility of symbol name collisions.  Anonymous namespaces are
1551*9880d681SAndroid Build Coastguard Workerto C++ as "static" is to C functions and global variables.  While "``static``"
1552*9880d681SAndroid Build Coastguard Workeris available in C++, anonymous namespaces are more general: they can make entire
1553*9880d681SAndroid Build Coastguard Workerclasses private to a file.
1554*9880d681SAndroid Build Coastguard Worker
1555*9880d681SAndroid Build Coastguard WorkerThe problem with anonymous namespaces is that they naturally want to encourage
1556*9880d681SAndroid Build Coastguard Workerindentation of their body, and they reduce locality of reference: if you see a
1557*9880d681SAndroid Build Coastguard Workerrandom function definition in a C++ file, it is easy to see if it is marked
1558*9880d681SAndroid Build Coastguard Workerstatic, but seeing if it is in an anonymous namespace requires scanning a big
1559*9880d681SAndroid Build Coastguard Workerchunk of the file.
1560*9880d681SAndroid Build Coastguard Worker
1561*9880d681SAndroid Build Coastguard WorkerBecause of this, we have a simple guideline: make anonymous namespaces as small
1562*9880d681SAndroid Build Coastguard Workeras possible, and only use them for class declarations.  For example, this is
1563*9880d681SAndroid Build Coastguard Workergood:
1564*9880d681SAndroid Build Coastguard Worker
1565*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
1566*9880d681SAndroid Build Coastguard Worker
1567*9880d681SAndroid Build Coastguard Worker  namespace {
1568*9880d681SAndroid Build Coastguard Worker  class StringSort {
1569*9880d681SAndroid Build Coastguard Worker  ...
1570*9880d681SAndroid Build Coastguard Worker  public:
1571*9880d681SAndroid Build Coastguard Worker    StringSort(...)
1572*9880d681SAndroid Build Coastguard Worker    bool operator<(const char *RHS) const;
1573*9880d681SAndroid Build Coastguard Worker  };
1574*9880d681SAndroid Build Coastguard Worker  } // end anonymous namespace
1575*9880d681SAndroid Build Coastguard Worker
1576*9880d681SAndroid Build Coastguard Worker  static void runHelper() {
1577*9880d681SAndroid Build Coastguard Worker    ...
1578*9880d681SAndroid Build Coastguard Worker  }
1579*9880d681SAndroid Build Coastguard Worker
1580*9880d681SAndroid Build Coastguard Worker  bool StringSort::operator<(const char *RHS) const {
1581*9880d681SAndroid Build Coastguard Worker    ...
1582*9880d681SAndroid Build Coastguard Worker  }
1583*9880d681SAndroid Build Coastguard Worker
1584*9880d681SAndroid Build Coastguard WorkerThis is bad:
1585*9880d681SAndroid Build Coastguard Worker
1586*9880d681SAndroid Build Coastguard Worker.. code-block:: c++
1587*9880d681SAndroid Build Coastguard Worker
1588*9880d681SAndroid Build Coastguard Worker  namespace {
1589*9880d681SAndroid Build Coastguard Worker
1590*9880d681SAndroid Build Coastguard Worker  class StringSort {
1591*9880d681SAndroid Build Coastguard Worker  ...
1592*9880d681SAndroid Build Coastguard Worker  public:
1593*9880d681SAndroid Build Coastguard Worker    StringSort(...)
1594*9880d681SAndroid Build Coastguard Worker    bool operator<(const char *RHS) const;
1595*9880d681SAndroid Build Coastguard Worker  };
1596*9880d681SAndroid Build Coastguard Worker
1597*9880d681SAndroid Build Coastguard Worker  void runHelper() {
1598*9880d681SAndroid Build Coastguard Worker    ...
1599*9880d681SAndroid Build Coastguard Worker  }
1600*9880d681SAndroid Build Coastguard Worker
1601*9880d681SAndroid Build Coastguard Worker  bool StringSort::operator<(const char *RHS) const {
1602*9880d681SAndroid Build Coastguard Worker    ...
1603*9880d681SAndroid Build Coastguard Worker  }
1604*9880d681SAndroid Build Coastguard Worker
1605*9880d681SAndroid Build Coastguard Worker  } // end anonymous namespace
1606*9880d681SAndroid Build Coastguard Worker
1607*9880d681SAndroid Build Coastguard WorkerThis is bad specifically because if you're looking at "``runHelper``" in the middle
1608*9880d681SAndroid Build Coastguard Workerof a large C++ file, that you have no immediate way to tell if it is local to
1609*9880d681SAndroid Build Coastguard Workerthe file.  When it is marked static explicitly, this is immediately obvious.
1610*9880d681SAndroid Build Coastguard WorkerAlso, there is no reason to enclose the definition of "``operator<``" in the
1611*9880d681SAndroid Build Coastguard Workernamespace just because it was declared there.
1612*9880d681SAndroid Build Coastguard Worker
1613*9880d681SAndroid Build Coastguard WorkerSee Also
1614*9880d681SAndroid Build Coastguard Worker========
1615*9880d681SAndroid Build Coastguard Worker
1616*9880d681SAndroid Build Coastguard WorkerA lot of these comments and recommendations have been culled from other sources.
1617*9880d681SAndroid Build Coastguard WorkerTwo particularly important books for our work are:
1618*9880d681SAndroid Build Coastguard Worker
1619*9880d681SAndroid Build Coastguard Worker#. `Effective C++
1620*9880d681SAndroid Build Coastguard Worker   <http://www.amazon.com/Effective-Specific-Addison-Wesley-Professional-Computing/dp/0321334876>`_
1621*9880d681SAndroid Build Coastguard Worker   by Scott Meyers.  Also interesting and useful are "More Effective C++" and
1622*9880d681SAndroid Build Coastguard Worker   "Effective STL" by the same author.
1623*9880d681SAndroid Build Coastguard Worker
1624*9880d681SAndroid Build Coastguard Worker#. `Large-Scale C++ Software Design
1625*9880d681SAndroid Build Coastguard Worker   <http://www.amazon.com/Large-Scale-Software-Design-John-Lakos/dp/0201633620/ref=sr_1_1>`_
1626*9880d681SAndroid Build Coastguard Worker   by John Lakos
1627*9880d681SAndroid Build Coastguard Worker
1628*9880d681SAndroid Build Coastguard WorkerIf you get some free time, and you haven't read them: do so, you might learn
1629*9880d681SAndroid Build Coastguard Workersomething.
1630