blob: ab02adfc32590b8940e7ded3b2c093da9f28bb35 [file] [log] [blame]
Michele Di Giorgio7b12bfb2019-10-25 16:34:28 +01001///
Adnan AlSinanabc093b2022-02-08 16:57:06 +00002/// Copyright (c) 2019-2022 Arm Limited.
Michele Di Giorgio7b12bfb2019-10-25 16:34:28 +01003///
4/// SPDX-License-Identifier: MIT
5///
6/// Permission is hereby granted, free of charge, to any person obtaining a copy
7/// of this software and associated documentation files (the "Software"), to
8/// deal in the Software without restriction, including without limitation the
9/// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
10/// sell copies of the Software, and to permit persons to whom the Software is
11/// furnished to do so, subject to the following conditions:
12///
13/// The above copyright notice and this permission notice shall be included in all
14/// copies or substantial portions of the Software.
15///
16/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22/// SOFTWARE.
23///
24namespace arm_compute
25{
26/**
Sheri Zhangd813bab2021-04-30 16:53:41 +010027@page contribution_guidelines Contribution Guidelines
Michele Di Giorgio7b12bfb2019-10-25 16:34:28 +010028
29@tableofcontents
30
31If you want to contribute to Arm Compute Library, be sure to review the following guidelines.
32
33The development is structured in the following way:
34- Release repository: https://github.com/arm-software/ComputeLibrary
35- Development repository: https://review.mlplatform.org/#/admin/projects/ml/ComputeLibrary
36- Please report issues here: https://github.com/ARM-software/ComputeLibrary/issues
37
Adnan AlSinanabc093b2022-02-08 16:57:06 +000038@section S5_0_inc_lang Inclusive language guideline
39As part of the initiative to use inclusive language, there are certain phrases and words that were removed or replaced by more inclusive ones. Examples include but not limited to:
40\includedoc non_inclusive_language_examples.dox
41
42Please also follow this guideline when committing changes to Compute Library.
43
44Futhermore, starting from next release (22.05), 'master' branch will no longer be used, it will be replaced by 'main'. Please update your clone jobs accordingly.
Michele Di Giorgio7b12bfb2019-10-25 16:34:28 +010045@section S5_1_coding_standards Coding standards and guidelines
46
47Best practices (as suggested by clang-tidy):
48
49- No uninitialised values
50
51Helps to prevent undefined behaviour and allows to declare variables const if they are not changed after initialisation. See http://clang.llvm.org/extra/clang-tidy/checks/cppcoreguidelines-pro-type-member-init.html
52
53@code{.cpp}
54const float32x4_t foo = vdupq_n_f32(0.f);
55const float32x4_t bar = foo;
56
57const int32x4x2_t i_foo = {{
58 vconvq_s32_f32(foo),
59 vconvq_s32_f32(foo)
60}};
61const int32x4x2_t i_bar = i_foo;
62@endcode
63
64- No C-style casts (in C++ source code)
65
66Only use static_cast, dynamic_cast, and (if required) reinterpret_cast and const_cast. See http://en.cppreference.com/w/cpp/language/explicit_cast for more information when to use which type of cast. C-style casts do not differentiate between the different cast types and thus make it easy to violate type safety. Also, due to the prefix notation it is less clear which part of an expression is going to be casted. See http://clang.llvm.org/extra/clang-tidy/checks/cppcoreguidelines-pro-type-cstyle-cast.html
67
68- No implicit casts to bool
69
70Helps to increase readability and might help to catch bugs during refactoring. See http://clang.llvm.org/extra/clang-tidy/checks/readability-implicit-bool-cast.html
71
72@code{.cpp}
73extern int *ptr;
74if(ptr){} // Bad
75if(ptr != nullptr) {} // Good
76
77extern int foo;
78if(foo) {} // Bad
79if(foo != 0) {} // Good
80@endcode
81
82- Use nullptr instead of NULL or 0
83
84The nullptr literal is type-checked and is therefore safer to use. See http://clang.llvm.org/extra/clang-tidy/checks/modernize-use-nullptr.html
85
86- No need to explicitly initialise std::string with an empty string
87
88The default constructor of std::string creates an empty string. In general it is therefore not necessary to specify it explicitly. See http://clang.llvm.org/extra/clang-tidy/checks/readability-redundant-string-init.html
89
90@code{.cpp}
91// Instead of
92std::string foo("");
93std::string bar = "";
94
95// The following has the same effect
96std::string foo;
97std::string bar;
98@endcode
99
100- Braces for all control blocks and loops (which have a body)
101
102To increase readability and protect against refactoring errors the body of control block and loops must be wrapped in braces. See http://clang.llvm.org/extra/clang-tidy/checks/readability-braces-around-statements.html
103
104For now loops for which the body is empty do not have to add empty braces. This exception might be revoked in the future. Anyway, situations in which this exception applies should be rare.
105
106@code{.cpp}
107Iterator it;
108while(it.next()); // No need for braces here
109
110// Make more use of it
111@endcode
112
113- Only one declaration per line
114
115Increase readability and thus prevent errors.
116
117@code{.cpp}
118int a, b; // BAD
119int c, *d; // EVEN WORSE
120
121int e = 0; // GOOD
122int *p = nullptr; // GOOD
123@endcode
124
125- Pass primitive types (and those that are cheap to copy or move) by value
126
127For primitive types it is more efficient to pass them by value instead of by const reference because:
128
129 - the data type might be smaller than the "reference type"
130 - pass by value avoids aliasing and thus allows for better optimisations
131 - pass by value is likely to avoid one level of indirection (references are often implemented as auto dereferenced pointers)
132
133This advice also applies to non-primitive types that have cheap copy or move operations and the function needs a local copy of the argument anyway.
134
135More information:
136
137 - http://stackoverflow.com/a/14013189
138 - http://stackoverflow.com/a/270435
139 - http://web.archive.org/web/20140113221447/http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/
140
141@code{.cpp}
142void foo(int i, long l, float32x4_t f); // Pass-by-value for builtin types
143void bar(const float32x4x4_t &f); // As this is a struct pass-by-const-reference is probably better
144void foobar(const MyLargeCustomTypeClass &m); // Definitely better as const-reference except if a copy has to be made anyway.
145@endcode
146
147- Don't use unions
148
Jakub Sujakee301b32021-06-04 09:46:08 +0100149Unions cannot be used to convert values between different types because (in C++) it is undefined behaviour to read from a member other than the last one that has been assigned to. This limits the use of unions to a few corner cases and therefore the general advice is not to use unions. See http://releases.llvm.org/3.8.0/tools/clang/tools/extra/docs/clang-tidy/checks/cppcoreguidelines-pro-type-union-access.html
Michele Di Giorgio7b12bfb2019-10-25 16:34:28 +0100150
151- Use pre-increment/pre-decrement whenever possible
152
Jakub Sujakee301b32021-06-04 09:46:08 +0100153In contrast to the pre-increment the post-increment has to make a copy of the incremented object. This might not be a problem for primitive types like int but for class like objects that overload the operators, like iterators, it can have a huge impact on the performance. See http://stackoverflow.com/a/9205011
Michele Di Giorgio7b12bfb2019-10-25 16:34:28 +0100154
155To be consistent across the different cases the general advice is to use the pre-increment operator unless post-increment is explicitly required. The same rules apply for the decrement operator.
156
157@code{.cpp}
158for(size_t i = 0; i < 9; i++); // BAD
159for(size_t i = 0; i < 9; ++i); // GOOD
160@endcode
161
162- Don't use uint in C/C++
163
164The C and C++ standards don't define a uint type. Though some compilers seem to support it by default it would require to include the header sys/types.h. Instead we use the slightly more verbose unsigned int type.
165
166- Don't use unsigned int in function's signature
167
168Unsigned integers are good for representing bitfields and modular arithmetic. The fact that unsigned arithmetic doesn't model the behavior of a simple integer, but is instead defined by the standard to model modular arithmetic (wrapping around on overflow/underflow), means that a significant class of bugs cannot be diagnosed by the compiler. Mixing signedness of integer types is responsible for an equally large class of problems.
169
170- No "Yoda-style" comparisons
171
172As compilers are now able to warn about accidental assignments if it is likely that the intention has been to compare values it is no longer required to place literals on the left-hand side of the comparison operator. Sticking to the natural order increases the readability and thus prevents logical errors (which cannot be spotted by the compiler). In the rare case that the desired result is to assign a value and check it the expression has to be surrounded by parentheses.
173
174@code{.cpp}
175if(nullptr == ptr || false == cond) // BAD
176{
177 //...
178}
179
180if(ptr == nullptr || cond == false) // GOOD
181{
182 //...
183}
184
185if(ptr = nullptr || cond = false) // Most likely a mistake. Will cause a compiler warning
186{
187 //...
188}
189
190if((ptr = nullptr) || (cond = false)) // Trust me, I know what I'm doing. No warning.
191{
192 //...
193}
194@endcode
195
196@subsection S5_1_1_rules Rules
197
198 - Use spaces for indentation and alignment. No tabs! Indentation should be done with 4 spaces.
199 - Unix line returns in all the files.
200 - Pointers and reference symbols attached to the variable name, not the type (i.e. char \&foo;, and not char& foo).
201 - No trailing spaces or tabs at the end of lines.
202 - No spaces or tabs on empty lines.
203 - Put { and } on a new line and increase the indentation level for code inside the scope (except for namespaces).
204 - Single space before and after comparison operators ==, <, >, !=.
205 - No space around parenthesis.
206 - No space before, one space after ; (unless it is at the end of a line).
207
208@code{.cpp}
209for(int i = 0; i < width * height; ++i)
210{
211 void *d = foo(ptr, i, &addr);
212 static_cast<uint8_t *>(data)[i] = static_cast<uint8_t *>(d)[0];
213}
214@endcode
215
216 - Put a comment after \#else, \#endif, and namespace closing brace indicating the related name
217
218@code{.cpp}
219namespace mali
220{
221#ifdef MALI_DEBUG
222 ...
223#else // MALI_DEBUG
224 ...
225#endif // MALI_DEBUG
226} // namespace mali
227@endcode
228
229- CamelCase for class names only and lower case words separated with _ (snake_case) for all the functions / methods / variables / arguments / attributes.
230
231@code{.cpp}
232class ClassName
233{
234 public:
235 void my_function();
236 int my_attribute() const; // Accessor = attribute name minus '_', const if it's a simple type
237 private:
238 int _my_attribute; // '_' in front of name
239};
240@endcode
241
242- Use quotes instead of angular brackets to include local headers. Use angular brackets for system headers.
243- Also include the module header first, then local headers, and lastly system headers. All groups should be separated by a blank line and sorted lexicographically within each group.
244- Where applicable the C++ version of system headers has to be included, e.g. cstddef instead of stddef.h.
245- See http://llvm.org/docs/CodingStandards.html#include-style
246
247@code{.cpp}
248#include "MyClass.h"
249
250#include "arm_cv/core/Helpers.h"
251#include "arm_cv/core/Types.h"
252
253#include <cstddef>
254#include <numeric>
255@endcode
256
257- Only use "auto" when the type can be explicitly deduced from the assignment.
258
259@code{.cpp}
260auto a = static_cast<float*>(bar); // OK: there is an explicit cast
261auto b = std::make_unique<Image>(foo); // OK: we can see it's going to be an std::unique_ptr<Image>
262auto c = img.ptr(); // NO: Can't tell what the type is without knowing the API.
263auto d = vdup_n_u8(0); // NO: It's not obvious what type this function returns.
264@endcode
265
266- OpenCL:
267 - Use __ in front of the memory types qualifiers and kernel: __kernel, __constant, __private, __global, __local.
268 - Indicate how the global workgroup size / offset / local workgroup size are being calculated.
269
270 - Doxygen:
271
272 - No '*' in front of argument names
273 - [in], [out] or [in,out] *in front* of arguments
274 - Skip a line between the description and params and between params and @return (If there is a return)
275 - Align params names and params descriptions (Using spaces), and with a single space between the widest column and the next one.
276 - Use an upper case at the beginning of the description
277
278@snippet arm_compute/runtime/NEON/functions/NEActivationLayer.h NEActivationLayer snippet
279
280@subsection S5_1_2_how_to_check_the_rules How to check the rules
281
282astyle (http://astyle.sourceforge.net/) and clang-format (https://clang.llvm.org/docs/ClangFormat.html) can check and help you apply some of these rules.
283
284@subsection S5_1_3_library_size_guidelines Library size: best practices and guidelines
285
286@subsubsection S5_1_3_1_template_suggestions Template suggestions
287
288When writing a new patch we should also have in mind the effect it will have in the final library size. We can try some of the following things:
289
290 - Place non-dependent template code in a different non-templated class/method
291
292@code{.cpp}
293template<typename T>
294class Foo
295{
296public:
297 enum { v1, v2 };
298 // ...
299};
300@endcode
301
302 can be converted to:
303
304@code{.cpp}
305struct Foo_base
306{
307 enum { v1, v2 };
308 // ...
309};
310
311template<typename T>
312class Foo : public Foo_base
313{
314public:
315 // ...
316};
317@endcode
318
319 - In some cases it's preferable to use runtime switches instead of template parameters
320
321 - Sometimes we can rewrite the code without templates and without any (significant) performance loss. Let's say that we've written a function where the only use of the templated argument is used for casting:
322
323@code{.cpp}
324template <typename T>
325void NETemplatedKernel::run(const Window &window)
326{
327...
328 *(reinterpret_cast<T *>(out.ptr())) = *(reinterpret_cast<const T *>(in.ptr()));
329...
330}
331@endcode
332
333The above snippet can be transformed to:
334
335@code{.cpp}
336void NENonTemplatedKernel::run(const Window &window)
337{
338...
339std::memcpy(out.ptr(), in.ptr(), element_size);
340...
341}
342@endcode
343
344@subsection S5_1_4_secure_coding_practices Secure coding practices
345
346@subsubsection S5_1_4_1_general_coding_practices General Coding Practices
347
348- **Use tested and approved managed code** rather than creating new unmanaged code for common tasks.
349- **Utilize locking to prevent multiple simultaneous requests** or use a synchronization mechanism to prevent race conditions.
350- **Protect shared variables and resources** from inappropriate concurrent access.
351- **Explicitly initialize all your variables and other data stores**, either during declaration or just before the first usage.
352- **In cases where the application must run with elevated privileges, raise privileges as late as possible, and drop them as soon as possible**.
353- **Avoid calculation errors** by understanding your programming language's underlying representation and how it interacts with numeric calculation. Pay close attention to byte size discrepancies, precision, signed/unsigned distinctions, truncation, conversion and casting between types, "not-a-number" calculations, and how your language handles numbers that are too large or too small for its underlying representation.
354- **Restrict users from generating new code** or altering existing code.
355
356
357@subsubsection S5_1_4_2_secure_coding_best_practices Secure Coding Best Practices
358
359- **Validate input**. Validate input from all untrusted data sources. Proper input validation can eliminate the vast majority of software vulnerabilities. Be suspicious of most external data sources, including command line arguments, network interfaces, environmental variables, and user controlled files.
360- **Heed compiler warnings**. Compile code using the default compiler flags that exist in the SConstruct file.
361- Use **static analysis tools** to detect and eliminate additional security flaws.
362- **Keep it simple**. Keep the design as simple and small as possible. Complex designs increase the likelihood that errors will be made in their implementation, configuration, and use. Additionally, the effort required to achieve an appropriate level of assurance increases dramatically as security mechanisms become more complex.
363- **Default deny**. Base access decisions on permission rather than exclusion. This means that, by default, access is denied and the protection scheme identifies conditions under which access is permitted
364- **Adhere to the principle of least privilege**. Every process should execute with the least set of privileges necessary to complete the job. Any elevated permission should only be accessed for the least amount of time required to complete the privileged task. This approach reduces the opportunities an attacker has to execute arbitrary code with elevated privileges.
365- **Sanitize data sent to other systems**. Sanitize all data passed to complex subsystems such as command shells, relational databases, and commercial off-the-shelf (COTS) components. Attackers may be able to invoke unused functionality in these components through the use of various injection attacks. This is not necessarily an input validation problem because the complex subsystem being invoked does not understand the context in which the call is made. Because the calling process understands the context, it is responsible for sanitizing the data before invoking the subsystem.
366- **Practice defense in depth**. Manage risk with multiple defensive strategies, so that if one layer of defense turns out to be inadequate, another layer of defense can prevent a security flaw from becoming an exploitable vulnerability and/or limit the consequences of a successful exploit. For example, combining secure programming techniques with secure runtime environments should reduce the likelihood that vulnerabilities remaining in the code at deployment time can be exploited in the operational environment.
367
Sang-Hoon Park776c2352020-10-21 10:30:20 +0100368@subsection S5_1_5_guidelines_for_stable_api_abi Guidelines for stable API/ABI
369
370The Application Programming Interface (API) and Application Binary Interface (ABI) are the interfaces exposed
371to users so their programs can interact with the library efficiently and effectively. Even though changing API/ABI
372in a way that does not give backward compatibility is not necessarily bad if it can improve other users' experience and the library,
373contributions should be made with the awareness of API/ABI stability. If you'd like to make changes that affects
374the library's API/ABI, please review and follow the guidelines shown in this section. Also, please note that
375these guidelines are not exhaustive list but discussing things that might be easily overlooked.
376
377@subsubsection S5_1_5_1_guidelines_for_api Guidelines for API
378
379- When adding new arguments, consider grouping arguments (including the old ones) into a struct rather than adding arguments with default values.
380Introducing a new struct might break the API/ABI once, but it will be helpful to keep the stability.
381- When new member variables are added, please make sure they are initialized.
382- Avoid adding enum elements in the middle.
383- When removing arguments, follow the deprecation process described in the following section.
384- When changing behavior affecting API contracts, follow the deprecation process described in the following section.
385
386@subsubsection S5_1_5_2_guidelines_for_abi Guidelines for ABI
387
388We recommend to read through <a href="https://community.kde.org/Policies/Binary_Compatibility_Issues_With_C%2B%2B">this page</a>
389and double check your contributions to see if they include the changes listed.
390
391Also, for classes that requires strong ABI stability, consider using <a href="https://en.cppreference.com/w/cpp/language/pimpl">pImpl idiom</a>.
392
393@subsubsection S5_1_5_3_api_deprecation_process API deprecation process
394
395In order to deprecate an existing API, these rules should be followed.
396
397- Removal of a deprecated API should wait at least for one official release.
398- Deprecation of runtime APIs should strictly follow the aforementioned period, whereas core APIs can have more flexibility as they are mostly used internally rather than user-facing.
399- Any API changes (update, addition and deprecation) in all components should be well documented by the contribution itself.
400
Georgios Pinitas40f51a62020-11-21 03:04:18 +0000401Also, it is recommended to use the following utility macros which is designed to work with both clang and gcc using C++14 and later.
Sang-Hoon Park776c2352020-10-21 10:30:20 +0100402
403- ARM_COMPUTE_DEPRECATED: Just deprecate the wrapped function
404- ARM_COMPUTE_DEPRECATED_REL: Deprecate the wrapped function and also capture the release that was deprecated
405- ARM_COMPUTE_DEPRECATED_REL_REPLACE: Deprecate the wrapped function and also capture the release that was deprecated along with a possible replacement candidate
406
407@code{.cpp}
408ARM_COMPUTE_DEPRECATED_REL_REPLACE(20.08, DoNewThing)
409void DoOldThing();
410
411void DoNewThing();
412@endcode
413
Michele Di Giorgio7b12bfb2019-10-25 16:34:28 +0100414@section S5_2_how_to_submit_a_patch How to submit a patch
415
416To be able to submit a patch to our development repository you need to have a GitHub account. With that, you will be able to sign in to Gerrit where your patch will be reviewed.
417
418Next step is to clone the Compute Library repository:
419
420 git clone "ssh://<your-github-id>@review.mlplatform.org:29418/ml/ComputeLibrary"
421
422If you have cloned from GitHub or through HTTP, make sure you add a new git remote using SSH:
423
424 git remote add acl-gerrit "ssh://<your-github-id>@review.mlplatform.org:29418/ml/ComputeLibrary"
425
426After that, you will need to upload an SSH key to https://review.mlplatform.org/#/settings/ssh-keys
427
428Then, make sure to install the commit-msg Git hook in order to add a change-ID to the commit message of your patch:
429
430 cd "ComputeLibrary" && mkdir -p .git/hooks && curl -Lo `git rev-parse --git-dir`/hooks/commit-msg https://review.mlplatform.org/tools/hooks/commit-msg; chmod +x `git rev-parse --git-dir`/hooks/commit-msg)
431
432When your patch is ready, remember to sign off your contribution by adding a line with your name and e-mail address to every git commit message:
433
434 Signed-off-by: John Doe <john.doe@example.org>
435
436You must use your real name, no pseudonyms or anonymous contributions are accepted.
437
438You can add this to your patch with:
439
440 git commit -s --amend
441
442You are now ready to submit your patch for review:
443
444 git push acl-gerrit HEAD:refs/for/master
445
446@section S5_3_code_review Patch acceptance and code review
447
Jakub Sujakee301b32021-06-04 09:46:08 +0100448Once a patch is uploaded for review, there is a pre-commit test that runs on a Jenkins server for continuous integration tests. In order to be merged a patch needs to:
Michele Di Giorgio7b12bfb2019-10-25 16:34:28 +0100449
450- get a "+1 Verified" from the pre-commit job
451- get a "+1 Comments-Addressed", in case of comments from reviewers the committer has to address them all. A comment is considered addressed when the first line of the reply contains the word "Done"
452- get a "+2" from a reviewer, that means the patch has the final approval
453
ramelg01b2eba7f2021-12-23 08:32:08 +0000454At the moment, the Jenkins server is not publicly accessible and for security reasons patches submitted by non-allowlisted committers do not trigger the pre-commit tests. For this reason, one of the maintainers has to manually trigger the job.
Michele Di Giorgio7b12bfb2019-10-25 16:34:28 +0100455
456If the pre-commit test fails, the Jenkins job will post a comment on Gerrit with the details about the failure so that the committer will be able to reproduce the error and fix the issue, if any (sometimes there can be infrastructure issues, a test platform disconnecting for example, where the job needs to be retriggered).
457
458*/
459} // namespace arm_compute