### Install Clang Source: https://clang.llvm.org/docs/LibASTMatchersTutorial.html Install the built Clang components to the system. This command should be run after successful building and testing. ```bash ninja install ``` -------------------------------- ### Basic YAML Configuration Example Source: https://clang.llvm.org/docs/ClangFormatStyleOptions.html A minimal example of a .clang-format file using YAML syntax for basic key-value style configurations. ```yaml key1: value1 key2: value2 # A comment. ... ``` -------------------------------- ### Hello World Module Example Source: https://clang.llvm.org/docs/StandardCPlusPlusModules.html A simple 'hello world' example demonstrating a primary module interface unit and its usage. Requires precompilation of the module. ```c++ // Hello.cppm module; #include export module Hello; export void hello() { std::cout << "Hello World!\n"; } // use.cpp import Hello; int main() { hello(); return 0; } ``` -------------------------------- ### C Example: Defining Device Images and Binary Descriptor Source: https://clang.llvm.org/docs/OffloadingDesign.html Illustrates the definition of device images and the binary descriptor. This code shows how to initialize image data, calculate image boundaries, and populate the __tgt_bin_desc structure. It is typically used for static offloading setups. ```c __attribute__((visibility("hidden"))) extern __tgt_offload_entry *__start_omp_offloading_entries; __attribute__((visibility("hidden"))) extern __tgt_offload_entry *__stop_omp_offloading_entries; static const char Image0[] = { }; ... static const char ImageN[] = { }; static const __tgt_device_image Images[] = { { Image0, /*ImageStart*/ Image0 + sizeof(Image0), /*ImageEnd*/ __start_omp_offloading_entries, /*EntriesBegin*/ __stop_omp_offloading_entries /*EntriesEnd*/ }, ... { ImageN, /*ImageStart*/ ImageN + sizeof(ImageN), /*ImageEnd*/ __start_omp_offloading_entries, /*EntriesBegin*/ __stop_omp_offloading_entries /*EntriesEnd*/ } }; static const __tgt_bin_desc BinDesc = { sizeof(Images) / sizeof(Images[0]), /*NumDeviceImages*/ Images, /*DeviceImages*/ __start_omp_offloading_entries, /*HostEntriesBegin*/ __stop_omp_offloading_entries /*HostEntriesEnd*/ }; ``` -------------------------------- ### Inline Style Configuration Example Source: https://clang.llvm.org/docs/ClangFormatStyleOptions.html Example of specifying style configuration directly in the -style= command line option using a JSON-like format. ```bash -style='{key1: value1, key2: value2, ...}' ``` -------------------------------- ### YAML Style Configuration Example Source: https://clang.llvm.org/docs/ClangFormatStyleOptions.html Example of a .clang-format file using YAML format to define style options, including language-specific overrides. ```yaml --- # We'll use defaults from the LLVM style, but with 4 columns indentation. BasedOnStyle: LLVM IndentWidth: 4 --- Language: Cpp # Force pointers to the type for C++. DerivePointerAlignment: false PointerAlignment: Left --- Language: JavaScript # Use 100 columns for JS. ColumnLimit: 100 --- Language: Proto # Don't format .proto files. DisableFormat: true --- Language: CSharp # Use 100 columns for C#. ColumnLimit: 100 ... ``` -------------------------------- ### DataFlowSanitizer ABI List Entry Examples Source: https://clang.llvm.org/docs/DataFlowSanitizer.html Provides examples of entries in a DataFlowSanitizer ABI list file, demonstrating how to categorize functions like 'main', 'malloc', 'tolower', and 'memcpy'. ```text # main is called by the C runtime using the native ABI. fun:main=uninstrumented fun:main=discard ``` ```text # malloc only writes to its internal data structures, not user-accessible memory. fun:malloc=uninstrumented fun:malloc=discard ``` ```text # tolower is a pure function. fun:tolower=uninstrumented fun:tolower=functional ``` ```text # memcpy needs to copy the shadow from the source to the destination region. # This is done in a custom function. fun:memcpy=uninstrumented fun:memcpy=custom ``` -------------------------------- ### Export-as Declaration Example Source: https://clang.llvm.org/docs/Modules.html An example illustrating how the `export_as` declaration allows a module to be re-exported via a different module name. ```c module MyFrameworkCore { export_as MyFramework } ``` -------------------------------- ### Profile Data Format Example Source: https://clang.llvm.org/docs/UsersManual.html This example demonstrates the format of a sampled line in a profile data file, showing a call instruction with potential targets and their sample counts. ```text 130: 7 foo:3 bar:2 baz:7 ``` -------------------------------- ### Compile Flags Text File Example Source: https://clang.llvm.org/docs/JSONCompilationDatabase.html This example demonstrates the 'compile_flags.txt' format, where each line represents a single compiler argument. Paths are relative to the directory containing this file. ```text -xc++ -I libwidget/include/ ``` -------------------------------- ### Example CTU Invocation List File Content Source: https://clang.llvm.org/docs/analyzer/user-docs/Options.html This example shows the expected format for the ctu-invocation-list file, mapping source files to their compilation commands. ```yaml {/main.cpp: [clang++, /main.cpp], other.cpp: [clang++, /other.cpp]} ``` -------------------------------- ### JSON Compilation Database Example Source: https://clang.llvm.org/docs/JSONCompilationDatabase.html This example shows the structure of a JSON compilation database, including entries for 'directory', 'arguments' or 'command', and 'file'. Use 'arguments' for direct command execution and 'command' for shell-escaped strings. ```json [ { "directory": "/home/user/llvm/build", "arguments": ["/usr/bin/clang++", "-Irelative", "-DSOMEDEF=With spaces, quotes and \\-es.", "-c", "-o", "file.o", "file.cc"], "file": "file.cc" }, { "directory": "/home/user/llvm/build", "command": "/usr/bin/clang++ -Irelative -DSOMEDEF=\"With spaces, quotes and \\-es.\" -c -o file.o file.cc", "file": "file2.cc" }, ... ] ``` -------------------------------- ### x86/x86-64 target_clones example with architecture and features Source: https://clang.llvm.org/docs/AttributeReference.html This example shows `target_clones` for x86/x86-64 targets, including architecture specifications (e.g., `arch=atom`, `arch=ivybridge`) and subtarget features (e.g., `avx2`). A `default` fallback implementation is required. ```cpp __attribute__((target_clones("arch=atom,avx2","arch=ivybridge","default"))) void foo() {} ``` -------------------------------- ### Configuration File Naming Convention Example Source: https://clang.llvm.org/docs/UsersManual.html When Clang searches for default configuration files, it uses a naming convention based on the target triple and driver name. This example shows the expected filename for a specific target and driver. ```text x86_64-pc-linux-gnu-clang++.cfg ``` -------------------------------- ### Deprecated: Get Start of Unsafe Stack Source: https://clang.llvm.org/docs/SafeStack.html The `__builtin___get_unsafe_stack_start()` builtin is deprecated and is an alias for `__safestack_get_unsafe_stack_bottom()`. ```c void* unsafe_stack_start = __builtin___get_unsafe_stack_start(); ``` -------------------------------- ### Example Configuration File Content Source: https://clang.llvm.org/docs/UsersManual.html Demonstrates the syntax of a configuration file, including comments, options, and multi-line options. ```text # Several options on line -c --target=x86_64-unknown-linux-gnu # Long option split between lines -I/usr/lib/gcc/x86_64-linux-gnu/5.4.0/../../../../\ include/c++/5.4.0 # other config files may be included @linux.options ``` -------------------------------- ### Example Suppressions File Content Source: https://clang.llvm.org/docs/ThreadSanitizer.html This example demonstrates various suppression types including data races in libraries/functions/files/variables, thread leaks, and calls from uninstrumented libraries. Lines starting with '#' are comments. ```text # Suppress data races in a third-party library 'foobar' race:foobar # Suppress data races in a specific function race:NuclearRocket::Launch # Suppress data races in a specific source file race:src/surgery/laser_scalpel.cc # Suppress data races on a specific global variable race:global_var # Suppress a leaked thread by name thread:MonitoringThread # Suppress warnings called from an uninstrumented library called_from_lib:libzmq.so ``` -------------------------------- ### Building and Running the AST Importer Demo Source: https://clang.llvm.org/docs/LibASTImporter.html Command-line instructions to build the `astimporter-demo` executable using Ninja and then run it. ```bash $ ninja astimporter-demo && ./bin/astimporter-demo ``` -------------------------------- ### Emit Optimization Reports with -Rpass Source: https://clang.llvm.org/docs/UsersManual.html Use -Rpass=regex to get a report from optimization passes. The regex identifies the pass name. For example, -Rpass=inline reports inlining decisions. ```bash $ clang -O2 -Rpass=inline code.cc -o code code.cc:4:25: remark: foo inlined into bar [-Rpass=inline] int bar(int j) { return foo(j, j - 2); } ^ ``` -------------------------------- ### Build and Run Command Example Source: https://clang.llvm.org/docs/LibASTMatchersTutorial.html Provides the commands to compile the tool using ninja and then run the compiled tool on a test file to discover for loops. ```bash cd ~/clang-llvm/build/ ninja loop-convert vim ~/test-files/simple-loops.cc bin/loop-convert ~/test-files/simple-loops.cc ``` -------------------------------- ### Get Chromium Style Format Source: https://clang.llvm.org/docs/LibFormat.html Retrieves a `FormatStyle` object that conforms to the Chromium style guide. This function is for applying formatting consistent with Chromium's development standards. ```cpp /// Returns a format style complying with Chromium's style guide: /// https://chromium.googlesource.com/chromium/src/+/refs/heads/main/styleguide/styleguide.md FormatStyle getChromiumStyle(); ``` -------------------------------- ### Get Microsoft Style Format Source: https://clang.llvm.org/docs/LibFormat.html Retrieves a `FormatStyle` object that conforms to Microsoft's style guide. This is useful for projects that follow Microsoft's recommended C++ coding practices. ```cpp /// Returns a format style complying with Microsoft's style guide: /// https://docs.microsoft.com/en-us/visualstudio/ide/editorconfig-code-style-settings-reference FormatStyle getMicrosoftStyle(); ``` -------------------------------- ### Complex Module Example with Partitions Source: https://clang.llvm.org/docs/StandardCPlusPlusModules.html Demonstrates a more complex module structure using primary, interface, and implementation partitions. Requires multiple precompilation steps. ```c++ // M.cppm export module M; export import :interface_part; import :impl_part; export void Hello(); // interface_part.cppm export module M:interface_part; export void World(); // impl_part.cppm module; #include #include module M:impl_part; import :interface_part; std::string W = "World."; void World() { std::cout << W << std::endl; } // Impl.cpp module; #include module M; void Hello() { std::cout << "Hello "; } // User.cpp import M; int main() { Hello(); World(); return 0; } ``` -------------------------------- ### Get Mozilla Style Format Source: https://clang.llvm.org/docs/LibFormat.html Retrieves a `FormatStyle` object that conforms to Mozilla's style guide. Use this to ensure code formatting aligns with Mozilla's project standards. ```cpp /// Returns a format style complying with Mozilla's style guide /// https://firefox-source-docs.mozilla.org/code-quality/coding-style/index.html FormatStyle getMozillaStyle(); ``` -------------------------------- ### Get Google Style Format Source: https://clang.llvm.org/docs/LibFormat.html Retrieves a `FormatStyle` object that conforms to Google's C++ style guide. Use this to format code according to Google's established practices. ```cpp /// Returns a format style complying with Google's C++ style guide: /// http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml. FormatStyle getGoogleStyle(); ``` -------------------------------- ### Tool Execution and Output Example Source: https://clang.llvm.org/docs/RAVFrontendAction.html Demonstrates how to run the compiled tool with a code snippet as an argument and shows the expected output indicating the found declaration location. ```bash $ ./bin/find-class-decls "namespace n { namespace m { class C {}; } }" Found declaration at 1:29 ``` -------------------------------- ### Get Webkit Style Format Source: https://clang.llvm.org/docs/LibFormat.html Retrieves a `FormatStyle` object that conforms to Webkit's style guide. This function helps in formatting code according to Webkit's established style guidelines. ```cpp /// Returns a format style complying with Webkit's style guide: /// https://webkit.org/code-style-guidelines/ FormatStyle getWebkitStyle(); ``` -------------------------------- ### Get Function Start Address with __builtin_function_start Source: https://clang.llvm.org/docs/LanguageExtensions.html Returns the address of a function's body. The returned pointer may differ from the normal function address and is not safe to call directly, especially with sanitizers like CFI. ```cpp void a() {} void *p = __builtin_function_start(a); ``` ```cpp void *pa1 = __builtin_function_start((void(A::*)(int)) &A::a); void *pa2 = __builtin_function_start((void(A::*)()) &A::a); ``` -------------------------------- ### Example Source Files for CTU Analysis Source: https://clang.llvm.org/docs/analyzer/user-docs/CrossTranslationUnit.html These C++ source files demonstrate a simple scenario where one translation unit (main.cpp) calls a function defined in another (foo.cpp). This setup is used to illustrate cross-translation unit analysis. ```cpp // main.cpp int foo(); int main() { return 3 / foo(); } ``` ```cpp // foo.cpp int foo() { return 0; } ``` -------------------------------- ### Clang Tool Main Function Setup Source: https://clang.llvm.org/docs/LibASTMatchersTutorial.html Sets up the ClangTool to run the defined AST matchers. It parses command-line arguments, creates a MatchFinder, registers the matcher with a callback, and executes the tool. ```c++ int main(int argc, const char **argv) { auto ExpectedParser = CommonOptionsParser::create(argc, argv, MyToolCategory); if (!ExpectedParser) { // Fail gracefully for unsupported options. llvm::errs() << ExpectedParser.takeError(); return 1; } CommonOptionsParser& OptionsParser = ExpectedParser.get(); ClangTool Tool(OptionsParser.getCompilations(), OptionsParser.getSourcePathList()); LoopPrinter Printer; MatchFinder Finder; Finder.addMatcher(LoopMatcher, &Printer); return Tool.run(newFrontendActionFactory(&Finder).get()); } ``` -------------------------------- ### Sanitizer Ignorelist Syntax Example Source: https://clang.llvm.org/docs/SanitizerSpecialCaseList.html Demonstrates various ignorelist entries including comments, source files, main files, functions, glob patterns, and sanitizer-specific sections. Lines starting with '#' are ignored. Entries without sections apply to all sanitizers. ```ignorelist # Lines starting with # are ignored. # Turn off checks for the source file # Entries without sections are placed into [*] and apply to all sanitizers src:path/to/source/file.c src:*/source/file.c # Turn off checks for this main file, including files included by it. # Useful when the main file instead of an included file should be ignored. mainfile:file.c # Turn off checks for a particular functions (use mangled names): fun:_Z8MyFooBarv # Glob brace expansions and character ranges are supported fun:bad_{foo,bar} src:bad_source[1-9].c # "*" matches zero or more characters src:bad/sources/* fun:*BadFunction* # Specific sanitizer tools may introduce categories. src:/special/path/*=special_sources # Sections can be used to limit ignorelist entries to specific sanitizers [address] fun:*BadASanFunc* # Section names are globs [{cfi-vcall,cfi-icall}] fun:*BadCfiCall ``` -------------------------------- ### AllowShortFunctionsOnASingleLine Configuration Example Source: https://clang.llvm.org/docs/ClangFormatStyleOptions.html Demonstrates configuration syntax for AllowShortFunctionsOnASingleLine, showing both simple and granular control. ```yaml # Example of usage: AllowShortFunctionsOnASingleLine: InlineOnly # or more granular control: AllowShortFunctionsOnASingleLine: Empty: false Inline: true Other: false ``` -------------------------------- ### Clang Offload Bundler Help Overview Source: https://clang.llvm.org/docs/ClangOffloadBundler.html Displays the overview, usage, and available options for the clang-offload-bundler tool. Use this to understand the tool's capabilities and arguments. ```bash $ clang-offload-bundler -help OVERVIEW: A tool to bundle several input files of the specified type referring to the same source file but different targets into a single one. The resulting file can also be unbundled into different files by this tool if -unbundle is provided. USAGE: clang-offload-bundler [options] OPTIONS: Generic Options: --help - Display available options (--help-hidden for more) --help-list - Display list of available options (--help-list-hidden for more) --version - Display the version of this program clang-offload-bundler options: --### - Print any external commands that are to be executed instead of actually executing them - for testing purposes. --allow-missing-bundles - Create empty files if bundles are missing when unbundling. --bundle-align= - Alignment of bundle for binary files --check-input-archive - Check if input heterogeneous archive is valid in terms of TargetID rules. --inputs= - [,...] --list - List bundle IDs in the bundled file. --outputs= - [,...] --targets= - [-,...] --type= - Type of the files to be bundled/unbundled. Current supported types are: i - cpp-output ii - c++-cpp-output cui - cuda/hip-output d - dependency ll - llvm bc - llvm-bc s - assembler o - object a - archive of bundled files gch - precompiled-header ast - clang AST file --unbundle - Unbundle bundled file into several output files. ``` -------------------------------- ### Using for Portable SDK Paths Source: https://clang.llvm.org/docs/UsersManual.html Shows how to use the token to create portable paths relative to the configuration file's location. ```text --target=foo -isystem /include -L /lib -T /ldscripts/link.ld ``` -------------------------------- ### HIP CTAD with User-Defined Deduction Guides Source: https://clang.llvm.org/docs/HIPSupport.html Illustrates user-defined deduction guides for C++17 CTAD in HIP. These guides enable type deduction for class templates in both host and device contexts. Note the deprecation of explicit HIP target attributes on deduction guides. ```cpp template struct MyType { T value; __device__ MyType(T v) : value(v) {} }; MyType(float) -> MyType; __device__ void deviceFunc() { MyType m(1.0f); // Deduces MyType } ``` -------------------------------- ### AlignConsecutiveMacros Example Source: https://clang.llvm.org/docs/ClangFormatStyleOptions.html Presents an example of aligned consecutive macro definitions. ```text #define SHORT_NAME 42 #define LONGER_NAME 0x007f #define EVEN_LONGER_NAME (2) #define foo(x) (x * x) #define bar(y, z) (y + z) ``` -------------------------------- ### Clang Commands for Complex Module Example Source: https://clang.llvm.org/docs/StandardCPlusPlusModules.html Command-line instructions for precompiling and compiling a complex module structure with partitions, followed by linking. ```bash # Precompiling the module $ clang++ -std=c++20 interface_part.cppm --precompile -o M-interface_part.pcm $ clang++ -std=c++20 impl_part.cppm --precompile -fprebuilt-module-path=. -o M-impl_part.pcm $ clang++ -std=c++20 M.cppm --precompile -fprebuilt-module-path=. -o M.pcm $ clang++ -std=c++20 Impl.cpp -fprebuilt-module-path=. -c -o Impl.o # Compiling the user $ clang++ -std=c++20 User.cpp -fprebuilt-module-path=. -c -o User.o # Compiling the module and linking it together $ clang++ -std=c++20 M-interface_part.pcm -fprebuilt-module-path=. -c -o M-interface_part.o $ clang++ -std=c++20 M-impl_part.pcm -fprebuilt-module-path=. -c -o M-impl_part.o $ clang++ -std=c++20 M.pcm -fprebuilt-module-path=. -c -o M.o $ clang++ User.o M-interface_part.o M-impl_part.o M.o Impl.o -o a.out ``` -------------------------------- ### Match C++ Deduction Guide Declarations Source: https://clang.llvm.org/docs/LibASTMatchersReference.html Matches C++ deduction guide declarations, which are used in template argument deduction for class templates. This matcher identifies user-defined and implicit deduction guides. ```c++ cxxDeductionGuideDecl() ``` -------------------------------- ### Install Ninja binary Source: https://clang.llvm.org/docs/HowToSetupToolingForLLVM.html Copy the built `ninja` executable to `/usr/local/bin/` and set execute permissions. This makes the `ninja` command available system-wide. ```bash $ sudo cp ninja /usr/local/bin/ $ sudo chmod a+rx /usr/local/bin/ninja ``` -------------------------------- ### Conflict Declaration Example Source: https://clang.llvm.org/docs/Modules.html Example showing a module conflict declaration between module A and module B. ```c module Conflicts { explicit module A { header "conflict_a.h" conflict B, "we just don't like B" } module B { header "conflict_b.h" } } ``` -------------------------------- ### Configuration File Name Example Source: https://clang.llvm.org/docs/UsersManual.html This shows the naming convention for a driver configuration file when a specific target is used. ```text i386-pc-linux-gnu-clang++.cfg ``` -------------------------------- ### Compile and Run SanitizerCoverage Example Source: https://clang.llvm.org/docs/SanitizerCoverage.html Compile a C++ file with AddressSanitizer and SanitizerCoverage enabled. Run the executable and observe the creation of .sancov files, then check their sizes. ```c++ #include __attribute__((noinline)) void foo() { printf("foo\n"); } int main(int argc, char **argv) { if (argc == 2) foo(); printf("main\n"); } ``` ```bash % clang++ -g cov.cc -fsanitize=address -fsanitize-coverage=trace-pc-guard % ASAN_OPTIONS=coverage=1 ./a.out; wc -c *.sancov main SanitizerCoverage: ./a.out.7312.sancov 2 PCs written 24 a.out.7312.sancov % ASAN_OPTIONS=coverage=1 ./a.out foo ; wc -c *.sancov foo main SanitizerCoverage: ./a.out.7316.sancov 3 PCs written 24 a.out.7312.sancov 32 a.out.7316.sancov ``` -------------------------------- ### Space Before Parentheses: Custom Configuration Example Source: https://clang.llvm.org/docs/ClangFormatStyleOptions.html Example of configuring individual space-before-parentheses options when SpaceBeforeParens is set to Custom. ```yaml # Example of usage: SpaceBeforeParens: Custom SpaceBeforeParensOptions: AfterControlStatements: true AfterFunctionDefinitionName: true ``` -------------------------------- ### IndentWidth Configuration Example Source: https://clang.llvm.org/docs/ClangFormatStyleOptions.html Sets the number of columns to use for indentation. This example shows a configuration value of 3. ```yaml IndentWidth: 3 void f() { someFunction(); if (true, false) { f(); } } ``` -------------------------------- ### Config Macros Declaration Example Source: https://clang.llvm.org/docs/Modules.html Example of a module using the 'exhaustive' attribute for configuration macros, like NDEBUG. ```c module MyLogger { umbrella header "MyLogger.h" config_macros [exhaustive] NDEBUG } ``` -------------------------------- ### Clang Command for Hello World Module Source: https://clang.llvm.org/docs/StandardCPlusPlusModules.html Command-line instructions to precompile and then compile and link a simple C++ module project. ```bash $ clang++ -std=c++20 Hello.cppm --precompile -o Hello.pcm $ clang++ -std=c++20 use.cpp -fmodule-file=Hello=Hello.pcm Hello.pcm -o Hello.out $ ./Hello.out Hello World! ``` -------------------------------- ### Clang-cl Help Option Source: https://clang.llvm.org/docs/UsersManual.html Execute this command to display a list of supported command-line options for clang-cl, which are designed for compatibility with cl.exe. ```bash clang-cl /? ``` -------------------------------- ### Warn on 'gets' Function Usage Source: https://clang.llvm.org/docs/analyzer/checkers.html Detects the use of the `gets` function, which is highly insecure due to its susceptibility to buffer overflows. ```c void test() { char buff[1024]; gets(buff); // warn } ``` -------------------------------- ### Manage multiple module versions with different caches Source: https://clang.llvm.org/docs/Modules.html Demonstrates managing multiple versions of prebuilt modules by using separate cache paths. ```bash rm -rf prebuilt ; mkdir prebuilt ; rm -rf prebuilt_a ; mkdir prebuilt_a clang -cc1 -emit-obj use.c -fmodules -fimplicit-module-maps -fmodules-cache-path=prebuilt -fdisable-module-hash clang -cc1 -emit-obj use.c -fmodules -fimplicit-module-maps -fmodules-cache-path=prebuilt_a -fdisable-module-hash -DENABLE_A clang -cc1 -emit-obj use.c -fmodules -fimplicit-module-maps -fprebuilt-module-path=prebuilt clang -cc1 -emit-obj use.c -fmodules -fimplicit-module-maps -fprebuilt-module-path=prebuilt_a -DENABLE_A ``` -------------------------------- ### BTF type information example Source: https://clang.llvm.org/docs/AttributeReference.html This is an example of the corresponding BTF (BPF Type Format) information generated for types tagged with `btf_type_tag`. ```text ... [2] TYPE_TAG 'tag' type_id=4 [3] TYPEDEF 'foo_t' type_id=2 [4] STRUCT 'foo' size=4 vlen=1 'c' type_id=5 bits_offset=0 [5] INT 'int' size=4 bits_offset=0 nr_bits=32 encoding=SIGNED ... ``` -------------------------------- ### Profile List Configuration File Format Source: https://clang.llvm.org/docs/UsersManual.html This file defines which files and functions to instrument. Supported sections include [clang], [llvm], [csllvm], and [sample-coldcov]. Prefixes like 'function' and 'source' and categories like 'allow', 'skip', and 'forbid' are used to control instrumentation. ```text cat fun.list # The following cases are for clang instrumentation. [clang] # We might not want to profile functions that are inlined in many places. function:inlinedLots=skip # We want to forbid profiling where it might be dangerous. source:lib/unsafe/*.cc=forbid # Otherwise we allow profiling. default:allow ``` -------------------------------- ### PowerPC Data Cache Block Flush Example Source: https://clang.llvm.org/docs/LanguageExtensions.html Example demonstrating the usage of the __builtin_dcbf function to flush a data cache block. ```c int a = 1; __builtin_dcbf (&a); ``` -------------------------------- ### Continuation Indent Width Example Source: https://clang.llvm.org/docs/ClangFormatStyleOptions.html Sets the indentation width for line continuations. This example demonstrates using an indent width of 2. ```cpp ContinuationIndentWidth: 2 int i = // VeryVeryVeryVeryVeryLongComment longFunction( // Again a long comment arg); ``` -------------------------------- ### Build LLVM with Make Source: https://clang.llvm.org/docs/HowToSetupToolingForLLVM.html After setting up the compilation database, use this command to build and test LLVM using the Make build system. ```bash make check-all ``` -------------------------------- ### Include Header File Source: https://clang.llvm.org/docs/Modules.html Demonstrates the standard C++ way to include a header file for library access. ```cpp #include ``` -------------------------------- ### Inferred Submodule Declaration Example Source: https://clang.llvm.org/docs/Modules.html An example demonstrating an inferred submodule declaration where a module maps to all headers within a specified directory. ```c module MyLib { umbrella "MyLib" explicit module * { export * } } ``` -------------------------------- ### Import Path Traversal Example Source: https://clang.llvm.org/docs/InternalsManual.html Shows the sequence of import paths generated during a Depth-First Search (DFS) traversal of an AST, before an error occurs. ```text A AB ABC ABCD ABC AB ABE AB A ``` -------------------------------- ### Comment Pragmas Example Source: https://clang.llvm.org/docs/ClangFormatStyleOptions.html Specifies a regular expression for comments that should be preserved without modification. This example shows how to keep a specific pragma line. ```cpp // CommentPragmas: '^ FOOBAR pragma:' // Will leave the following line unaffected #include // FOOBAR pragma: keep ``` -------------------------------- ### Complete LibClang Example: Parsing and Type Analysis Source: https://clang.llvm.org/docs/LibClang.html A comprehensive example demonstrating the LibClang workflow: creating an index, parsing a translation unit from 'file.cpp', obtaining the root cursor, and then visiting children to analyze cursor types (including pointers and records) and their spelling. It also includes a second visit to print cursor names and line spans. ```cpp // main.cpp #include #include int main(){ CXIndex index = clang_createIndex(0, 0); //Create index CXTranslationUnit unit = clang_parseTranslationUnit( index, "file.cpp", nullptr, 0, nullptr, 0, CXTranslationUnit_None); //Parse "file.cpp" if (unit == nullptr){ std::cerr << "Unable to parse translation unit. Quitting.\n"; return 0; } CXCursor cursor = clang_getTranslationUnitCursor(unit); //Obtain a cursor at the root of the translation unit clang_visitChildren( cursor, [](CXCursor current_cursor, CXCursor parent, CXClientData client_data){ CXType cursor_type = clang_getCursorType(current_cursor); CXString type_kind_spelling = clang_getTypeKindSpelling(cursor_type.kind); std::cout << "TypeKind: " << clang_getCString(type_kind_spelling); clang_disposeString(type_kind_spelling); if(cursor_type.kind == CXType_Pointer || // If cursor_type is a pointer cursor_type.kind == CXType_LValueReference || // or an LValue Reference (&) cursor_type.kind == CXType_RValueReference){ // or an RValue Reference (&&), CXType pointed_to_type = clang_getPointeeType(cursor_type);// retrieve the pointed-to type CXString pointed_to_type_spelling = clang_getTypeSpelling(pointed_to_type); // Spell out the entire std::cout << "pointing to type: " << clang_getCString(pointed_to_type_spelling);// pointed-to type clang_disposeString(pointed_to_type_spelling); } else if(cursor_type.kind == CXType_Record){ CXString type_spelling = clang_getTypeSpelling(cursor_type); std::cout << ", namely " << clang_getCString(type_spelling); clang_disposeString(type_spelling); } std::cout << "\n"; return CXChildVisit_Recurse; }, nullptr ); clang_visitChildren( cursor, [](CXCursor current_cursor, CXCursor parent, CXClientData client_data){ CXType cursor_type = clang_getCursorType(current_cursor); CXString cursor_spelling = clang_getCursorSpelling(current_cursor); CXSourceRange cursor_range = clang_getCursorExtent(current_cursor); std::cout << "Cursor " << clang_getCString(cursor_spelling); CXFile file; unsigned start_line, start_column, start_offset; unsigned end_line, end_column, end_offset; clang_getExpansionLocation(clang_getRangeStart(cursor_range), &file, &start_line, &start_column, &start_offset); clang_getExpansionLocation(clang_getRangeEnd (cursor_range), &file, &end_line , &end_column , &end_offset); std::cout << " spanning lines " << start_line << " to " << end_line; clang_disposeString(cursor_spelling); std::cout << "\n"; return CXChildVisit_Recurse; }, nullptr ); } ``` -------------------------------- ### Create and Run ClangTool Source: https://clang.llvm.org/docs/LibTooling.html Instantiate a `ClangTool` with a `CompilationDatabase` and a list of source files, then run a `FrontendActionFactory` over the sources. ```c++ // A clang tool can run over a number of sources in the same process... std::vector Sources; Sources.push_back("a.cc"); Sources.push_back("b.cc"); // We hand the CompilationDatabase we created and the sources to run over into // the tool constructor. ClangTool Tool(OptionsParser.getCompilations(), Sources); // The ClangTool needs a new FrontendAction for each translation unit we run // on. Thus, it takes a FrontendActionFactory as parameter. To create a // FrontendActionFactory from a given FrontendAction type, we call // newFrontendActionFactory(). int result = Tool.run(newFrontendActionFactory().get()); ``` -------------------------------- ### C++ Header-Only Library Example Source: https://clang.llvm.org/docs/StandardCPlusPlusModules.html Illustrates a typical C++ header file for a library before module adoption. ```cpp // header.h #pragma once #include namespace example { class C { public: std::size_t inline_get() { return 42; } std::size_t get(); }; } // src.cpp #include "header.h" std::size_t example::C::get() { return 43 + inline_get(); } ``` -------------------------------- ### Suppression File Format Example Source: https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html An example of the format for suppression entries in a UBSan suppression file. Each line specifies a check type and its location. ```text signed-integer-overflow:file-with-known-overflow.cpp alignment:function_doing_unaligned_access vptr:shared_object_with_vptr_failures.so ``` -------------------------------- ### Prebuild modules using prebuilt module path Source: https://clang.llvm.org/docs/Modules.html Prebuilds modules A and B, then compiles use.c using the prebuilt module path and implicit module maps. ```bash rm -rf prebuilt; mkdir prebuilt clang -cc1 -emit-module -o prebuilt/A.pcm -fmodules module.modulemap -fmodule-name=A clang -cc1 -emit-module -o prebuilt/B.pcm -fmodules module.modulemap -fmodule-name=B -fprebuilt-module-path=prebuilt clang -cc1 -emit-obj use.c -fmodules -fimplicit-module-maps -fprebuilt-module-path=prebuilt ``` -------------------------------- ### BraceWrapping Configuration Example Source: https://clang.llvm.org/docs/ClangFormatStyleOptions.html Demonstrates the configuration of `BraceWrapping` options when `BreakBeforeBraces` is set to `Custom`. This allows precise control over individual brace wrapping cases. ```yaml # Example of usage: BreakBeforeBraces: Custom BraceWrapping: AfterEnum: true AfterStruct: false SplitEmptyFunction: false ``` -------------------------------- ### Example sanstats Output Source: https://clang.llvm.org/docs/SanitizerStats.html This is an example of the output format produced by the 'sanstats' utility, showing file, line, function, statistic type, and count. ```text vcall.cc:6 _Z1gP1A cfi-vcall 1 ``` -------------------------------- ### Trace PC Guard Output Example Source: https://clang.llvm.org/docs/SanitizerCoverage.html Sample output from running the instrumented program. It shows the initialization messages and the trace of executed guards with their associated PCs and descriptions. ```text INIT: 0x71bcd0 0x71bce0 guard: 0x71bcd4 2 PC 0x4ecd5b in main trace-pc-guard-example.cc:2 guard: 0x71bcd8 3 PC 0x4ecd9e in main trace-pc-guard-example.cc:3:7 ``` ```text INIT: 0x71bcd0 0x71bce0 guard: 0x71bcd4 2 PC 0x4ecd5b in main trace-pc-guard-example.cc:3 guard: 0x71bcdc 4 PC 0x4ecdc7 in main trace-pc-guard-example.cc:4:17 guard: 0x71bcd0 1 PC 0x4ecd20 in foo() trace-pc-guard-example.cc:2:14 ``` -------------------------------- ### AArch64 target_clones example Source: https://clang.llvm.org/docs/AttributeReference.html This example demonstrates the `target_clones` attribute for AArch64, specifying multiple target features like SHA2, MEMTAG, FCMA, and SVE2-PMULL128. ```cpp __attribute__((target_clones("sha2+memtag", "fcma+sve2-pmull128"))) void foo() {} ``` -------------------------------- ### Optimization Record File Naming Examples Source: https://clang.llvm.org/docs/UsersManual.html Provides examples of how optimization record files are named based on input and output files when using -fsave-optimization-record. ```text clang -fsave-optimization-record -c in.c -o out.o will generate `out.opt.yaml` ``` ```text clang -fsave-optimization-record -c in.c will generate `in.opt.yaml` ``` -------------------------------- ### Compile with prebuilt modules and explicit path Source: https://clang.llvm.org/docs/Modules.html Compiles use.c using prebuilt modules from a specified path, demonstrating potential compatibility warnings. ```bash clang -cc1 -emit-obj use.c -fmodules -fimplicit-module-maps -fprebuilt-module-path=prebuilt -DENABLE_A # use.c:4:10: warning: implicit declaration of function 'a' is invalid in C99 [-Wimplicit-function-declaration] # return a(x); # ^ # 1 warning generated. ``` -------------------------------- ### Module Use Example Source: https://clang.llvm.org/docs/Modules.html Demonstrates module declarations where use of A from C is not declared, triggering a warning. ```c module A { header "a.h" } module B { header "b.h" } module C { header "c.h" use B } ``` -------------------------------- ### Debugging Clang Linker Wrapper with Verbose Output and Saved Temps Source: https://clang.llvm.org/docs/ClangLinkerWrapper.html This example demonstrates how to enable verbose output and save intermediate files when using the clang-linker-wrapper. This allows for detailed inspection of the wrapper's internal steps and provides a self-contained sequence of commands to reproduce its output. ```bash $> clang openmp.c -fopenmp --offload-arch=gfx90a -c $> clang openmp.o -fopenmp --offload-arch=gfx90a -Wl,--wrapper-verbose -Wl,--save-temps # 1. Extract each embedded device image from the host object. llvm-offload-binary openmp.o --image=kind=openmp,triple=amdgcn-amd-amdhsa,arch=gfx90a,file=openmp.gfx90a.o # 2. Link the extracted image for the device target. clang --target=amdgcn-amd-amdhsa -mcpu=gfx90a openmp.gfx90a.o -o openmp.gfx90a.img <...> # 3. Bundle the linked image back into the offloading binary format. llvm-offload-binary -o openmp.gfx90a.offload --image=file=openmp.gfx90a.img,kind=openmp,triple=amdgcn-amd-amdhsa,arch=gfx90a # 4. Generate the host runtime registration code for the bundled images. llvm-offload-wrapper --kind=openmp --triple=x86_64-unknown-linux-gnu -o openmp.wrapper.bc openmp.gfx90a.offload # 5. Compile the registration code into a host object. clang --target=x86_64-unknown-linux-gnu -c -fPIC -o openmp.wrapper.o openmp.wrapper.bc # 6. Link the host objects with the registration code into the executable. ld.lld openmp.host.o openmp.wrapper.o -o a.out <...> ``` -------------------------------- ### Emit Object File with Prebuilt Modules Source: https://clang.llvm.org/docs/Modules.html Use this command to emit an object file while leveraging prebuilt modules. Ensure the prebuilt module path is correctly specified. ```c clang -cc1 -emit-obj -o use.o use.c -fmodules -fimplicit-module-maps -fprebuilt-module-path=prebuilt -fprebuilt-implicit-modules ``` ```c clang -cc1 -emit-obj -o use.o use.c -fmodules -fimplicit-module-maps -fprebuilt-module-path=prebuilt -fprebuilt-implicit-modules -DENABLE_A ``` -------------------------------- ### C++ Code for Throwing Destructor Example Source: https://clang.llvm.org/docs/CIR/CleanupAndEHDesign.html Defines a C++ struct with a destructor that can throw an exception and a function that uses it. This serves as the source for the CIR examples. ```cpp struct ThrowingDtor { ~ThrowingDtor() noexcept(false); }; void someFunc() { ThrowingDtor c; c.doSomething(); } ``` -------------------------------- ### Display clang-format Help Information Source: https://clang.llvm.org/docs/ClangFormat.html Use this command to display the help message and available options for the clang-format tool. This is useful for understanding its capabilities and syntax. ```bash $ clang-format --help ``` -------------------------------- ### InsertBraces Option Example Source: https://clang.llvm.org/docs/ClangFormatStyleOptions.html Controls the insertion of braces after control statements in C++. This example shows the 'false' and 'true' configurations for 'if', 'while', and 'do' statements. ```cpp false: true: if (isa(D)) vs. if (isa(D)) { handleFunctionDecl(D); handleFunctionDecl(D); else if (isa(D)) } else if (isa(D)) { handleVarDecl(D); handleVarDecl(D); else } else { return; return; } while (i--) vs. while (i--) { for (auto *A : D.attrs()) for (auto *A : D.attrs()) { handleAttr(A); handleAttr(A); } } do vs. do { --i; --i; while (i); } while (i); ``` -------------------------------- ### Linker-Specific Options with $ Prefix Source: https://clang.llvm.org/docs/UsersManual.html Demonstrates how to specify options that are only applied when the linker is invoked, using the '$' prefix. ```text $-Wl,-Bstatic $-lm $-Wl,-Bshared ``` -------------------------------- ### TypeSanitizer Error Output Example Source: https://clang.llvm.org/docs/TypeSanitizer.html Example of TypeSanitizer output when a strict aliasing violation is detected. The program continues execution, allowing multiple violations to be reported. ```text % ./a.out ==1375532==ERROR: TypeSanitizer: type-aliasing-violation on address 0x7ffeebf1a72c (pc 0x5b3b1145ff41 bp 0x7ffeebf1a660 sp 0x7ffeebf19e08 tid 1375532) READ of size 4 at 0x7ffeebf1a72c with type float accesses an existing object of type int #0 0x5b3b1145ff40 in main example_AliasViolation.c:4:10 ==1375532==ERROR: TypeSanitizer: type-aliasing-violation on address 0x7ffeebf1a72c (pc 0x5b3b1146008a bp 0x7ffeebf1a660 sp 0x7ffeebf19e08 tid 1375532) WRITE of size 4 at 0x7ffeebf1a72c with type float accesses an existing object of type int #0 0x5b3b11460089 in main example_AliasViolation.c:4:10 ``` -------------------------------- ### C++ Example for Branching through Cleanup Source: https://clang.llvm.org/docs/CIR/CleanupAndEHDesign.html A C++ code snippet illustrating a loop with `continue` and `break` statements, which serves as the basis for the CIR cleanup scope example. ```C++ int someFunc() { int i = 0; while (true) { SomeClass c; if (i == 3) continue; if (i == 7) break; i = c.get(); } return i; } ``` -------------------------------- ### Create First Clang Tool Source: https://clang.llvm.org/docs/LibTooling.html This C++ code snippet demonstrates how to create a basic Clang tool using CommonOptionsParser and ClangTool. It includes setup for command-line arguments and running a SyntaxOnlyAction. ```cpp // Declares clang::SyntaxOnlyAction. #include "clang/Frontend/FrontendActions.h" #include "clang/Tooling/CommonOptionsParser.h" #include "clang/Tooling/Tooling.h" // Declares llvm::cl::extrahelp. #include "llvm/Support/CommandLine.h" using namespace clang::tooling; using namespace llvm; // Apply a custom category to all command-line options so that they are the // only ones displayed. static cl::OptionCategory MyToolCategory("my-tool options"); // CommonOptionsParser declares HelpMessage with a description of the common // command-line options related to the compilation database and input files. // It's nice to have this help message in all tools. static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage); // A help message for this specific tool can be added afterwards. static cl::extrahelp MoreHelp("\nMore help text...\n"); int main(int argc, const char **argv) { auto ExpectedParser = CommonOptionsParser::create(argc, argv, MyToolCategory); if (!ExpectedParser) { llvm::errs() << toString(ExpectedParser.takeError()); return 1; } CommonOptionsParser& OptionsParser = ExpectedParser.get(); ClangTool Tool(OptionsParser.getCompilations(), OptionsParser.getSourcePathList()); return Tool.run(newFrontendActionFactory().get()); } ```